Skip to content

QCIOModelBase

qcio.models.base_models.QCIOModelBase

Base Model for all QCIO objects.

Attributes:

Name Type Description
version

The version of the schema.

extras Dict[str, Any]

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

open classmethod

open(filepath: Union[Path, str]) -> Union[Self, List[Self]]

Instantiate an object from data saved to disk.

Parameters:

Name Type Description Default
filepath Union[Path, str]

The path to the object on disk.

required

Returns:

Type Description
Union[Self, List[Self]]

The instantiated object or a list of objects if the file contains multiple

Union[Self, List[Self]]

objects (e.g., a multi-structure xyz file).

Example
my_obj = MyModel.open("path/to/file.json")
Source code in qcio/models/base_models.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@classmethod
def open(cls, filepath: Union[Path, str]) -> Union[Self, List[Self]]:
    """Instantiate an object from data saved to disk.

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

    Returns:
        The instantiated object or a list of objects if the file contains multiple
        objects (e.g., a multi-structure xyz file).

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

    if filepath.suffix in [".yaml", ".yml"]:
        return cls.model_validate(yaml.safe_load(data))
    elif filepath.suffix == ".toml":
        return cls.model_validate(toml.loads(data))

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

save

save(
    filepath: Union[Path, str],
    exclude_none: bool = True,
    exclude_unset: bool = True,
    indent: int = 4,
    **kwargs
) -> None

Save an object to disk as json, yaml, or toml. Objects such as Structure and OptimizationResults can additionally be saved as xyz files.

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 OptimizationResults which contains .trajectory: list[Structure]).

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.

Parameters:

Name Type Description Default
filepath Union[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, attributes that have not been set will not be written (i.e., values set to their default value).

True
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

Additional keyword arguments to pass to the serialization method.

{}
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 qcio/models/base_models.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def save(
    self,
    filepath: Union[Path, str],
    exclude_none: bool = True,
    exclude_unset: bool = True,
    indent: int = 4,
    **kwargs,
) -> None:
    """
    Save an object to disk as `json`, `yaml`, or `toml`. Objects such as `Structure`
    and `OptimizationResults` can additionally be saved as `xyz` files.

    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 `OptimizationResults`
        which contains `.trajectory: list[Structure]`).

        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.

    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, attributes that have not been set will not be
            written (i.e., values set to their default value).
        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.

    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)

    if self.extras:
        # Ensure pydantic knows the field has been set
        self.__pydantic_fields_set__.add("extras")

    model_dict = self.model_dump(
        mode="json",
        exclude_none=exclude_none,
        exclude_unset=exclude_unset,
        **kwargs,
    )

    if filepath.suffix in [".yaml", ".yml"]:
        data = yaml.dump(model_dict, indent=indent)

    elif filepath.suffix == ".toml":
        data = toml.dumps(model_dict)

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

    filepath.write_text(data)