Пример #1
0
def test_api():
    tr = get_rand_traj()
    st = get_rand_struct()
    for name in st.attr_lst:
        assert getattr(tr, name) is not None
    for name in tr.attrs_only_traj:
        assert getattr(st, name) is None
    
    aa = tr[0]      # Structure
    bb = tr[0:1]    # Trajectory
    keys = set.difference(set(aa.attr_lst), set(aa.attrs_only_traj))
    assert aa.is_struct
    assert bb.is_traj
    # remove timeaxis before comparing arrays
    for name in bb.attrs_nstep:
        attr = getattr(bb, name)
        if attr.ndim == 1:
            setattr(bb, name, attr[0])
        else:            
            setattr(bb, name, attr[0,...])
    assert_dict_with_all_types_equal(aa.__dict__, bb.__dict__, keys=keys)
Пример #2
0
def test_api():
    tr = get_rand_traj()
    st = get_rand_struct()
    for name in st.attr_lst:
        assert getattr(tr, name) is not None
    for name in tr.attrs_only_traj:
        assert getattr(st, name) is None

    aa = tr[0]  # Structure
    bb = tr[0:1]  # Trajectory
    keys = set.difference(set(aa.attr_lst), set(aa.attrs_only_traj))
    assert aa.is_struct
    assert bb.is_traj
    # remove timeaxis before comparing arrays
    for name in bb.attrs_nstep:
        attr = getattr(bb, name)
        if attr.ndim == 1:
            setattr(bb, name, attr[0])
        else:
            setattr(bb, name, attr[0, ...])
    assert_dict_with_all_types_equal(aa.__dict__, bb.__dict__, keys=keys)
Пример #3
0
def test_concatenate():
    st = get_rand_struct()
    nstep = 5
    
    # cat Structure
    tr_cat = crys.concatenate([st]*nstep)
    keys = tr_cat.attr_lst
    assert tr_cat.nstep == nstep
    for x in tr_cat:
        assert_dict_with_all_types_equal(x.__dict__, st.__dict__,
                                         keys=keys)
    none_attrs = ['ekin', 'timestep', 'velocity', 'temperature', 'time']
    for attr_name in tr_cat.attrs_nstep:
        if attr_name in none_attrs:
            assert getattr(tr_cat, attr_name) is None
        else:
            print "test_concatenate: shape[0] == nstep:", attr_name
            assert getattr(tr_cat, attr_name).shape[0] == nstep
            print "test_concatenate: shape[0] == nstep:", attr_name, "...ok"
    
    # cat Trajectory
    tr = get_rand_traj()
    tr_cat = crys.concatenate([tr]*3)
    assert tr_cat.nstep == 3*tr.nstep
    none_attrs = ['timestep', 'time']
    keys = remove_from_lst(tr_cat.attr_lst, none_attrs)
    for x in [tr_cat[0:tr.nstep], 
              tr_cat[tr.nstep:2*tr.nstep], 
              tr_cat[2*tr.nstep:3*tr.nstep]]:
        assert_dict_with_all_types_equal(x.__dict__, tr.__dict__,
                                         keys=keys) 
    for attr_name in tr_cat.attrs_nstep:
        if attr_name in none_attrs:
            assert getattr(tr_cat, attr_name) is None
        else:
            assert getattr(tr_cat, attr_name).shape[0] == 3*tr.nstep

    # cat mixed, Structure is minimal API
    st = get_rand_struct()
    tr = crys.concatenate([st]*5)
    tr_cat = crys.concatenate([st]*5 + [tr])
    assert tr_cat.nstep == 10
    none_attrs = ['ekin', 'timestep', 'velocity', 'temperature', 'time']
    keys = remove_from_lst(tr_cat.attr_lst, none_attrs)
    for x in tr_cat:
        assert_dict_with_all_types_equal(x.__dict__, st.__dict__,
                                         keys=keys)
    for attr_name in tr_cat.attrs_nstep:
        if attr_name in none_attrs:
            assert getattr(tr_cat, attr_name) is None
        else:
            assert getattr(tr_cat, attr_name).shape[0] == 10
Пример #4
0
def test_concatenate():
    st = get_rand_struct()
    nstep = 5

    # cat Structure
    tr_cat = crys.concatenate([st] * nstep)
    keys = tr_cat.attr_lst
    assert tr_cat.nstep == nstep
    for x in tr_cat:
        assert_dict_with_all_types_equal(x.__dict__, st.__dict__, keys=keys)
    none_attrs = ['ekin', 'timestep', 'velocity', 'temperature', 'time']
    for attr_name in tr_cat.attrs_nstep:
        if attr_name in none_attrs:
            assert getattr(tr_cat, attr_name) is None
        else:
            print("test_concatenate: shape[0] == nstep:", attr_name)
            assert getattr(tr_cat, attr_name).shape[0] == nstep
            print("test_concatenate: shape[0] == nstep:", attr_name, "...ok")

    # cat Trajectory
    tr = get_rand_traj()
    tr_cat = crys.concatenate([tr] * 3)
    assert tr_cat.nstep == 3 * tr.nstep
    none_attrs = ['timestep', 'time']
    keys = remove_from_lst(tr_cat.attr_lst, none_attrs)
    for x in [
            tr_cat[0:tr.nstep], tr_cat[tr.nstep:2 * tr.nstep],
            tr_cat[2 * tr.nstep:3 * tr.nstep]
    ]:
        assert_dict_with_all_types_equal(x.__dict__, tr.__dict__, keys=keys)
    for attr_name in tr_cat.attrs_nstep:
        if attr_name in none_attrs:
            assert getattr(tr_cat, attr_name) is None
        else:
            assert getattr(tr_cat, attr_name).shape[0] == 3 * tr.nstep

    # cat mixed, Structure is minimal API
    st = get_rand_struct()
    tr = crys.concatenate([st] * 5)
    tr_cat = crys.concatenate([st] * 5 + [tr])
    assert tr_cat.nstep == 10
    none_attrs = ['ekin', 'timestep', 'velocity', 'temperature', 'time']
    keys = remove_from_lst(tr_cat.attr_lst, none_attrs)
    for x in tr_cat:
        assert_dict_with_all_types_equal(x.__dict__, st.__dict__, keys=keys)
    for attr_name in tr_cat.attrs_nstep:
        if attr_name in none_attrs:
            assert getattr(tr_cat, attr_name) is None
        else:
            assert getattr(tr_cat, attr_name).shape[0] == 10
Пример #5
0
def assert_equal(d1, d2, keys=None):
    if keys is None:
        keys = ['x', 'y', 'xx', 'yy', 'zz', 'X', 'Y', 'Z', 'XY']
    tools.assert_dict_with_all_types_equal(d1.__dict__, d2.__dict__, keys=keys)
Пример #6
0
def assert_equal(d1, d2, keys=None):
    if keys is None:
        keys = ['x','y','xx','yy','zz','X','Y','Z','XY']
    tools.assert_dict_with_all_types_equal(d1.__dict__, d2.__dict__,
                                           keys=keys)
Пример #7
0
def test_traj():
    natoms = 10
    nstep = 100
    cell = rand(nstep,3,3)
    stress = rand(nstep,3,3)
    forces = rand(nstep,natoms,3)
    etot = rand(nstep)
    cryst_const = crys.cell2cc3d(cell, axis=0)
    coords_frac = rand(nstep,natoms,3)
    coords = crys.coord_trans3d(coords=coords_frac,
                                old=cell,
                                new=num.extend_array(np.identity(3),
                                                     nstep,axis=0),
                                axis=1,
                                timeaxis=0)                                                    
    assert cryst_const.shape == (nstep, 6)
    assert coords.shape == (nstep,natoms,3)
    symbols = ['H']*natoms
    
    # automatically calculated:
    #   coords
    #   cell
    #   pressure
    #   velocity (from coords)
    #   temperature (from ekin)
    #   ekin (from velocity)
    traj = Trajectory(coords_frac=coords_frac,
                    cell=cell,
                    symbols=symbols,
                    forces=forces,
                    stress=stress,
                    etot=etot,
                    timestep=1,
                    )
    # Test if all getters work.
    for name in traj.attr_lst:
        print "test if getters work:", name
        traj.try_set_attr(name)
        assert getattr(traj, name) is not None, "attr None: %s" %name
        assert eval('traj.get_%s()'%name) is not None, "getter returns None: %s" %name
        print "test if getters work:", name, "... ok"
    aaae(coords_frac, traj.coords_frac)
    aaae(coords, traj.coords)
    aaae(cryst_const, traj.cryst_const)
    aaae(np.trace(stress, axis1=1, axis2=2)/3.0, traj.pressure)
    assert traj.coords.shape == (nstep,natoms,3)
    assert traj.cell.shape == (nstep,3,3)
    assert traj.velocity.shape == (nstep, natoms, 3)
    assert traj.temperature.shape == (nstep,)
    assert traj.ekin.shape == (nstep,)
    assert traj.nstep == nstep
    assert traj.natoms == natoms

    traj = Trajectory(coords_frac=coords_frac,
                    symbols=symbols,
                    cell=cell)
    aaae(coords, traj.coords)
    
    # Cell calculated from cryst_const has defined orientation in space which may be
    # different from the original `cell`, but the volume and underlying cryst_const
    # must be the same.
    traj = Trajectory(coords_frac=coords_frac,
                    symbols=symbols,
                    cryst_const=cryst_const)
    np.testing.assert_almost_equal(crys.volume_cell3d(cell),
                                   crys.volume_cell3d(traj.cell))
    aaae(cryst_const, crys.cell2cc3d(traj.cell))
    
    # extend arrays
    cell2d = rand(3,3)
    cc2d = crys.cell2cc(cell2d)
    traj = Trajectory(coords_frac=coords_frac,
                      cell=cell2d,
                      symbols=symbols)
    assert traj.cell.shape == (nstep,3,3)
    assert traj.cryst_const.shape == (nstep,6)
    for ii in range(traj.nstep):
        assert (traj.cell[ii,...] == cell2d).all()
        assert (traj.cryst_const[ii,:] == cc2d).all()
    
    traj = Trajectory(coords_frac=coords_frac,
                      cryst_const=cc2d,
                      symbols=symbols)
    assert traj.cell.shape == (nstep,3,3)
    assert traj.cryst_const.shape == (nstep,6)
    for ii in range(traj.nstep):
        assert (traj.cryst_const[ii,:] == cc2d).all()

    # units
    traj = Trajectory(coords_frac=coords_frac,
                    cell=cell,
                    symbols=symbols,
                    stress=stress,
                    forces=forces,
                    units={'length': 2, 'forces': 3, 'stress': 4})
    aaae(2*coords, traj.coords)                    
    aaae(3*forces, traj.forces)                    
    aaae(4*stress, traj.stress)                    
    
    # iterate, check if Structures are complete
    traj = Trajectory(coords=coords, 
                      symbols=symbols,
                      cell=cell,
                      forces=forces,
                      stress=stress,
                      etot=etot,
                      timestep=1.0)
    for struct in traj:
        assert struct.is_struct, "st is not Structure"
        assert not struct.is_traj, "st is Trajectory"
        assert_attrs_not_none(struct)
    struct = traj[0]
    for attr_name in traj.attr_lst:
        if attr_name in struct.attrs_only_traj:
            msg = "tr[0] %s is not None" %attr_name
            assert getattr(struct,attr_name) is None, msg
        else:            
            msg = "tr[0] %s is None" %attr_name
            assert getattr(struct,attr_name) is not None, msg
    
    # slices, return traj
    keys = traj.attr_lst[:]
    tsl = traj[10:80:2]
    assert tsl.nstep == traj.nstep / 2 - 15
    assert_attrs_not_none(tsl, attr_lst=keys)
    tsl = traj[slice(10,80,2)]
    assert tsl.nstep == traj.nstep / 2 - 15
    assert_attrs_not_none(tsl, attr_lst=keys)
    tsl = traj[np.s_[10:80:2]]
    assert tsl.nstep == traj.nstep / 2 - 15
    assert_attrs_not_none(tsl, attr_lst=keys)
    assert tsl.is_traj
    
    # iteration over sliced traj
    tsl = traj[10:80:2]
    for x in tsl:
        pass
    for x in tsl.copy():
        pass

    # repeat iter
    for i in range(2):
        cnt = 0
        for st in traj:
            cnt += 1
        assert cnt == nstep, "%i, %i" %(cnt, nstep)    
    
    # copy
    traj2 = traj.copy()
    for name in traj.attr_lst:
        val = getattr(traj,name)
        if val is not None and not (isinstance(val, types.IntType) or \
            isinstance(val, types.FloatType)):
            val2 = getattr(traj2,name)
            print "test copy:", name, type(val), type(val2)
            assert id(val2) != id(val)
            assert_all_types_equal(val2, val)
    assert_dict_with_all_types_equal(traj.__dict__, traj2.__dict__,
                                     keys=traj.attr_lst)
Пример #8
0
def test_tools():
    x1 = {
        'a': 3,
        type(1): 'foo',
        'b': {
            'aa': 1,
            'bb': np.array([1, 2]),
            'cc': {
                'aaa': np.array([1, 2.0]),
                'bbb': np.array([2, 4.0])
            }
        }
    }
    x2 = copy.deepcopy(x1)
    tools.assert_dict_with_all_types_equal(x1, x2)
    tools.assert_all_types_equal(x1, x2)

    # not equal array
    x2['b']['cc']['bbb'] *= 2.0
    assert not tools.all_types_equal(x1, x2)

    # almost equal array and float
    x2 = copy.deepcopy(x1)
    x2['b']['cc']['bbb'] += 1e-5
    x2['b']['aa'] += 1e-5
    tools.assert_all_types_almost_equal(x1, x2)

    # sub-dict different (keys don't match)
    x2 = copy.deepcopy(x1)
    x2['b']['cc']['fff'] = 'extra'
    assert not tools.all_types_equal(x1, x2)

    # test only some keys of a dict
    tools.assert_dict_with_all_types_equal({
        'a': 1,
        'b': 1
    }, {
        'a': 1,
        'b': 3
    },
                                           keys=['a'])

    # simple stuff
    tools.assert_all_types_equal(1, 1)
    tools.assert_all_types_equal(1.0, 1.0)
    tools.assert_all_types_equal(1.0, 1)
    tools.assert_all_types_equal(1, 1.0)
    tools.assert_all_types_equal([1], [1])
    tools.assert_all_types_equal([1], [1.0])
    tools.assert_all_types_equal('a', 'a')
    tools.assert_all_types_almost_equal(1.0, 1.0 + 1e-5)
    tools.assert_all_types_almost_equal(np.array([1.0]),
                                        np.array([1.0 + 1e-5]))
    assert not tools.all_types_equal(1, 2)
    assert not tools.all_types_equal(1.0, 1.1)
    assert not tools.all_types_equal([1], [1, 2])
    assert not tools.all_types_equal('a', 'b')

    # different types not allowed if strict=True
    assert not tools.all_types_equal(1.0, 1, strict=True)

    # test keys=[...], i.e. ignore some keys in both dicts
    x2 = copy.deepcopy(x1)
    x2['c'] = 1.0
    assert tools.dict_with_all_types_equal(x1, x2, keys=['a', 'b', type(1)])

    # fail on same array content but different dimensions
    a = np.random.rand(1, 2, 3)
    b = a[None, ...]
    # this is True and IMHO a numpy bug b/c the dimensions are
    # different
    assert (a == b).all()
    # must catch that here
    assert not tools.array_equal(a, b)

    a = np.random.rand(1, 2, 3)
    b = (a + 1e-8)[None, ...]
    assert not (a == b).all()  # make sure they are numerically differrent
    assert np.allclose(a, b)  # True but should be False
    assert not tools.array_almost_equal(a, b)  # ok

    flt = 1.0
    np_flt = np.array([1.0 + 1e-9])[0]
    assert not tools.all_types_equal(flt, np_flt)
    assert not tools.all_types_equal(np_flt, flt)
    assert tools.all_types_almost_equal(flt, np_flt)
    assert tools.all_types_almost_equal(np_flt, flt)
Пример #9
0
def test_dcd():
    # nstep = 101
    # natoms = 16
    dir_lmp = tools.unpack_compressed('files/lammps/md-npt.tgz')
    fn_lmp = pj(dir_lmp, 'lmp.out.dcd')

    # nstep = 16
    # natoms = 57
    dir_cp2k = tools.unpack_compressed('files/cp2k/dcd/npt_dcd.tgz')
    fn_cp2k = pj(dir_cp2k, 'PROJECT-pos-1.dcd')

    # read headers
    hdr_lmp = dcd.read_dcd_header(fn_lmp)
    hdr_cp2k = dcd.read_dcd_header(fn_cp2k)

    print(">>> comparing headers")
    for ref, dct in [(hdr_cp2k_ref, hdr_cp2k), (hdr_lmp_ref, hdr_lmp)]:
        tools.assert_dict_with_all_types_equal(ref,
                                               dct,
                                               keys=list(ref.keys()),
                                               strict=True)

    # compare data read by python (dcd.py) and fortran (dcd.f90, _dcd)
    # implementations
    # cc = cryst_const
    # co = coords
    print(">>> comparing data")
    for fn, convang, nstephdr, nstep, natoms in [
        (fn_lmp, True, True, 101, 16), (fn_lmp, True, False, 101, 16),
        (fn_cp2k, False, False, 16, 57)
    ]:
        cc_py, co_py = dcd.read_dcd_data(fn, convang=convang)
        cc_f, co_f = dcd.read_dcd_data_f(fn,
                                         convang=convang,
                                         nstephdr=nstephdr)
        print(">>> ... cryst_const")
        tools.assert_array_equal(cc_py, cc_f)
        print(">>> ... coords")
        tools.assert_array_equal(co_py, co_f)
        print(">>> ... shapes")
        assert cc_f.shape == (nstep, 6)
        assert co_f.shape == (nstep, natoms, 3)
        # lmp angles are around 60, cp2k around 90 degree, cosines are between
        # -1 and 1, make sure the angle conversion works
        print(">>> ... angles")
        assert (cc_py[:, 3:] > 50).all()

    # compare slow and fast python versions
    # cc = cryst_const
    # co = coords
    print(">>> comparing data")
    for fn, convang, nstep, natoms in [(fn_lmp, True, 101, 16),
                                       (fn_lmp, True, 101, 16),
                                       (fn_cp2k, False, 16, 57)]:
        cc_py_fast, co_py_fast = dcd.read_dcd_data(fn, convang=convang)
        cc_py_ref, co_py_ref = dcd.read_dcd_data_ref(fn, convang=convang)
        print(">>> ... cryst_const")
        tools.assert_array_equal(cc_py_fast, cc_py_ref)
        print(">>> ... coords")
        tools.assert_array_equal(co_py_fast, co_py_ref)
        print(">>> ... shapes")
        assert cc_py_ref.shape == (nstep, 6)
        assert co_py_ref.shape == (nstep, natoms, 3)
        # lmp angles are around 60, cp2k around 90 degree, cosines are between
        # -1 and 1, make sure the angle conversion works
        print(">>> ... angles")
        assert (cc_py_fast[:, 3:] > 50).all()
Пример #10
0
def test_tools():
    x1 = {'a': 3,
          type(1): 'foo',
          'b': {'aa': 1,  
                'bb': np.array([1,2]),
                'cc': {'aaa': np.array([1,2.0]),
                       'bbb': np.array([2,4.0])}}}
    x2 = copy.deepcopy(x1)
    tools.assert_dict_with_all_types_equal(x1, x2)
    tools.assert_all_types_equal(x1, x2)
    
    # not equal array
    x2['b']['cc']['bbb'] *= 2.0
    assert not tools.all_types_equal(x1, x2)
    
    # almost equal array and float
    x2 = copy.deepcopy(x1)
    x2['b']['cc']['bbb'] += 1e-5
    x2['b']['aa'] += 1e-5
    tools.assert_all_types_almost_equal(x1, x2)
    
    # sub-dict different (keys don't match)
    x2 = copy.deepcopy(x1)
    x2['b']['cc']['fff'] = 'extra'
    assert not tools.all_types_equal(x1, x2)
    
    # test only some keys of a dict
    tools.assert_dict_with_all_types_equal({'a':1,'b':1}, {'a':1, 'b':3},
        keys=['a'])

    # simple stuff
    tools.assert_all_types_equal(1, 1)
    tools.assert_all_types_equal(1.0, 1.0)
    tools.assert_all_types_equal(1.0, 1)
    tools.assert_all_types_equal(1, 1.0)
    tools.assert_all_types_equal([1], [1])
    tools.assert_all_types_equal([1], [1.0])
    tools.assert_all_types_equal('a', 'a')
    tools.assert_all_types_almost_equal(1.0, 1.0+1e-5)
    tools.assert_all_types_almost_equal(np.array([1.0]), np.array([1.0+1e-5]))
    assert not tools.all_types_equal(1, 2)
    assert not tools.all_types_equal(1.0, 1.1)
    assert not tools.all_types_equal([1], [1,2])
    assert not tools.all_types_equal('a', 'b')
   
    # different types not allowed if strict=True
    assert not tools.all_types_equal(1.0, 1, strict=True)
    
    # test keys=[...], i.e. ignore some keys in both dicts
    x2 = copy.deepcopy(x1)
    x2['c'] = 1.0
    assert tools.dict_with_all_types_equal(x1, x2, keys=['a','b',type(1)])

    # fail on same array content but different dimensions
    a = np.random.rand(1,2,3)
    b = a[None,...]
    # this is True and IMHO a numpy bug b/c the dimensions are
    # different
    assert (a==b).all()
    # must catch that here
    assert not tools.array_equal(a,b)

    a = np.random.rand(1,2,3)
    b = (a + 1e-8)[None,...]
    assert not (a==b).all() # make sure they are numerically differrent
    assert np.allclose(a,b) # True but should be False
    assert not tools.array_almost_equal(a,b) # ok
Пример #11
0
def test_traj():
    natoms = 10
    nstep = 100
    cell = rand(nstep, 3, 3)
    stress = rand(nstep, 3, 3)
    forces = rand(nstep, natoms, 3)
    etot = rand(nstep)
    cryst_const = crys.cell2cc3d(cell, axis=0)
    coords_frac = rand(nstep, natoms, 3)
    coords = crys.coord_trans3d(coords=coords_frac,
                                old=cell,
                                new=num.extend_array(np.identity(3),
                                                     nstep,
                                                     axis=0),
                                axis=1,
                                timeaxis=0)
    assert cryst_const.shape == (nstep, 6)
    assert coords.shape == (nstep, natoms, 3)
    symbols = ['H'] * natoms

    # automatically calculated:
    #   coords
    #   cell
    #   pressure
    #   velocity (from coords)
    #   temperature (from ekin)
    #   ekin (from velocity)
    traj = Trajectory(
        coords_frac=coords_frac,
        cell=cell,
        symbols=symbols,
        forces=forces,
        stress=stress,
        etot=etot,
        timestep=1,
    )
    # Test if all getters work.
    for name in traj.attr_lst:
        print("test if getters work:", name)
        traj.try_set_attr(name)
        assert getattr(traj, name) is not None, "attr None: %s" % name
        assert eval('traj.get_%s()' %
                    name) is not None, "getter returns None: %s" % name
        print("test if getters work:", name, "... ok")
    aaae(coords_frac, traj.coords_frac)
    aaae(coords, traj.coords)
    aaae(cryst_const, traj.cryst_const)
    aaae(np.trace(stress, axis1=1, axis2=2) / 3.0, traj.pressure)
    assert traj.coords.shape == (nstep, natoms, 3)
    assert traj.cell.shape == (nstep, 3, 3)
    assert traj.velocity.shape == (nstep, natoms, 3)
    assert traj.temperature.shape == (nstep, )
    assert traj.ekin.shape == (nstep, )
    assert traj.nstep == nstep
    assert traj.natoms == natoms

    traj = Trajectory(coords_frac=coords_frac, symbols=symbols, cell=cell)
    aaae(coords, traj.coords)

    # Cell calculated from cryst_const has defined orientation in space which may be
    # different from the original `cell`, but the volume and underlying cryst_const
    # must be the same.
    traj = Trajectory(coords_frac=coords_frac,
                      symbols=symbols,
                      cryst_const=cryst_const)
    np.testing.assert_almost_equal(crys.volume_cell3d(cell),
                                   crys.volume_cell3d(traj.cell))
    aaae(cryst_const, crys.cell2cc3d(traj.cell))

    # extend arrays
    cell2d = rand(3, 3)
    cc2d = crys.cell2cc(cell2d)
    traj = Trajectory(coords_frac=coords_frac, cell=cell2d, symbols=symbols)
    assert traj.cell.shape == (nstep, 3, 3)
    assert traj.cryst_const.shape == (nstep, 6)
    for ii in range(traj.nstep):
        assert (traj.cell[ii, ...] == cell2d).all()
        assert (traj.cryst_const[ii, :] == cc2d).all()

    traj = Trajectory(coords_frac=coords_frac,
                      cryst_const=cc2d,
                      symbols=symbols)
    assert traj.cell.shape == (nstep, 3, 3)
    assert traj.cryst_const.shape == (nstep, 6)
    for ii in range(traj.nstep):
        assert (traj.cryst_const[ii, :] == cc2d).all()

    # units
    traj = Trajectory(coords_frac=coords_frac,
                      cell=cell,
                      symbols=symbols,
                      stress=stress,
                      forces=forces,
                      units={
                          'length': 2,
                          'forces': 3,
                          'stress': 4
                      })
    aaae(2 * coords, traj.coords)
    aaae(3 * forces, traj.forces)
    aaae(4 * stress, traj.stress)

    # iterate, check if Structures are complete
    traj = Trajectory(coords=coords,
                      symbols=symbols,
                      cell=cell,
                      forces=forces,
                      stress=stress,
                      etot=etot,
                      timestep=1.0)
    for struct in traj:
        assert struct.is_struct, "st is not Structure"
        assert not struct.is_traj, "st is Trajectory"
        assert_attrs_not_none(struct)
    struct = traj[0]
    for attr_name in traj.attr_lst:
        if attr_name in struct.attrs_only_traj:
            msg = "tr[0] %s is not None" % attr_name
            assert getattr(struct, attr_name) is None, msg
        else:
            msg = "tr[0] %s is None" % attr_name
            assert getattr(struct, attr_name) is not None, msg

    # slices, return traj
    keys = traj.attr_lst[:]
    tsl = traj[10:80:2]
    assert tsl.nstep == traj.nstep / 2 - 15
    assert_attrs_not_none(tsl, attr_lst=keys)
    tsl = traj[slice(10, 80, 2)]
    assert tsl.nstep == traj.nstep / 2 - 15
    assert_attrs_not_none(tsl, attr_lst=keys)
    tsl = traj[np.s_[10:80:2]]
    assert tsl.nstep == traj.nstep / 2 - 15
    assert_attrs_not_none(tsl, attr_lst=keys)
    assert tsl.is_traj

    # iteration over sliced traj
    tsl = traj[10:80:2]
    for x in tsl:
        pass
    for x in tsl.copy():
        pass

    # repeat iter
    for i in range(2):
        cnt = 0
        for st in traj:
            cnt += 1
        assert cnt == nstep, "%i, %i" % (cnt, nstep)

    # copy
    traj2 = traj.copy()
    for name in traj.attr_lst:
        val = getattr(traj, name)
        if val is not None and not (isinstance(val, int) or \
            isinstance(val, float)):
            val2 = getattr(traj2, name)
            print("test copy:", name, type(val), type(val2))
            assert id(val2) != id(val)
            assert_all_types_equal(val2, val)
    assert_dict_with_all_types_equal(traj.__dict__,
                                     traj2.__dict__,
                                     keys=traj.attr_lst)
Пример #12
0
def test_dcd():
    # nstep = 101
    # natoms = 16
    dir_lmp = tools.unpack_compressed('files/lammps/md-npt.tgz')
    fn_lmp = pj(dir_lmp, 'lmp.out.dcd') 

    # nstep = 16
    # natoms = 57
    dir_cp2k = tools.unpack_compressed('files/cp2k/dcd/npt_dcd.tgz')
    fn_cp2k = pj(dir_cp2k, 'PROJECT-pos-1.dcd')
    
    # read headers
    hdr_lmp = dcd.read_dcd_header(fn_lmp)
    hdr_cp2k = dcd.read_dcd_header(fn_cp2k)
    
    print ">>> comparing headers"
    for ref, dct in [(hdr_cp2k_ref, hdr_cp2k), (hdr_lmp_ref, hdr_lmp)]:
        tools.assert_dict_with_all_types_equal(ref, dct, keys=ref.keys(),
                                               strict=True)
    
    # compare data read by python (dcd.py) and fortran (dcd.f90, _dcd)
    # implementations
    # cc = cryst_const
    # co = coords
    print ">>> comparing data"
    for fn,convang,nstephdr,nstep,natoms in [(fn_lmp,True,True,101,16), 
                                             (fn_lmp,True,False,101,16),
                                             (fn_cp2k,False,False,16,57)]:
        cc_py, co_py = dcd.read_dcd_data(fn, convang=convang)
        cc_f, co_f = dcd.read_dcd_data_f(fn, convang=convang, nstephdr=nstephdr)
        print ">>> ... cryst_const"
        tools.assert_array_equal(cc_py, cc_f)
        print ">>> ... coords"
        tools.assert_array_equal(co_py, co_f)
        print ">>> ... shapes"
        assert cc_f.shape == (nstep,6)
        assert co_f.shape == (nstep,natoms,3)
        # lmp angles are around 60, cp2k around 90 degree, cosines are between
        # -1 and 1, make sure the angle conversion works
        print ">>> ... angles"
        assert (cc_py[:,3:] > 50).all()

    # compare slow and fast python versions
    # cc = cryst_const
    # co = coords
    print ">>> comparing data"
    for fn,convang,nstep,natoms in [(fn_lmp,True,101,16), 
                                    (fn_lmp,True,101,16),
                                    (fn_cp2k,False,16,57)]:
        cc_py_fast, co_py_fast = dcd.read_dcd_data(fn, convang=convang)
        cc_py_ref, co_py_ref = dcd.read_dcd_data_ref(fn, convang=convang)
        print ">>> ... cryst_const"
        tools.assert_array_equal(cc_py_fast, cc_py_ref)
        print ">>> ... coords"
        tools.assert_array_equal(co_py_fast, co_py_ref)
        print ">>> ... shapes"
        assert cc_py_ref.shape == (nstep,6)
        assert co_py_ref.shape == (nstep,natoms,3)
        # lmp angles are around 60, cp2k around 90 degree, cosines are between
        # -1 and 1, make sure the angle conversion works
        print ">>> ... angles"
        assert (cc_py_fast[:,3:] > 50).all()