config_io
tit.config_io ¶
JSON serialisation for config dataclasses.
Provides helpers to serialise typed config dataclasses (with Enum fields, nested dataclasses, and union-typed ROI/electrode specs) to JSON files and read them back.
Public API¶
serialize_config
Convert a config dataclass to a JSON-serialisable dict (with
project_dir injection).
write_config_json
Serialise a config dataclass to a temporary JSON file.
read_config_json
Read a JSON config file and return the parsed dict.
deserialize_config
Rebuild a config dataclass instance from its serialized dict form --
the symmetric inverse of serialize_config.
json_schema
Build a draft 2020-12 JSON Schema for a config dataclass, with the
same _type discriminator conventions serialize_config /
deserialize_config use.
Examples¶
from tit.config_io import write_config_json, read_config_json path = write_config_json(my_flex_config, prefix="flex") data = read_config_json(path)
See Also¶
tit.opt.config : FlexConfig and ExConfig dataclasses.
tit.sim.config : Montage dataclass.
serialize_config ¶
Convert a config dataclass to a JSON-serialisable dict.
Handles Enum fields (via .value), nested dataclasses (recursed),
union-typed ROI / electrode specs (injects a _type discriminator),
and None values (preserved as JSON null).
Also injects project_dir from the active :class:~tit.paths.PathManager
so that subprocess entry points can initialise their own singleton.
Parameters¶
config : dataclass instance
Any config dataclass (e.g., FlexConfig, ExConfig).
Returns¶
dict JSON-serialisable dictionary representation of config.
See Also¶
write_config_json : Serialise and write to a temp file in one step. read_config_json : Read a JSON config back into a dict.
Source code in tit/config_io.py
write_config_json ¶
Serialise a config dataclass to a temporary JSON file.
Parameters¶
config : dataclass instance
Config object to serialise.
prefix : str, optional
Filename prefix for the temp file. Default is "config".
Returns¶
str Absolute path to the created JSON file.
See Also¶
serialize_config : Convert to dict without writing to disk. read_config_json : Read a JSON config file.
Source code in tit/config_io.py
read_config_json ¶
Read a JSON config file and return the parsed dict.
Parameters¶
path : str Path to the JSON file.
Returns¶
dict Parsed JSON contents.
See Also¶
write_config_json : Create a config JSON file from a dataclass.
Source code in tit/config_io.py
resolve_config_class ¶
Import and return the class registered under name.
Parameters¶
name : str
A key of :data:CONFIG_CLASS_REGISTRY.
Returns¶
type The resolved dataclass.
Raises¶
KeyError If name is not registered.
Source code in tit/config_io.py
deserialize_config ¶
Rebuild a config dataclass instance from its serialized dict form.
The symmetric inverse of :func:serialize_config: walks cls's own
dataclasses.fields() (resolving each field's type -- including
forward-referenced nested-class unions such as FlexConfig.roi --
with typing.get_type_hints) and converts every value back into
whatever serialize_config produced it from: nested dataclasses
(a single required type, or a union disambiguated by _type), lists
of dataclasses, Enum members, tuples (including tuples nested
inside lists, e.g. Montage.electrode_pairs), dict values whose declared
key type isn't str (JSON object keys are always strings, so e.g.
SimulationConfig.tissue_conductivities: dict[int, float] round-trips
as {"1": 2.5} and is coerced back to {1: 2.5}), and Optional
values. By default, keys in data that are not fields of cls (e.g.
"project_dir", which the runners pop themselves -- see
tit.sim.__main__.main -- or "_type" on an ambiguous kind's
top-level config, see tit.server.routes.validate) are silently
ignored; pass strict to change that.
Parameters¶
cls : type
A dataclass, e.g. one of :data:CONFIG_CLASS_REGISTRY's values.
data : dict
Parsed JSON as produced by :func:serialize_config (directly, or
round-tripped through :func:write_config_json /
:func:read_config_json).
strict : bool, optional
If True, raise instead of silently ignoring a key in data that
is not one of cls's own fields (recursively, for every nested
dataclass reached along the way) -- catching a misspelled or
renamed field at validation time instead of it becoming a silent
no-op. "_type" is never flagged as unknown even in strict mode
(every discriminated dataclass and every ambiguous top-level kind
uses it without it being a real field). Off by default: a caller
with its own legacy flat-dict layout (e.g.
tit.analyzer.__main__'s pre-AnalyzerConfig fallback) is
unaffected unless it opts in.
Returns¶
Any A cls instance.
Raises¶
TypeError
If cls is not a dataclass.
ValueError
If data carries a _type that does not match cls itself, if
a union-typed field's value is missing its _type tag or
carries one not registered for that union's members, or (only
when strict is True) if data carries a key that is not one of
cls's fields.
See Also¶
serialize_config : The inverse conversion.
json_schema : Describes the same shape as a JSON Schema, including the
additionalProperties: false this function's strict mode
enforces at runtime.
Source code in tit/config_io.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
json_schema ¶
Build a draft 2020-12 JSON Schema for a config dataclass.
Wraps pydantic.TypeAdapter(cls).json_schema() with this project's
discriminated-union conventions, so the result matches exactly what
:func:serialize_config emits and :func:deserialize_config accepts:
- every reachable class
serialize_configtags with a_typediscriminator (:data:_TYPE_DISCRIMINATED/ :data:_TYPE_DISCRIMINATED_BY_NAME) gets"_type": {"const": ...}injected into its properties and required list -- whether that class is cls itself (e.g.json_schema(Montage)) or a nested$defsentry (e.g.FlexConfig'sSphericalROI/AtlasROI/SubcorticalROI); - every
anyOfwhose members are all$refs to such discriminated classes (plus an optionalnullbranch forOptional[...]) is rewritten tooneOf+discriminator: {"propertyName": "_type"}; $defsentries whose bare name collides with another registered class's (:data:_COLLIDING_DEFS_NAMES:AtlasROIon three classes,PoolElectrodes/BucketElectrodeson two,Subjecton two) are renamed to"<cls.__name__><bare name>", so merging many classes' schemas into one document (seedev/build_schema.py) can never let one definition silently clobber another's under the same key;- every fixed-shape object schema (the top level and each
$defsentry with its own"properties") gets"additionalProperties": false(:func:_close_object_schemas), matching what :func:deserialize_config'sstrict=Truerejects at runtime -- a misspelled or renamed field fails schema validation (e.g. atPOST /api/validate/{kind}) instead of silently vanishing. A free-form mapping field (e.g.SimulationConfig.tissue_conductivities: dict[int, float]) has no"properties"of its own and is left open.
Parameters¶
cls : type
A dataclass, e.g. one of :data:CONFIG_CLASS_REGISTRY's values.
Returns¶
dict
A JSON Schema document: cls's own shape at the top level, nested
types under $defs.
See Also¶
deserialize_config : Accepts exactly the data this schema validates.
Source code in tit/config_io.py
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | |