コード例 #1
0
    def save(self, filename: Path):
        """
        Save a model to disk.

        Args:
            filename: Path to store the model.
        """
        filename = to_path(filename)
        create_directory(filename)
        torch.save(self.state_dict(), str(filename))

        # save descriptor mean and stdev
        fname = filename.parent.joinpath("mean_and_stdev.pkl")
        self.descriptor.dump_mean_stdev(fname)
コード例 #2
0
ファイル: model_torch.py プロジェクト: mjwen/kliff
    def save(self, filename: Path):
        """
        Save a model to disk.

        Args:
            filename: Path to store the model.
        """
        state_dict = {
            "model_state_dict": self.state_dict(),
            "descriptor_state_dict": self.descriptor.state_dict(),
        }

        filename = to_path(filename)
        create_directory(filename)

        torch.save(state_dict, str(filename))
コード例 #3
0
    def _compute_single_config(self, ca, normalize, verbose, common_path,
                               prefix):

        self.calculator.compute(ca)
        conf = _get_config(ca)
        conf_path = os.path.abspath(conf.path)
        natoms = conf.get_num_atoms()

        if self.compute_energy:
            pred_e = self.calculator.get_energy(ca)
            pred_e = _to_numpy(pred_e, ca)
            ref_e = conf.energy
            ediff = pred_e - ref_e
            enorm = abs(ediff)
            if normalize:
                enorm /= natoms
        else:
            ediff = None
            enorm = None

        if self.compute_forces:
            pred_f = self.calculator.get_forces(ca)
            pred_f = _to_numpy(pred_f, ca).reshape(-1, 3)
            ref_f = conf.forces.reshape(-1, 3)
            fdiff = pred_f - ref_f
            fnorm = np.linalg.norm(fdiff)
            if normalize:
                fnorm /= natoms
        else:
            fdiff = None
            fnorm = None

        # write the difference to extxyz files
        if verbose >= 2:
            if conf_path.startswith(common_path):
                base = conf_path[len(common_path):]
            else:
                raise AnalyzerError(
                    'identifier "{}" not start with common_path "{}".'.format(
                        conf_path, common_path))

            path = os.path.join(prefix, base)
            create_directory(path)
            conf.to_file(path)

        return enorm, fnorm
コード例 #4
0
ファイル: descriptor.py プロジェクト: mjwen/kliff
    def _dump_fingerprints(
        self,
        configs,
        fname,
        all_zeta,
        all_dzetadr_forces,
        all_dzetadr_stress,
        fit_forces,
        fit_stress,
    ):
        """
        Dump fingerprints to a pickle file.
        """

        logger.info(f"Pickling fingerprints to `{fname}`")

        create_directory(fname, is_directory=False)

        # remove it, because we use append mode for the file below
        fname = to_path(fname)
        if fname.exists():
            fname.unlink()

        with open(fname, "ab") as f:
            for i, conf in enumerate(configs):
                if i % 100 == 0:
                    logger.info(f"Processing configuration: {i}.")

                if all_zeta is None:
                    zeta, dzetadr_f, dzetadr_s = self.transform(
                        conf, fit_forces, fit_stress
                    )
                else:
                    zeta = all_zeta[i]
                    dzetadr_f = all_dzetadr_forces[i]
                    dzetadr_s = all_dzetadr_stress[i]

                # centering and normalization
                if self.normalize:
                    zeta = (zeta - self.mean) / self.stdev
                    if fit_forces or fit_stress:
                        stdev_3d = np.atleast_3d(self.stdev)
                    if fit_forces:
                        dzetadr_f = dzetadr_f / stdev_3d
                    if fit_stress:
                        dzetadr_s = dzetadr_s / stdev_3d

                # pickling data
                zeta = np.asarray(zeta, self.dtype)
                energy = np.asarray(conf.energy, self.dtype)
                if fit_forces:
                    dzetadr_f = np.asarray(dzetadr_f, self.dtype)
                    forces = np.asarray(conf.forces, self.dtype)
                if fit_stress:
                    dzetadr_s = np.asarray(dzetadr_s, self.dtype)
                    stress = np.asarray(conf.stress, self.dtype)
                    volume = np.asarray(conf.get_volume(), self.dtype)

                example = {"configuration": conf, "zeta": zeta, "energy": energy}
                if fit_forces:
                    example["dzetadr_forces"] = dzetadr_f
                    example["forces"] = forces
                if fit_stress:
                    example["dzetadr_stress"] = dzetadr_s
                    example["stress"] = stress
                    example["volume"] = volume

                pickle.dump(example, f)

        logger.info(f"Pickle {len(configs)} configurations finished.")