43from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
47 """Construct and run a native QD optimisation from YAML.
49 The file defines named containers and algorithms and identifies
50 ``main_algorithm_name``. Domain entries named after objectives and
51 descriptors can supply bounds to the configured archives.
53 Override eval_fn for a real objective. The base evaluator draws
54 demonstration values from the configured domains. Override
55 several_eval_fn to evaluate packed candidates as a group.
57 :param config_filename: YAML file describing the experiment.
58 :param parallelism_type: Backend for ParallelismManager.
59 :param seed: Optional seed override for Python and NumPy.
60 :param base_config: Top-level configuration overrides applied after loading.
62 def __init__(self, config_filename, parallelism_type = "concurrent", seed = None, base_config = None):
64 if base_config
is not None:
67 self.
config[
'parallelism_type'] = parallelism_type
71 def __getstate__(self):
72 odict = self.__dict__.copy()
74 del odict[
'container']
78 def _loadConfig(self, config_filename):
80 self.
config_name = os.path.splitext(os.path.basename(config_filename))[0]
81 self.
config = yaml.safe_load(open(config_filename))
84 """Insert a key into a nested configuration mapping using the supplied path."""
88 insert_dict(d, path[-1], val)
91 def _get_features_list(self):
93 assert not (
'fitness_list' in self.
config and 'fitness_type' in self.
config), f
"'fitness_list' and 'fitness_type' cannot both be specified at the same time."
94 if 'fitness_type' in self.
config:
95 fitness_list.append(self.
config[
'fitness_type'])
96 elif 'fitness_list' in self.
config:
97 fitness_list += self.
config[
'fitness_list']
100 assert not (
'features_list' in self.
config and 'feature_type' in self.
config), f
"'features_list' and 'feature_type' cannot both be specified at the same time."
101 if 'feature_type' in self.
config:
102 features_list.append(self.
config[
'feature_type'])
103 elif 'features_list' in self.
config:
104 features_list += self.
config[
'features_list']
105 return features_list, fitness_list
108 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
109 current_version=qdpy.__version__,
110 details=
"Use 'self.fitness_list' instead.")
112 """First configured objective name, or None when no objective name is configured."""
115 def _define_domains(self):
117 self.
config[
'features_domain'] = []
119 val = self.
config[
'%s%s' % (feature_name,
"Domain")]
120 self.
config[
'features_domain'] += [tuple(val)]
121 self.
config[
'fitness_domain'] = []
123 val = self.
config[
'%s%s' % (fitness_name,
"Domain")]
124 self.
config[
'fitness_domain'] += [tuple(val)]
133 if rnd_seed
is not None:
135 elif "seed" in self.
config:
136 seed = self.
config[
"seed"]
138 seed = np.random.randint(1000000)
143 self.
config[
"seed"] = seed
144 print(
"Seed: %i" % seed)
149 """Rebuild the configured archives, algorithms, logger, and output paths.
151 The constructor seeds the random generators before calling reinit.
152 This method can also be called after changing the configuration.
154 self.
instance_name = datetime.datetime.now().strftime(
'%Y%m%d%H%M%S')
156 if not self.
config.get(
'dataDir'):
157 resultsBaseDir = self.
config.get(
'resultsBaseDir')
or "./results/"
158 dataDir = os.path.join(os.path.expanduser(resultsBaseDir), os.path.splitext(os.path.basename(self.
config_filename))[0])
159 self.
config[
'dataDir'] = dataDir
160 pathlib.Path(self.
config[
'dataDir']).mkdir(parents=
True, exist_ok=
True)
165 if self.
config[
'fitness_domain'] !=
None and len(self.
config[
'fitness_domain']) > 0:
166 default_config[
"fitness_domain"] = self.
config[
'fitness_domain']
167 if self.
config[
'features_domain'] !=
None and len(self.
config[
'features_domain']) > 0:
168 default_config[
"features_domain"] = self.
config[
'features_domain']
170 default_config[
"fitness_score_names"] = self.
fitness_list
177 assert "containers" in self.
config, f
"Please specify configuration entry 'containers' containing the description of all containers."
178 factory.build(self.
config[
"containers"], default_config)
179 assert "algorithms" in self.
config, f
"Please specify configuration entry 'algorithms' containing the description of all algorithms."
180 factory.build(self.
config[
"algorithms"])
181 assert "main_algorithm_name" in self.
config, f
"Please specify configuration entry 'main_algorithm' containing the name of the main algorithm."
182 self.
algo = factory[self.
config[
"main_algorithm_name"]]
192 logger_type = self.
config.get(
'logger_type',
"tqdm").lower()
193 if logger_type ==
"tqdm":
197 elif logger_type ==
"basic":
202 raise ValueError(f
"Unknown value for `logger_type`: {logger_type}. It can be either 'tqdm' or 'basic'.")
206 """Execute the selected optimiser and write result files and plots.
208 Use the YAML batch mode and packed evaluator settings, create the
209 selected executor, and close it after the run. The output directory
210 holds timestamped final results and grid plots.
212 verbose = self.
config.get(
'verbose',
False)
213 send_several_suggestions_to_fn = self.
config.get(
'send_several_suggestions_to_fn',
False)
214 max_nb_suggestions_per_call = self.
config.get(
'max_nb_suggestions_per_call', 10)
216 initial_evaluations = self.
algo.nb_evaluations
219 best = self.
algo.optimise(eval_fn, executor = pMgr.executor, batch_mode=self.
batch_mode, verbose=verbose, send_several_suggestions_to_fn=send_several_suggestions_to_fn, max_nb_suggestions_per_call=max_nb_suggestions_per_call)
222 configuration=self.
config, evaluate=eval_fn, initial_evaluations=initial_evaluations,
223 final_pickle=self.
logger.final_filename,
224 execution={
"backend": pMgr.parallelism_type,
"start_method": pMgr.start_method,
225 "max_workers": pMgr.max_workers,
"batch_mode": self.
batch_mode,
226 "batch_size": self.
algo.batch_size,
227 "packed": send_several_suggestions_to_fn,
228 "max_suggestions_per_call": max_nb_suggestions_per_call},
231 print(
"\n------------------------\n")
232 print(self.
algo.summary())
234 to_grid_parameters = self.
config.get(
'to_grid_parameters', {})
235 default_plots_grid(self.
logger, self.
log_base_path, suffix=f
"-{self.instance_name}", to_grid_parameters=to_grid_parameters)
236 print(
"\nA plot of the performance grid was saved in '%s'." % os.path.abspath(os.path.join(self.
log_base_path, f
"performancesGrid-{self.instance_name}.pdf")))
237 print(
"\nA plot of the activity grid was saved in '%s'." % os.path.abspath(os.path.join(self.
log_base_path, f
"activityGrid-{self.instance_name}.pdf")))
238 print(
"All results are available in the '%s' pickle file." % self.
logger.final_filename)
241 def _removeTmpFiles(self, fileList):
242 keepTemporaryFiles = self.
config.get(
'keepTemporaryFiles')
243 if not keepTemporaryFiles:
246 if os.path.isfile(f):
254 """Evaluate each candidate in input order and return one result per candidate."""
262 """Return demonstration fitness, descriptors, and named scores for one candidate.
264 The base implementation draws random values inside declared domains.
265 Subclasses supply the real measurements for an application.
267 fitness = [np.random.uniform(x[0], x[1])
for x
in self.
config[
'fitness_domain']]
268 features = [np.random.uniform(x[0], x[1])
for x
in self.
config[
'features_domain']]
269 scores = {f
"{i}": v
for i, v
in enumerate(features)}
270 scores[
'perf'] = fitness[0]
271 return fitness, features, scores