示例#1
0
 def setUp(self):
     profile = {'Mo': {'r': 0.6, 'w': 1.}}
     self.describer1 = BispectrumCoefficients(cutoff=4.6,
                                              twojmax=6,
                                              element_profile=profile,
                                              quadratic=False,
                                              pot_fit=True)
     model1 = SKLModel(describer=self.describer1, model=LinearRegression())
     self.potential1 = SNAPotential(model=model1, name='test')
     self.describer2 = BispectrumCoefficients(cutoff=4.6,
                                              twojmax=6,
                                              element_profile=profile,
                                              quadratic=True,
                                              pot_fit=True)
     model2 = SKLModel(describer=self.describer2, model=LinearRegression())
     self.potential2 = SNAPotential(model=model2, name='test')
     self.test_pool = test_datapool
     self.test_structures = []
     self.test_energies = []
     self.test_forces = []
     self.test_stresses = []
     for d in self.test_pool:
         self.test_structures.append(d['structure'])
         self.test_energies.append(d['outputs']['energy'])
         self.test_forces.append(d['outputs']['forces'])
         self.test_stresses.append(d['outputs']['virial_stress'])
     self.test_struct = self.test_pool[-1]['structure']
示例#2
0
class GaussianProcessTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.this_dir = os.path.dirname(os.path.abspath(__file__))
        cls.test_dir = tempfile.mkdtemp()

    def setUp(self):
        self.x_train = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T
        self.y_train = (self.x_train * np.sin(self.x_train)).ravel()
        self.gpr = SKLModel(model=GaussianProcessRegressor())

    @classmethod
    def tearDownClass(cls):
        os.chdir(cls.this_dir)
        shutil.rmtree(cls.test_dir)

    def test_fit_predict(self):
        self.gpr.fit(features=self.x_train, targets=self.y_train)
        x_test = np.atleast_2d(np.linspace(0, 9, 1000)).T
        y_test = x_test * np.sin(x_test)
        y_pred, sigma = self.gpr._predict(x_test, return_std=True)
        upper_bound = y_pred + 1.96 * sigma
        lower_bound = y_pred - 1.96 * sigma
        self.assertTrue(
            np.all([
                l < y and y < u
                for u, y, l in zip(upper_bound, y_test, lower_bound)
            ]))
示例#3
0
    def setUp(self):
        element_profile = {'Ni': {'r': 0.5, 'w': 1}}
        describer1 = BispectrumCoefficients(cutoff=4.1,
                                            twojmax=8,
                                            element_profile=element_profile,
                                            quadratic=False,
                                            pot_fit=True)
        model1 = SKLModel(describer=describer1, model=LinearRegression())
        model1.model.coef_ = coeff
        model1.model.intercept_ = intercept
        snap1 = SNAPotential(model=model1)
        self.ff_settings1 = snap1

        describer2 = BispectrumCoefficients(cutoff=4.1,
                                            twojmax=8,
                                            element_profile=element_profile,
                                            quadratic=True,
                                            pot_fit=True)
        model2 = SKLModel(describer=describer2, model=LinearRegression())
        model2.model.coef_ = coeff
        model2.model.intercept_ = intercept
        snap2 = SNAPotential(model=model2)
        self.ff_settings2 = snap2

        self.struct = Structure.from_spacegroup('Fm-3m', Lattice.cubic(3.506),
                                                ['Ni'], [[0, 0, 0]])
示例#4
0
 def test_model_none(self):
     m = SKLModel(model=LinearRegression())
     x = np.array([[1, 2], [2, 1], [1, 1]])
     y = np.array([[3], [3], [2]])
     m.train(x, y)
     np.testing.assert_almost_equal(m.model.coef_.ravel(),
                                    np.array([1.0, 1.0]))
示例#5
0
 def setUp(self):
     profile = {"Mo": {"r": 0.6, "w": 1.0}}
     self.describer1 = BispectrumCoefficients(rcutfac=4.6,
                                              twojmax=6,
                                              element_profile=profile,
                                              quadratic=False,
                                              pot_fit=True)
     model1 = SKLModel(describer=self.describer1, model=LinearRegression())
     self.potential1 = SNAPotential(model=model1, name="test")
     self.describer2 = BispectrumCoefficients(rcutfac=4.6,
                                              twojmax=6,
                                              element_profile=profile,
                                              quadratic=True,
                                              pot_fit=True)
     model2 = SKLModel(describer=self.describer2, model=LinearRegression())
     self.potential2 = SNAPotential(model=model2, name="test")
     self.test_pool = test_datapool
     self.test_structures = []
     self.test_energies = []
     self.test_forces = []
     self.test_stresses = []
     for d in self.test_pool:
         self.test_structures.append(d["structure"])
         self.test_energies.append(d["outputs"]["energy"])
         self.test_forces.append(d["outputs"]["forces"])
         self.test_stresses.append(d["outputs"]["virial_stress"])
     self.test_struct = self.test_pool[-1]["structure"]
示例#6
0
    def from_config(param_file, coeff_file, **kwargs):
        """
        Initialize potentials with parameters file and coefficient file.

        Args:
            param_file (str): The file storing the configuration of potentials.
            coeff_file (str): The file storing the coefficients of potentials.

        Return:
            SNAPotential.
        """
        with open(coeff_file) as f:
            coeff_lines = f.readlines()
        coeff_lines = [
            line for line in coeff_lines if not line.startswith("#")
        ]
        element_profile = {}
        ne, nbc = coeff_lines[0].split()
        ne, nbc = int(ne), int(nbc)
        for n in range(ne):
            specie, r, w = coeff_lines[1 + n * (nbc + 1)].split()
            r, w = float(r), float(w)
            element_profile[specie] = {"r": r, "w": w}

        rcut_pattern = re.compile(r"rcutfac (.*?)\n", re.S)
        twojmax_pattern = re.compile(r"twojmax (\d*)\n", re.S)
        quadratic_pattern = re.compile(r"quadraticflag (.*?)(?=\n|$)", re.S)

        with zopen(param_file, "rt") as f:
            param_lines = f.read()

        rcut = float(rcut_pattern.findall(param_lines)[-1])
        twojmax = int(twojmax_pattern.findall(param_lines)[-1])
        if quadratic_pattern.findall(param_lines):
            quadratic = bool(int(quadratic_pattern.findall(param_lines)[-1]))
        else:
            quadratic = False

        describer = BispectrumCoefficients(rcutfac=rcut,
                                           twojmax=twojmax,
                                           element_profile=element_profile,
                                           quadratic=quadratic,
                                           pot_fit=True)
        model = SKLModel(model=LinearRegression(),
                         describer=describer,
                         **kwargs)
        coef = np.array(
            np.concatenate([
                coeff_lines[(2 + nbc * n + n):(2 + nbc * (n + 1) + n)]
                for n in range(ne)
            ]),
            dtype=np.float64,
        )
        model.model.coef_ = coef
        model.model.intercept_ = 0
        snap = SNAPotential(model=model)
        return snap
示例#7
0
 def setUp(self):
     element_profile = {'Ni': {'r': 0.5, 'w': 1}}
     describer = BispectrumCoefficients(cutoff=4.1, twojmax=8,
                                        element_profile=element_profile,
                                        pot_fit=True)
     model = SKLModel(describer=describer, model=LinearRegression())
     model.model.coef_ = coeff
     model.model.intercept_ = intercept
     snap = SNAPotential(model=model)
     self.ff_settings = snap
示例#8
0
class LinearModelTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.x_train = np.random.rand(10, 2)
        cls.coef = np.random.rand(2)
        cls.intercept = np.random.rand()
        cls.y_train = cls.x_train.dot(cls.coef) + cls.intercept

    def setUp(self):

        self.lm = SKLModel(model=LinearRegression())
        self.test_dir = tempfile.mkdtemp()

    def tearDown(self):
        # Remove the directory after the test
        shutil.rmtree(self.test_dir)

    def test_fit_predict(self):
        self.lm.fit(features=self.x_train, targets=self.y_train)
        x_test = np.random.rand(10, 2)
        y_test = x_test.dot(self.coef) + self.intercept
        y_pred = self.lm._predict(x_test)
        np.testing.assert_array_almost_equal(y_test, y_pred)
        np.testing.assert_array_almost_equal(self.coef, self.lm.model.coef_)
        self.assertAlmostEqual(self.intercept, self.lm.model.intercept_)

    def test_model_save_load(self):
        self.lm.fit(features=self.x_train, targets=self.y_train)
        with ScratchDir('.'):
            self.lm.save('test_lm.save')
            ori = self.lm.model.coef_
            self.lm.load('test_lm.save')
            loaded = self.lm.model.coef_

            np.testing.assert_almost_equal(ori, loaded)

            lm2 = SKLModel.from_file('test_lm.save')
            np.testing.assert_almost_equal(lm2.model.coef_, ori)

    def test_model_none(self):
        m = SKLModel(model=LinearRegression())
        x = np.array([[1, 2], [2, 1], [1, 1]])
        y = np.array([[3], [3], [2]])
        m.train(x, y)
        np.testing.assert_almost_equal(m.model.coef_.ravel(),
                                       np.array([1.0, 1.0]))
示例#9
0
    def test_model_save_load(self):
        self.lm.fit(features=self.x_train, targets=self.y_train)
        with ScratchDir('.'):
            self.lm.save('test_lm.save')
            ori = self.lm.model.coef_
            self.lm.load('test_lm.save')
            loaded = self.lm.model.coef_

            np.testing.assert_almost_equal(ori, loaded)

            lm2 = SKLModel.from_file('test_lm.save')
            np.testing.assert_almost_equal(lm2.model.coef_, ori)
示例#10
0
 def setUp(self):
     element_profile = {"Ni": {"r": 0.5, "w": 1}}
     describer = BispectrumCoefficients(rcutfac=4.1,
                                        twojmax=8,
                                        element_profile=element_profile,
                                        pot_fit=True)
     model = SKLModel(describer=describer, model=LinearRegression())
     model.model.coef_ = coeff
     model.model.intercept_ = intercept
     snap = SNAPotential(model=model)
     self.struct = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.506),
                                             ["Ni"], [[0, 0, 0]])
     self.ff_settings = snap
示例#11
0
    def setUp(self):

        self.lm = SKLModel(model=LinearRegression())
        self.test_dir = tempfile.mkdtemp()
示例#12
0
 def setUp(self):
     self.x_train = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T
     self.y_train = (self.x_train * np.sin(self.x_train)).ravel()
     self.gpr = SKLModel(model=GaussianProcessRegressor())