|
| 1 | +import csv |
| 2 | +import random |
| 3 | +import tarfile |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from qml2 import Compound |
| 8 | +from qml2.kernels import local_dn_matern_kernel, local_dn_matern_kernel_symmetric |
| 9 | +from qml2.models.krr import KRRLocalModel |
| 10 | +from qml2.models.loss_functions import MAE |
| 11 | +from qml2.representations.calculators import SLATMCalculator |
| 12 | +from qml2.utils import get_sorted_elements |
| 13 | + |
| 14 | +xyzs = [] |
| 15 | +energies = [] |
| 16 | + |
| 17 | +training_set_size = 501 |
| 18 | +test_set_size = 1000 |
| 19 | +num_mols = training_set_size + test_set_size |
| 20 | + |
| 21 | +with open("../../tests/test_data/hof_qm7.txt") as csvfile: |
| 22 | + reader = csv.reader(csvfile, delimiter=" ") |
| 23 | + all_rows = list(reader) |
| 24 | + random.shuffle(all_rows) |
| 25 | + for row in all_rows[:num_mols]: |
| 26 | + xyzs.append(row[0]) |
| 27 | + energies.append(float(row[1])) |
| 28 | + |
| 29 | +energies = np.array(energies) |
| 30 | +all_nuclear_charges = [] |
| 31 | + |
| 32 | +compounds = [] |
| 33 | +with tarfile.open("../../tests/test_data/qm7.tar.gz") as tar: |
| 34 | + for xyz_name in xyzs: |
| 35 | + xyz = tar.extractfile(xyz_name) |
| 36 | + comp = Compound(xyz=xyz) |
| 37 | + compounds.append(comp) |
| 38 | + all_nuclear_charges.append(comp.nuclear_charges) |
| 39 | + |
| 40 | +train_compounds = compounds[:training_set_size] |
| 41 | +test_compounds = compounds[training_set_size:] |
| 42 | + |
| 43 | +train_quantities = energies[:training_set_size] |
| 44 | +test_quantities = energies[training_set_size:] |
| 45 | + |
| 46 | +slatm_calculator = SLATMCalculator(all_nuclear_charges) |
| 47 | +possible_nuclear_charges = get_sorted_elements(np.concatenate(all_nuclear_charges)) |
| 48 | +print("Nuclear charges found:", possible_nuclear_charges) |
| 49 | + |
| 50 | +# using "shift_quantites=True" means using dressed atom approach; requires defining `possible_nuclear_charges` though. |
| 51 | +model = KRRLocalModel( |
| 52 | + shift_quantities=True, |
| 53 | + possible_nuclear_charges=possible_nuclear_charges, |
| 54 | + representation_function=slatm_calculator, |
| 55 | + rep_kwargs={"local": True}, |
| 56 | + kernel_kwargs={"order": 0, "metric": "l2"}, |
| 57 | + kernel_function=local_dn_matern_kernel, |
| 58 | + kernel_function_symmetric=local_dn_matern_kernel_symmetric, |
| 59 | +) |
| 60 | + |
| 61 | +model.train(training_compounds=train_compounds, training_quantities=train_quantities) |
| 62 | + |
| 63 | +print("Optimized sigma:", model.sigma) |
| 64 | +print("Optimized l2reg divided by average kernel element:", model.l2reg_diag_ratio) |
| 65 | + |
| 66 | +predictions = model.predict_from_compounds(test_compounds) |
| 67 | +print("Prediction MAE:", MAE()(predictions - test_quantities)) |
| 68 | +print("Test set quantity STD:", np.std(test_quantities)) |
0 commit comments