import numpy as np from typing import List import random from .chip_component import ChipComponent class ChipDesign: def __init__(self, width: int, height: int, components: List[ChipComponent]): self.width = width self.height = height self.components = components self.fitness = 0.0 self.layout = np.zeros((height, width)) self._place_components_randomly() def _place_components_randomly(self): self.layout = np.zeros((self.height, self.width)) for component in self.components: placed = False while not placed: x = random.randint(0, self.width - component.width) y = random.randint(0, self.height - component.height) if self._can_place_component(x, y, component): component.position = (x, y) self.layout[y:y+component.height, x:x+component.width] = 1 placed = True def _can_place_component(self, x: int, y: int, component: ChipComponent) -> bool: if x + component.width > self.width or y + component.height > self.height: return False return np.sum(self.layout[y:y+component.height, x:x+component.width]) == 0 def calculate_fitness(self) -> float: total_power = sum(c.power_consumption for c in self.components) total_performance = sum(c.performance_score for c in self.components) distances = [] for i in range(len(self.components)): for j in range(i + 1, len(self.components)): dist = np.sqrt( (self.components[i].position[0] - self.components[j].position[0])**2 + (self.components[i].position[1] - self.components[j].position[1])**2 ) distances.append(dist) avg_distance = np.mean(distances) if distances else 0 self.fitness = (total_performance / (total_power + 1)) * (1 / (avg_distance + 1)) return self.fitness