コード例 #1
0
ファイル: schnetpack.py プロジェクト: arnabmaj/ML_Calc_Driver
 def __init__(
     self,
     model_dir,
     available_properties=None,
     device="cpu",
     units=eVA,
 ):
     r"""
     Parameters
     ----------
     model_dir : str
         Path to the stored model on which the calculator
         will be based. If $MODELDIR is defined, the path can
         be relative to it. If not, the path must be absolute
         or relative to the working directory.
     available_properties : str or list of str
         Properties that the model can predict. If `None`, they
         automatically determined from the model. Default is `None`.
     device : str
         Can be either `"cpu"` to use cpu or `"cuda"` to use "gpu"
     units : dict
         Dictionnary containing the units in which the calculator
         makes predictions. Default is mlcalcdriver.globals.eVA for
         a SchnetPackCalculator.
     """
     self.device = device
     try:
         self.model = load_model(model_dir, map_location=self.device)
     except Exception:
         self.model = load_model(os.environ["MODELDIR"] + model_dir,
                                 map_location=self.device)
     super(SchnetPackCalculator, self).__init__(units=units)
     self.model.eval()
     self._get_representation_type()
コード例 #2
0
    def __init__(
        self,
        model_dir,
        available_properties=None,
        device="cpu",
        units=eVA,
        md=False,
        dropout=False,
    ):
        r"""
        Parameters
        ----------
        model_dir : str
            Path to the stored model on which the calculator
            will be based. If $MODELDIR is defined, the path can
            be relative to it. If not, the path must be absolute
            or relative to the working directory.
        available_properties : str or list of str
            Properties that the model can predict. If `None`, they
            automatically determined from the model. Default is `None`.
        device : str
            Can be either `"cpu"` to use cpu or `"cuda"` to use "gpu"
        units : dict
            Dictionnary containing the units in which the calculator
            makes predictions. Default is mlcalcdriver.globals.eVA for
            a SchnetPackCalculator.
        md : bool
            Whether the calculator is used with ASE to do molecular dynamics.
            Default is False and should be changed through the
            :class:`AseSpkCalculator` object.
        dropout : bool
            Whether the calculator should use the dropout layers to estimate
            a confidence interval for the prediction. Default is False. No
            effect if the model hasn't been trained with dropout layers.
        """
        self.device = device
        self.md = md
        self.dropout = dropout

        try:
            self.model = load_model(model_dir, map_location=self.device)
        except Exception:
            self.model = load_model(os.environ["MODELDIR"] + model_dir,
                                    map_location=self.device)
        super(SchnetPackCalculator, self).__init__(units=units)
        if self.dropout:
            self.model.train()
        else:
            self.model.eval()
        self._get_representation_type()
コード例 #3
0
def spk_calculator(model_file, environment_provider, device):

	model = load_model(model_file)
	model.output_modules[0].create_graph = False

	return SpkCalculator(model=model, device=device, environment_provider=environment_provider,
		energy='energy', forces='forces', stress='stress')
コード例 #4
0
def get_dos(
        model,
        posinp,
        device="cpu",
        supercell=(6, 6, 6),
        qpoints=[30, 30, 30],
        npts=1000,
        width=0.004,
):
    if isinstance(posinp, str):
        atoms = posinp_to_ase_atoms(Posinp.from_file(posinp))
    elif isinstance(posinp, Posinp):
        atoms = posinp_to_ase_atoms(posinp)
    else:
        raise ValueError("The posinp variable is not recognized.")

    if isinstance(model, str):
        model = load_model(model, map_location=device)
    elif isinstance(model, torch.nn.Module):
        pass
    else:
        raise ValueError("The model variable is not recognized.")

    # Bugfix to make older models work with PyTorch 1.6
    # Hopefully temporary
    for mod in model.modules():
        if not hasattr(mod, "_non_persistent_buffers_set"):
            mod._non_persistent_buffers_set = set()

    assert len(supercell) == 3, "Supercell should be a length 3 object."
    assert len(qpoints) == 3, "Qpoints should be a length 3 object."
    supercell = tuple(supercell)

    cutoff = float(model.state_dict()
                   ["representation.interactions.0.cutoff_network.cutoff"])
    calculator = SpkCalculator(
        model,
        device=device,
        energy="energy",
        forces="forces",
        environment_provider=AseEnvironmentProvider(cutoff),
    )
    ph = Phonons(atoms, calculator, supercell=supercell, delta=0.02)
    ph.run()
    ph.read(acoustic=True)
    dos = ph.get_dos(kpts=qpoints).sample_grid(npts=npts, width=width)
    ph.clean()
    return Dos(dos.energy * 8065.6, dos.weights[0])
コード例 #5
0
    def evaluate(self, batch_size, num_workers, device, log_remaining=True):

        model = load_model('output_%i/best_model' % self.i,
                           map_location=device)
        model.output_modules[0].create_graph = False

        remaining = self.dataset.create_subset(self.idx_rem)

        loader = AtomsLoader(remaining,
                             batch_size=round(batch_size / 2),
                             num_workers=num_workers,
                             pin_memory=True)

        print('Running evaluation!')

        if log_remaining:
            fid = open('log_%i/remaining.csv' % self.i, 'w')
            fid.write('Energy (eV),Force (eV/Å),Stress (eV/ų)\n')
        else:
            fid = None

        passfail = []
        for batch in loader:
            batch = {k: v.to(device) for k, v in batch.items()}
            result = model(batch)
            passfail += self.evaluate_fn(batch, result, fid).tolist()

        fid.close()

        I = np.where(passfail)[0]
        percentage = 100 * len(I) / len(self.idx_rem)

        if percentage > 5.0:
            np.random.shuffle(I)
            J = I[0:round(self.frac * len(I))]

            self.idx_red = np.append(self.idx_red, self.idx_rem[J])
            self.idx_rem = np.delete(self.idx_rem, J)
        else:
            1 + 1

        print('            Failed images: %i' % len(I))
        print('             Added images: %i' % len(J))
        print('  Percentage of remaining: %5.2f' % percentage)
        print(' Reduced/Remaining images: %i/%i' %
              (len(self.idx_red), len(self.idx_rem)))
        print('')
コード例 #6
0
fid.write(header)
fid.flush()

for dataset_file in natsorted(os.listdir(datasets_path)):

    dataset = AtomsData(datasets_path + dataset_file,
                        load_only=properties,
                        environment_provider=OpenCLEnvironmentProvider(
                            cutoff, 0),
                        centering_function=None)

    loader = AtomsLoader(dataset,
                         batch_size=20,
                         num_workers=1,
                         pin_memory=True)

    for model_file in natsorted(os.listdir(models_path)):

        model = load_model(models_path + model_file)

        # Disable the creation of graph, which is not needed since we are only evaluating.
        model.output_modules[0].create_graph = False

        fid.write(
            format_results(dataset_file, model_file,
                           evaluate_dataset(metrics, model, loader, device)))
        fid.flush()

fid.close()
コード例 #7
0
do_3state = True
if model_type == '2state':
    do_3state = False
elif model_type == '3state':
    do_3state = True
else:
    print('Provide a model type (2state or 3state) as an argument')
# flag that indicates on which state the trajectory is running
flag_es = 3
# flags for hopping
do_hop = True
hop = False
skip_next = False

# SchNet calculator
model_s = load_model(path1, map_location=torch_device('cpu'))
model2_s = load_model(path2, map_location=torch_device('cpu'))
if do_3state:
    model3_s = load_model(path3, map_location=torch_device('cpu'))

model = model_s.double()
model2 = model2_s.double()
if do_3state:
    model3 = model3_s.double()

# demon-nano calculator
input_arguments = {
    'DFTB': 'SCC LRESP EXST=2',
    'CHARGE': '0.0',
    'PARAM': 'PTYPE=BIO'
}
コード例 #8
0
import torch
from ase.db import connect
from schnetpack.interfaces import SpkCalculator
from schnetpack.utils import load_model

# path definitions
path_to_model = "tutorials/training/best_model"
path_to_db = "tutorials/data/snippet.db"
# load model
model = load_model(path_to_model)
# get example atom
conn = connect(path_to_db)
ats = conn.get_atoms(1)
# build calculator
calc = SpkCalculator(model, device="cpu", energy="energy", forces="forces")
# add calculator to atoms object
ats.set_calculator(calc)

# test
print("forces:", ats.get_forces())
print("total_energy", ats.get_total_energy())