QDpy
Loading...
Searching...
No Matches
base.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"""Some base classes, stubs and types."""
20#from __future__ import annotations
21
22#__all__ = ["jit"]
23
24
25
26from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, overload
27from typing_extensions import runtime, Protocol
28from operator import mul, truediv
29import math
30import sys
31import importlib
32import pickle
33import textwrap
34import copy
35from inspect import signature
36from functools import partial
37from contextlib import contextmanager
38from pathlib import Path
39import tempfile
40from time import monotonic
41import warnings
42import numpy as np
43
44import os
45import psutil
46import signal
47
48from qdpy.utils import *
49
50
51
52T = TypeVar("T")
53DomainLike = Tuple[float, float]
54ShapeLike = Tuple[int, ...]
55
56
57
58
59@runtime
60class FutureLike(Protocol):
61 """Future interface used to retrieve evaluator results and observe completion."""
62 def cancelled(self) -> bool: ...
63 def done(self) -> bool: ...
64 def result(self) -> Any: ...
65 def exception(self) -> Any: ...
66 def add_done_callback(self, fn: Callable, **kwargs: Any) -> None: ...
67 def as_completed(self, fs: Sequence) -> Any: ...
68
69@runtime
70class ExecutorLike(Protocol):
71 """Executor interface for submitting work, mapping a callable, and shutting down."""
72 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike: ...
73 def map(self, fn: Callable, *iterables: Any) -> Iterable: ...
74 def shutdown(self, wait: bool = True) -> None: ...
75
76
78 """Hold an evaluation result that is already available in the controlling process."""
79 _result: Any
80 def __init__(self, result: Any) -> None:
81 self._result = result
82 def cancelled(self) -> bool:
83 return False
84 def cancel(self) -> bool:
85 return False
86 def done(self) -> bool:
87 return True
88 def result(self) -> Any:
89 return self._result
90 def exception(self) -> Any:
91 return None
92 def add_done_callback(self, fn: Callable, **kwargs: Any) -> None:
93 # Call directly the callback
94 fn(self)
95
97 """Run evaluator calls synchronously in the controlling process.
98
99 Submission executes the callable immediately. Map evaluates zipped
100 inputs in order and exposes their results through an iterator.
101 """
102 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
103 return SequentialFuture(fn(*args, **kwargs))
104 def map(self, fn: Callable, *iterables: Any) -> Iterable:
105 # From cpython code 'concurrent/futures/_base.py'
106 fs = [self.submit(fn, *args) for args in zip(*iterables)]
107 # Yield must be hidden in closure so that the futures are submitted
108 # before the first iterator value is required.
109 def result_iterator():
110 try:
111 # reverse to keep finishing order
112 fs.reverse()
113 while fs:
114 # Careful not to keep a reference to the popped future
115 yield fs.pop().result()
116 finally:
117 for future in fs:
118 future.cancel()
119 return result_iterator()
120 def shutdown(self, wait: bool = True) -> None:
121 pass
122
123
124try:
125 import scoop.futures
127 """Adapt futures from a program launched with SCOOP.
128
129 Install SCOOP separately and launch the script with the SCOOP module.
130 The submit adapter accepts positional evaluator arguments.
131 """
132 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
133 assert len(kwargs) == 0, f"`ScoopExecutor.submit` does not handle **kwargs."
134 return scoop.futures.submit(fn, *args)
135 def map(self, fn: Callable, *iterables: Any) -> Iterable:
136 return scoop.futures.map(fn, *iterables)
137 def shutdown(self, wait: bool = True) -> None:
138 scoop.futures.shutdown(wait)
139 _scoop_as_completed: Optional[Callable] = scoop.futures.as_completed
140 _scoop_future_class: Optional[Any] = scoop.futures.Future
141
142except ImportError:
143 class ScoopExecutor(ExecutorLike): # type: ignore
144 """Executor that encapsulate scoop concurrency functions. Need the scoop package to be installed and importable."""
145 def __init__(self) -> None:
146 raise NotImplementedError("`ScoopExecutor` needs the scoop package to be installed and importable.")
147 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
148 raise NotImplementedError("`ScoopExecutor` needs the scoop package to be installed and importable.")
149 def map(self, fn: Callable, *iterables: Any) -> Iterable:
150 raise NotImplementedError("`ScoopExecutor` needs the scoop package to be installed and importable.")
151 def shutdown(self, wait: bool = True) -> None:
152 raise NotImplementedError("`ScoopExecutor` needs the scoop package to be installed and importable.")
153 _scoop_as_completed: Optional[Callable] = None # type: ignore
154 _scoop_future_class: Optional[Any] = None # type: ignore
155
156
157
158try:
159 import ray
160
162 """Future object returned by `RayExecutor` methods."""
163 oid: Any
164 def __init__(self, oid: Any) -> None:
165 self.oid = oid
166 def cancelled(self) -> bool:
167 return self.done() and isinstance(self.exception(), ray.exceptions.TaskCancelledError)
168 def cancel(self) -> bool:
169 if self.done():
170 return False
171 ray.cancel(self.oid)
172 return True
173 def done(self) -> bool:
174 return bool(ray.wait([self.oid], num_returns=1, timeout=0)[0])
175 def result(self) -> Any:
176 return ray.get(self.oid)
177 def exception(self) -> Any:
178 return self.oid.future().exception()
179
184 def add_done_callback(self, fn: Callable, **kwargs: Any) -> None:
185 self.oid.future().add_done_callback(lambda _: fn(self))
186
187 @ray.remote
188 def _ray_deploy_func(func, kwargs, *args):
189 return func(*args, **kwargs)
190
191 @ray.remote
192 class RayDeployment(object):
193 def __init__(self, i):
194 pass # TODO
195 def ray_deploy_func(self, func, kwargs, *args):
196 return func(*args, **kwargs)
197
198 class RayExecutor(ExecutorLike): # type: ignore
199 """Expose Ray tasks through the executor interface.
200
201 Install the ``ray`` extra. Pass a cluster address or set ``RAY_ADDRESS``
202 to attach to a running cluster. Otherwise start local Ray. An active
203 Ray connection in the calling process is reused unless an explicit
204 address was passed. The executor closes connections it opens.
205
206 :param address: Optional Ray cluster address. Use "local" to start
207 local Ray even when ``RAY_ADDRESS`` is set.
208 :param max_workers: CPU count for local Ray. An attached cluster
209 controls its own resources.
210 """
211 def __init__(self, *, address: Optional[str] = None,
212 max_workers: Optional[int] = None) -> None:
213 self._owns_connection = False
214 if ray.is_initialized():
215 if address is not None:
216 raise ValueError("Ray is already initialized. Omit the address to reuse its connection.")
217 return
218 endpoint = address if address is not None else (os.environ.get("RAY_ADDRESS") or "local")
219 if endpoint == "local" and max_workers is not None:
220 ray.init(address=endpoint, num_cpus=max_workers)
221 else:
222 ray.init(address=endpoint)
223 self._owns_connection = True
224 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
225 return RayFuture(_ray_deploy_func.remote(fn, kwargs, *args))
226 def map(self, fn: Callable, *iterables: Any) -> Iterable:
227 # From cpython code 'concurrent/futures/_base.py'
228 fs = [self.submit(fn, *args) for args in zip(*iterables)]
229 # Yield must be hidden in closure so that the futures are submitted
230 # before the first iterator value is required.
231 def result_iterator():
232 try:
233 # Reverse so popping from the end preserves submission order.
234 fs.reverse()
235 while fs:
236 # Careful not to keep a reference to the popped future
237 yield fs.pop().result()
238 finally:
239 for future in fs:
240 future.cancel()
241 return result_iterator()
242 def shutdown(self, wait: bool = True) -> None:
243 """Close the Ray connection if this executor opened it."""
244 if self._owns_connection:
245 ray.shutdown()
246 self._owns_connection = False
247
248
249
254 def _ray_as_completed_fn(fs, timeout=None):
255 oid_dict = {x.oid: x for x in fs}
256 pending = list(oid_dict)
257 deadline = None if timeout is None else monotonic() + timeout
258 while pending:
259 remaining_time = None if deadline is None else max(0, deadline - monotonic())
260 ready, pending = ray.wait(pending, num_returns=1, timeout=remaining_time)
261 if not ready:
262 raise TimeoutError("Ray tasks did not finish within the requested timeout.")
263 yield oid_dict[ready[0]]
264 _ray_as_completed: Optional[Callable] = _ray_as_completed_fn
265 _ray_future_class: Optional[Any] = RayFuture
266
267
268except ImportError:
269 class RayExecutor(ExecutorLike): # type: ignore
270 """Executor that encapsulate ray concurrency functions. Need the ray package to be installed and importable."""
271 def __init__(self, *, address: Optional[str] = None,
272 max_workers: Optional[int] = None) -> None:
273 raise NotImplementedError("`RayExecutor` needs the ray package to be installed and importable.")
274 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
275 raise NotImplementedError("`RayExecutor` needs the ray package to be installed and importable.")
276 def map(self, fn: Callable, *iterables: Any) -> Iterable:
277 raise NotImplementedError("`RayExecutor` needs the ray package to be installed and importable.")
278 def shutdown(self, wait: bool = True) -> None:
279 raise NotImplementedError("`RayExecutor` needs the ray package to be installed and importable.")
280 _ray_as_completed: Optional[Callable] = None # type: ignore
281 _ray_future_class: Optional[Any] = None # type: ignore
282
283
284
285def generic_as_completed(fs: Sequence[FutureLike], timeout: Optional[int]=None) -> FutureLike:
286 """Return the next completed future from a homogeneous nonempty sequence.
287
288 Sequential futures have already completed. Concurrent futures, SCOOP,
289 and Ray use their respective completion mechanisms.
290
291 :param fs: Pending futures from one backend.
292 :param timeout: Optional wait limit in seconds, passed to that backend.
293 :raises ValueError: If the input is empty or the backend is unknown.
294 """
295 if len(fs) == 0:
296 raise ValueError(f"`fs` must not be empty.")
297 # Verify if the futures are instances of SequentialFuture (assume all items have the same class)
298 if isinstance(fs[0], SequentialFuture):
299 return fs[0]
300 if _scoop_future_class is not None and isinstance(fs[0], _scoop_future_class) and _scoop_as_completed is not None:
301 return next(_scoop_as_completed(fs, timeout))
302 if _ray_future_class is not None and isinstance(fs[0], _ray_future_class) and _ray_as_completed is not None:
303 return next(_ray_as_completed(fs, timeout))
304 # Get the class and module of the first item (assume all items have the same class)
305 futures_module = fs[0].__module__
306 # Verify if a `as_completed` function is already available
307 m = importlib.import_module(futures_module)
308 if hasattr(m, "as_completed"):
309 return next(m.as_completed(fs, timeout)) # type: ignore
310 else:
311 raise ValueError(f"Futures from `fs` are of unknown type, with unknown `as_completed` corresponding function.")
312
313
314
315
316# Hack to terminate child process/threads gracefully using Ctrl-C
317# From https://stackoverflow.com/questions/32160054/keyboard-interrupts-with-pythons-multiprocessing-pool-and-map-function/45259908
318_parent_id = os.getpid()
319def _worker_init():
320# signal.signal(signal.SIGINT, signal.SIG_IGN)
321 def sig_int(signal_num, frame):
322 #print('signal: %s' % signal_num)
323 parent = psutil.Process(_parent_id)
324 for child in parent.children():
325 if child.pid != os.getpid():
326 print("killing child: %s" % child.pid)
327 child.kill()
328 #print("killing parent: %s" % _parent_id)
329 parent.kill()
330 #print("suicide: %s" % os.getpid())
331 psutil.Process(os.getpid()).kill()
332 signal.signal(signal.SIGINT, sig_int)
333
334
335# TODO Support for Dask
336class ParallelismManager(object):
337 """Open and close an evaluation executor as a context manager.
338
339 Use ``none`` or ``sequential`` for in-process evaluation,
340 ``multithreading`` for a thread pool, and ``multiprocessing`` or
341 ``concurrent`` for a process pool. The process pool prefers forkserver
342 when available and otherwise uses spawn. SCOOP and Ray require
343 their optional runtime packages.
344
345 :param parallelism_type: Executor backend name.
346 :param max_workers: Optional worker count for the standard pools or CPU
347 count for a local Ray runtime.
348 :param toolbox: Optional DEAP toolbox copied and bound to executor.map.
349 :param force_worker_suicide: Install the process worker's interrupt handler.
350 :param ray_address: Optional cluster address for the Ray backend.
351
352 Process evaluation needs picklable evaluation functions and candidates.
353 Protect executable entry points with the usual main guard.
354 """
355
356 executor: ExecutorLike
357 toolbox: Optional[Any]
358 orig_toolbox: Optional[Any]
359 max_workers: Optional[int]
360 _parallelism_type: str = ""
361 _parallelism_type_list: Sequence[str] = ['none', 'sequential', 'multiprocessing', 'concurrent', 'multithreading', 'scoop', 'ray']
362 force_worker_suicide: bool
363
364 def __init__(self, parallelism_type: str = "multiprocessing", max_workers: Optional[int] = None,
365 toolbox: Optional[Any] = None, force_worker_suicide: bool = True, *,
366 ray_address: Optional[str] = None) -> None:
367 self.parallelism_type = parallelism_type
368 if ray_address is not None and self.parallelism_type != "ray":
369 raise ValueError("ray_address requires the Ray backend.")
370 self.ray_address = ray_address
371 self.max_workers = max_workers
372 self.orig_toolbox = toolbox
373 self.toolbox = copy.deepcopy(toolbox) if toolbox is not None else None
374 self.force_worker_suicide = force_worker_suicide
375 self.start_method: Optional[str] = None
376
377 @property
378 def parallelism_type(self) -> str:
379 return self._parallelism_type
380
381 @parallelism_type.setter
382 def parallelism_type(self, val: str) -> None:
383 if len(self._parallelism_type) > 0:
384 raise NotImplementedError("`parallelism_type` cannot be set after initialisation.")
385 lval = val.lower()
386 if not lval in self._parallelism_type_list:
387 raise ValueError(f"`parallelism_type` can only be from [{','.join(self._parallelism_type_list)}].")
388 self._parallelism_type = lval
389
390 def __enter__(self) -> Any:
391 self.open()
392 return self
393
394 def __exit__(self, exc_type, exc_value, traceback):
395 self.close()
396
397 def open(self) -> Any:
398 """Open and prepare a new executor according to `self.parallelism_type`."""
399 if self.force_worker_suicide:
400 init_fn: Optional[Callable] = _worker_init
401 else:
402 init_fn = None
403 if self.parallelism_type == "none" or self.parallelism_type == "sequential":
405 elif self.parallelism_type == "multiprocessing" or self.parallelism_type == "concurrent":
406 import concurrent.futures
407 import multiprocessing
408 methods = multiprocessing.get_all_start_methods()
409 ctx = multiprocessing.get_context("forkserver" if "forkserver" in methods else "spawn")
410 self.start_method = ctx.get_start_method()
411 self.executor = concurrent.futures.ProcessPoolExecutor(
412 max_workers=self.max_workers, mp_context=ctx, initializer=init_fn
413 )
414 elif self.parallelism_type == "multithreading":
415 import concurrent.futures
416 self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) # type: ignore
417 elif self.parallelism_type == "scoop":
418 import scoop
419 self.executor = ScoopExecutor()
420 elif self.parallelism_type == "ray":
421 import ray
422 self.executor = RayExecutor(address=self.ray_address, max_workers=self.max_workers)
423 else:
424 raise ValueError("Unknown parallelism_type: '%s'" % self.parallelism_type)
425 if self.toolbox is not None:
426 self.toolbox.register("map", self.executor.map)
427 return self
428
429 def close(self) -> None:
430 """Close the current executor."""
431 self.executor.shutdown()
432
433
434
435
436class Summarisable(object):
437 """Describes a class that can be summarised by using the `self.summary` method.
438 The summarised information is provided by the `self.__get_summary_state__` method. """
439
440
441 def __get_summary_state__(self) -> Mapping[str, Any]:
442 """Return a dictionary containing the relevant entries to build a summary of the class.
443 By default, it includes all public attributes of the class. Must be overridden by subclasses."""
444 # Find public attributes
445 entries = {}
446 for k, v in inspect.getmembers(self):
447 if not k.startswith('_') and not inspect.ismethod(v):
448 try:
449 entries[k] = v
450 except Exception:
451 pass
452 return entries
453
454
455 def summary(self, max_depth: Optional[int] = None, max_entry_length: Optional[int] = 250) -> str:
456 """Return a summary description of the class.
457 The summarised information is provided by the `self.__get_summary_state__` method.
458
459 Parameters
460 ----------
461 :param max_depth: Optional[int]
462 The maximal recursion depth allowed. Used to summarise attributes of `self` that are also Summarisable.
463 If the maximal recursion depth is reached, the attribute is only described with a reduced representation (`repr(attribute)`).
464 If `max_depth` is set to None, there are no recursion limit.
465 :param max_entry_length: Optional[int]
466 If `max_entry_length` is not None, the description of a non-Summarisable entry exceeding `max_entry_length`
467 is cropped to this limit.
468 """
469 res: str = f"Summary {self.__class__.__name__}:\n"
470 subs_max_depth = max_depth - 1 if max_depth is not None else None
471 summary_state = self.__get_summary_state__()
472 for i, k in enumerate(summary_state.keys()):
473 v = summary_state[k]
474 res += f" {k}:"
475 if isinstance(v, Summarisable):
476 if max_depth is None or max_depth > 0:
477 res += textwrap.indent(v.summary(subs_max_depth), ' ')
478 else:
479 res += f" {repr(v)}"
480 else:
481 str_v = f" {v}"
482 str_v = str_v.replace("\n", " ")
483 if max_entry_length is not None and len(str_v) > max_entry_length:
484 str_v = str_v[:max_entry_length - 4] + " ..."
485 res += str_v
486 if i != len(summary_state) - 1:
487 res += "\n"
488 return res
489
490 def __repr__(self) -> str:
491 return f"{self.__class__.__name__}"
492
493
494
495
500@contextmanager
501def _atomic_output_path(output_path):
502 destination = Path(output_path)
503 with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as file:
504 temporary = Path(file.name)
505 try:
506 yield temporary
507 os.replace(temporary, destination)
508 finally:
509 temporary.unlink(missing_ok=True)
510
511
512class Saveable(object):
513 """Write a result dictionary supplied by the object.
514
515 Subclasses choose what the snapshot holds through the saved-state
516 hook. Result files can contain Python objects and should only be
517 loaded from trusted sources.
518 """
519
520 def __get_saved_state__(self) -> Mapping[str, Any]:
521 """Return a dictionary containing the relevant information to save.
522 By default, it includes all public attributes of the class. Must be overridden by subclasses."""
523 # Find public attributes
524 entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)}
525 return entries
526
527 def save(self, output_path: str, output_type: str = "pickle") -> None:
528 """Serialize a result dictionary and replace the destination atomically.
529
530 Write the new pickle to a temporary file in the destination directory.
531 Preserve the previous result if serialisation or replacement fails.
532
533 :param output_path: Destination file in an existing directory.
534 :param output_type: Output format. The supported value is ``pickle``.
535 :raises ValueError: If another output type is requested.
536 """
537 if output_type != "pickle":
538 raise ValueError(f"Invalid `output_type` value. Currently, only supports 'pickle'.")
539 saved_state = self.__get_saved_state__()
540 with _atomic_output_path(output_path) as temporary:
541 with temporary.open("wb") as file:
542 pickle.dump(saved_state, file)
543
544
545class Copyable(object):
546 """Describes a class capable to be copied and deepcopied."""
547
548 def __copy__(self):
549 cls = self.__class__
550 result = cls.__new__(cls)
551 result.__dict__.update(self.__dict__)
552 return result
553
554 def __deepcopy__(self, memo):
555 cls = self.__class__
556 result = cls.__new__(cls)
557 memo[id(self)] = result
558 for k, v in self.__dict__.items():
559 setattr(result, k, copy.deepcopy(v, memo))
560 return result
561
562
563
565 """Describe a class capable to be created from a configuration dictionary."""
566
567 @classmethod
568 def from_config(cls, config: Mapping[str, Any], **kwargs: Any) -> Any:
569 """Create a class using the information from `config` to call the class constructor.
570
571 Parameters
572 ----------
573 :param config: Mapping[str, Any]
574 The configuration mapping used to create the class. For each entry, the key corresponds
575 to the name of a parameter of the constructor of the class.
576 :param kwargs: Any
577 Additional information used to create the class. The configuration entries from kwargs
578 take precedence over the entry in `config`.
579 """
580 final_kwargs = {**config, **kwargs}
581 final_kwargs.pop("type", None)
582 return cls(**final_kwargs) # type: ignore
583
584
585# Inspired from Nevergrad (MIT License) Registry class (https://github.com/facebookresearch/nevergrad/blob/master/nevergrad/common/decorators.py)
586class Registry(dict):
587 """Map configured type names to registered Python classes."""
588
589 def __init__(self) -> None:
590 super().__init__()
591 self._information: MutableMapping[str, Mapping] = {}
592
593 def register(self, obj: Any, info: Optional[Mapping[Any, Any]] = None) -> Any:
594 """Decorator method for registering functions/classes
595 The `info` variable can be filled up using the register_with_info
596 decorator instead of this one.
597 """
598 name = obj.__name__
599 if name in self:
600 #raise RuntimeError(f'Encountered a name collision "{name}".')
601 warnings.warn(f'Encountered a name collision "{name}".')
602 return self[name]
603 self[name] = obj
604 if info is not None:
605 self._information[name] = info
606 return obj
607
608 def get_info(self, name: str) -> Mapping[str, Any]:
609 if name not in self:
610 raise ValueError(f'`{name}` is not registered.')
611 return self._information.setdefault(name, {})
612
613registry = Registry()
614
615
616class Factory(dict):
617 """Resolve registered types and named objects in a configuration.
618
619 A mapping with a type entry describes an object. A string matching a
620 previously built object's name refers to that object. Lists and
621 count mappings can request copies of registered configurations,
622 with reinitialisation where supported. Plain settings mappings
623 pass through to the constructor.
624
625 Build dependencies before the objects that refer to them. Use the
626 same Factory for the containers and algorithms of one experiment.
627 """
628
629 def __init__(self, registry: Registry=registry) -> None:
630 super().__init__()
631 self.registry = registry
632
633
634 def _get_name(self, obj: Any, key: Optional[str], config: Mapping[str, Any]) -> Optional[str]:
635 """Check if `obj` possess a name, and return it."""
636 name: str = ""
637 if hasattr(obj, "name"):
638 return obj.name
639 elif key is not None:
640 return key
641 elif "name" in config:
642 return config["name"]
643 else:
644 return None
645
646
647 def _build_internal(self, config: MutableMapping[str, Any], default_params: Mapping[str, Any] = {}, **kwargs: Any) -> Any:
648 # Recursively explore config and create objects for each entry possessing a "type" configuration entry
649 built_objs = []
650 default_config = {**default_params}
651 for k, v in config.items():
652 is_object = isinstance(v, Mapping) and "type" in v
653 if is_object:
654 sub_obj = self._build_internal(v, {**default_config, "name": k})
655 sub_name = self._get_name(sub_obj, k, v)
656 if sub_name is not None and len(sub_name) > 0 and not sub_name in self:
657 self[sub_name] = sub_obj
658 built_objs.append(sub_obj)
659 config[k] = sub_obj
660 elif isinstance(v, str) and v in self:
661 config[k] = self[v]
662 elif isinstance(v, Mapping) and v and all(key in self and isinstance(n, int) for key, n in v.items()):
663 objects = []
664 for name, count in v.items():
665 obj = self[name]
666 for _ in range(count):
667 if hasattr(obj, "reinit"):
668 clone = copy.deepcopy(obj)
669 clone.reinit()
670 objects.append(clone)
671 else:
672 objects.append(obj)
673 config[k] = objects
674 elif isinstance(v, list):
675 for i, val in enumerate(v):
676 if isinstance(val, str) and val in self:
677 if hasattr(self[val], "reinit"): # XXX refactor
678 new_val = copy.deepcopy(self[val])
679 new_val.reinit()
680 else:
681 new_val = self[val]
682 config[k][i] = new_val
683 if not is_object:
684 default_config[k] = config[k]
685
686 # If the configuration describes an object, build it
687 if "type" in config:
688 # Retrieve the class from registry
689 #assert "type" in config, f"The configuration must include an entry 'type' containing the type of the object to be built."
690 type_name: str = config["type"]
691 assert type_name in self.registry, f"The class `{type_name}` is not declared in the registry. To get the list of registered classes, use: 'print(registry.keys())'."
692 cls: Any = self.registry[type_name]
693 assert issubclass(cls, CreatableFromConfig), f"The class `{cls}` must inherit from `CreatableFromConfig` to be built."
694 # Build object
695 obj: Any = cls.from_config(config, **default_params, **kwargs)
696 # If 'obj' possess a name, add it to the factory
697 name: Optional[str] = self._get_name(obj, None, config)
698 if name is not None and len(name) > 0 and not name in self:
699 self[name] = obj
700 return obj
701
702 else: # Return all built objects
703 return built_objs
704
705
706
707 def build(self, config: Mapping[str, Any], default_params: Mapping[str, Any] = {}, **kwargs: Any) -> Any:
708 """Build a registered object or the named objects in a configuration section.
709
710 :param config: Mapping containing a type or nested object definitions.
711 :param default_params: Defaults inherited by object definitions.
712 :param kwargs: Additional arguments forwarded to the top-level factory hook.
713 :returns: The constructed object or a list of objects from a section.
714
715 The builder transforms a deep copy of the supplied mapping. A known
716 top-level name can return a previously built object.
717 """
718 if "name" in config and config["name"] in self:
719 return self[config["name"]]
720 final_config: MutableMapping[str, Any] = dict(copy.deepcopy(config))
721 return self._build_internal(final_config, default_params, **kwargs)
722
723
724
725from qdpy.phenotype import *
726
727# MODELINE "{{{1
728# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
729# vim:foldmethod=marker
Any from_config(cls, Mapping[str, Any] config, **Any kwargs)
Definition base.py:568
FutureLike submit(self, Callable fn, *Any args, **Any kwargs)
Definition base.py:72
Any _build_internal(self, MutableMapping[str, Any] config, Mapping[str, Any] default_params={}, **Any kwargs)
Definition base.py:647
Optional[str] _get_name(self, Any obj, Optional[str] key, Mapping[str, Any] config)
Definition base.py:634
Any build(self, Mapping[str, Any] config, Mapping[str, Any] default_params={}, **Any kwargs)
Definition base.py:707
CONCURRENCY ########### {{{1.
Definition base.py:60
bool done(self)
Definition base.py:63
Any exception(self)
Definition base.py:65
Optional[str] start_method
Definition base.py:375
None shutdown(self, bool wait=True)
Definition base.py:242
None add_done_callback(self, Callable fn, **Any kwargs)
Run a callback after the Ray reference becomes ready.
Definition base.py:184
dict _information
Definition base.py:591
Any register(self, Any obj, Optional[Mapping[Any, Any]] info=None)
Definition base.py:593
None save(self, str output_path, str output_type="pickle")
Definition base.py:527
Mapping[str, Any] __get_saved_state__(self)
Definition base.py:520
str summary(self, Optional[int] max_depth=None, Optional[int] max_entry_length=250)
Definition base.py:455
Mapping[str, Any] __get_summary_state__(self)
Definition base.py:441