Skip to content

Base model behavior

All qcdata models have a read-only qcdata_version property holding the installed package version. A dumped object is a document: model_dump(), model_dump_json(), save() and json_dumps() write qcdata_version at its top level only, even with exclude_unset=True (pass exclude={"qcdata_version"} to leave it out), and nested objects carry none. extras is left out wherever it is empty. Neither appears in the usual representation, to keep scientific values readable.

On loading, a saved stamp is accepted and discarded; serialization supplies the current version. This identifies the last writer of the representation, not the original creator, a minimum reader version, or a formal schema version. Reading a stamped file does not guarantee that an older or newer package can interpret it. Files without a stamp are accepted normally.

JSON, YAML, and TOML preserve this metadata. Structure XYZ exports include it as a comment token. External QCSchema conversions exclude it from model and identifier fields.

Mutation and persistence

Attribute assignment is frozen, but nested dictionaries, lists, and arrays are not deeply immutable. Direct container mutation is unsupported. Use model_dump(), edit the returned built-in values, and reconstruct with model_validate() so validation runs again. Scientific array fields dump as independent lists. Arbitrary custom objects in extras are not covered by this independence guarantee. File-collection helpers and Structure.add_identifiers() remain explicit mutation exceptions.

save() returns every file it wrote, the model's file first. An array field whose float64 size exceeds 1 MiB is written to its own .npy file beside the saved file, named by the file's stem and the array's path (output.results.hessian.npy), and the document holds a pointer with its relative path, shape, dtype and sha256; open() reads it back, so models always hold arrays. Smaller arrays stay in the document and round-trip exactly through JSON and YAML. See Saved files.

save() is lossless by default (exclude_unset=False), so containers filled after construction are kept. Pass exclude_unset=True for a compact file without the fields omitted during construction; explicitly supplied values are retained even when equal to their defaults, and the version stamp is still written. exclude_none=True remains the default.

Supported file and identifier helpers mark changed fields as set so those changes are saved. Direct mutation of initially unset containers is unsupported and may be omitted. The dump/edit/validate workflow preserves edits, but reconstructing from a full dump makes its fields explicitly set and can produce larger files.

qcdata.models.base_models.QCDataBaseModel

Base model for all QCData objects.

A dumped object is a document: the top-level one carries qcdata_version, the installed qcdata version writing it (not a schema version), and nested objects do not. extras is left out wherever it is empty.

Attributes:

Name Type Description
extras FreeDict

Additional information to bundle with the object. Use for schema development and scratch space.

qcdata_version str

@property The installed qcdata version, which serialization writes into the top-level document.

qcdata_version property

qcdata_version: str

The package version serializing the object, not its original creator.

open classmethod

open(filepath: Path | str) -> Self

Instantiate an object from data saved to disk.

Arrays that save put in their own .npy files are read back from beside the file, each checked against the sha256, shape and dtype saved with it.

Parameters:

Name Type Description Default
filepath Path | str

The path to the object on disk.

required

Returns:

Type Description
Self

The instantiated object.

Example
my_obj = MyModel.open("path/to/file.json")
Source code in src/qcdata/models/base_models.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@classmethod
def open(cls, filepath: Path | str) -> Self:
    """Instantiate an object from data saved to disk.

    Arrays that `save` put in their own `.npy` files are read back from beside the
    file, each checked against the sha256, shape and dtype saved with it.

    Args:
        filepath: The path to the object on disk.

    Returns:
        The instantiated object.

    Example:
        ```python
        my_obj = MyModel.open("path/to/file.json")
        ```
    """
    filepath = Path(filepath)
    data = filepath.read_text()
    context = {array_files.DIRECTORY: filepath.parent}

    if filepath.suffix in [".yaml", ".yml"]:
        import yaml  # imported on use: most callers never read YAML

        return cls.model_validate(yaml.safe_load(data), context=context)
    elif filepath.suffix == ".toml":
        import toml

        return cls.model_validate(toml.loads(data), context=context)

    # Assume json for all other file extensions
    return cls.model_validate_json(data, context=context)

open_multi classmethod

open_multi(filepath: Path | str) -> list[Self]

Instantiate a list of objects from data saved to disk.

Parameters:

Name Type Description Default
filepath Path | str

The path to the object on disk. Must be a list of objects.

required

Returns:

Type Description
list[Self]

A list of instantiated objects.

Example
my_objs = MyModel().open_multi("path/to/file.json")
Source code in src/qcdata/models/base_models.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
@classmethod
def open_multi(cls, filepath: Path | str) -> list[Self]:
    """Instantiate a list of objects from data saved to disk.

    Args:
        filepath: The path to the object on disk. Must be a list of objects.

    Returns:
        A list of instantiated objects.

    Example:
        ```python
        my_objs = MyModel().open_multi("path/to/file.json")
        ```
    """
    filepath = Path(filepath)
    data = filepath.read_text()

    if filepath.suffix in [".yaml", ".yml"]:
        import yaml

        return [cls.model_validate(d) for d in yaml.safe_load(data)]
    elif filepath.suffix == ".toml":
        import toml

        return [cls.model_validate(d) for d in toml.loads(data)]

    # Assume json for all other file extensions
    return [cls.model_validate(d) for d in json.loads(data)]

save

save(
    filepath: Path | str,
    exclude_none: bool = True,
    exclude_unset: bool = False,
    indent: int = 4,
    **kwargs: Any,
) -> list[Path]

Save an object to disk as json, yaml, or toml.

Objects such as Structure and OptimizationData can additionally be saved as xyz files.

Every array field whose float64 size exceeds 1 MiB is written to its own .npy file beside the saved file, named by the file's stem and the array's path in the document (output.results.hessian.npy for output.json). The document holds a pointer in its place: {"path", "shape", "dtype", "sha256"}, the digest being the .npy file's. A text in files over 1 MiB (UTF-8) goes to a file of its own the same way, named by the stem and its path with no suffix added (output.results.files.orbitals%2Emolden), with {"path", "sha256"} in its place. open reads them back, so a model never holds a file reference. These files are written first and the model's file last. Smaller arrays and texts stay in the document, where every float round-trips exactly through JSON and YAML.

Note

By default the object will be saved as a json file. If the file extension is .yaml or .yml, the object will be saved as a yaml file. If the file extension is .toml, the object will be saved as a toml file. If the file extension is .xyz, the object will be saved as an xyz file (for objects that support this format such as a Structure or an OptimizationData whose frames hold structures).

Additionally, padding will be added to the file by default to make it more human-readable. You can adjust the amount of padding added by changing the indent parameter. Pass indent=None to create a more compact file. An indented JSON file keeps each innermost array (a list holding no lists or objects, such as a row of coordinates) on one line.

Parameters:

Name Type Description Default
filepath Path | str

The path to write the object to.

required
exclude_none bool

If True, attributes with a value of None will not be written. Changing default behavior from pydantic.model_dump() to True.

True
exclude_unset bool

If True, fields omitted during construction are not written, even when their containers were filled in later (a record a program filled after building the output would be lost). Defaults to False, so a save is lossless.

False
indent int

The number of spaces to use for indentation in the JSON file. 0 creates a more compact JSON file, 4 is more human-readable.

4
**kwargs Any

Additional keyword arguments to pass to the serialization method.

{}

Returns:

Type Description
list[Path]

Every file written: the model's file first, then one file per array or text

list[Path]

saved apart, in document order.

Example
my_obj.save("path/to/file.json")
my_obj.save("path/to/file.yaml")
my_obj.save("path/to/file.toml")
my_obj.save("path/to/file.xyz")
Source code in src/qcdata/models/base_models.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
def save(
    self,
    filepath: Path | str,
    exclude_none: bool = True,
    exclude_unset: bool = False,
    indent: int = 4,
    **kwargs: Any,
) -> list[Path]:
    """Save an object to disk as `json`, `yaml`, or `toml`.

    Objects such as `Structure` and `OptimizationData` can additionally be saved
    as `xyz` files.

    Every array field whose float64 size exceeds 1 MiB is written to its own `.npy`
    file beside the saved file, named by the file's stem and the array's path in
    the document (`output.results.hessian.npy` for `output.json`). The document
    holds a pointer in its place: `{"path", "shape", "dtype", "sha256"}`, the
    digest being the `.npy` file's. A text in `files` over 1 MiB (UTF-8) goes to
    a file of its own the same way, named by the stem and its path with no suffix
    added (`output.results.files.orbitals%2Emolden`), with `{"path", "sha256"}` in
    its place. `open` reads them back, so a model never holds a file reference.
    These files are written first and the model's file last. Smaller arrays and
    texts stay in the document, where every float round-trips exactly through
    JSON and YAML.

    Note:
        By default the object will be saved as a `json` file. If the file extension
        is `.yaml` or `.yml`, the object will be saved as a `yaml` file. If the file
        extension is `.toml`, the object will be saved as a `toml` file. If the file
        extension is `.xyz`, the object will be saved as an `xyz` file (for objects
        that support this format such as a `Structure` or an `OptimizationData`
        whose frames hold structures).

        Additionally, padding will be added to the file by default to make it more
        human-readable. You can adjust the amount of padding added by changing the
        `indent` parameter. Pass `indent=None` to create a more compact file. An
        indented JSON file keeps each innermost array (a list holding no lists or
        objects, such as a row of coordinates) on one line.

    Args:
        filepath: The path to write the object to.
        exclude_none: If True, attributes with a value of None will not be written.
            Changing default behavior from pydantic.model_dump() to True.
        exclude_unset: If True, fields omitted during construction are not written,
            even when their containers were filled in later (a `record` a program
            filled after building the output would be lost). Defaults to False, so
            a save is lossless.
        indent: The number of spaces to use for indentation in the JSON file. 0
            creates a more compact JSON file, 4 is more human-readable.
        **kwargs: Additional keyword arguments to pass to the serialization method.

    Returns:
        Every file written: the model's file first, then one file per array or text
        saved apart, in document order.

    Example:
        ```python
        my_obj.save("path/to/file.json")
        ```

        ```python
        my_obj.save("path/to/file.yaml")
        ```

        ```python
        my_obj.save("path/to/file.toml")
        ```

        ```python
        my_obj.save("path/to/file.xyz")
        ```
    """
    filepath = Path(filepath)
    filepath.parent.mkdir(exist_ok=True, parents=True)

    sink = array_files.ArraySink(text_files=True)
    model_dict = self.model_dump(
        mode="json",
        exclude_none=exclude_none,
        exclude_unset=exclude_unset,
        context={array_files.SINK: sink},
        **kwargs,
    )
    model_dict, array_paths = sink.place(model_dict, filepath.parent, filepath.stem)

    if filepath.suffix in [".yaml", ".yml"]:
        import yaml

        data = yaml.dump(model_dict, indent=indent)

    elif filepath.suffix == ".toml":
        import toml

        data = toml.dumps(model_dict)

    elif indent is None:
        data = json.dumps(model_dict)
    else:
        # Write data to json regardless of file extension
        data = _indented_json(model_dict, indent)

    filepath.write_text(data)
    return [filepath, *array_paths]