epymorph 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. epymorph/__init__.py +7 -0
  2. epymorph/__main__.py +16 -0
  3. epymorph/adrio/__init__.py +0 -0
  4. epymorph/adrio/acs5.py +1378 -0
  5. epymorph/adrio/adrio.py +953 -0
  6. epymorph/adrio/cdc.py +1826 -0
  7. epymorph/adrio/commuting_flows.py +283 -0
  8. epymorph/adrio/csv.py +499 -0
  9. epymorph/adrio/humidity.py +206 -0
  10. epymorph/adrio/lodes.py +509 -0
  11. epymorph/adrio/numpy.py +160 -0
  12. epymorph/adrio/prism.py +345 -0
  13. epymorph/adrio/processing.py +1221 -0
  14. epymorph/adrio/soda.py +602 -0
  15. epymorph/adrio/us_tiger.py +289 -0
  16. epymorph/adrio/validation.py +382 -0
  17. epymorph/attribute.py +614 -0
  18. epymorph/cache.py +680 -0
  19. epymorph/cli/__init__.py +0 -0
  20. epymorph/cli/cache.py +78 -0
  21. epymorph/cli/main.py +29 -0
  22. epymorph/compartment_model.py +1873 -0
  23. epymorph/data/__init__.py +1 -0
  24. epymorph/data/ipm/__init__.py +22 -0
  25. epymorph/data/ipm/no.py +14 -0
  26. epymorph/data/ipm/pei.py +40 -0
  27. epymorph/data/ipm/seirs.py +50 -0
  28. epymorph/data/ipm/sirh.py +55 -0
  29. epymorph/data/ipm/sirs.py +48 -0
  30. epymorph/data/ipm/sparsemod.py +96 -0
  31. epymorph/data/mm/__init__.py +22 -0
  32. epymorph/data/mm/centroids.py +76 -0
  33. epymorph/data/mm/flat.py +61 -0
  34. epymorph/data/mm/icecube.py +50 -0
  35. epymorph/data/mm/no.py +29 -0
  36. epymorph/data/mm/pei.py +105 -0
  37. epymorph/data/mm/sparsemod.py +73 -0
  38. epymorph/data/pei.py +424 -0
  39. epymorph/data_shape.py +593 -0
  40. epymorph/data_type.py +185 -0
  41. epymorph/data_usage.py +258 -0
  42. epymorph/database.py +1301 -0
  43. epymorph/error.py +195 -0
  44. epymorph/event.py +196 -0
  45. epymorph/geography/__init__.py +0 -0
  46. epymorph/geography/custom.py +93 -0
  47. epymorph/geography/scope.py +457 -0
  48. epymorph/geography/us_census.py +1056 -0
  49. epymorph/geography/us_geography.py +502 -0
  50. epymorph/geography/us_tiger.py +1083 -0
  51. epymorph/initializer.py +786 -0
  52. epymorph/kit.py +107 -0
  53. epymorph/log/__init__.py +0 -0
  54. epymorph/log/file.py +128 -0
  55. epymorph/log/messaging.py +139 -0
  56. epymorph/log/movement.py +228 -0
  57. epymorph/movement_model.py +347 -0
  58. epymorph/parameter_fitting/__init__.py +0 -0
  59. epymorph/parameter_fitting/distribution.py +68 -0
  60. epymorph/parameter_fitting/dynamics.py +19 -0
  61. epymorph/parameter_fitting/filter/__init__.py +0 -0
  62. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  63. epymorph/parameter_fitting/filter/particle.py +32 -0
  64. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  65. epymorph/parameter_fitting/likelihood.py +54 -0
  66. epymorph/parameter_fitting/output.py +73 -0
  67. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  68. epymorph/parameter_fitting/perturbation.py +19 -0
  69. epymorph/parameter_fitting/utils/__init__.py +0 -0
  70. epymorph/parameter_fitting/utils/data_loader.py +97 -0
  71. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  72. epymorph/parameter_fitting/utils/observations.py +63 -0
  73. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  74. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  75. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  76. epymorph/parameter_fitting/utils/resampler.py +258 -0
  77. epymorph/parameter_fitting/utils/utils.py +101 -0
  78. epymorph/params.py +438 -0
  79. epymorph/py.typed +0 -0
  80. epymorph/rume.py +871 -0
  81. epymorph/simulation.py +991 -0
  82. epymorph/simulator/__init__.py +0 -0
  83. epymorph/simulator/basic/__init__.py +0 -0
  84. epymorph/simulator/basic/basic_simulator.py +171 -0
  85. epymorph/simulator/basic/ipm_exec.py +437 -0
  86. epymorph/simulator/basic/mm_exec.py +244 -0
  87. epymorph/simulator/basic/output.py +213 -0
  88. epymorph/simulator/world.py +149 -0
  89. epymorph/simulator/world_list.py +274 -0
  90. epymorph/strata.py +24 -0
  91. epymorph/sympy_shim.py +57 -0
  92. epymorph/time.py +1197 -0
  93. epymorph/tools/__init__.py +0 -0
  94. epymorph/tools/data.py +297 -0
  95. epymorph/tools/ipm_diagram.py +208 -0
  96. epymorph/tools/out_map.py +551 -0
  97. epymorph/tools/out_plot.py +423 -0
  98. epymorph/tools/out_table.py +582 -0
  99. epymorph/util.py +1036 -0
  100. epymorph-1.0.0.dist-info/METADATA +57 -0
  101. epymorph-1.0.0.dist-info/RECORD +104 -0
  102. epymorph-1.0.0.dist-info/WHEEL +5 -0
  103. epymorph-1.0.0.dist-info/entry_points.txt +2 -0
  104. epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/database.py ADDED
@@ -0,0 +1,1301 @@
1
+ """
2
+ A `Database` in epymorph organizes data attributes in a hierarchical namespace of three
3
+ components, as in: "strata::module::attribute_id".
4
+
5
+ The goal is to be as flexibile as possible for users specifying requirements and values
6
+ which fulfill those requirements. For example, you can provide a value for
7
+ "*::*::population" to indicate that every strata and every module should use the same
8
+ value if they require a "population" attribute. Or you can provide "*::init::population"
9
+ to indicate that only initializers should use this value, and, presumably, another value
10
+ is more appropriate for other modules like movement.
11
+
12
+ Specialized database instances provide the ability to "layer" data for a simulation --
13
+ if the outermost database has a matching value, that value is used, otherwise the search
14
+ for a match proceeds to the inner layers (recursively).
15
+ """
16
+
17
+ import dataclasses
18
+ from abc import ABC, abstractmethod
19
+ from dataclasses import dataclass, field
20
+ from functools import singledispatch
21
+ from typing import (
22
+ Callable,
23
+ Generic,
24
+ Iterable,
25
+ Iterator,
26
+ Literal,
27
+ Mapping,
28
+ NamedTuple,
29
+ Protocol,
30
+ Sequence,
31
+ TypeGuard,
32
+ TypeVar,
33
+ overload,
34
+ )
35
+
36
+ import numpy as np
37
+ from typing_extensions import override
38
+
39
+ from epymorph.attribute import (
40
+ AbsoluteName,
41
+ AttributeDef,
42
+ NamePattern,
43
+ )
44
+ from epymorph.compartment_model import BaseCompartmentModel
45
+ from epymorph.data_shape import (
46
+ DataShape,
47
+ Dimensions,
48
+ Node,
49
+ Scalar,
50
+ Shapes,
51
+ Time,
52
+ TimeAndNode,
53
+ )
54
+ from epymorph.data_type import (
55
+ AttributeArray,
56
+ AttributeType,
57
+ AttributeValue,
58
+ dtype_as_np,
59
+ dtype_str,
60
+ )
61
+ from epymorph.error import DataAttributeError, DataAttributeErrorGroup
62
+ from epymorph.geography.scope import GeoScope
63
+ from epymorph.time import TimeFrame
64
+ from epymorph.util import (
65
+ ANSIColor,
66
+ ANSIStyle,
67
+ ansi_stylize,
68
+ filter_unique,
69
+ )
70
+
71
+ ############
72
+ # Database #
73
+ ############
74
+
75
+
76
+ T = TypeVar("T")
77
+ """Type of database values."""
78
+
79
+
80
+ class Match(NamedTuple, Generic[T]):
81
+ """The result of a database query."""
82
+
83
+ pattern: NamePattern
84
+ """The name pattern of the value that matched."""
85
+ value: T
86
+ """The matched value."""
87
+
88
+
89
+ class Database(Generic[T]):
90
+ """
91
+ A dictionary of key/value pairs where keys obey epymorph's namespace system.
92
+
93
+ Namespaces are in the form "a::b::c", where "a" is a strata, "b" is a module,
94
+ and "c" is an attribute name. Values can be assigned with wildcards (specified by
95
+ asterisks), so that key "*::b::c" matches queries for both "a::b::c" and "z::b::c".
96
+
97
+ See Also
98
+ --------
99
+ `Database` is mostly used to store raw-form parameter values declared by the user.
100
+ In constrast [epymorph.database.DataResolver][] stores fully-evaluated parameters
101
+ optimized for use by simulation logic.
102
+
103
+ Parameters
104
+ ----------
105
+ data :
106
+ The key/value pairs to store.
107
+ """
108
+
109
+ _data: dict[NamePattern, T]
110
+ """The data values."""
111
+
112
+ def __init__(self, data: dict[NamePattern, T]):
113
+ self._data = data
114
+
115
+ # Check for key ambiguity:
116
+ conflicts = filter_unique(
117
+ [
118
+ key
119
+ for key, _ in self._data.items()
120
+ for other, _ in self._data.items()
121
+ if key != other and key.match(other)
122
+ ]
123
+ )
124
+
125
+ if len(conflicts) > 0:
126
+ conflicts = ", ".join(map(str, conflicts))
127
+ msg = f"Keys in data source are ambiguous; conflicts:\n{conflicts}"
128
+ raise ValueError(msg)
129
+
130
+ def query(self, key: str | AbsoluteName) -> Match[T] | None:
131
+ """
132
+ Query this database for a key match.
133
+
134
+ Parameters
135
+ ----------
136
+ key :
137
+ The name to find. If given as a string, it is first parsed as an
138
+ `AbsoluteName`.
139
+
140
+ Returns
141
+ -------
142
+ :
143
+ The found value, if any, else `None`.
144
+ """
145
+ if not isinstance(key, AbsoluteName):
146
+ key = AbsoluteName.parse(key)
147
+ for pattern, value in self._data.items():
148
+ if pattern.match(key):
149
+ return Match(pattern, value)
150
+ return None
151
+
152
+ def to_dict(self) -> dict[NamePattern, T]:
153
+ """
154
+ Return the database's data as a dictionary.
155
+
156
+ Returns
157
+ -------
158
+ :
159
+ A copy of this database's data.
160
+ """
161
+ return {**self._data}
162
+
163
+
164
+ class DatabaseWithFallback(Database[T]):
165
+ """
166
+ A specialization of `Database` which has its own key/value pairs as well as a
167
+ fallback `Database`.
168
+
169
+ If a match is not found in this database, the fallback is checked (recursively).
170
+
171
+ Parameters
172
+ ----------
173
+ data :
174
+ The highest priority values in the database.
175
+ fallback :
176
+ A database containing fallback values; if a match cannot be found
177
+ in `data`, this database will be checked.
178
+ """
179
+
180
+ _fallback: Database[T]
181
+ """The fallback."""
182
+
183
+ def __init__(self, data: dict[NamePattern, T], fallback: Database[T]):
184
+ super().__init__(data)
185
+ self._fallback = fallback
186
+
187
+ @override
188
+ def query(self, key: str | AbsoluteName) -> Match[T] | None:
189
+ if not isinstance(key, AbsoluteName):
190
+ key = AbsoluteName.parse(key)
191
+ # First check "our" data:
192
+ matched = super().query(key)
193
+ # Otherwise check fallback data:
194
+ if matched is None:
195
+ matched = self._fallback.query(key)
196
+ return matched
197
+
198
+ @override
199
+ def to_dict(self) -> dict[NamePattern, T]:
200
+ def is_overridden(fb_key: NamePattern) -> bool:
201
+ for override_key in self._data.keys():
202
+ if override_key.match(fb_key):
203
+ return True
204
+ return False
205
+
206
+ results = {
207
+ fb_key: fb_value
208
+ for fb_key, fb_value in self._fallback.to_dict().items()
209
+ if not is_overridden(fb_key)
210
+ }
211
+ results.update(self._data)
212
+ return results
213
+
214
+
215
+ class DatabaseWithStrataFallback(Database[T]):
216
+ """
217
+ A specialization of `Database` which has per-strata fallback databases.
218
+
219
+ For example consider querying this database for "a::b::c". If there is no match in
220
+ this database but there is a fallback for strata "a", the search proceeds to that
221
+ database (which could continue recursively).
222
+
223
+ Parameters
224
+ ----------
225
+ data :
226
+ The highest-priority values in the database.
227
+ children :
228
+ Fallback databases by strata.
229
+ """
230
+
231
+ _children: dict[str, Database[T]]
232
+ """The fallbacks by strata name."""
233
+
234
+ def __init__(self, data: dict[NamePattern, T], children: dict[str, Database[T]]):
235
+ super().__init__(data)
236
+ self._children = children
237
+
238
+ @override
239
+ def query(self, key: str | AbsoluteName) -> Match[T] | None:
240
+ if not isinstance(key, AbsoluteName):
241
+ key = AbsoluteName.parse(key)
242
+ # First check "our" data:
243
+ matched = super().query(key)
244
+ # Otherwise check strata fallback for match:
245
+ if matched is None and (db := self._children.get(key.strata)) is not None:
246
+ matched = db.query(key)
247
+ return matched
248
+
249
+ @override
250
+ def to_dict(self) -> dict[NamePattern, T]:
251
+ def is_overridden(fb_key: NamePattern) -> bool:
252
+ for override_key in self._data.keys():
253
+ if override_key.match(fb_key):
254
+ return True
255
+ return False
256
+
257
+ results = {
258
+ fb_key: fb_value
259
+ for strata_db in self._children.values()
260
+ for fb_key, fb_value in strata_db.to_dict().items()
261
+ if not is_overridden(fb_key)
262
+ }
263
+ results.update(self._data)
264
+ return results
265
+
266
+
267
+ ############
268
+ # Resolver #
269
+ ############
270
+
271
+
272
+ def assert_can_adapt(
273
+ data_type: AttributeType,
274
+ data_shape: DataShape,
275
+ dim: Dimensions,
276
+ value: AttributeArray,
277
+ ) -> None:
278
+ """
279
+ Check that we can adapt the given `value` to the given type and shape,
280
+ given dimensional information.
281
+
282
+ Parameters
283
+ ----------
284
+ data_type :
285
+ The final data type to adapt to.
286
+ data_shape :
287
+ The final data shape to adapt to.
288
+ dim :
289
+ Simulation dimensions.
290
+ value :
291
+ The value to adapt.
292
+
293
+ Raises
294
+ ------
295
+ DataAttributeError
296
+ If not.
297
+ """
298
+ if not np.can_cast(value, dtype_as_np(data_type)):
299
+ raise DataAttributeError("Not a compatible type.")
300
+ if not data_shape.matches(dim, value):
301
+ raise DataAttributeError("Not a compatible shape.")
302
+
303
+
304
+ def adapt(
305
+ data_type: AttributeType,
306
+ data_shape: DataShape,
307
+ dim: Dimensions,
308
+ value: AttributeArray,
309
+ ) -> AttributeArray:
310
+ """
311
+ Adapt the given `value` to the given type and shape, given dimensional
312
+ information.
313
+
314
+ Parameters
315
+ ----------
316
+ data_type :
317
+ The final data type to adapt to.
318
+ data_shape :
319
+ The final data shape to adapt to.
320
+ dim :
321
+ Simulation dimensions.
322
+ value :
323
+ The value to adapt.
324
+
325
+ Returns
326
+ -------
327
+ :
328
+ The adapated array.
329
+
330
+ Raises
331
+ ------
332
+ DataAttributeError
333
+ If this fails.
334
+ """
335
+ assert_can_adapt(data_type, data_shape, dim, value)
336
+ try:
337
+ typed = value.astype(
338
+ dtype_as_np(data_type),
339
+ casting="safe",
340
+ subok=False,
341
+ copy=False,
342
+ )
343
+ return data_shape.adapt(dim, typed)
344
+ except Exception as e:
345
+ raise DataAttributeError("Failed to adapt value.") from e
346
+
347
+
348
+ class DataResolver:
349
+ """
350
+ Stores evaluated data attributes for a simulation.
351
+
352
+ Data (typically parameter values) are provided by the user as a collection
353
+ of key-value pairs, with the values in several forms. These are evaluated
354
+ to turn them into our internal data representation which is optimized for
355
+ simulation execution.
356
+
357
+ Users typically provide parameter values with keys in `NamePattern` form, but
358
+ during parameter resolution values are stored by `AbsoluteName` to facilitate
359
+ lookups by the systems that use them. It is possible that multiple `AbsoluteNames`
360
+ resolve to the same value (which is done in a memory-efficient way).
361
+
362
+ Data requirements also specify the expected type and shape of the data,
363
+ and `DataResolver` also manages the resulting complexity. Two requirements could be
364
+ fulfilled by the same value while having different type and shape specifications.
365
+ Instead of rejecting this as an error, epymorph allows this provided the given value
366
+ can be successfully coerced to fit both requirements independently. For example, a
367
+ scalar integer value can be coerced to fit requirements for an N-shaped array of
368
+ floats as well as a T-shaped array of integers. `DataResolver` accomplishes this
369
+ in an efficient way by storing both the original values and all adapted values.
370
+ If multiple requirements specify the same type/shape adaptation for one value,
371
+ the adaptation only needs to happen once.
372
+
373
+ `DataResolver` is partially mutable -- new values can be added but values cannot
374
+ be overwritten or removed.
375
+
376
+ Parameters
377
+ ----------
378
+ dim :
379
+ The simulation dimensions; needed to perform shape adaptations.
380
+ values :
381
+ The values that should be in the resolver to begin with.
382
+ """
383
+
384
+ Key = tuple[AbsoluteName, AttributeType, DataShape]
385
+ """The type of the key used to track adapted values."""
386
+
387
+ _dim: Dimensions
388
+ """Simulation dimensions."""
389
+ _raw_values: dict[AbsoluteName, AttributeArray]
390
+ """Values in their 'input' form."""
391
+ _adapted_values: dict[Key, AttributeArray]
392
+ """Values in their 'output' form, after adaptation."""
393
+
394
+ def __init__(
395
+ self,
396
+ dim: Dimensions,
397
+ values: dict[AbsoluteName, AttributeArray] | None = None,
398
+ ):
399
+ self._dim = dim
400
+ self._raw_values = values or {}
401
+ self._adapted_values = {}
402
+
403
+ def has(self, name: AbsoluteName) -> bool:
404
+ """
405
+ Test whether or not a given name is in this resolver.
406
+
407
+ Parameters
408
+ ----------
409
+ name :
410
+ The name to test.
411
+
412
+ Returns
413
+ -------
414
+ :
415
+ True if `name` is in this resolver.
416
+ """
417
+ return name in self._raw_values
418
+
419
+ @property
420
+ def raw_values(self) -> Mapping[AbsoluteName, AttributeArray]:
421
+ """
422
+ The mapping of raw values in the resolver, by absolute name.
423
+
424
+ Warning:
425
+ -------
426
+ It is not safe to modify this mapping!
427
+ """
428
+ return self._raw_values
429
+
430
+ def get_raw(self, name: str | NamePattern | AbsoluteName) -> AttributeArray:
431
+ """
432
+ Retrieve a raw value that matches the given name.
433
+
434
+ Parameters
435
+ ----------
436
+ name :
437
+ The name of the value to retrieve. This can be an `AbsoluteName`,
438
+ a `NamePattern`, or a string. A string will be parsed as an
439
+ `AbsoluteName` if possible, and fall back to parsing it as a `NamePattern`.
440
+ In any case, the name must match exactly one value in order to
441
+ return successfully.
442
+
443
+ Returns
444
+ -------
445
+ :
446
+ The requested value, if found.
447
+
448
+ Raises
449
+ ------
450
+ ValueError
451
+ If the name is not present in the resolver, or if the name
452
+ is ambiguous and matches more than one value.
453
+ """
454
+ if isinstance(name, str):
455
+ # if we can parse string as an absolute name, do that
456
+ # otherwise, parse it as a name pattern
457
+ try:
458
+ name = AbsoluteName.parse(name)
459
+ except ValueError:
460
+ name = NamePattern.parse(name)
461
+
462
+ if isinstance(name, NamePattern):
463
+ # if we have a name pattern, find matching absolute names
464
+ # if there is exactly one match we can proceed
465
+ matches = [x for x in self._raw_values if name.match(x)]
466
+ match len(matches):
467
+ case 0:
468
+ err = f"Name '{name}' does not match any values."
469
+ raise ValueError(err)
470
+ case 1:
471
+ name = matches[0]
472
+ case _:
473
+ err = f"Name '{name}' matches more than one value."
474
+ raise ValueError(err)
475
+
476
+ # at this point we must have an absolute name, try to fetch it
477
+ if name not in self._raw_values:
478
+ err = f"Name '{name}' does not match any values."
479
+ raise ValueError(err)
480
+ return self._raw_values[name]
481
+
482
+ def add(self, name: AbsoluteName, value: AttributeArray) -> None:
483
+ """
484
+ Add a value to this resolver. You may not overwrite an existing name.
485
+
486
+ Parameters
487
+ ----------
488
+ name :
489
+ The name for the value.
490
+ value : AttributeArray
491
+ The value to add.
492
+
493
+ Raises
494
+ ------
495
+ ValueError
496
+ If `name` is already in this resolver.
497
+ """
498
+ if name in self._raw_values:
499
+ err = (
500
+ f"A value for '{name}' already exists in this resolver; "
501
+ "values cannot be overwritten."
502
+ )
503
+ raise ValueError(err)
504
+ self._raw_values[name] = value
505
+
506
+ def resolve(self, name: AbsoluteName, definition: AttributeDef) -> AttributeArray:
507
+ """
508
+ Resolve a value known by `name` to fit the given requirement `definition`.
509
+
510
+ Parameters
511
+ ----------
512
+ name :
513
+ The name of the value to resolve.
514
+ definition :
515
+ The definition of the requirement being fulfilled; this provides the
516
+ necessary type and shape information.
517
+
518
+ Returns
519
+ -------
520
+ :
521
+ The resolved value in adapted form.
522
+
523
+ Raises
524
+ ------
525
+ DataAttributeError
526
+ If resolution of adaptation fails.
527
+ """
528
+ key = (name, definition.type, definition.shape)
529
+ if key in self._adapted_values:
530
+ return self._adapted_values[key]
531
+
532
+ if name not in self._raw_values:
533
+ raise DataAttributeError(f"No value for name '{name}'")
534
+ value = self._raw_values[name]
535
+ adapted_value = adapt(definition.type, definition.shape, self._dim, value)
536
+ self._adapted_values[key] = adapted_value
537
+ return adapted_value
538
+
539
+ def resolve_txn_series(
540
+ self,
541
+ requirements: Iterable[tuple[AbsoluteName, AttributeDef]],
542
+ tau_steps: int,
543
+ ) -> Iterator[list[AttributeValue]]:
544
+ """
545
+ Generate an iterator on the series of values for the given requirements.
546
+ Each item produced by the generator is a sequence of scalar values, one for
547
+ each attribute (in the given order).
548
+
549
+ The sequence of items is generated in simulation order --
550
+
551
+ - day=0, tau step=0, node=0 => [beta, gamma, xi]
552
+ - day=0, tau_step=0; node=1 => [beta, gamma, xi]
553
+ - day=0, tau_step=1; node=0 => [beta, gamma, xi]
554
+ - day=0, tau_step=1; node=1 => [beta, gamma, xi]
555
+ - and so on.
556
+
557
+ This is a convenient alternative to resolving all of the TxN arrays separately,
558
+ and managing the iteration yourself.
559
+
560
+ Parameters
561
+ ----------
562
+ requirements :
563
+ The name-definition pairs for all of the attributes to include.
564
+ tau_steps :
565
+ The number of tau steps per day; since T in a TxN array is simulation days,
566
+ this simply repeats values such that all of a day's tau steps
567
+ see the same value.
568
+
569
+ Returns
570
+ -------
571
+ :
572
+ An iterator by tau step where each value is the list of attribute values for
573
+ that step.
574
+ """
575
+
576
+ def as_txn(attr_name: AbsoluteName, attr_def: AttributeDef) -> AttributeDef:
577
+ # We want to resolve every attribute as TxN, however it's defined.
578
+ # But we should check that this is possible first.
579
+ if not isinstance(attr_def.shape, Scalar | Time | Node | TimeAndNode):
580
+ err = (
581
+ "Cannot generate a TxN series unless all attributes "
582
+ f"broadcast to TxN. {attr_name} is {attr_def.shape}"
583
+ )
584
+ raise DataAttributeError(err)
585
+ return dataclasses.replace(attr_def, shape=Shapes.TxN)
586
+
587
+ resolved = [self.resolve(n, as_txn(n, d)) for n, d in requirements]
588
+
589
+ T, N = (self._dim.T, self._dim.N)
590
+ for t in range(T):
591
+ # values-per-node repeats if tau_steps > 1, so compute it outside that loop.
592
+ vals_by_node = [[v[t, n] for v in resolved] for n in range(N)]
593
+ for _ in range(tau_steps):
594
+ for vals in vals_by_node: # implicitly: range(N)
595
+ yield vals
596
+
597
+ @overload
598
+ def to_dict(
599
+ self, *, simplify_names: Literal[False] = False
600
+ ) -> dict[AbsoluteName, AttributeArray]: ...
601
+
602
+ @overload
603
+ def to_dict(
604
+ self, *, simplify_names: Literal[True]
605
+ ) -> dict[str, AttributeArray]: ...
606
+
607
+ def to_dict(
608
+ self, *, simplify_names: bool = False
609
+ ) -> dict[AbsoluteName, AttributeArray] | dict[str, AttributeArray]:
610
+ """
611
+ Extract a dictionary from this resolver containing all of its raw (non-adapted)
612
+ key-value pairs.
613
+
614
+ Parameters
615
+ ----------
616
+ simplify_names :
617
+ True to return stringified names. By default, names are returned in
618
+ `AbsoluteName` form.
619
+
620
+ Returns
621
+ -------
622
+ :
623
+ The dictionary of all values in this resolver, with names
624
+ either simplified or not according to `simplify_names`.
625
+ """
626
+ if simplify_names:
627
+ return {str(k): v for k, v in self._raw_values.items()}
628
+ return {**self._raw_values}
629
+
630
+
631
+ class Requirement(NamedTuple):
632
+ """A RUME data requirement: a name and a definition."""
633
+
634
+ name: AbsoluteName
635
+ """The requirement name."""
636
+ definition: AttributeDef
637
+ """The requirement definition."""
638
+
639
+ def __str__(self) -> str:
640
+ properties = [dtype_str(self.definition.type), str(self.definition.shape)]
641
+ return f"{self.name} ({', '.join(properties)})"
642
+
643
+
644
+ class Resolution(ABC):
645
+ """Describes the source used to resolve a requirement in a RUME."""
646
+
647
+ # NOTE: it is required that all Resolution instances be hashable!
648
+ # NOTE: This should be treated as a sealed type.
649
+
650
+ cacheable: bool
651
+ """True if this resolution can be cached."""
652
+
653
+
654
+ @dataclass(frozen=True)
655
+ class MissingValue(Resolution):
656
+ """Requirement was not resolved."""
657
+
658
+ cacheable: bool = field(init=False, default=False)
659
+
660
+ def __str__(self) -> str:
661
+ return "missing"
662
+
663
+
664
+ @dataclass(frozen=True)
665
+ class ParameterValue(Resolution):
666
+ """
667
+ Requirement was resolved by a RUME parameter.
668
+
669
+ Parameters
670
+ ----------
671
+ cacheable :
672
+ True if this resolution can be cached.
673
+ pattern :
674
+ The name by which the value was resolved.
675
+ """
676
+
677
+ cacheable: bool
678
+ pattern: NamePattern
679
+ """The name by which the value was resolved."""
680
+
681
+ def __str__(self) -> str:
682
+ return f"parameter value '{self.pattern}'"
683
+
684
+
685
+ @dataclass(frozen=True)
686
+ class DefaultValue(Resolution):
687
+ """
688
+ Requirement was resolved by an attribute default value.
689
+
690
+ Parameters
691
+ ----------
692
+ default_value :
693
+ The value that was resolved.
694
+ """
695
+
696
+ cacheable: bool = field(init=False, default=True)
697
+ default_value: AttributeValue
698
+ """The value that was resolved."""
699
+
700
+ # NOTE: we need default_value here so that default resolutions
701
+ # are only cached as one if they use the same value;
702
+ # this is critical for conflicting defaults detection.
703
+ # Since this also needs to be hashable, that means default values
704
+ # cannot be numpy arrays (unless we add some code to handle those).
705
+
706
+ def __str__(self) -> str:
707
+ return "default value"
708
+
709
+
710
+ @dataclass(frozen=True)
711
+ class ResolutionTree:
712
+ """
713
+ In resolving parameters, parameter values might have their own requirements.
714
+ This potentially forms a tree of requirements that must be resolved first in order
715
+ to resolve the root of the tree.
716
+
717
+ If two values share the same resolution tree, and if the tree is comprised entirely
718
+ of pure functions and constant values, then the resolution result would be the same.
719
+
720
+ Parameters
721
+ ----------
722
+ resolution :
723
+ The root node resolution.
724
+ children :
725
+ The resolution of the root's requirements (empty if it has no requirements).
726
+
727
+
728
+ See Also
729
+ --------
730
+ A resolution tree is a dual of the [epymorph.database.ReqTree][], but contains
731
+ only the resolution results and not any resolved values.
732
+ """
733
+
734
+ resolution: Resolution
735
+ """The root node resolution."""
736
+ children: "tuple[ResolutionTree, ...]"
737
+ """The resolution of the root's requirements (empty if it has no requirements)."""
738
+
739
+ @property
740
+ def is_tree_cacheable(self) -> bool:
741
+ """Is the entire tree cacheable? Only true if all resolutions are cacheable."""
742
+ return (
743
+ self.resolution.cacheable #
744
+ and all(x.is_tree_cacheable for x in self.children)
745
+ )
746
+
747
+
748
+ class RecursiveValue(Protocol):
749
+ """The interface for parameter values that may depend on other parameter values."""
750
+
751
+ requirements: Sequence[AttributeDef]
752
+ """Defines the data requirements for this value."""
753
+ randomized: bool
754
+ """
755
+ Should this value be re-evaluated every time it's referenced?
756
+ Mostly useful for results that incorporate random values.
757
+ """
758
+
759
+
760
+ @singledispatch
761
+ def is_recursive_value(value: object) -> TypeGuard[RecursiveValue]:
762
+ """
763
+ Check if a value is recursive, as a type guard.
764
+
765
+ Implemented by single dispatch.
766
+
767
+ Parameters
768
+ ----------
769
+ value :
770
+ The value to check.
771
+
772
+ Returns
773
+ -------
774
+ :
775
+ True if the value can be recursive, as a type-guard.
776
+ """
777
+ return False
778
+
779
+
780
+ V = TypeVar("V")
781
+ """The value type for a requirements tree."""
782
+
783
+
784
+ @dataclass(frozen=True)
785
+ class ReqTree(Generic[V]):
786
+ """
787
+ A requirements tree describes how data requirements are resolved for a RUME.
788
+
789
+ Models used in the RUME have a set of requirements, each of which may be fulfilled
790
+ by RUME parameters or default values. RUME parameters may also have data
791
+ requirements, and those requirements may have requirements, etc., hence the need
792
+ to represent this as a tree structure. The top of a `ReqTree` is a `ReqRoot` and
793
+ each requirement is a `ReqNode`. Each `ReqNode` tracks the attribute itself
794
+ (its `AbsoluteName` and `AttributeDef`), whether it is fulfilled, and if so how.
795
+
796
+ Parameters
797
+ ----------
798
+ children :
799
+ The child nodes of this node.
800
+ """
801
+
802
+ children: "tuple[ReqNode, ...]"
803
+ """The child nodes of this node."""
804
+
805
+ def __str__(self) -> str:
806
+ # Built-in stringify is just to_string() with default args.
807
+ return self.to_string()
808
+
809
+ @abstractmethod
810
+ def to_string(
811
+ self,
812
+ /,
813
+ format_name: Callable[[AbsoluteName], str] = str,
814
+ depth: int = 0,
815
+ ) -> str:
816
+ """
817
+ Convert this tree to a string.
818
+
819
+ Parameters
820
+ ----------
821
+ format_name :
822
+ A method to convert an absolute name into a string.
823
+ This allows you to control how absolute names are rendered.
824
+ depth :
825
+ The resolution "depth" of this node in the tree. Top-level requirements have
826
+ a depth of 0. A requirement that itself is required by one other requirement
827
+ would have a depth of 1.
828
+
829
+ Returns
830
+ -------
831
+ :
832
+ The stringified tree.
833
+ """
834
+ return "\n".join(
835
+ [x.to_string(format_name=format_name, depth=depth) for x in self.children]
836
+ )
837
+
838
+ def traverse(self) -> "Iterable[ReqNode]":
839
+ """
840
+ Perform a depth-first traversal of the nodes of this tree.
841
+
842
+ Yields
843
+ ------
844
+ :
845
+ Each node in the tree in depth-first order.
846
+ """
847
+ for x in self.children:
848
+ yield from x.traverse()
849
+ # NOTE: method overridden by ReqNode; yields children and then itself
850
+
851
+ def missing(self) -> Iterable[Requirement]:
852
+ """
853
+ Return the missing requirements from this tree.
854
+
855
+ Returns
856
+ -------
857
+ :
858
+ All requirements which were determined by resolution to be missing.
859
+ """
860
+ return (
861
+ Requirement(node.name, node.definition)
862
+ for node in self.traverse()
863
+ if isinstance(node.resolution, MissingValue)
864
+ )
865
+
866
+ def evaluate(
867
+ self,
868
+ scope: GeoScope | None,
869
+ time_frame: TimeFrame | None,
870
+ ipm: BaseCompartmentModel | None,
871
+ rng: np.random.Generator | None,
872
+ ) -> DataResolver:
873
+ """
874
+ Evaluate this tree. Defers to `evaluate_requirements()`.
875
+
876
+ Parameters
877
+ ----------
878
+ scope :
879
+ The geographic scope information of this simulation context, if available.
880
+ time_frame :
881
+ The temporal scope information of this simulation context, if available.
882
+ ipm :
883
+ The disease model for this simulation context, if available.
884
+ rng :
885
+ The random number generator to use, if available.
886
+
887
+ Returns
888
+ -------
889
+ :
890
+ The resolver containing all evaluated parameters.
891
+
892
+ Raises
893
+ ------
894
+ DataAttributeError
895
+ If any attribute fails evaluation.
896
+ """
897
+ return evaluate_requirements(self, scope, time_frame, ipm, rng)
898
+
899
+ @staticmethod
900
+ def of(
901
+ requirements: Mapping[AbsoluteName, AttributeDef],
902
+ params: Database[V],
903
+ ) -> "ReqTree":
904
+ """
905
+ Compute the requirements tree for the given set of requirements and a database
906
+ supplying values. Note that missing values do not stop us from computing the
907
+ tree -- these nodes will have `MissingValue` as the resolution.
908
+
909
+ Parameters
910
+ ----------
911
+ requirements :
912
+ The top-level requirements of the tree.
913
+ params :
914
+ The database of values, where each value may be recursive in the sense of
915
+ having its own data requirements.
916
+
917
+ Returns
918
+ -------
919
+ :
920
+ The requirements tree.
921
+
922
+ Raises
923
+ ------
924
+ DataAttributeError
925
+ If the tree cannot be evaluated, for instance, due to it containing
926
+ circular dependencies.
927
+ """
928
+
929
+ def recurse(
930
+ name: AbsoluteName,
931
+ definition: AttributeDef,
932
+ chain: list[AbsoluteName],
933
+ ) -> ReqNode:
934
+ if name in chain:
935
+ err = f"Circular dependency in evaluation of parameter {name}"
936
+ raise DataAttributeError(err)
937
+
938
+ if (val_match := params.query(name)) is not None:
939
+ # User provided a parameter value to use.
940
+ pattern, value = val_match
941
+ if is_recursive_value(value):
942
+ # might have its own requirements
943
+ ns = name.to_namespace()
944
+ children = tuple(
945
+ recurse(ns.to_absolute(r.name), r, [name, *chain])
946
+ for r in value.requirements
947
+ )
948
+ # is this resolution node cacheable?
949
+ cacheable = not value.randomized
950
+ else:
951
+ children = ()
952
+ cacheable = True
953
+ resolution = ParameterValue(
954
+ cacheable=cacheable,
955
+ pattern=pattern,
956
+ )
957
+
958
+ elif definition.default_value is not None:
959
+ # User did not provide a value, but we have a default.
960
+ value = definition.default_value
961
+ resolution = DefaultValue(value)
962
+ children = ()
963
+
964
+ else:
965
+ # Missing value!
966
+ value = None
967
+ resolution = MissingValue()
968
+ children = ()
969
+
970
+ return ReqNode(children, name, definition, resolution, value)
971
+
972
+ top_level_reqs = tuple(recurse(r, d, []) for r, d in requirements.items())
973
+ return ReqTree(top_level_reqs)
974
+
975
+
976
+ @dataclass(frozen=True)
977
+ class ReqNode(ReqTree[V]):
978
+ """
979
+ A non-root node of a requirements tree, identifying a requirement, how (or if)
980
+ it was resolved, and its value (if available).
981
+
982
+ Parameters
983
+ ----------
984
+ children :
985
+ The dependencies of this node (if any).
986
+ name :
987
+ The name of this requirement.
988
+ definition :
989
+ The definition of this requirement.
990
+ resolution :
991
+ How this requirement was resolved (or not).
992
+ value :
993
+ The value for this requirement if available.
994
+ """
995
+
996
+ children: "tuple[ReqNode, ...]"
997
+ """The dependencies of this node (if any)."""
998
+ name: AbsoluteName
999
+ """The name of this requirement."""
1000
+ definition: AttributeDef
1001
+ """The definition of this requirement."""
1002
+ resolution: Resolution
1003
+ """How this requirement was resolved (or not)."""
1004
+ value: V | None
1005
+ """The value for this requirement if available."""
1006
+
1007
+ @override
1008
+ def to_string(
1009
+ self,
1010
+ /,
1011
+ format_name: Callable[[AbsoluteName], str] = str,
1012
+ depth: int = 0,
1013
+ ) -> str:
1014
+ attr = self.definition
1015
+ properties = [dtype_str(attr.type), str(attr.shape)]
1016
+
1017
+ match self.resolution:
1018
+ case ParameterValue(_cacheable, value_name):
1019
+ color = None
1020
+ resd = f" <- {value_name}"
1021
+ case DefaultValue():
1022
+ properties.append(f"default={self.value}")
1023
+ color = ANSIColor.CYAN
1024
+ resd = ""
1025
+ case MissingValue():
1026
+ color = ANSIColor.RED
1027
+ resd = ""
1028
+ case x:
1029
+ # have to handle the impossible case
1030
+ # because Python doesn't have sealed types yet
1031
+ raise NotImplementedError(f"Unsupported resolution type ({type(x)})")
1032
+
1033
+ indent = " " * depth
1034
+ corner = "└╴" if depth > 0 else ""
1035
+ name = ansi_stylize(format_name(self.name), color)
1036
+ prop = ansi_stylize(f"({', '.join(properties)})", color, ANSIStyle.ITALIC)
1037
+
1038
+ return "\n".join(
1039
+ [
1040
+ f"{indent}{corner}{name} {prop}{resd}",
1041
+ *(
1042
+ x.to_string(format_name=format_name, depth=depth + 1)
1043
+ for x in self.children
1044
+ ),
1045
+ ]
1046
+ )
1047
+
1048
+ @override
1049
+ def traverse(self) -> "Iterable[ReqNode]":
1050
+ yield from super().traverse() # traverse children
1051
+ yield self # and then self
1052
+
1053
+ def as_res_tree(self) -> ResolutionTree:
1054
+ """
1055
+ Extract the resolution tree from this requirements tree.
1056
+
1057
+ Returns
1058
+ -------
1059
+ :
1060
+ The resolution tree.
1061
+ """
1062
+ return ResolutionTree(
1063
+ self.resolution,
1064
+ tuple(x.as_res_tree() for x in self.children),
1065
+ )
1066
+
1067
+
1068
+ @singledispatch
1069
+ def evaluate_param(
1070
+ value: object,
1071
+ name: AbsoluteName,
1072
+ data: DataResolver,
1073
+ scope: GeoScope | None,
1074
+ time_frame: TimeFrame | None,
1075
+ ipm: BaseCompartmentModel | None,
1076
+ rng: np.random.Generator | None,
1077
+ ) -> AttributeArray:
1078
+ """
1079
+ Evaluate a parameter, transforming acceptable input values (type: `ParamValue`) to
1080
+ the form required internally by epymorph (`AttributeArray`).
1081
+
1082
+ Different types of parameters are supported by single dispatch, so there should be a
1083
+ registered implementation for every supported type of parameter.
1084
+
1085
+ It is possible that the user is attempting to evaluate parameters with a
1086
+ partial context (`scope`, `time_frame`, `ipm`, `rng`), and so one or more of these
1087
+ may be missing. In that case, parameter evaluation is expected to happen on a
1088
+ "best effort" basis -- if no parameter accesses the missing scope elements,
1089
+ parameter evaluation succeeds. Otherwise, it raises a `DataAttributeError`.
1090
+
1091
+ Parameters
1092
+ ----------
1093
+ value :
1094
+ The value being evaluated.
1095
+ name :
1096
+ The full name given to the value in the simulation context.
1097
+ data :
1098
+ A resolved instance which should contain values for all of the data
1099
+ requirements needed by this value (only `RecursiveValues` have requirements).
1100
+ scope :
1101
+ The geographic scope information of this simulation context, if available.
1102
+ time_frame :
1103
+ The temporal scope information of this simulation context, if available.
1104
+ ipm :
1105
+ The disease model for this simulation context, if available.
1106
+ rng :
1107
+ The random number generator to use, if available.
1108
+
1109
+ Returns
1110
+ -------
1111
+ :
1112
+ The evaluated value.
1113
+
1114
+ Raises
1115
+ ------
1116
+ DataAttributeError
1117
+ If parameter evaluation fails.
1118
+ """
1119
+ err = f"Parameter not a supported type (found: {type(value)})"
1120
+ raise DataAttributeError(err)
1121
+
1122
+
1123
+ @evaluate_param.register
1124
+ def _(
1125
+ value: np.ndarray,
1126
+ name: AbsoluteName,
1127
+ data: DataResolver,
1128
+ scope: GeoScope | None,
1129
+ time_frame: TimeFrame | None,
1130
+ ipm: BaseCompartmentModel | None,
1131
+ rng: np.random.Generator | None,
1132
+ ) -> AttributeArray:
1133
+ # Evaluate numpy arrays.
1134
+ # numpy array: make a copy so we don't risk unexpected mutations
1135
+ return value.copy()
1136
+
1137
+
1138
+ @evaluate_param.register
1139
+ def _(
1140
+ value: int | float | str | tuple | list,
1141
+ name: AbsoluteName,
1142
+ data: DataResolver,
1143
+ scope: GeoScope | None,
1144
+ time_frame: TimeFrame | None,
1145
+ ipm: BaseCompartmentModel | None,
1146
+ rng: np.random.Generator | None,
1147
+ ) -> AttributeArray:
1148
+ # Evluate scalars.
1149
+ # scalar value or python collection: re-pack it as a numpy array
1150
+ return np.asarray(value, dtype=None)
1151
+
1152
+
1153
+ @evaluate_param.register
1154
+ def _(
1155
+ value: type,
1156
+ name: AbsoluteName,
1157
+ data: DataResolver,
1158
+ scope: GeoScope | None,
1159
+ time_frame: TimeFrame | None,
1160
+ ipm: BaseCompartmentModel | None,
1161
+ rng: np.random.Generator | None,
1162
+ ) -> AttributeArray:
1163
+ # Evaluate Python type instances.
1164
+ # forgot to instantiate? a common error worth checking for
1165
+ err = (
1166
+ "Parameter was given as a class instead of an instance. "
1167
+ "Did you forget to instantiate it?"
1168
+ )
1169
+ raise DataAttributeError(err)
1170
+
1171
+
1172
+ def evaluate_requirements(
1173
+ req: ReqTree,
1174
+ scope: GeoScope | None,
1175
+ time_frame: TimeFrame | None,
1176
+ ipm: BaseCompartmentModel | None,
1177
+ rng: np.random.Generator | None,
1178
+ ) -> DataResolver:
1179
+ """
1180
+ Evaluate all parameters in the tree, using the given simulation context
1181
+ (`scope`, `time_frame`, `ipm`, `rng`).
1182
+
1183
+ You may attempt to evaluate parameters with a partial context, so one or more of
1184
+ these may be missing. In that case, parameter evaluation happens on a "best effort"
1185
+ basis -- if no parameter accesses the missing scope elements, parameter evaluation
1186
+ succeeds; otherwise it will raise an `DataAttributeError`.
1187
+
1188
+ Parameters
1189
+ ----------
1190
+ req :
1191
+ The requirements tree.
1192
+ scope :
1193
+ The geographic scope information of this simulation context, if available.
1194
+ time_frame :
1195
+ The temporal scope information of this simulation context, if available.
1196
+ ipm :
1197
+ The disease model for this simulation context, if available.
1198
+ rng :
1199
+ The random number generator to use, if available.
1200
+
1201
+ Returns
1202
+ -------
1203
+ :
1204
+ The resolver containing all evaluated parameters.
1205
+
1206
+ Raises
1207
+ ------
1208
+ DataAttributeError
1209
+ If any attribute fails evaluation.
1210
+ """
1211
+
1212
+ # First make sure there are no missing values.
1213
+ missing = list(req.missing())
1214
+ if len(missing) > 0:
1215
+ err = "\n".join(
1216
+ [
1217
+ "Cannot evaluate parameters, there are missing values:",
1218
+ *(str(r.name) for r in missing),
1219
+ ]
1220
+ )
1221
+ raise DataAttributeError(err)
1222
+
1223
+ # For each node in the requirements tree (traversing depth-first),
1224
+ # evaluate each value and validate it against the requirement's definition;
1225
+ # fulfilled requirements get stored to `resolved` and we use `evaluated` as
1226
+ # an evaluation cache, to avoid evaluating the same parameter (input value)
1227
+ # twice. Accumulate validation errors into `errors` to be raised as a group.
1228
+ dim = Dimensions.of(
1229
+ T=time_frame.duration_days if time_frame is not None else None,
1230
+ N=scope.nodes if scope is not None else None,
1231
+ C=ipm.num_compartments if ipm is not None else None,
1232
+ E=ipm.num_events if ipm is not None else None,
1233
+ )
1234
+ errors = list[DataAttributeError]()
1235
+ resolved = DataResolver(dim)
1236
+ resolved_by = dict[AbsoluteName, ResolutionTree]()
1237
+ evaluated = dict[ResolutionTree, AttributeArray]()
1238
+
1239
+ for node in req.traverse():
1240
+ try:
1241
+ res_tree = node.as_res_tree()
1242
+ if res_tree in evaluated:
1243
+ # Use cached value
1244
+ value = evaluated[res_tree]
1245
+ else:
1246
+ # Evaluate
1247
+ value = evaluate_param(
1248
+ node.value,
1249
+ node.name,
1250
+ resolved,
1251
+ scope,
1252
+ time_frame,
1253
+ ipm,
1254
+ rng,
1255
+ )
1256
+
1257
+ if not isinstance(value, np.ndarray):
1258
+ err = (
1259
+ f"Attribute '{node.name}' ({node.resolution}) did "
1260
+ f"not evaluate to a numpy array."
1261
+ )
1262
+ raise DataAttributeError(err)
1263
+
1264
+ if res_tree.is_tree_cacheable:
1265
+ evaluated[res_tree] = value
1266
+
1267
+ # If we have the necessary info, check that the raw value
1268
+ # can be successfully adapted to fulfill this requirement.
1269
+ # Raise DataAttributeError if not.
1270
+ try:
1271
+ d = node.definition
1272
+ assert_can_adapt(d.type, d.shape, dim, value)
1273
+ except DataAttributeError as e:
1274
+ err = (
1275
+ f"Attribute '{node.name}' ({node.resolution}) is "
1276
+ f"not properly specified: {e}"
1277
+ )
1278
+ raise DataAttributeError(err)
1279
+
1280
+ # Store value
1281
+ if not resolved.has(node.name):
1282
+ resolved.add(node.name, value)
1283
+ resolved_by[node.name] = res_tree
1284
+ elif res_tree != resolved_by[node.name]:
1285
+ # Raise error for conflicting resolutions.
1286
+ err = (
1287
+ "Detected conflicting resolutions for requirement "
1288
+ f"'{node.name}'\n"
1289
+ "This is likely caused by AttributeDefs with different default "
1290
+ "values both resolving to the same name. If this is the case, "
1291
+ "you will need to provide an explicit value instead."
1292
+ )
1293
+ raise DataAttributeError(err)
1294
+
1295
+ except DataAttributeError as e:
1296
+ errors.append(e)
1297
+
1298
+ if len(errors) > 0:
1299
+ raise DataAttributeErrorGroup("Errors found evaluating parameters.", errors)
1300
+
1301
+ return resolved