def chemfile_read(self,filename,format_='LAMMPS Data'):
     data = Trajectory(filename,format=format_)
     frame=data.read()
     topology=frame.topology
     self.numberatom_permole=int(len(frame.atoms)/self.system.Number_Moles)
     self.atoms=frame.atoms
     self.bonds=topology.bonds[0:int(topology.bonds.shape[0]/self.system.Number_Moles)]+1
     self.angles=topology.angles[0:int(topology.angles.shape[0]/self.system.Number_Moles)]+1
     self.dihedrals=topology.dihedrals[0:int(topology.dihedrals.shape[0]/self.system.Number_Moles)]+1
Exemple #2
0
    def test_repr(self):
        with Trajectory(get_data_path("topology.xyz")) as trajectory:
            expected = "Trajectory('" + get_data_path(
                "topology.xyz") + "', 'r', '')"
            self.assertEqual(trajectory.__repr__(), expected)

        with Trajectory(get_data_path("topology.xyz"), "r",
                        "XYZ") as trajectory:
            expected = "Trajectory('" + get_data_path(
                "topology.xyz") + "', 'r', 'XYZ')"
            self.assertEqual(trajectory.__repr__(), expected)

        with Trajectory("test-tmp.xyz", "w") as trajectory:
            self.assertEqual(trajectory.__repr__(),
                             "Trajectory('test-tmp.xyz', 'w', '')")
        os.unlink("test-tmp.xyz")
Exemple #3
0
    def test_errors(self):
        with remove_warnings:
            self.assertRaises(ChemfilesError, Trajectory,
                              get_data_path("not-here.xyz"))
            self.assertRaises(ChemfilesError, Trajectory,
                              get_data_path("empty.unknown"))

            with Trajectory("test-tmp.xyz", "w") as trajectory:
                self.assertRaises(AttributeError, trajectory.write, None)

            os.unlink("test-tmp.xyz")
Exemple #4
0
    def test_indexes(self):
        # Create an input file
        frame = Frame()
        for i in range(120):
            frame.add_atom(Atom('X'), [i % 10, i + 1 % 10, i + 2 % 10])

        with Trajectory("filename.xyz", "w") as file:
            file.write(frame)

        path = os.path.join(ROOT, "..", "examples", "indexes.py")
        # disable output
        exec(open(path).read(), globals(), {'print': lambda _: None})
Exemple #5
0
    def test_select(self):
        # Create an input file
        frame = Frame()
        NAMES = ["N", "Zn", "C", "O"]
        for i in range(120):
            frame.add_atom(Atom(NAMES[i % 4]),
                           [i % 10, i + 1 % 10, i + 2 % 10])

        with Trajectory("input.arc", "w") as file:
            file.write(frame)

        path = os.path.join(ROOT, "..", "examples", "select.py")
        exec(open(path).read(), globals())
Exemple #6
0
    def test_last_error(self):
        chemfiles.misc._clear_errors()
        self.assertEqual(chemfiles.misc._last_error(), "")

        try:
            with remove_warnings:
                Trajectory("noextention")
        except ChemfilesError:
            pass
        self.assertEqual(
            chemfiles.misc._last_error(),
            "file at 'noextention' does not have an extension, provide a "
            "format name to read it",
        )

        chemfiles.misc._clear_errors()
        self.assertEqual(chemfiles.misc._last_error(), "")
Exemple #7
0
    def test_write(self):
        frame = Frame()
        for i in range(4):
            frame.add_atom(Atom("X"), [1, 2, 3])

        with Trajectory("test-tmp.xyz", "w") as fd:
            fd.write(frame)

        expected_content = """4
Written by the chemfiles library
X 1 2 3
X 1 2 3
X 1 2 3
X 1 2 3
"""
        with open("test-tmp.xyz") as fd:
            self.assertEqual(fd.read(), expected_content)

        os.unlink("test-tmp.xyz")
Exemple #8
0
    def test_warning(self):
        def callback(message):
            global LAST_MESSAGE
            LAST_MESSAGE = message

        chemfiles.set_warnings_callback(callback)

        try:
            Trajectory("noextention")
        except ChemfilesError:
            pass

        self.assertEqual(
            LAST_MESSAGE,
            "file at 'noextention' does not have an extension, provide a "
            "format name to read it",
        )

        chemfiles.misc._set_default_warning_callback()
Exemple #9
0
    def test_warning_with_exception(self):
        def callback(message):
            global LAST_MESSAGE
            LAST_MESSAGE = message
            raise Exception("test exception in callback")

        chemfiles.set_warnings_callback(callback)

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            try:
                Trajectory("noextention")
            except ChemfilesError:
                pass

        self.assertEqual(
            LAST_MESSAGE,
            "file at 'noextention' does not have an extension, provide a "
            "format name to read it",
        )

        chemfiles.misc._set_default_warning_callback()
from chemfiles import Trajectory

file = Trajectory("filename.xyz")
frame = file.read()

print("There are {} atoms in the frame".format(len(frame.atoms)))
positions = frame.positions

# Do awesome science here with the positions

if frame.has_velocities():
    velocities = frame.velocities
    # If the file contains information about the
    # velocities, you will find them here.
Exemple #11
0
import numpy as np
import math

from chemfiles import Trajectory, UnitCell, Atom, Topology, Frame, Selection
name = 'nt12-24-full.trj_wrap'  #name of the trajectory wrapped around the nanotube axis
a = 24  #the a box length

# Read the traj
trajectory = Trajectory(name + '.xyz')

# Set the topology
topo = Trajectory("topology.pdb").read()
trajectory.set_topology(topo.topology())

# Select all
selection = Selection("all")

Ral = 6.5

with Trajectory(name + '_flat.xyz', 'w') as output:
    for frame in trajectory:
        nt = selection.evaluate(frame)
        positions = frame.positions()

        for atom in nt:
            x = positions[atom][0]
            y = positions[atom][1]

            r = math.sqrt(x * x + y * y)
            theta = math.atan2(y, x)
Exemple #12
0
# This file is an example for the chemfiles library
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
#!/usr/bin/env python
from chemfiles import Trajectory, Selection

trajectory = Trajectory("input.arc")
output = Trajectory("output.pdb", 'w')

selection = Selection("name Zn or name N")

for frame in trajectory:
    to_remove = selection.evaluate(frame)
    for i in reversed(sorted(to_remove)):
        frame.remove(i)
    output.write(frame)
Exemple #13
0
# Benchmark the parsing of a mmCIF file given as an argument

import sys
import time
from chemfiles import Trajectory

mmcif_filepath = sys.argv[1]

start = time.time()
trajectory = Trajectory(mmcif_filepath, 'r', 'mmCIF')
for frame in trajectory:
    pass
end = time.time()

print(end - start)
Exemple #14
0
 def test_close(self):
     trajectory = Trajectory(get_data_path("water.xyz"))
     trajectory.close()
     self.assertRaises(ChemfilesError, trajectory.read)
Exemple #15
0
from chemfiles import Trajectory, UnitCell, Atom, Topology, Frame, Selection

name = "nt12.opt"
a = 24.2

# Read the frame
frame = Trajectory(name+".xyz").read()

# Set the topology
topo = Trajectory("topology.pdb").read()
frame.set_topology(topo.topology())

# Get the positions
positions = frame.positions()

# Set the cell
cell = UnitCell(a, a, 42.43, 90, 90, 120)
frame.set_cell(cell)

# Select all except hydroxyl groups
#selection = Selection("atoms: name Al or name Obr or name Si")
selection = Selection("atoms: name Hext or name Oext or name Al or name Obr or name Si")
framework = selection.evaluate(frame)

with open(name+".cris",'w') as cris:
    with open(name+".slice.xyz",'w') as slic:
        with open(name+".framework.xyz",'w') as out:
            cris.write(" .false.\n")
            cris.write('{} {} 8.486 90.0 90.0 120.0\n'.format(a, a))
            cris.write('{}\n'.format(len(framework)/5))
 
Exemple #16
0
# Benchmark the parsing of a PDB file given as an argument

import sys
import time
from chemfiles import Trajectory

pdb_filepath = sys.argv[1]

start = time.time()
trajectory = Trajectory(pdb_filepath)
for frame in trajectory:
    pass
end = time.time()

print(end - start)
Exemple #17
0
import numpy as np
import math

from chemfiles import Trajectory, UnitCell, Atom, Topology, Frame, Selection
name='nt12-24-full.trj_wrap'  #name of the trajectory wrapped around the nanotube axis
a=24 #the a box length

# Read the traj
trajectory = Trajectory(name+'.xyz')

# Set the topology
topo = Trajectory("topology.pdb").read()
trajectory.set_topology(topo.topology())

# Select all
selection = Selection("all")

Ral=6.5

with Trajectory(name+'_flat.xyz','w') as output:
    for frame in trajectory:
        nt = selection.evaluate(frame)
        positions = frame.positions()

        for atom in nt:
            x=positions[atom][0]
            y=positions[atom][1]

            r=math.sqrt(x*x+y*y)
            theta=math.atan2(y,x)
Exemple #18
0
#!/usr/bin/env python
import numpy as np
from chemfiles import Topology, Frame, Atom, UnitCell, Trajectory

topology = Topology()
topology.atoms.append(Atom("H"))
topology.atoms.append(Atom("O"))
topology.atoms.append(Atom("H"))

topology.add_bond(0, 1)
topology.add_bond(2, 1)

frame = Frame()
frame.resize(3)
frame.topology = topology

frame.positions[0, :] = np.array([1.0, 0.0, 0.0])
frame.positions[1, :] = np.array([0.0, 0.0, 0.0])
frame.positions[2, :] = np.array([0.0, 1.0, 0.0])

frame.add_atom(Atom("O"), [5.0, 0.0, 0.0])
frame.add_atom(Atom("C"), [6.0, 0.0, 0.0])
frame.add_atom(Atom("O"), [7.0, 0.0, 0.0])
frame.add_bond(3, 4)
frame.add_bond(4, 5)

frame.cell = UnitCell(10, 10, 10)

with Trajectory("water-co2.pdb", 'w') as trajectory:
    trajectory.write(frame)
Exemple #19
0
# This trajectory is an example for the chemtrajectorys library
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
#!/usr/bin/env python
from chemfiles import Trajectory

trajectory = Trajectory("filename.xyz")
frame = trajectory.read()

less_than_five = []
positions = frame.positions()

for i in range(len(frame)):
    if positions[i, 0] < 5:
        less_than_five.append(i)

print("Atoms with x < 5: ")
for i in less_than_five:
    print("  - {}".format(i))
Exemple #20
0
# This trajectory is an example for the chemtrajectorys library
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
#!/usr/bin/env python
from chemfiles import Trajectory

with Trajectory("filename.xyz") as trajectory:
    frame = trajectory.read()

less_than_five = []
for i in range(len(frame.atoms)):
    if frame.positions[i, 0] < 5:
        less_than_five.append(i)

print("Atoms with x < 5: ")
for i in less_than_five:
    print("  - {}".format(i))
Exemple #21
0
from chemfiles import Trajectory, UnitCell, Atom, Topology, Frame, Selection

name = "nt12.opt"
a = 24.2

# Read the frame
frame = Trajectory(name + ".xyz").read()

# Set the topology
topo = Trajectory("topology.pdb").read()
frame.set_topology(topo.topology())

# Get the positions
positions = frame.positions()

# Set the cell
cell = UnitCell(a, a, 42.43, 90, 90, 120)
frame.set_cell(cell)

# Select all except hydroxyl groups
#selection = Selection("atoms: name Al or name Obr or name Si")
selection = Selection(
    "atoms: name Hext or name Oext or name Al or name Obr or name Si")
framework = selection.evaluate(frame)

with open(name + ".cris", 'w') as cris:
    with open(name + ".slice.xyz", 'w') as slic:
        with open(name + ".framework.xyz", 'w') as out:
            cris.write(" .false.\n")
            cris.write('{} {} 8.486 90.0 90.0 120.0\n'.format(a, a))
            cris.write('{}\n'.format(len(framework) / 5))
Exemple #22
0
def parse(filepath):
    t = Trajectory(filepath)
    for _ in range(t.nsteps):
        t.read()
Exemple #23
0
        return 0, 0, 0, 0, 0, 0, 0
    if state == 8:
        return x, y, x, y - 1, x, y, height + 1
    if state == 9:
        return x, y, x + 0.866, y + 0.5, x, y, height + 1
    if state == 10:
        return x, y, x - 0.866, y + 0.5, x, y, height + 1
    if state == 11:
        return x, y, x, y - 1, x + 0.866, y + 0.5, height
    if state == 12:
        return x, y, x - 0.866, y + 0.5, x + 0.866, y + 0.5, height
    if state == 13:
        return x, y, x - 0.866, y + 0.5, x, y - 1, height


with Trajectory('conf.xyz', 'w') as output:
    with open('conf.dat', 'r') as conf:
        ring = 0
        skip = 0
        for line in conf:
            if line.startswith("Step:") and skip % 100 == 0:
                frame = Frame()
                ring = 0
            elif line.startswith("####"):
                if skip % 100 == 0:
                    output.write(frame)
                skip += 1
            elif skip % 100 == 0:
                row = map(int, line.split())
                for column, state in enumerate(row):
                    if state < 7:
Exemple #24
0
    def test_read(self):
        trajectory = Trajectory(get_data_path("water.xyz"))

        self.assertEqual(trajectory.nsteps, 100)
        self.assertEqual(trajectory.path, get_data_path("water.xyz"))

        frame = trajectory.read()
        self.assertEqual(len(frame.atoms), 297)

        self.assertEqual(frame.positions[0].all(),
                         np.array([0.417219, 8.303366, 11.737172]).all())
        self.assertEqual(frame.positions[124].all(),
                         np.array([5.099554, -0.045104, 14.153846]).all())

        self.assertEqual(len(frame.atoms), 297)
        self.assertEqual(frame.atoms[0].name, "O")
        self.assertEqual(frame.atoms[1].name, "H")

        trajectory.set_cell(UnitCell(30, 30, 30))
        frame = trajectory.read_step(41)
        self.assertEqual(frame.cell.lengths, (30.0, 30.0, 30.0))

        self.assertEqual(frame.positions[0].all(),
                         np.array([0.761277, 8.106125, 10.622949]).all())
        self.assertEqual(frame.positions[124].all(),
                         np.array([5.13242, 0.079862, 14.194161]).all())

        self.assertEqual(len(frame.atoms), 297)
        self.assertEqual(frame.topology.bonds_count(), 0)

        frame.guess_bonds()
        self.assertEqual(frame.topology.bonds_count(), 181)
        self.assertEqual(frame.topology.angles_count(), 87)

        topology = Topology()
        for i in range(297):
            topology.atoms.append(Atom("Cs"))

        trajectory.set_topology(topology)
        frame = trajectory.read_step(10)
        self.assertEqual(frame.atoms[10].name, "Cs")

        trajectory.set_topology(get_data_path("topology.xyz"), "XYZ")
        frame = trajectory.read()
        self.assertEqual(frame.atoms[100].name, "Rd")
Exemple #25
0
    def test_read(self):
        trajectory = Trajectory(get_data_path("water.xyz"))

        self.assertEqual(trajectory.nsteps, 100)
        self.assertEqual(trajectory.path, get_data_path("water.xyz"))

        frame = trajectory.read()
        self.assertEqual(len(frame.atoms), 297)

        self.assertEqual(
            frame.positions[0].all(),
            np.array([0.417219, 8.303366, 11.737172]).all()
        )
        self.assertEqual(
            frame.positions[124].all(),
            np.array([5.099554, -0.045104, 14.153846]).all()
        )

        self.assertEqual(len(frame.atoms), 297)
        self.assertEqual(frame.atoms[0].name, "O")
        self.assertEqual(frame.atoms[1].name, "H")

        trajectory.set_cell(UnitCell(30, 30, 30))
        frame = trajectory.read_step(41)
        self.assertEqual(frame.cell.lengths, (30.0, 30.0, 30.0))

        self.assertEqual(
            frame.positions[0].all(),
            np.array([0.761277, 8.106125, 10.622949]).all()
        )
        self.assertEqual(
            frame.positions[124].all(),
            np.array([5.13242, 0.079862, 14.194161]).all()
        )

        self.assertEqual(len(frame.atoms), 297)
        self.assertEqual(frame.topology.bonds_count(), 0)

        frame.guess_bonds()
        self.assertEqual(frame.topology.bonds_count(), 181)
        self.assertEqual(frame.topology.angles_count(), 87)

        topology = Topology()
        for i in range(297):
            topology.atoms.append(Atom("Cs"))

        trajectory.set_topology(topology)
        frame = trajectory.read_step(10)
        self.assertEqual(frame.atoms[10].name, "Cs")

        trajectory.set_topology(get_data_path("topology.xyz"), "XYZ")
        frame = trajectory.read()
        self.assertEqual(frame.atoms[100].name, "Rd")
Exemple #26
0
# Benchmark the counting of alanine residues in a PDB file

import time
from chemfiles import Trajectory, Selection


def count(frame):
    selection = Selection("resname ALA")
    return len(selection.evaluate(frame))


pdb_filepath = "data/1AKE.pdb"
frame = Trajectory(pdb_filepath).read()

start = time.time()
count(frame)
end = time.time()

print(end - start)
Exemple #27
0
 def test_protocols(self):
     with Trajectory(get_data_path("water.xyz")) as trajectory:
         for frame in trajectory:
             self.assertEqual(len(frame.atoms), 297)
Exemple #28
0
 def test_close(self):
     trajectory = Trajectory(get_data_path("water.xyz"))
     trajectory.close()
     self.assertRaises(ChemfilesError, trajectory.read)
Exemple #29
0
import sys
from shared import timeit

from chemfiles import Selection, Trajectory


def distance(f):
    ai = Selection("resid 50").evaluate(f)
    bi = Selection("resid 60").evaluate(f)
    min_dist = float("inf")
    for i in ai:
        for j in bi:
            d = f.distance(i, j)
            if d < min_dist:
                min_dist = d


pdbfile = sys.argv[1]
repeats = int(sys.argv[2])

f = Trajectory(pdbfile).read()

print(timeit(distance, f, repeats=repeats))
Exemple #30
0
# Benchmark the parsing of a MMTF file given as an argument

import sys
import time
from chemfiles import Trajectory

mmtf_filepath = sys.argv[1]

start = time.time()
trajectory = Trajectory(mmtf_filepath)
for frame in trajectory:
    pass
end = time.time()

print(end - start)
Exemple #31
0
import numpy as np
from chemfiles import Topology, Frame, Atom, UnitCell, Trajectory

topology = Topology()
topology.add_atom(Atom("H"))
topology.add_atom(Atom("O"))
topology.add_atom(Atom("H"))

topology.add_bond(0, 1)
topology.add_bond(2, 1)

frame = Frame()
frame.resize(3)
frame.set_topology(topology)

positions = frame.positions()
positions[0, :] = np.array([1.0, 0.0, 0.0])
positions[1, :] = np.array([0.0, 0.0, 0.0])
positions[2, :] = np.array([0.0, 1.0, 0.0])

frame.add_atom(Atom("O"), [5.0, 0.0, 0.0])
frame.add_atom(Atom("C"), [6.0, 0.0, 0.0])
frame.add_atom(Atom("O"), [7.0, 0.0, 0.0])
frame.add_bond(3, 4)
frame.add_bond(4, 5)

frame.set_cell(UnitCell(10, 10, 10))

trajectory = Trajectory("water-co2.pdb", 'w')
trajectory.write(frame)
Exemple #32
0
# This file is an example for the chemfiles library
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
#!/usr/bin/env python
from chemfiles import Trajectory, Selection

trajectory = Trajectory("input.arc")
output = Trajectory("output.pdb", 'w')

selection = Selection("name Zn or name N")

for frame in trajectory:
    to_remove = selection.evaluate(frame)
    for i in reversed(sorted(to_remove)):
        frame.remove(i)
    output.write(frame)

trajectory.close()
output.close()