Skip to content

API Reference

cgcnn2.data

AtomInitializer

Atom feature vectors read from an atom_init.json file, a dictionary mapping atomic numbers to feature vectors.

Parameters:

Name Type Description Default
elem_embedding_file str

Path to the JSON file.

required
Source code in cgcnn2/data.py
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
class AtomInitializer:
    """
    Atom feature vectors read from an `atom_init.json` file, a dictionary mapping
    atomic numbers to feature vectors.

    Args:
        elem_embedding_file (str): Path to the JSON file.
    """

    def __init__(self, elem_embedding_file):
        with open(elem_embedding_file) as f:
            elem_embedding = json.load(f)
        self._embedding = {
            int(number): np.array(vector, dtype=float)
            for number, vector in elem_embedding.items()
        }

    def get_atom_fea(self, atom_type):
        """
        Return the feature vector of an atomic number.

        Args:
            atom_type (int): Atomic number.
        """
        return self._embedding[atom_type]

get_atom_fea(atom_type)

Return the feature vector of an atomic number.

Parameters:

Name Type Description Default
atom_type int

Atomic number.

required
Source code in cgcnn2/data.py
126
127
128
129
130
131
132
133
def get_atom_fea(self, atom_type):
    """
    Return the feature vector of an atomic number.

    Args:
        atom_type (int): Atomic number.
    """
    return self._embedding[atom_type]

CIFData

Bases: Dataset

Crystal structures stored as CIF files in one directory.

  • atom_init.json: the initialization vector of each element.
  • ID.cif: one CIF file per crystal, where ID is the unique ID of the crystal.
  • id_prop.csv (optional): two columns, the ID of each crystal and the value of its target property. Without it every CIF file in the directory is loaded with a NaN target, which is all that prediction needs.

Parsed crystal graphs are kept in a per-instance LRU cache, so each CIF file is parsed once per process.

Parameters:

Name Type Description Default
root_dir str

The dataset directory.

required
max_num_nbr int

Maximum number of neighbors per atom in the crystal graph.

12
radius float

Cutoff radius for the neighbor search.

8
dmin float

Center of the first Gaussian of the distance expansion.

0
step float

Spacing of the Gaussian centers.

0.2
cache_size int | None

Number of parsed crystals kept in memory. None (default) keeps all of them, 0 disables the cache.

None

Each item is ((atom_fea, nbr_fea, nbr_fea_idx), target, cif_id):

atom_fea (torch.Tensor): shape (n_i, atom_fea_len)
nbr_fea (torch.Tensor): shape (n_i, M, nbr_fea_len)
nbr_fea_idx (torch.LongTensor): shape (n_i, M)
target (torch.Tensor): shape (1,)
cif_id (str): the ID of the crystal
Source code in cgcnn2/data.py
184
185
186
187
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
217
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
class CIFData(Dataset):
    """
    Crystal structures stored as CIF files in one directory.

    - `atom_init.json`: the initialization vector of each element.
    - `ID.cif`: one CIF file per crystal, where `ID` is the unique ID of the crystal.
    - `id_prop.csv` (optional): two columns, the ID of each crystal and the value of its
      target property. Without it every CIF file in the directory is loaded with a NaN
      target, which is all that prediction needs.

    Parsed crystal graphs are kept in a per-instance LRU cache, so each CIF file is
    parsed once per process.

    Args:
        root_dir (str): The dataset directory.
        max_num_nbr (int): Maximum number of neighbors per atom in the crystal graph.
        radius (float): Cutoff radius for the neighbor search.
        dmin (float): Center of the first Gaussian of the distance expansion.
        step (float): Spacing of the Gaussian centers.
        cache_size (int | None): Number of parsed crystals kept in memory. None (default)
            keeps all of them, 0 disables the cache.

    Each item is `((atom_fea, nbr_fea, nbr_fea_idx), target, cif_id)`:

        atom_fea (torch.Tensor): shape (n_i, atom_fea_len)
        nbr_fea (torch.Tensor): shape (n_i, M, nbr_fea_len)
        nbr_fea_idx (torch.LongTensor): shape (n_i, M)
        target (torch.Tensor): shape (1,)
        cif_id (str): the ID of the crystal
    """

    _cache_load: Callable[[int], Item]

    def __init__(
        self,
        root_dir: str | os.PathLike[str],
        max_num_nbr=12,
        radius=8,
        dmin=0,
        step=0.2,
        cache_size=None,
    ):
        assert os.path.isdir(root_dir), f"{root_dir} is not a directory"
        self.root_dir = root_dir
        self.max_num_nbr, self.radius = max_num_nbr, radius
        id_prop_file = os.path.join(root_dir, "id_prop.csv")
        if os.path.isfile(id_prop_file):
            with open(id_prop_file) as f:
                self.id_prop_data = [
                    (row[0], float(row[1])) for row in csv.reader(f) if row
                ]
        else:
            self.id_prop_data = sorted(
                (name[:-4], float("nan"))
                for name in os.listdir(root_dir)
                if name.endswith(".cif")
            )
        self.ari = AtomInitializer(os.path.join(root_dir, "atom_init.json"))
        self.gdf = GaussianDistance(dmin=dmin, dmax=radius, step=step)
        self.cache_size = cache_size
        self._configure_cache()

    def __len__(self):
        return len(self.id_prop_data)

    def __getitem__(self, index):
        return self._cache_load(index)

    def __getstate__(self):
        # The lru_cache wrapper around a bound method is not picklable; drop
        # it so instances survive spawn-based DataLoader workers.
        state = self.__dict__.copy()
        state.pop("_cache_load", None)
        return state

    def __setstate__(self, state):
        self.__dict__.update(state)
        self._configure_cache()

    def _configure_cache(self) -> None:
        if self.cache_size is not None and self.cache_size <= 0:
            self._cache_load = self._load_item
        else:
            self._cache_load = functools.lru_cache(maxsize=self.cache_size)(
                self._load_item
            )

    def _load_item(self, index: int) -> Item:
        cif_id, target = self.id_prop_data[index]
        crystal = Structure.from_file(os.path.join(self.root_dir, f"{cif_id}.cif"))
        graph = _crystal_graph(
            crystal, cif_id, self.ari, self.gdf, self.max_num_nbr, self.radius
        )
        return graph, torch.tensor([target], dtype=torch.float32), cif_id

GaussianDistance

Expands interatomic distances (in angstrom) in a Gaussian basis.

Parameters:

Name Type Description Default
dmin float

Center of the first Gaussian.

required
dmax float

Center of the last Gaussian.

required
step float

Spacing between consecutive centers.

required
var float | None

Variance of each Gaussian. Defaults to step.

None
Source code in cgcnn2/data.py
 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
class GaussianDistance:
    """
    Expands interatomic distances (in angstrom) in a Gaussian basis.

    Args:
        dmin (float): Center of the first Gaussian.
        dmax (float): Center of the last Gaussian.
        step (float): Spacing between consecutive centers.
        var (float | None): Variance of each Gaussian. Defaults to `step`.
    """

    def __init__(self, dmin, dmax, step, var=None):
        assert dmin < dmax
        assert dmax - dmin > step
        self.filter = np.arange(dmin, dmax + step, step)
        self.var = step if var is None else var

    def expand(self, distances):
        """
        Project distances onto the Gaussian basis.

        Args:
            distances (np.ndarray): Interatomic distances of any shape.

        Returns:
            np.ndarray: `distances.shape + (len(filter),)` basis values.
        """
        return np.exp(-((distances[..., np.newaxis] - self.filter) ** 2) / self.var**2)

expand(distances)

Project distances onto the Gaussian basis.

Parameters:

Name Type Description Default
distances ndarray

Interatomic distances of any shape.

required

Returns:

Type Description

np.ndarray: distances.shape + (len(filter),) basis values.

Source code in cgcnn2/data.py
 96
 97
 98
 99
100
101
102
103
104
105
106
def expand(self, distances):
    """
    Project distances onto the Gaussian basis.

    Args:
        distances (np.ndarray): Interatomic distances of any shape.

    Returns:
        np.ndarray: `distances.shape + (len(filter),)` basis values.
    """
    return np.exp(-((distances[..., np.newaxis] - self.filter) ** 2) / self.var**2)

batch_to_device(batch, device)

Move the batch tensors produced by collate_pool to a device.

Parameters:

Name Type Description Default
batch tuple[Tensor, ...]

(atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx)

required
device device | str

Target device.

required

Returns:

Type Description

tuple[torch.Tensor, ...]: The same tensors on device.

Source code in cgcnn2/data.py
65
66
67
68
69
70
71
72
73
74
75
76
def batch_to_device(batch, device):
    """
    Move the batch tensors produced by `collate_pool` to a device.

    Args:
        batch (tuple[torch.Tensor, ...]): (atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx)
        device (torch.device | str): Target device.

    Returns:
        tuple[torch.Tensor, ...]: The same tensors on `device`.
    """
    return tuple(t.to(device) for t in batch)

collate_pool(dataset_list)

Collate a list of dataset items into one batch.

Parameters:

Name Type Description Default
dataset_list list

Items ((atom_fea, nbr_fea, nbr_fea_idx), target, cif_id) as returned by CIFData, with n_i atoms and M neighbors per atom.

required

Returns:

Name Type Description
tuple

((atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx), target, cif_ids) where

  • atom_fea (torch.Tensor): shape (N, orig_atom_fea_len), all atoms of the batch
  • nbr_fea (torch.Tensor): shape (N, M, nbr_fea_len), bond features of each atom's neighbors
  • nbr_fea_idx (torch.LongTensor): shape (N, M), neighbor indices into the batch
  • crystal_atom_idx (torch.LongTensor): shape (N,), the crystal of each atom, sorted ascending
  • target (torch.Tensor): shape (B, 1)
  • cif_ids (list[str]): the ID of each crystal
Source code in cgcnn2/data.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def collate_pool(dataset_list: list[Item]):
    """
    Collate a list of dataset items into one batch.

    Args:
        dataset_list (list): Items `((atom_fea, nbr_fea, nbr_fea_idx), target, cif_id)` as
            returned by `CIFData`, with `n_i` atoms and `M` neighbors per atom.

    Returns:
        tuple: `((atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx), target, cif_ids)` where

            - atom_fea (torch.Tensor): shape (N, orig_atom_fea_len), all atoms of the batch
            - nbr_fea (torch.Tensor): shape (N, M, nbr_fea_len), bond features of each atom's neighbors
            - nbr_fea_idx (torch.LongTensor): shape (N, M), neighbor indices into the batch
            - crystal_atom_idx (torch.LongTensor): shape (N,), the crystal of each atom, sorted ascending
            - target (torch.Tensor): shape (B, 1)
            - cif_ids (list[str]): the ID of each crystal
    """
    batch_atom_fea, batch_nbr_fea, batch_nbr_fea_idx = [], [], []
    crystal_atom_idx, batch_target, batch_cif_ids = [], [], []
    base_idx = 0
    for crystal_i, ((atom_fea, nbr_fea, nbr_fea_idx), target, cif_id) in enumerate(
        dataset_list
    ):
        n_i = atom_fea.shape[0]
        batch_atom_fea.append(atom_fea)
        batch_nbr_fea.append(nbr_fea)
        batch_nbr_fea_idx.append(nbr_fea_idx + base_idx)
        crystal_atom_idx.append(torch.full((n_i,), crystal_i, dtype=torch.long))
        batch_target.append(target)
        batch_cif_ids.append(cif_id)
        base_idx += n_i
    return (
        (
            torch.cat(batch_atom_fea),
            torch.cat(batch_nbr_fea),
            torch.cat(batch_nbr_fea_idx),
            torch.cat(crystal_atom_idx),
        ),
        torch.stack(batch_target),
        batch_cif_ids,
    )

full_set_split(full_set_dir, train_ratio, valid_ratio, train_force_dir=None, random_seed=0)

Split a dataset directory into train, valid and test directories.

The CIF files are copied into three temporary directories that are removed when the process exits. The test set receives whatever the two ratios leave.

Parameters:

Name Type Description Default
full_set_dir str

The dataset to split.

required
train_ratio float

Fraction of the dataset used for training.

required
valid_ratio float

Fraction of the dataset used for validation.

required
train_force_dir str | None

A dataset directory whose structures are all added to the training set on top of the split.

None
random_seed int

Seed of the shuffle.

0

Returns:

Type Description

tuple[str, str, str]: The train, valid and test directories.

Source code in cgcnn2/data.py
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
def full_set_split(
    full_set_dir: str,
    train_ratio: float,
    valid_ratio: float,
    train_force_dir: str | None = None,
    random_seed: int = 0,
):
    """
    Split a dataset directory into train, valid and test directories.

    The CIF files are copied into three temporary directories that are removed when
    the process exits. The test set receives whatever the two ratios leave.

    Args:
        full_set_dir (str): The dataset to split.
        train_ratio (float): Fraction of the dataset used for training.
        valid_ratio (float): Fraction of the dataset used for validation.
        train_force_dir (str | None): A dataset directory whose structures are all added
            to the training set on top of the split.
        random_seed (int): Seed of the shuffle.

    Returns:
        tuple[str, str, str]: The train, valid and test directories.
    """
    df = pd.read_csv(
        os.path.join(full_set_dir, "id_prop.csv"),
        header=None,
        names=["cif_id", "property"],
    )
    rng = np.random.default_rng(random_seed)
    df = df.sample(frac=1.0, random_state=rng).reset_index(drop=True)
    n_train, n_valid = int(len(df) * train_ratio), int(len(df) * valid_ratio)
    splits = [
        [(df[:n_train], full_set_dir)],
        [(df[n_train : n_train + n_valid], full_set_dir)],
        [(df[n_train + n_valid :], full_set_dir)],
    ]
    if train_force_dir is not None:
        df_force = pd.read_csv(
            os.path.join(train_force_dir, "id_prop.csv"),
            header=None,
            names=["cif_id", "property"],
        )
        splits[0].append((df_force, train_force_dir))

    temp_dirs = []
    for parts in splits:
        temp_dir = tempfile.mkdtemp()
        atexit.register(shutil.rmtree, temp_dir, ignore_errors=True)
        for part, source_dir in parts:
            for cif_id in part["cif_id"]:
                shutil.copy(os.path.join(source_dir, f"{cif_id}.cif"), temp_dir)
        pd.concat([part for part, _ in parts]).to_csv(
            os.path.join(temp_dir, "id_prop.csv"), index=False, header=False
        )
        shutil.copy(os.path.join(full_set_dir, "atom_init.json"), temp_dir)
        temp_dirs.append(temp_dir)
    return tuple(temp_dirs)

cgcnn2.model

ConvLayer

Bases: Module

Crystal graph convolution: updates the features of every atom from its neighbors and the bonds to them.

Parameters:

Name Type Description Default
atom_fea_len int

Number of hidden atom features.

required
nbr_fea_len int

Number of bond features.

required
Source code in cgcnn2/model.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class ConvLayer(nn.Module):
    """
    Crystal graph convolution: updates the features of every atom from its
    neighbors and the bonds to them.

    Args:
        atom_fea_len (int): Number of hidden atom features.
        nbr_fea_len (int): Number of bond features.
    """

    def __init__(self, atom_fea_len: int, nbr_fea_len: int) -> None:
        super().__init__()
        self.atom_fea_len = atom_fea_len
        self.nbr_fea_len = nbr_fea_len
        self.fc_full = nn.Linear(2 * atom_fea_len + nbr_fea_len, 2 * atom_fea_len)
        self.bn1 = nn.BatchNorm1d(2 * atom_fea_len)
        self.bn2 = nn.BatchNorm1d(atom_fea_len)
        self.softplus = nn.Softplus()

    def forward(
        self,
        atom_in_fea: torch.Tensor,
        nbr_fea: torch.Tensor,
        nbr_fea_idx: torch.Tensor,
    ) -> torch.Tensor:
        """
        `N` is the number of atoms in the batch and `M` the number of neighbors per atom.

        Args:
            atom_in_fea (torch.Tensor): shape (N, atom_fea_len), atom features before the convolution.
            nbr_fea (torch.Tensor): shape (N, M, nbr_fea_len), bond features of each atom's neighbors.
            nbr_fea_idx (torch.LongTensor): shape (N, M), indices of each atom's neighbors.

        Returns:
            torch.Tensor: shape (N, atom_fea_len), atom features after the convolution.
        """
        n_atoms, n_nbr = nbr_fea_idx.shape
        # fc_full acts on the concatenation [atom_i, atom_j, bond_ij]. Applying its
        # three weight blocks separately gives the same result while the two atom
        # terms are computed once per atom instead of once per neighbor pair, and
        # the (N, M, 2 * atom_fea_len + nbr_fea_len) concatenation never exists.
        # index_select gathers the neighbor term with a deterministic backward.
        w_self, w_nbr, w_bond = self.fc_full.weight.split(
            [self.atom_fea_len, self.atom_fea_len, self.nbr_fea_len], dim=1
        )
        nbr_term = F.linear(atom_in_fea, w_nbr).index_select(0, nbr_fea_idx.reshape(-1))
        gated_fea = (
            F.linear(atom_in_fea, w_self, self.fc_full.bias).unsqueeze(1)
            + nbr_term.view(n_atoms, n_nbr, -1)
            + F.linear(nbr_fea, w_bond)
        )
        gated_fea = self.bn1(gated_fea.view(-1, 2 * self.atom_fea_len)).view(
            n_atoms, n_nbr, 2 * self.atom_fea_len
        )
        nbr_filter, nbr_core = gated_fea.chunk(2, dim=2)
        nbr_summed = (torch.sigmoid(nbr_filter) * self.softplus(nbr_core)).sum(dim=1)
        return self.softplus(atom_in_fea + self.bn2(nbr_summed))

forward(atom_in_fea, nbr_fea, nbr_fea_idx)

N is the number of atoms in the batch and M the number of neighbors per atom.

Parameters:

Name Type Description Default
atom_in_fea Tensor

shape (N, atom_fea_len), atom features before the convolution.

required
nbr_fea Tensor

shape (N, M, nbr_fea_len), bond features of each atom's neighbors.

required
nbr_fea_idx LongTensor

shape (N, M), indices of each atom's neighbors.

required

Returns:

Type Description
Tensor

torch.Tensor: shape (N, atom_fea_len), atom features after the convolution.

Source code in cgcnn2/model.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def forward(
    self,
    atom_in_fea: torch.Tensor,
    nbr_fea: torch.Tensor,
    nbr_fea_idx: torch.Tensor,
) -> torch.Tensor:
    """
    `N` is the number of atoms in the batch and `M` the number of neighbors per atom.

    Args:
        atom_in_fea (torch.Tensor): shape (N, atom_fea_len), atom features before the convolution.
        nbr_fea (torch.Tensor): shape (N, M, nbr_fea_len), bond features of each atom's neighbors.
        nbr_fea_idx (torch.LongTensor): shape (N, M), indices of each atom's neighbors.

    Returns:
        torch.Tensor: shape (N, atom_fea_len), atom features after the convolution.
    """
    n_atoms, n_nbr = nbr_fea_idx.shape
    # fc_full acts on the concatenation [atom_i, atom_j, bond_ij]. Applying its
    # three weight blocks separately gives the same result while the two atom
    # terms are computed once per atom instead of once per neighbor pair, and
    # the (N, M, 2 * atom_fea_len + nbr_fea_len) concatenation never exists.
    # index_select gathers the neighbor term with a deterministic backward.
    w_self, w_nbr, w_bond = self.fc_full.weight.split(
        [self.atom_fea_len, self.atom_fea_len, self.nbr_fea_len], dim=1
    )
    nbr_term = F.linear(atom_in_fea, w_nbr).index_select(0, nbr_fea_idx.reshape(-1))
    gated_fea = (
        F.linear(atom_in_fea, w_self, self.fc_full.bias).unsqueeze(1)
        + nbr_term.view(n_atoms, n_nbr, -1)
        + F.linear(nbr_fea, w_bond)
    )
    gated_fea = self.bn1(gated_fea.view(-1, 2 * self.atom_fea_len)).view(
        n_atoms, n_nbr, 2 * self.atom_fea_len
    )
    nbr_filter, nbr_core = gated_fea.chunk(2, dim=2)
    nbr_summed = (torch.sigmoid(nbr_filter) * self.softplus(nbr_core)).sum(dim=1)
    return self.softplus(atom_in_fea + self.bn2(nbr_summed))

CrystalGraphConvNet

Bases: Module

Crystal graph convolutional neural network for predicting a material property.

Parameters:

Name Type Description Default
orig_atom_fea_len int

Number of atom features in the input.

required
nbr_fea_len int

Number of bond features.

required
atom_fea_len int

Number of hidden atom features in the convolutional layers.

64
n_conv int

Number of convolutional layers.

3
h_fea_len int

Number of hidden features after pooling.

128
n_h int

Number of hidden layers after pooling.

1
Source code in cgcnn2/model.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 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
class CrystalGraphConvNet(nn.Module):
    """
    Crystal graph convolutional neural network for predicting a material property.

    Args:
        orig_atom_fea_len (int): Number of atom features in the input.
        nbr_fea_len (int): Number of bond features.
        atom_fea_len (int): Number of hidden atom features in the convolutional layers.
        n_conv (int): Number of convolutional layers.
        h_fea_len (int): Number of hidden features after pooling.
        n_h (int): Number of hidden layers after pooling.
    """

    def __init__(
        self,
        orig_atom_fea_len: int,
        nbr_fea_len: int,
        atom_fea_len: int = 64,
        n_conv: int = 3,
        h_fea_len: int = 128,
        n_h: int = 1,
    ) -> None:
        super().__init__()
        self.embedding = nn.Linear(orig_atom_fea_len, atom_fea_len)
        self.convs = nn.ModuleList(
            [ConvLayer(atom_fea_len, nbr_fea_len) for _ in range(n_conv)]
        )
        self.conv_to_fc = nn.Linear(atom_fea_len, h_fea_len)
        self.fcs = nn.ModuleList(
            [nn.Linear(h_fea_len, h_fea_len) for _ in range(n_h - 1)]
        )
        self.fc_out = nn.Linear(h_fea_len, 1)
        self.softplus = nn.Softplus()

    def forward(
        self,
        atom_fea: torch.Tensor,
        nbr_fea: torch.Tensor,
        nbr_fea_idx: torch.Tensor,
        crystal_atom_idx: torch.Tensor,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """
        `N` is the number of atoms in the batch, `M` the number of neighbors per atom
        and `B` the number of crystals.

        Args:
            atom_fea (torch.Tensor): shape (N, orig_atom_fea_len), atom features from the atom type.
            nbr_fea (torch.Tensor): shape (N, M, nbr_fea_len), bond features of each atom's neighbors.
            nbr_fea_idx (torch.LongTensor): shape (N, M), indices of each atom's neighbors.
            crystal_atom_idx (torch.LongTensor): shape (N,), the crystal of each atom, sorted ascending.

        Returns:
            out (torch.Tensor): shape (B, 1), the predicted property.
            crys_fea (torch.Tensor): shape (B, atom_fea_len), the mean atom features of each crystal after the convolutions.
        """
        atom_fea = self.embedding(atom_fea)
        for conv in self.convs:
            atom_fea = conv(atom_fea, nbr_fea, nbr_fea_idx)
        crys_fea = self.pooling(atom_fea, crystal_atom_idx)
        h_fea = self.softplus(self.conv_to_fc(self.softplus(crys_fea)))
        for fc in self.fcs:
            h_fea = self.softplus(fc(h_fea))
        return self.fc_out(h_fea), crys_fea

    def pooling(
        self, atom_fea: torch.Tensor, crystal_atom_idx: torch.Tensor
    ) -> torch.Tensor:
        """
        Mean-pool atom features into crystal features.

        Args:
            atom_fea (torch.Tensor): shape (N, atom_fea_len), the atom embeddings of the batch.
            crystal_atom_idx (torch.LongTensor): shape (N,), the crystal of each atom, sorted ascending.

        Returns:
            torch.Tensor: shape (B, atom_fea_len), the mean embedding of each crystal.
        """
        n_crystals = int(crystal_atom_idx[-1]) + 1
        index = crystal_atom_idx.unsqueeze(1).expand(-1, atom_fea.shape[1])
        return atom_fea.new_zeros(n_crystals, atom_fea.shape[1]).scatter_reduce_(
            0, index, atom_fea, reduce="mean", include_self=False
        )

forward(atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx)

N is the number of atoms in the batch, M the number of neighbors per atom and B the number of crystals.

Parameters:

Name Type Description Default
atom_fea Tensor

shape (N, orig_atom_fea_len), atom features from the atom type.

required
nbr_fea Tensor

shape (N, M, nbr_fea_len), bond features of each atom's neighbors.

required
nbr_fea_idx LongTensor

shape (N, M), indices of each atom's neighbors.

required
crystal_atom_idx LongTensor

shape (N,), the crystal of each atom, sorted ascending.

required

Returns:

Name Type Description
out Tensor

shape (B, 1), the predicted property.

crys_fea Tensor

shape (B, atom_fea_len), the mean atom features of each crystal after the convolutions.

Source code in cgcnn2/model.py
 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
def forward(
    self,
    atom_fea: torch.Tensor,
    nbr_fea: torch.Tensor,
    nbr_fea_idx: torch.Tensor,
    crystal_atom_idx: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    `N` is the number of atoms in the batch, `M` the number of neighbors per atom
    and `B` the number of crystals.

    Args:
        atom_fea (torch.Tensor): shape (N, orig_atom_fea_len), atom features from the atom type.
        nbr_fea (torch.Tensor): shape (N, M, nbr_fea_len), bond features of each atom's neighbors.
        nbr_fea_idx (torch.LongTensor): shape (N, M), indices of each atom's neighbors.
        crystal_atom_idx (torch.LongTensor): shape (N,), the crystal of each atom, sorted ascending.

    Returns:
        out (torch.Tensor): shape (B, 1), the predicted property.
        crys_fea (torch.Tensor): shape (B, atom_fea_len), the mean atom features of each crystal after the convolutions.
    """
    atom_fea = self.embedding(atom_fea)
    for conv in self.convs:
        atom_fea = conv(atom_fea, nbr_fea, nbr_fea_idx)
    crys_fea = self.pooling(atom_fea, crystal_atom_idx)
    h_fea = self.softplus(self.conv_to_fc(self.softplus(crys_fea)))
    for fc in self.fcs:
        h_fea = self.softplus(fc(h_fea))
    return self.fc_out(h_fea), crys_fea

pooling(atom_fea, crystal_atom_idx)

Mean-pool atom features into crystal features.

Parameters:

Name Type Description Default
atom_fea Tensor

shape (N, atom_fea_len), the atom embeddings of the batch.

required
crystal_atom_idx LongTensor

shape (N,), the crystal of each atom, sorted ascending.

required

Returns:

Type Description
Tensor

torch.Tensor: shape (B, atom_fea_len), the mean embedding of each crystal.

Source code in cgcnn2/model.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def pooling(
    self, atom_fea: torch.Tensor, crystal_atom_idx: torch.Tensor
) -> torch.Tensor:
    """
    Mean-pool atom features into crystal features.

    Args:
        atom_fea (torch.Tensor): shape (N, atom_fea_len), the atom embeddings of the batch.
        crystal_atom_idx (torch.LongTensor): shape (N,), the crystal of each atom, sorted ascending.

    Returns:
        torch.Tensor: shape (B, atom_fea_len), the mean embedding of each crystal.
    """
    n_crystals = int(crystal_atom_idx[-1]) + 1
    index = crystal_atom_idx.unsqueeze(1).expand(-1, atom_fea.shape[1])
    return atom_fea.new_zeros(n_crystals, atom_fea.shape[1]).scatter_reduce_(
        0, index, atom_fea, reduce="mean", include_self=False
    )

cgcnn2.utils

cgcnn_pred(model_path, full_set, device='cpu', batch_size=256, num_workers=0)

Predict the property of every structure in a directory with a trained model.

Parameters:

Name Type Description Default
model_path str

Path to the checkpoint.

required
full_set str

Directory with the CIF files and atom_init.json; id_prop.csv is optional.

required
device device | str

Where to run the model.

'cpu'
batch_size int

Crystals per batch.

256
num_workers int

DataLoader worker processes.

0

Returns:

Name Type Description
predictions ndarray

shape (n,), the predicted property of each crystal, in the order of id_prop.csv or sorted by ID without it.

descriptors ndarray

shape (n, atom_fea_len), the mean atom features of each crystal after the convolutions, for downstream analysis.

Source code in cgcnn2/utils.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def cgcnn_pred(
    model_path: str | os.PathLike[str],
    full_set: str | os.PathLike[str],
    device: torch.device | str = "cpu",
    batch_size: int = 256,
    num_workers: int = 0,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Predict the property of every structure in a directory with a trained model.

    Args:
        model_path (str): Path to the checkpoint.
        full_set (str): Directory with the CIF files and `atom_init.json`; `id_prop.csv`
            is optional.
        device (torch.device | str): Where to run the model.
        batch_size (int): Crystals per batch.
        num_workers (int): DataLoader worker processes.

    Returns:
        predictions (np.ndarray): shape (n,), the predicted property of each crystal, in
            the order of `id_prop.csv` or sorted by ID without it.
        descriptors (np.ndarray): shape (n, atom_fea_len), the mean atom features of each
            crystal after the convolutions, for downstream analysis.
    """
    dataset = CIFData(full_set)
    model = model_from_checkpoint(load_checkpoint(model_path), dataset).to(device)
    loader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=False,
        num_workers=num_workers,
        collate_fn=collate_pool,
    )
    predictions, descriptors, _, _ = predict(model, loader, device)
    return predictions, descriptors

cgcnn_test(model, loader, device, results_file='results.csv', plot_file='parity_plot.png', axis_limits=None, xlabel='Actual', ylabel='Predicted')

Predict over a loader and write the results to a CSV file. When the dataset has targets, also log the MAE, MSE and R² and save a parity plot.

Parameters:

Name Type Description Default
model Module

The model.

required
loader DataLoader

The data, batched with collate_pool.

required
device device | str

Where the model lives.

required
results_file str

CSV file receiving cif_id,true,pred rows sorted by ID.

'results.csv'
plot_file str

PNG file receiving the parity plot.

'parity_plot.png'
axis_limits Sequence[float] | None

(min, max) of true values for an additional parity plot clipped to that range.

None
xlabel str

x-axis label of the parity plot.

'Actual'
ylabel str

y-axis label of the parity plot.

'Predicted'
Source code in cgcnn2/utils.py
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def cgcnn_test(
    model: torch.nn.Module,
    loader: DataLoader,
    device: torch.device | str,
    results_file: str = "results.csv",
    plot_file: str = "parity_plot.png",
    axis_limits: Sequence[float] | None = None,
    xlabel: str = "Actual",
    ylabel: str = "Predicted",
) -> None:
    """
    Predict over a loader and write the results to a CSV file. When the dataset has
    targets, also log the MAE, MSE and R² and save a parity plot.

    Args:
        model (torch.nn.Module): The model.
        loader (DataLoader): The data, batched with `collate_pool`.
        device (torch.device | str): Where the model lives.
        results_file (str): CSV file receiving `cif_id,true,pred` rows sorted by ID.
        plot_file (str): PNG file receiving the parity plot.
        axis_limits (Sequence[float] | None): `(min, max)` of true values for an
            additional parity plot clipped to that range.
        xlabel (str): x-axis label of the parity plot.
        ylabel (str): y-axis label of the parity plot.
    """
    predictions, _, targets, cif_ids = predict(model, loader, device)
    df = pd.DataFrame(
        {"cif_id": cif_ids, "true": targets, "pred": predictions}
    ).sort_values("cif_id")
    df.to_csv(results_file, index=False)
    logging.info(f"Prediction results have been saved to {results_file}")

    if df["true"].isna().any():
        logging.info("The dataset has no targets; metrics and parity plot are skipped.")
        return
    errors = df["true"] - df["pred"]
    mae = np.mean(np.abs(errors))
    mse = np.mean(errors**2)
    r2 = 1 - np.sum(errors**2) / np.sum((df["true"] - df["true"].mean()) ** 2)
    logging.info(f"MAE: {mae:.4f}, MSE: {mse:.4f}, R2 Score: {r2:.4f}")

    plot_hexbin(df, xlabel, ylabel, out_png=plot_file)
    logging.info(f"Hexbin plot has been saved to {plot_file}")
    if axis_limits is not None:
        low, high = axis_limits
        clipped_file = plot_file.replace(".png", f"_axis_limits_{low}_{high}.png")
        plot_hexbin(
            df[(df["true"] >= low) & (df["true"] <= high)],
            xlabel,
            ylabel,
            out_png=clipped_file,
        )
        logging.info(
            f"Hexbin plot clipped to {axis_limits} on true has been saved to {clipped_file}"
        )

id_prop_gen(cif_dir)

Write an id_prop.csv listing every CIF file in a directory with the target 0.

Parameters:

Name Type Description Default
cif_dir str

Directory containing the CIF files.

required
Source code in cgcnn2/utils.py
74
75
76
77
78
79
80
81
82
83
84
85
86
def id_prop_gen(cif_dir: str) -> None:
    """
    Write an `id_prop.csv` listing every CIF file in a directory with the target 0.

    Args:
        cif_dir (str): Directory containing the CIF files.
    """
    cif_ids = [
        os.path.basename(cif).split(".")[0] for cif in glob.glob(f"{cif_dir}/*.cif")
    ]
    pd.DataFrame({"id": cif_ids, "prop": [0] * len(cif_ids)}).to_csv(
        f"{cif_dir}/id_prop.csv", index=False, header=False
    )

input_feature_lengths(dataset)

Return (orig_atom_fea_len, nbr_fea_len) of a dataset, read from its first item.

Parameters:

Name Type Description Default
dataset CIFData

The dataset.

required
Source code in cgcnn2/utils.py
121
122
123
124
125
126
127
128
129
def input_feature_lengths(dataset: CIFData) -> tuple[int, int]:
    """
    Return `(orig_atom_fea_len, nbr_fea_len)` of a dataset, read from its first item.

    Args:
        dataset (CIFData): The dataset.
    """
    (atom_fea, nbr_fea, _), _, _ = dataset[0]
    return atom_fea.shape[-1], nbr_fea.shape[-1]

load_checkpoint(model_path)

Load a cgcnn2 checkpoint onto the CPU and log its epoch and validation error.

Checkpoints hold only tensors and plain Python values, so they are read with weights_only=True.

Parameters:

Name Type Description Default
model_path str

Path to the checkpoint file.

required

Returns:

Name Type Description
dict dict

The checkpoint, with the keys epoch, state_dict, args and best_mae_error (best_mse_error in checkpoints trained with 0.6).

Source code in cgcnn2/utils.py
 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
def load_checkpoint(model_path: str | os.PathLike[str]) -> dict:
    """
    Load a cgcnn2 checkpoint onto the CPU and log its epoch and validation error.

    Checkpoints hold only tensors and plain Python values, so they are read with
    `weights_only=True`.

    Args:
        model_path (str): Path to the checkpoint file.

    Returns:
        dict: The checkpoint, with the keys `epoch`, `state_dict`, `args` and
            `best_mae_error` (`best_mse_error` in checkpoints trained with 0.6).
    """
    checkpoint = torch.load(model_path, map_location="cpu", weights_only=True)
    metrics = [
        f"{key[5:8].upper()}={checkpoint[key]:.4f}"
        for key in ("best_mse_error", "best_mae_error")
        if key in checkpoint
    ]
    logging.info(
        f"=> Loaded checkpoint '{model_path}' (epoch {checkpoint.get('epoch', 'N/A')}, "
        f"validation {', '.join(metrics) or 'N/A'})"
    )
    return checkpoint

metrics_text(df, metrics=('mae', 'r2'), metrics_precision='3f', unit=None, unit_scale=1.0)

Format metrics of the true and pred columns of a DataFrame as LaTeX lines.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with true and pred columns.

required
metrics Sequence[str]

Any of mae, mse, rmse and r2.

('mae', 'r2')
metrics_precision str

Format spec of the metric values.

'3f'
unit str | None

Unit of the property.

None
unit_scale float

Factor applied to the error metrics.

1.0

Returns:

Name Type Description
str str

One line per metric.

Source code in cgcnn2/utils.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def metrics_text(
    df: pd.DataFrame,
    metrics: Sequence[str] = ("mae", "r2"),
    metrics_precision: str = "3f",
    unit: str | None = None,
    unit_scale: float = 1.0,
) -> str:
    """
    Format metrics of the `true` and `pred` columns of a DataFrame as LaTeX lines.

    Args:
        df (pd.DataFrame): DataFrame with `true` and `pred` columns.
        metrics (Sequence[str]): Any of `mae`, `mse`, `rmse` and `r2`.
        metrics_precision (str): Format spec of the metric values.
        unit (str | None): Unit of the property.
        unit_scale (float): Factor applied to the error metrics.

    Returns:
        str: One line per metric.
    """
    errors = df["true"] - df["pred"]
    values: dict[str, float] = {}
    for m in metrics:
        m_lower = m.lower()
        if m_lower == "mae":
            values["MAE"] = np.mean(np.abs(errors)) * unit_scale
        elif m_lower == "mse":
            values["MSE"] = np.mean(errors**2) * unit_scale**2
        elif m_lower == "rmse":
            values["RMSE"] = np.sqrt(np.mean(errors**2)) * unit_scale
        elif m_lower == "r2":
            values["R^2"] = 1 - np.sum(errors**2) / np.sum(
                (df["true"] - df["true"].mean()) ** 2
            )
        else:
            raise ValueError(f"Unsupported metric: {m}")

    text_lines: list[str] = []
    for name, val in values.items():
        if name == "R^2":
            text_lines.append(rf"$R^2: {val:.3f}$")
            continue
        unit_str = ""
        if unit:
            unit_str = (
                rf"\,\mathrm{{{unit}}}^2" if name == "MSE" else rf"\,\mathrm{{{unit}}}"
            )
        text_lines.append(rf"$\mathrm{{{name}}}: {val:.{metrics_precision}}{unit_str}$")
    return "\n".join(text_lines)

model_from_checkpoint(checkpoint, dataset)

Build the model described by a checkpoint's args and load its weights.

Parameters:

Name Type Description Default
checkpoint dict

A checkpoint from load_checkpoint.

required
dataset CIFData

A dataset built with the same atom_init.json and neighbor settings as the training data; it provides the input feature lengths.

required

Returns:

Name Type Description
CrystalGraphConvNet CrystalGraphConvNet

The model, on the CPU.

Source code in cgcnn2/utils.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def model_from_checkpoint(checkpoint: dict, dataset: CIFData) -> CrystalGraphConvNet:
    """
    Build the model described by a checkpoint's `args` and load its weights.

    Args:
        checkpoint (dict): A checkpoint from `load_checkpoint`.
        dataset (CIFData): A dataset built with the same `atom_init.json` and neighbor
            settings as the training data; it provides the input feature lengths.

    Returns:
        CrystalGraphConvNet: The model, on the CPU.
    """
    orig_atom_fea_len, nbr_fea_len = input_feature_lengths(dataset)
    args = checkpoint["args"]
    model = CrystalGraphConvNet(
        orig_atom_fea_len,
        nbr_fea_len,
        atom_fea_len=args["atom_fea_len"],
        n_conv=args["n_conv"],
        h_fea_len=args["h_fea_len"],
        n_h=args["n_h"],
    )
    model.load_state_dict(checkpoint["state_dict"])
    return model

plot_hexbin(df, xlabel, ylabel, ax=None, metrics=('mae', 'r2'), metrics_precision='3f', unit=None, unit_scale=1.0, subfigure_label=None, out_png=None)

Draw a hexbin parity plot of the true and pred columns of a DataFrame.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with true and pred columns.

required
xlabel str

Label of the x-axis.

required
ylabel str

Label of the y-axis.

required
ax Axes | None

Axes to draw on; a new figure when None.

None
metrics Sequence[str]

Metrics written on the plot, see metrics_text.

('mae', 'r2')
metrics_precision str

Format spec of the metric values.

'3f'
unit str | None

Unit of the property.

None
unit_scale float

Factor applied to the error metrics.

1.0
subfigure_label str | None

Label written above the metrics.

None
out_png str | None

PNG file to save the figure to.

None
Source code in cgcnn2/utils.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def plot_hexbin(
    df: pd.DataFrame,
    xlabel: str,
    ylabel: str,
    ax: plt.Axes | None = None,
    metrics: Sequence[str] = ("mae", "r2"),
    metrics_precision: str = "3f",
    unit: str | None = None,
    unit_scale: float = 1.0,
    subfigure_label: str | None = None,
    out_png: str | None = None,
) -> None:
    """
    Draw a hexbin parity plot of the `true` and `pred` columns of a DataFrame.

    Args:
        df (pd.DataFrame): DataFrame with `true` and `pred` columns.
        xlabel (str): Label of the x-axis.
        ylabel (str): Label of the y-axis.
        ax (plt.Axes | None): Axes to draw on; a new figure when None.
        metrics (Sequence[str]): Metrics written on the plot, see `metrics_text`.
        metrics_precision (str): Format spec of the metric values.
        unit (str | None): Unit of the property.
        unit_scale (float): Factor applied to the error metrics.
        subfigure_label (str | None): Label written above the metrics.
        out_png (str | None): PNG file to save the figure to.
    """
    with plt.rc_context(PLOT_RC_PARAMS):
        if ax is None:
            fig, ax = plt.subplots(figsize=(8, 6), layout="constrained")
        else:
            fig = ax.get_figure()
            if not isinstance(fig, plt.Figure):
                raise TypeError("`ax` must be attached to a top-level Figure")

        hb = ax.hexbin(df["true"], df["pred"], gridsize=40, cmap="viridis", bins="log")
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_box_aspect(1)

        # y = x reference line over the current limits
        xlim, ylim = ax.get_xlim(), ax.get_ylim()
        min_val, max_val = min(xlim[0], ylim[0]), max(xlim[1], ylim[1])
        ax.plot([min_val, max_val], [min_val, max_val], "--", color="grey", linewidth=2)
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)

        # density colorbar inside the plot
        cax = inset_axes(
            ax, width="3.5%", height="70%", loc="lower right", borderpad=0.5
        )
        fig.colorbar(hb, cax=cax)
        cax.yaxis.set_ticks_position("left")
        cax.yaxis.set_label_position("left")

        text = metrics_text(df, metrics, metrics_precision, unit, unit_scale)
        if subfigure_label is not None:
            text = f"{subfigure_label}\n{text}"
        ax.text(0.025, 0.975, text, transform=ax.transAxes, ha="left", va="top")

        if out_png is not None:
            fig.savefig(out_png, format="png", dpi=300, bbox_inches="tight")

predict(model, loader, device)

Run a model over a loader.

Parameters:

Name Type Description Default
model Module

The model.

required
loader DataLoader

The data, batched with collate_pool.

required
device device | str

Where the model lives.

required

Returns:

Name Type Description
predictions ndarray

shape (n,), the predicted property of each crystal.

descriptors ndarray

shape (n, atom_fea_len), the mean atom features of each crystal after the convolutions.

targets ndarray

shape (n,), NaN where the dataset has no targets.

cif_ids list[str]

The ID of each crystal.

Source code in cgcnn2/utils.py
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
def predict(
    model: torch.nn.Module, loader: DataLoader, device: torch.device | str
) -> tuple[np.ndarray, np.ndarray, np.ndarray, list[str]]:
    """
    Run a model over a loader.

    Args:
        model (torch.nn.Module): The model.
        loader (DataLoader): The data, batched with `collate_pool`.
        device (torch.device | str): Where the model lives.

    Returns:
        predictions (np.ndarray): shape (n,), the predicted property of each crystal.
        descriptors (np.ndarray): shape (n, atom_fea_len), the mean atom features of each crystal after the convolutions.
        targets (np.ndarray): shape (n,), NaN where the dataset has no targets.
        cif_ids (list[str]): The ID of each crystal.
    """
    model.eval()
    predictions, descriptors, targets, cif_ids = [], [], [], []
    with torch.inference_mode():
        for batch, target, cif_id in loader:
            output, crys_fea = model(*batch_to_device(batch, device))
            predictions.append(output.cpu().numpy().ravel())
            descriptors.append(crys_fea.cpu().numpy())
            targets.append(target.numpy().ravel())
            cif_ids.extend(cif_id)
    return (
        np.concatenate(predictions),
        np.concatenate(descriptors),
        np.concatenate(targets),
        cif_ids,
    )

seed_everything(seed)

Seed the random number generators of Python, NumPy and PyTorch (CPU and CUDA).

Parameters:

Name Type Description Default
seed int

The seed.

required
Source code in cgcnn2/utils.py
60
61
62
63
64
65
66
67
68
69
70
71
def seed_everything(seed: int) -> None:
    """
    Seed the random number generators of Python, NumPy and PyTorch (CPU and CUDA).

    Args:
        seed (int): The seed.
    """
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)

setup_logging()

Log to stdout with timestamps and record the cgcnn2, torch and CUDA versions.

Source code in cgcnn2/utils.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def setup_logging() -> None:
    """
    Log to stdout with timestamps and record the cgcnn2, torch and CUDA versions.
    """
    logging.basicConfig(
        stream=sys.stdout,
        level=logging.INFO,
        format="%(asctime)s.%(msecs)03d %(levelname)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    logging.captureWarnings(True)
    logging.info(f"cgcnn2 version: {cgcnn2.__version__}")
    logging.info(f"cuda version: {torch.version.cuda}")
    logging.info(f"torch version: {torch.__version__}")

standardize_output(model, target_stats)

Make a model that predicts in the original units predict standardized targets, by rewriting its output layer. train needs this for a model loaded from a checkpoint.

Parameters:

Name Type Description Default
model CrystalGraphConvNet

The model, changed in place.

required
target_stats tuple[float, float]

Mean and standard deviation from target_statistics.

required
Source code in cgcnn2/utils.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def standardize_output(
    model: CrystalGraphConvNet, target_stats: tuple[float, float]
) -> None:
    """
    Make a model that predicts in the original units predict standardized targets, by
    rewriting its output layer. `train` needs this for a model loaded from a checkpoint.

    Args:
        model (CrystalGraphConvNet): The model, changed in place.
        target_stats (tuple[float, float]): Mean and standard deviation from `target_statistics`.
    """
    mean, std = target_stats
    with torch.no_grad():
        model.fc_out.bias.sub_(mean).div_(std)
        model.fc_out.weight.div_(std)

target_statistics(dataset)

Mean and standard deviation of the targets of a dataset.

Parameters:

Name Type Description Default
dataset CIFData

The dataset, usually the training set.

required
Source code in cgcnn2/utils.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def target_statistics(dataset: CIFData) -> tuple[float, float]:
    """
    Mean and standard deviation of the targets of a dataset.

    Args:
        dataset (CIFData): The dataset, usually the training set.
    """
    targets = np.array([target for _, target in dataset.id_prop_data])
    mean, std = float(targets.mean()), float(targets.std())
    if not std > 0:  # NaN without targets, 0 when they are all equal
        raise ValueError(
            "The targets are missing or all equal, so they cannot be standardized."
        )
    return mean, std

train(model, train_loader, valid_loader, optimizer, device, epochs, checkpoint_path, checkpoint_args, target_stats, scheduler=None, stop_patience=None, bias_temperature=-1.0)

Train a model and keep the weights with the lowest validation MAE.

The model is trained on standardized targets, (target - mean) / std, so that one learning rate suits properties of any unit and scale. A new model can be passed as it is; a model that already predicts in the original units, such as one loaded from a checkpoint, needs standardize_output first. The loss is the mean squared error.

Checkpoints have the statistics folded into the output layer, so they predict in the original units. When training ends the model holds the weights of the best checkpoint.

Parameters:

Name Type Description Default
model CrystalGraphConvNet

The model, already on device.

required
train_loader DataLoader

Training data, batched with collate_pool.

required
valid_loader DataLoader

Validation data.

required
optimizer Optimizer

The optimizer.

required
device device | str

Where the model lives.

required
epochs int

Number of epochs.

required
checkpoint_path str

Where the best checkpoint is written.

required
checkpoint_args dict

Stored under the checkpoint's args key. It must hold the model hyperparameters (atom_fea_len, n_conv, h_fea_len, n_h) so that model_from_checkpoint can rebuild the model.

required
target_stats tuple[float, float]

Mean and standard deviation of the training targets, from target_statistics.

required
scheduler ReduceLROnPlateau | None

Stepped with the validation MAE every epoch.

None
stop_patience int | None

Epochs without improvement before training stops.

None
bias_temperature float

If positive, every error is weighted by exp(-target / bias_temperature) in the loss and in the validation MAE, so that structures with low targets (low energies) weigh more.

-1.0
Source code in cgcnn2/utils.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
def train(
    model: CrystalGraphConvNet,
    train_loader: DataLoader,
    valid_loader: DataLoader,
    optimizer: torch.optim.Optimizer,
    device: torch.device | str,
    epochs: int,
    checkpoint_path: str,
    checkpoint_args: dict,
    target_stats: tuple[float, float],
    scheduler: torch.optim.lr_scheduler.ReduceLROnPlateau | None = None,
    stop_patience: int | None = None,
    bias_temperature: float = -1.0,
) -> None:
    """
    Train a model and keep the weights with the lowest validation MAE.

    The model is trained on standardized targets, `(target - mean) / std`, so that one
    learning rate suits properties of any unit and scale. A new model can be passed as it
    is; a model that already predicts in the original units, such as one loaded from a
    checkpoint, needs `standardize_output` first. The loss is the mean squared error.

    Checkpoints have the statistics folded into the output layer, so they predict in the
    original units. When training ends the model holds the weights of the best checkpoint.

    Args:
        model (CrystalGraphConvNet): The model, already on `device`.
        train_loader (DataLoader): Training data, batched with `collate_pool`.
        valid_loader (DataLoader): Validation data.
        optimizer (torch.optim.Optimizer): The optimizer.
        device (torch.device | str): Where the model lives.
        epochs (int): Number of epochs.
        checkpoint_path (str): Where the best checkpoint is written.
        checkpoint_args (dict): Stored under the checkpoint's `args` key. It must hold the
            model hyperparameters (`atom_fea_len`, `n_conv`, `h_fea_len`, `n_h`) so that
            `model_from_checkpoint` can rebuild the model.
        target_stats (tuple[float, float]): Mean and standard deviation of the training
            targets, from `target_statistics`.
        scheduler (ReduceLROnPlateau | None): Stepped with the validation MAE every epoch.
        stop_patience (int | None): Epochs without improvement before training stops.
        bias_temperature (float): If positive, every error is weighted by
            `exp(-target / bias_temperature)` in the loss and in the validation MAE, so
            that structures with low targets (low energies) weigh more.
    """
    mean, std = target_stats
    best_valid_mae = float("inf")
    epochs_without_improvement = 0
    for epoch in range(1, epochs + 1):
        model.train()
        train_loss = 0.0
        for batch, targets, _ in train_loader:
            targets = targets.to(device)
            optimizer.zero_grad()
            outputs, _ = model(*batch_to_device(batch, device))
            loss = (outputs - (targets - mean) / std) ** 2
            if bias_temperature > 0:
                loss = loss * torch.exp(-targets / bias_temperature)
            loss = loss.mean()
            loss.backward()
            optimizer.step()
            train_loss += loss.item()
        train_loss /= len(train_loader)

        predictions, _, targets, _ = predict(model, valid_loader, device)
        errors = np.abs(predictions * std + mean - targets)
        if bias_temperature > 0:
            errors = errors * np.exp(-targets / bias_temperature)
        valid_mae = float(errors.mean())
        if scheduler is not None:
            scheduler.step(valid_mae)
        learning_rates = [group["lr"] for group in optimizer.param_groups]
        logging.info(
            f"Epoch [{epoch:03d}/{epochs}] - Train Loss: {train_loss:.5f}, "
            f"Valid MAE: {valid_mae:.5f}, LR: {learning_rates}"
        )
        if valid_mae < best_valid_mae:
            best_valid_mae = valid_mae
            epochs_without_improvement = 0
            # fold the target statistics into the output layer: the checkpoint predicts
            # in the original units
            state_dict = dict(model.state_dict())
            state_dict["fc_out.weight"] = state_dict["fc_out.weight"] * std
            state_dict["fc_out.bias"] = state_dict["fc_out.bias"] * std + mean
            torch.save(
                {
                    "epoch": epoch,
                    "state_dict": state_dict,
                    "best_mae_error": valid_mae,
                    "args": checkpoint_args,
                },
                checkpoint_path,
            )
            logging.info(f"  [SAVE] Best model at epoch {epoch}.")
        elif stop_patience is not None:
            epochs_without_improvement += 1
            if epochs_without_improvement >= stop_patience:
                logging.info(
                    f"Early stopping after {stop_patience} epochs without improvement."
                )
                break
    logging.info("Training complete.")
    model.load_state_dict(torch.load(checkpoint_path, weights_only=True)["state_dict"])