MCPcopy Create free account
hub / github.com/FareedKhan-dev/ai-long-task / _sample_from_island_weighted

Method _sample_from_island_weighted

data/database.py:1431–1486  ·  view source on GitHub ↗

Sample a parent from a specific island using fitness-weighted selection Args: island_id: The island to sample from Returns: Parent program selected using fitness-weighted sampling

(self, island_id: int)

Source from the content-addressed store, hash-verified

1429 return self.programs[program_id]
1430
1431 def _sample_from_island_weighted(self, island_id: int) -> Program:
1432 """
1433 Sample a parent from a specific island using fitness-weighted selection
1434
1435 Args:
1436 island_id: The island to sample from
1437
1438 Returns:
1439 Parent program selected using fitness-weighted sampling
1440 """
1441 island_id = island_id % len(self.islands)
1442 island_programs = list(self.islands[island_id])
1443
1444 if not island_programs:
1445 # Island is empty, fall back to any available program
1446 logger.debug(f"Island {island_id} is empty, sampling from all programs")
1447 return self._sample_random_parent()
1448
1449 # Select parent from island programs
1450 if len(island_programs) == 1:
1451 parent_id = island_programs[0]
1452 else:
1453 # Use weighted sampling based on program scores
1454 island_program_objects = [
1455 self.programs[pid] for pid in island_programs if pid in self.programs
1456 ]
1457
1458 if not island_program_objects:
1459 # Fallback if programs not found
1460 parent_id = random.choice(island_programs)
1461 else:
1462 # Calculate weights based on fitness scores
1463 weights = []
1464 for prog in island_program_objects:
1465 fitness = get_fitness_score(prog.metrics, self.config.feature_dimensions)
1466 # Add small epsilon to avoid zero weights
1467 weights.append(max(fitness, 0.001))
1468
1469 # Normalize weights
1470 total_weight = sum(weights)
1471 if total_weight > 0:
1472 weights = [w / total_weight for w in weights]
1473 else:
1474 weights = [1.0 / len(island_program_objects)] * len(island_program_objects)
1475
1476 # Sample parent based on weights
1477 parent = random.choices(island_program_objects, weights=weights, k=1)[0]
1478 parent_id = parent.id
1479
1480 parent = self.programs.get(parent_id)
1481 if not parent:
1482 # Should not happen, but handle gracefully
1483 logger.error(f"Parent program {parent_id} not found in database")
1484 return self._sample_random_parent()
1485
1486 return parent
1487
1488 def _sample_from_island_random(self, island_id: int) -> Program:

Callers 2

sample_from_islandMethod · 0.95

Calls 3

_sample_random_parentMethod · 0.95
get_fitness_scoreFunction · 0.90
getMethod · 0.80

Tested by

no test coverage detected