QDpy
Loading...
Searching...
No Matches
experiment.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""The :mod:`qdpy.experiment` module contains classes providing a standard way of performing a QD Experiment """
20
21__all__ = ["QDExperiment"]
22
23#from collections.abc import Iterable
24#from typing import Optional, Tuple, TypeVar, Union, Any, MutableSet, Mapping, MutableMapping, Sequence, MutableSequence, Callable, Tuple
25#from typing_extensions import runtime, Protocol
26#import inspect
27
28from qdpy.algorithms import *
29from qdpy.containers import *
30from qdpy.plots import *
31from qdpy.base import *
32from qdpy import tools
33from qdpy.results import write_run_manifest
34import qdpy
35
36import yaml
37import random
38import datetime
39import pathlib
40import traceback
41import deprecation
42
43from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
44
45
46class QDExperiment(object):
47 """Construct and run a native QD optimisation from YAML.
48
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.
52
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.
56
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.
61 """
62 def __init__(self, config_filename, parallelism_type = "concurrent", seed = None, base_config = None):
63 self._loadConfig(config_filename)
64 if base_config is not None:
65 self.config = {**self.config, **base_config}
66 self.parallelism_type = parallelism_type
67 self.config['parallelism_type'] = parallelism_type
68 self._init_seed(seed)
69 self.reinit()
70
71 def __getstate__(self):
72 odict = self.__dict__.copy()
73 del odict['algo']
74 del odict['container']
75 return odict
76
77
78 def _loadConfig(self, config_filename):
79 self.config_filename = config_filename
80 self.config_name = os.path.splitext(os.path.basename(config_filename))[0]
81 self.config = yaml.safe_load(open(config_filename))
82
83 def set_defaultconfig_entry(self, path, val):
84 """Insert a key into a nested configuration mapping using the supplied path."""
85 d = self.config
86 for p in path[:-1]:
87 d = d[p]
88 insert_dict(d, path[-1], val)
89
90
91 def _get_features_list(self):
92 fitness_list = []
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']
98
99 features_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
106
107 @property # type: ignore
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.")
111 def fitness_type(self):
112 """First configured objective name, or None when no objective name is configured."""
113 return self.fitness_list[0] if len(self.fitness_list) > 0 else None
114
115 def _define_domains(self):
117 self.config['features_domain'] = []
118 for feature_name in self.features_list:
119 val = self.config['%s%s' % (feature_name, "Domain")]
120 self.config['features_domain'] += [tuple(val)]
121 self.config['fitness_domain'] = []
122 for fitness_name in self.fitness_list:
123 val = self.config['%s%s' % (fitness_name, "Domain")]
124 self.config['fitness_domain'] += [tuple(val)]
125 #self.config['fitness_domain'] = tuple(self.config['%s%s' % (self.fitness_type, "Domain")]),
126
127
131 def _init_seed(self, rnd_seed = None):
132 # Find random seed
133 if rnd_seed is not None:
134 seed = rnd_seed
135 elif "seed" in self.config:
136 seed = self.config["seed"]
137 else:
138 seed = np.random.randint(1000000)
139
140 # Update and print seed
141 np.random.seed(seed)
142 random.seed(seed)
143 self.config["seed"] = seed
144 print("Seed: %i" % seed)
145
146
147 def reinit(self):
148 # Name of the expe instance based on the current timestamp
149 """Rebuild the configured archives, algorithms, logger, and output paths.
150
151 The constructor seeds the random generators before calling reinit.
152 This method can also be called after changing the configuration.
153 """
154 self.instance_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
155 # Identify and create result data dir
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)
161
162 # Find the domains of the fitness and features
163 self._define_domains()
164 default_config = {}
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']
169 if len(self.fitness_list) > 0:
170 default_config["fitness_score_names"] = self.fitness_list
171 if len(self.features_list) > 0:
172 default_config["features_score_names"] = self.features_list
173 #print(default_config)
174
175 # Create containers and algorithms from configuration
176 factory = Factory()
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"]]
183 self.container = self.algo.container
184
185 self.batch_mode = self.config.get('batch_mode', False)
186 self.log_base_path = self.config['dataDir']
187
188 # Create a logger to pretty-print everything and generate output data files
189 self.iteration_filenames = os.path.join(self.log_base_path, "iteration-%i_" + self.instance_name + ".p")
190 self.final_filename = os.path.join(self.log_base_path, "final_" + self.instance_name + ".p")
191 self.save_period = self.config.get('save_period', 0)
192 logger_type = self.config.get('logger_type', "tqdm").lower()
193 if logger_type == "tqdm":
194 self.logger = TQDMAlgorithmLogger(self.algo,
195 iteration_filenames=self.iteration_filenames, final_filename=self.final_filename, save_period=self.save_period,
196 config=self.config)
197 elif logger_type == "basic":
198 self.logger = AlgorithmLogger(self.algo,
199 iteration_filenames=self.iteration_filenames, final_filename=self.final_filename, save_period=self.save_period,
200 config=self.config)
201 else:
202 raise ValueError(f"Unknown value for `logger_type`: {logger_type}. It can be either 'tqdm' or 'basic'.")
203
204
205 def run(self):
206 """Execute the selected optimiser and write result files and plots.
207
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.
211 """
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)
215 eval_fn = self.several_eval_fn if send_several_suggestions_to_fn else self.eval_fn
216 initial_evaluations = self.algo.nb_evaluations
217 # Run illumination process !
218 with ParallelismManager(self.parallelism_type) as pMgr:
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)
220 write_run_manifest(
221 pathlib.Path(self.log_base_path) / f"run_{self.instance_name}.json", self.algo,
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},
229 )
230
231 print("\n------------------------\n")
232 print(self.algo.summary())
233
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)
239
240
241 def _removeTmpFiles(self, fileList):
242 keepTemporaryFiles = self.config.get('keepTemporaryFiles')
243 if not keepTemporaryFiles:
244 for f in fileList:
245 try:
246 if os.path.isfile(f):
247 os.remove(f)
248 else:
249 shutil.rmtree(f)
250 except:
251 pass
252
253 def several_eval_fn(self, inds):
254 """Evaluate each candidate in input order and return one result per candidate."""
255 res = []
256 for ind in inds:
257 res.append(self.eval_fn(ind))
258 return res
259
260 def eval_fn(self, ind):
261 #print(ind.name)
262 """Return demonstration fitness, descriptors, and named scores for one candidate.
263
264 The base implementation draws random values inside declared domains.
265 Subclasses supply the real measurements for an application.
266 """
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
272
273
274# MODELINE "{{{1
275# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
276# vim:foldmethod=marker
set_defaultconfig_entry(self, path, val)
Definition experiment.py:83
_loadConfig(self, config_filename)
Definition experiment.py:78
_init_seed(self, rnd_seed=None)
Resolve and record the seed used by the experiment.