def test_study_system_attr_for_population_cache() -> None: sampler = multi_objective.samplers.NSGAIIMultiObjectiveSampler( population_size=10) study = multi_objective.create_study(["minimize"], sampler=sampler) def get_cached_entries( study: multi_objective.study.MultiObjectiveStudy, ) -> List[Tuple[int, List[int]]]: return [ v for k, v in study.system_attrs.items() if k.startswith( multi_objective.samplers._nsga2._POPULATION_CACHE_KEY_PREFIX) ] study.optimize(lambda t: [t.suggest_float("x", 0, 9)], n_trials=10) cached_entries = get_cached_entries(study) assert len(cached_entries) == 0 study.optimize(lambda t: [t.suggest_float("x", 0, 9)], n_trials=1) cached_entries = get_cached_entries(study) assert len(cached_entries) == 1 assert cached_entries[0][0] == 0 # Cached generation. assert len(cached_entries[0][1]) == 10 # Population size. study.optimize(lambda t: [t.suggest_float("x", 0, 9)], n_trials=10) cached_entries = get_cached_entries(study) assert len(cached_entries) == 1 assert cached_entries[0][0] == 1 # Cached generation. assert len(cached_entries[0][1]) == 10 # Population size.
def test_population_size() -> None: # Set `population_size` to 10. sampler = multi_objective.samplers.NSGAIIMultiObjectiveSampler( population_size=10) study = multi_objective.create_study(["minimize"], sampler=sampler) study.optimize(lambda t: [t.suggest_uniform("x", 0, 9)], n_trials=40) generations = Counter([ t.system_attrs[multi_objective.samplers._nsga2._GENERATION_KEY] for t in study.trials ]) assert generations == {0: 10, 1: 10, 2: 10, 3: 10} # Set `population_size` to 2. sampler = multi_objective.samplers.NSGAIIMultiObjectiveSampler( population_size=2) study = multi_objective.create_study(["minimize"], sampler=sampler) study.optimize(lambda t: [t.suggest_uniform("x", 0, 9)], n_trials=40) generations = Counter([ t.system_attrs[multi_objective.samplers._nsga2._GENERATION_KEY] for t in study.trials ]) assert generations == {i: 2 for i in range(20)} # Invalid population size. with pytest.raises(ValueError): # Less than 2. multi_objective.samplers.NSGAIIMultiObjectiveSampler(population_size=1) with pytest.raises(TypeError): # Not an integer. multi_objective.samplers.NSGAIIMultiObjectiveSampler( population_size=2.5) # type: ignore