예제 #1
0
    def test_raise(self):
        # if func is not support pmap
        self.assertRaises(ValueError, lambda: pt.pmap(pt.bfactors, self.traj))

        # run time: openmp vs pmap
        if 'OPENMP' in pt.compiled_info():
            self.assertRaises(RuntimeError,
                              lambda: pt.pmap(pt.watershell, self.traj))

        # if traj is not TrajectoryIterator
        self.assertRaises(ValueError, lambda: pt.pmap(pt.radgyr, self.traj[:]))

        # raise if a given method does not support pmap
        def need_to_raise(traj=self.traj):
            pt.pmap(2, pt.bfactors, traj)

        self.assertRaises(ValueError, lambda: need_to_raise())

        # raise if a traj is not TrajectoryIterator
        def need_to_raise_2(traj=self.traj):
            pt.pmap(pt.bfactors, traj[:], n_cores=2)

        # raise if turn off pmap by setting _is_parallelizable to False
        pt.radgyr._is_parallelizable = False
        self.assertRaises(ValueError, lambda: pt.pmap(pt.radgyr, self.traj))
        pt.radgyr._is_parallelizable = True
예제 #2
0
    def test_raise(self):
        # if func is not support pmap
        self.assertRaises(ValueError, lambda: pt.pmap(pt.bfactors, self.traj))

        # run time: openmp vs pmap
        if 'OPENMP' in pt.compiled_info():
            self.assertRaises(RuntimeError,
                              lambda: pt.pmap(pt.watershell, self.traj))

        # if traj is not TrajectoryIterator
        self.assertRaises(ValueError, lambda: pt.pmap(pt.radgyr, self.traj[:]))

        # raise if a given method does not support pmap
        def need_to_raise(traj=self.traj):
            pt.pmap(2, pt.bfactors, traj)

        self.assertRaises(ValueError, lambda: need_to_raise())

        # raise if a traj is not TrajectoryIterator
        def need_to_raise_2(traj=self.traj):
            pt.pmap(pt.bfactors, traj[:], n_cores=2)

        # raise if turn off pmap by setting _is_parallelizable to False
        pt.radgyr._is_parallelizable = False
        self.assertRaises(ValueError, lambda: pt.pmap(pt.radgyr, self.traj))
        pt.radgyr._is_parallelizable = True
예제 #3
0
class TestNHOrderParamters(unittest.TestCase):

    @unittest.skipIf('DNO_MATHLIB' in pt.compiled_info(), 'there is no LAPACK')
    def test_nh_paramters(self):
        parmfile = cpptraj_test_dir + '/Test_IRED/1IEE_A_prot.prmtop'
        trajfile = cpptraj_test_dir + '/Test_IRED/1IEE_A_test.mdcrd'
        traj = pt.iterload(trajfile, parmfile)

        h_indices = pt.select_atoms('@H', traj.top)
        n_indices = h_indices - 1
        nh_indices = list(zip(n_indices, h_indices))

        # single core
        orders = pt.NH_order_parameters(traj, nh_indices, tcorr=8000.)
        saved_S2 = np.loadtxt(cpptraj_test_dir +
                              '/Test_IRED/orderparam.save').T[-1]

        aa_eq(orders, saved_S2)

        # multiple core
        # default 2
        orders = pt.pmap(pt.NH_order_parameters, traj, nh_indices, tcorr=8000.)
        aa_eq(orders, saved_S2)

        for n_cores in [1, 2, 3, 4, -1]:
            orders = pt.NH_order_parameters(traj,
                                            nh_indices,
                                            tcorr=8000.,
                                            n_cores=n_cores)
            aa_eq(orders, saved_S2)

            orders = pt.pmap(pt.NH_order_parameters,
                             traj,
                             nh_indices,
                             tcorr=8000.,
                             n_cores=n_cores)
            aa_eq(orders, saved_S2)
예제 #4
0
class TestIred(unittest.TestCase):

    def test_simple_for_coverage(self):
        '''
        '''
        traj = pt.iterload(traj_dir, parm_dir)
        h_indices = pt.select_atoms('@H', traj.top)
        n_indices = pt.select_atoms('@H', traj.top) - 1
        nh_indices = list(zip(n_indices, h_indices))
        vecs_and_mat = pt.ired_vector_and_matrix(traj, nh_indices, dtype='tuple')
        vecs_and_mat = pt.ired_vector_and_matrix(traj, nh_indices, dtype='tuple')
        state_vecs = vecs_and_mat[0]
        mat_ired = vecs_and_mat[1]

        # get eigenvalues and eigenvectors
        modes = pt.matrix.diagonalize(mat_ired, n_vecs=len(state_vecs))
        evals, evecs = modes

        data_0 = _ired(state_vecs,
                       modes=(evals, evecs),
                       NHbond=True,
                       tcorr=10000,
                       tstep=1.)

        data_1 = _ired(state_vecs,
                       modes=modes,
                       NHbond=True,
                       tcorr=10000,
                       tstep=1)

        for d0, d1 in zip(data_0, data_1):
            if d0.dtype not in ['modes', ]:
                aa_eq(d0.values, d1.values)
            else:
                # modes
                # values: tuple
                aa_eq(d0.values[0], d1.values[0])
                aa_eq(d0.values[1], d1.values[1])

        # try different dtype
        out_try_new_dtype = pt.ired_vector_and_matrix(traj, nh_indices, dtype='cpptraj_dataset')

    @unittest.skipIf('DNO_MATHLIB' in pt.compiled_info(), 'there is no LAPACK')
    # TODO: how can I get order paramters?
    def test_ired_need_lapack_cpptraj(self):
        state = pt.load_cpptraj_state(txt)
        state.run()
        xyz = state.data['CRD1'].xyz
        top = state.data['CRD1'].top
        traj = pt.Trajectory(xyz=xyz, top=top)
        state_vecs = state.data[1:-3].values

        h_indices = pt.select_atoms('@H', traj.top)
        n_indices = pt.select_atoms('@H', traj.top) - 1
        nh_indices = list(zip(n_indices, h_indices))
        mat_ired = pt.ired_vector_and_matrix(traj,
                                             mask=nh_indices,
                                             order=2)[-1]
        mat_ired /= mat_ired[0, 0]

        # matired: make sure to reproduce cpptraj output
        aa_eq(mat_ired, state.data['matired'].values)

        # get modes
        modes = state.data[-2]
        cpp_eigenvalues = modes.eigenvalues
        cpp_eigenvectors = modes.eigenvectors
        evals, evecs = np.linalg.eigh(mat_ired)

        # need to sort a bit
        evals = evals[::-1]
        # cpptraj's eigvenvalues
        aa_eq(evals, cpp_eigenvalues)

        # cpptraj's eigvenvectors
        # use absolute values to avoid flipped sign
        # from Dan Roe
        # In practice, the "sign" of an eigenvector depends on the math library used to calculate it.
        # This is in fact why the modes command displacement test is disabled for cpptraj.
        # I bet if you use a different math library (e.g. use your system BLAS/LAPACK instead of the one bundled with Amber
        # or vice versa) you will get different signs.
        # Bottom line is that eigenvector sign doesn't matter.

        aa_eq(np.abs(evecs[:, ::-1].T), np.abs(cpp_eigenvectors), decimal=4)
        data = _ired(state_vecs, modes=(cpp_eigenvalues, cpp_eigenvectors))
        order_s2 = data['IRED_00127[S2]']

        # load cpptraj's output and compare to pytraj' values for S2 order paramters
        cpp_order_s2 = np.loadtxt(os.path.join(cpptraj_test_dir, 'Test_IRED',
                                               'orderparam.save')).T[-1]
        aa_eq(order_s2, cpp_order_s2, decimal=5)

    @unittest.skip('do not test now, get nan in some runs')
    def test_ired_lapack_in_numpy(self):
        parmfile = parm_dir
        trajfile = traj_dir

        # load to TrajectoryIterator
        traj = pt.iterload(trajfile, parmfile)

        # create N-H vectors
        h_indices = pt.select_atoms('@H', traj.top)
        n_indices = pt.select_atoms('@H', traj.top) - 1
        nh_indices = list(zip(n_indices, h_indices))

        # compute N-H vectors and ired matrix
        vecs_and_mat = pt.ired_vector_and_matrix(traj,
                                                 mask=nh_indices,
                                                 order=2)
        state_vecs = vecs_and_mat[:-1].values
        mat_ired = vecs_and_mat[-1]
        mat_ired /= mat_ired[0, 0]

        # cpptraj
        data_cpp = pt.matrix.diagonalize(mat_ired, n_vecs=len(state_vecs))[0]
        print(data_cpp.eigenvectors)

        # numpy
        data_np = pt.matrix._diag_np(mat_ired, n_vecs=len(state_vecs))

        def order_(modes):
            data = _ired(state_vecs, modes=modes)
            order_s2_v0 = data['IRED_00127[S2]']
            # make sure the S2 values is 1st array

            # load cpptraj's output and compare to pytraj' values for S2 order paramters
            cpp_order_s2 = np.loadtxt(os.path.join(
                cpptraj_test_dir, 'Test_IRED', 'orderparam.save')).T[-1]
            aa_eq(order_s2_v0.values, cpp_order_s2, decimal=4)

        order_(data_cpp.values)

        def plot_(x, y):
            import seaborn as sb
            sb.heatmap(x - y)
            pt.show()

        print((data_cpp.values[1] - data_np[1]).shape)
예제 #5
0
average crdset AVG
run
# Step two. RMS-Fit to average structure. Calculate covariance matrix.
# Save the fit coordinates.
rms ref AVG !@H=
matrix covar name MyMatrix !@H=
createcrd CRD1
run
# Step three. Diagonalize matrix.
runanalysis diagmatrix MyMatrix vecs 2 name MyEvecs
# Step four. Project saved fit coordinates along eigenvectors 1 and 2
crdaction CRD1 projection evecs MyEvecs !@H= out project.dat beg 1 end 2
'''


@unittest.skipIf('DNO_MATHLIB' in pt.compiled_info(), 'there is no LAPACK')
class TestCpptrajDatasetWithMathLib(unittest.TestCase):

    def setUp(self):
        self.state = pt.datafiles.load_cpptraj_state(txt)
        self.state.run()
        self.traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7')

    def test_call_values(self):
        for d in self.state.data:
            d.values

    def test_dataset_coords_ref(self):
        traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7')
        avg_frame = pt.mean_structure(traj(rmsfit=(0, '!@H=')))
        state = self.state
예제 #6
0
average crdset AVG
run
# Step two. RMS-Fit to average structure. Calculate covariance matrix.
# Save the fit coordinates.
rms ref AVG !@H=
matrix covar name MyMatrix !@H=
createcrd CRD1
run
# Step three. Diagonalize matrix.
runanalysis diagmatrix MyMatrix vecs 2 name MyEvecs
# Step four. Project saved fit coordinates along eigenvectors 1 and 2
crdaction CRD1 projection evecs MyEvecs !@H= out project.dat beg 1 end 2
'''


@unittest.skipIf('DNO_MATHLIB' in pt.compiled_info(), 'there is no LAPACK')
class TestCpptrajDatasetWithMathLib(unittest.TestCase):
    def setUp(self):
        self.state = pt.datafiles.load_cpptraj_state(txt)
        self.state.run()
        self.traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7')

    def test_call_values(self):
        for d in self.state.data:
            d.values

    def test_dataset_coords_ref(self):
        traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7')
        avg_frame = pt.mean_structure(traj(rmsfit=(0, '!@H=')))
        state = self.state
예제 #7
0
class TestDiagMatrix(unittest.TestCase):

    @unittest.skipIf('DNO_MATHLIB' in pt.compiled_info(), 'there is no LAPACK')
    def test_diagmatrix(self):
        traj = pt.iterload("./data/tz2.nc", "./data/tz2.parm7")

        state = pt.load_batch(traj, '''
        #matrix covar @CA name mymat
        matrix dist @CA name mymat
        diagmatrix mymat vecs 6''')

        state.run()
        mat = state.data['mymat']
        cpp_evals, cpp_evecs = state.data[-1].eigenvalues, state.data[
            -1].eigenvectors

        # test triu_indices
        mat2 = mat.__class__()
        indices = np.triu_indices(mat.n_cols)

        mat2._set_data_half_matrix(mat._to_cpptraj_sparse_matrix(), mat.size,
                                   mat.n_cols)

        # OK
        data = matrix.diagonalize(mat.values, n_vecs=6, dtype='dataset')[-1]
        data2 = matrix.diagonalize(mat, n_vecs=6, dtype='dataset')[0]
        aa_eq(data.eigenvalues, cpp_evals, decimal=10)
        aa_eq(data2.eigenvalues, cpp_evals, decimal=10)

        # try numpy
        np_vals, np_vecs = np.linalg.eigh(mat2.values, UPLO='U')
        np_vals = np_vals[::-1][:6]
        np_vecs = np_vecs[:, ::-1].T[:6]

        # at least the absolute values are equal
        aa_eq(np.abs(data.eigenvectors), np.abs(cpp_evecs))
        aa_eq(np.abs(np_vecs), np.abs(cpp_evecs))

        # test raise if not having supported dtype
        self.assertRaises(ValueError, lambda: pt.matrix.diagonalize(mat, 3, dtype='ndarray'))

        # plot
        def plot_():
            try:
                from pytraj.plot import plot_matrix
                from matplotlib import pyplot as plt

                fig, ax, bar = plot_matrix(np.abs(data.eigenvectors) - np.abs(
                    cpp_evecs))
                fig.colorbar(bar)
                plt.title('data vs cpp_evecs')

                fig, ax, bar = plot_matrix(np.abs(np_vecs) - np.abs(cpp_evecs))
                fig.colorbar(bar)
                plt.title('np vs cpp_evecs')

                fig, ax, bar = plot_matrix(np.abs(np_vecs) - np.abs(
                    data.eigenvectors))
                fig.colorbar(bar)
                plt.title('np vs data')
                pt.show()
            except ImportError:
                pass