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 | |
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 | |
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, whereIDis 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 | |
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 |
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 | |
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: |
Source code in cgcnn2/data.py
96 97 98 99 100 101 102 103 104 105 106 | |
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 |
Source code in cgcnn2/data.py
65 66 67 68 69 70 71 72 73 74 75 76 | |
collate_pool(dataset_list)
¶
Collate a list of dataset items into one batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_list
|
list
|
Items |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 |
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 | |
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 |
required |
device
|
device | str
|
Where the model lives. |
required |
results_file
|
str
|
CSV file receiving |
'results.csv'
|
plot_file
|
str
|
PNG file receiving the parity plot. |
'parity_plot.png'
|
axis_limits
|
Sequence[float] | None
|
|
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 | |
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 | |
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 | |
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 |
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 | |
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 |
required |
metrics
|
Sequence[str]
|
Any of |
('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 | |
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 |
required |
dataset
|
CIFData
|
A dataset built with the same |
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 | |
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 |
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 |
('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 | |
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 |
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 | |
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 | |
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 | |
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 |
required |
Source code in cgcnn2/utils.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
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 | |
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 |
required |
train_loader
|
DataLoader
|
Training data, batched with |
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 |
required |
target_stats
|
tuple[float, float]
|
Mean and standard deviation of the training
targets, from |
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
|
-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 | |