コード例 #1
0
def main(filename, imode, omode):

    ipos = open(filename, "r")
    ifr = 0

    # extracts the dimension, its units and the cell_units from the first frame
    ret = read_file_raw(imode, ipos)
    ipos.close()
    comment = ret["comment"]
    cell_units = get_cell_units(comment, imode)
    key, dim, dim_units = get_key_dim_units(comment, imode)

    ipos = open(filename, "r")
    while True:
        try:
            ret = read_file(imode, ipos)
            pos = ret["atoms"]
            cell = ret["cell"]

        except EOFError:  # finished reading files
            sys.exit(0)
        print_file(
            omode,
            pos,
            cell,
            filedesc=sys.stdout,
            title="",
            key=key,
            dimension=dim,
            units=dim_units,
            cell_units=cell_units,
        )
        ifr += 1
コード例 #2
0
def main(fns_in, fn_out, begin, end, stride):

    verbosity.level = "low"
    print('Multiplexing {:d} beads into one trajectory.'.format(len(fns_in)))
    print()

    print('input file names:')
    for fn in fns_in:
        print(fn)
    print()

    print('output file name:', fn_out)
    print()

    # Open input trajectory iterators.
    trjs_in = [iter_file_name(fn) for fn in fns_in]

    # Open output file.
    f_out = open_backup(fn_out, 'w')
    mode_out = os.path.splitext(fn_out)[1]

    # Loop over all frames.
    i_frame = 0
    i_frame_saved = 0
    while True:

        # Check the endpoint index, exit if we're done.
        if (end > -1) and (i_frame >= end):
            break

        # Should we save output from this frame?
        do_output = (i_frame >= begin) and ((i_frame % stride) == 0)

        try:
            # Get the frames from all trajectories...
            for trj in trjs_in:
                frame = trj.next()
                # ... and possibly save them in the output trajectory.
                if do_output:
                    print_file(mode_out, frame['atoms'], frame['cell'], f_out)
            if do_output:
                i_frame_saved += 1
        except StopIteration:
            # Stop when any of the trajectories runs out of frames.
            break

        # Count frames and print information on progress.
        i_frame += 1
        if i_frame % 100 == 0:
            print('\rframe {:d}'.format(i_frame), end='')
        sys.stdout.flush()

    f_out.close()

    print()
    print()
    print('Loaded {:d} frames.'.format(i_frame))
    print('Saved {:d} frames.'.format(i_frame_saved))
コード例 #3
0
def test_print_xyz():
    """Tests that xyz files are printed correctly."""

    with open(local("test.pos_0.xyz"), "r") as f:
        with open(local("test.pos_1.xyz"), "w") as out:
            for num, ret in enumerate(iter_file("xyz", f)):
                atoms = ret["atoms"]
                assert len(atoms) == 3
                assert_equal(pos_xyz * (num + 1), atoms.q)
                print_file("xyz", atoms, ret["cell"], filedesc=out)

    assert filecmp.cmp(local("test.pos_0.xyz"), local("test.pos_1.xyz"))
    os.unlink(local("test.pos_1.xyz"))
コード例 #4
0
ファイル: test_io.py プロジェクト: epfl-cosmo/i-pi-dev
def test_print_xyz():
    """Tests that xyz files are printed correctly."""

    with open(local("test.pos_0.xyz"), "r") as f:
        with open(local("test.pos_1.xyz"), "w") as out:
            for num, ret in enumerate(iter_file("xyz", f)):
                atoms = ret["atoms"]
                assert len(atoms) == 3
                assert_equal(pos_xyz * (num + 1), atoms.q)
                print_file("xyz", atoms, ret["cell"], filedesc=out)

    assert filecmp.cmp(local("test.pos_0.xyz"), local("test.pos_1.xyz"))
    os.unlink(local("test.pos_1.xyz"))
コード例 #5
0
def main(filename, natoms):

    ipos = open(filename, "r")
    imode = filename[-3:]
    natoms = int(natoms)

    ifr = 0
    nn = 2.5
    while True:
        try:
            ret = read_file(imode, ipos, readcell=True)
            pos = ret["atoms"]
            cell = ret["cell"]
            q = depstrip(pos.q).copy()
            cell.array_pbc(q)

            natin = pos.natoms
            q.shape = (natin, 3)
            s = np.dot(depstrip(cell.ih), q.T).T

            # now replicate in scaled coordinates
            nrep = int((natoms / natin * nn)**(1. / 3.))

            natrep = natin * (2 * nrep + 1)**3

            ns = np.zeros((natrep, 3))
            ik = 0
            for ix in range(-nrep, nrep + 1):
                for iy in range(-nrep, nrep + 1):
                    for iz in range(-nrep, nrep + 1):
                        for i in range(natin):
                            ns[ik] = s[i] + [ix, iy, iz]
                            ik += 1

            ns = np.dot(depstrip(cell.h), ns.T).T

            # now removes atoms until we only have natoms
            d = np.zeros(natrep)
            for i in range(natrep):
                d[i] = np.sqrt(np.dot(ns[i], ns[i]))
            di = np.argsort(d)

            npos = Atoms(natoms)
            for i in range(natoms):
                npos.q[3 * i:3 * (i + 1)] = ns[di[i]]

        except EOFError:  # finished reading files
            sys.exit(0)

        print_file("pdb", npos, cell)
        ifr += 1
コード例 #6
0
ファイル: mkball.py プロジェクト: albapa/glosim
def main(filename, natoms):

   ipos=open(filename,"r")
   imode=filename[-3:]
   natoms = int(natoms)
   
   ifr = 0
   nn = 2.5
   while True:
      try:
         ret = read_file(imode,ipos,readcell=True)
         pos = ret["atoms"]
         cell = ret["cell"]
         q=depstrip(pos.q).copy()
         cell.array_pbc(q)
         
         natin = pos.natoms
         q.shape=(natin,3)
         s=np.dot(depstrip(cell.ih),q.T).T
         
         # now replicate in scaled coordinates
         nrep  = int((natoms/natin*nn)**(1./3.))
         
         natrep = natin*(2*nrep+1)**3
         
         ns = np.zeros((natrep,3))
         ik = 0
         for ix in range(-nrep,nrep+1):
          for iy in range(-nrep,nrep+1):
		   for iz in range(-nrep,nrep+1):
			for i in range(natin):
			 ns[ik] = s[i]+[ix,iy,iz]
			 ik+=1
		
         ns = np.dot(depstrip(cell.h),ns.T).T          
         
         # now removes atoms until we only have natoms
         d = np.zeros(natrep)
         for i in range(natrep):
           d[i] = np.sqrt(np.dot(ns[i],ns[i]))
         di = np.argsort(d)
		 
         npos = Atoms(natoms)
         for i in range(natoms):           
           npos.q[3*i:3*(i+1)]=ns[di[i]]
         
      except EOFError: # finished reading files
         sys.exit(0)

      print_file("pdb",npos, cell)
      ifr+=1
コード例 #7
0
ファイル: bin2xyz.py プロジェクト: mahrossi/i-pi
def main(filename):

    ipos = open(filename, "rb")

    ifr = 0
    while True:
        try:
            ret = read_file("bin", ipos)
            pos = ret["atoms"]
            cell = ret["cell"]
            cell.array_pbc(pos.q)
        except EOFError:  # finished reading files
            sys.exit(0)

        print_file("xyz", pos, cell)
        ifr += 1
コード例 #8
0
ファイル: xyz2bin.py プロジェクト: epfl-cosmo/i-pi-dev
def main(filename):

    ipos = open(filename, "r")

    natoms = 0
    ifr = 0
    while True:
        try:
            ret = read_file("xyz", ipos)
            pos = ret["atoms"]
            cell = ret["cell"]
            cell.array_pbc(pos.q)
        except EOFError:  # finished reading files
            sys.exit(0)

        print_file("bin", pos, cell)
        ifr += 1
コード例 #9
0
def main(filename, wrap=True):

    ipos = open(filename, "r")
    if (wrap == "False"):
        wrap = False

    natoms = 0
    ifr = 0
    while True:
        try:
            ret = read_file("xyz", ipos, readcell=True)
            pos = ret["atoms"]
            cell = ret["cell"]
            if (wrap): cell.array_pbc(pos.q)
        except EOFError:  # finished reading files
            sys.exit(0)

        print_file("pdb", pos, cell)
        ifr += 1
コード例 #10
0
ファイル: xyz2pdb.py プロジェクト: epfl-cosmo/i-pi-dev
def main(filename, wrap=True):

    ipos = open(filename, "r")
    if(wrap == "False"):
        wrap = False

    natoms = 0
    ifr = 0
    while True:
        try:
            ret = read_file("xyz", ipos)
            pos = ret["atoms"]
            cell = ret["cell"]
            if(wrap): cell.array_pbc(pos.q)
        except EOFError:  # finished reading files
            sys.exit(0)

        print_file("pdb", pos, cell)
        ifr += 1
コード例 #11
0
ファイル: al6xxx_kmc.py プロジェクト: kzinovjev/i-pi
    def ts_thread(self, ieval, ostr, nstr, nevent, setfev=1):
        # computes TS energy by linearly interpolating initial & final state
        # interpolates between two structures considering PBCs
        qstart = self.qcache[ostr]
        qend = self.qcache[nstr].copy()
        # finds atom matching assuming initial and final states differ only by a vacancy swap and are based on unique_idx lists
        midx = self.unique_idx_match(list(ostr), list(nstr))[0:self.natoms]
        qend.shape = (self.natoms, 3)
        qend[:] = qend[midx]
        qend.shape = (3*self.natoms)

        qts = qend - qstart
        self.dcell.array_pbc(qts) # use pbc!
        qts *= 0.5
        qts += qstart
        self.dbeads[ieval].q[0,:] = qts

        tspot = self.dforces[ieval].pot
        io.print_file("xyz", self.beads[0], self.dcell, self.tslist, title=("START  "  ), key="positions", dimension="length", units="angstrom", cell_units="angstrom" )
        io.print_file("xyz", self.dbeads[ieval][0], self.dcell, self.tslist, title=("TS: %s %s  Energy: %15.8e  %15.8e " % (ostr, nstr, tspot, tspot-self.forces.pot) ), key="positions", dimension="length", units="angstrom", cell_units="angstrom" )
        self.dbeads[ieval].q[0] = qend
        io.print_file("xyz", self.dbeads[ieval][0], self.dcell, self.tslist, title=("END  "  ), key="positions", dimension="length", units="angstrom", cell_units="angstrom" )
        self.tslist.flush()

        with self._threadlock:
            # sets the tscache for both FW and BW transition (uses a dictionary to be super-safe and lazy, although of course this could be just a list)
            self.tscache[ostr][nstr] = tspot
            if not nstr in self.tscache: self.tscache[nstr]  = {}
            self.tscache[nstr][ostr] = tspot
            self.feval[ieval] = 1
            nevent[4] = tspot
コード例 #12
0
    def write_traj(self, data, what, stream, b=0, format="xyz", dimension="", units="automatic", cell_units="automatic", flush=True):
        """Prints out a frame of a trajectory for the specified quantity and bead.

        Args:
           what: A string specifying what to print.
           b: The bead index. Defaults to 0.
           stream: A reference to the stream on which data will be printed.
           format: The output file format.
           cell_units: The units used to specify the cell parameters.
           flush: A boolean which specifies whether to flush the output buffer
              after each write to file or not.
        """

        key = getkey(what)
        if key in ["extras"]:
            stream.write(" #*EXTRAS*# Step:  %10d  Bead:  %5d  \n" % (self.system.simul.step + 1, b))
            stream.write(data[b])
            stream.write("\n")
            if flush:
                stream.flush()
                os.fsync(stream)
            return
        elif getkey(what) in ["positions", "velocities", "forces", "forces_sc", "momenta"]:
            fatom = Atoms(self.system.beads.natoms)
            fatom.names[:] = self.system.beads.names
            fatom.q[:] = data[b]
        else:
            fatom = Atoms(self.system.beads.natoms)
            fatom.names[:] = self.system.beads.names
            fatom.q[:] = data

        fcell = Cell()
        fcell.h = self.system.cell.h

        if units == "": units = "automatic"
        if cell_units == "": cell_units = "automatic"
        io.print_file(format, fatom, fcell, stream, title=("Step:  %10d  Bead:   %5d " % (self.system.simul.step + 1, b)), key=key, dimension=dimension, units=units, cell_units=cell_units)
        if flush:
            stream.flush()
            os.fsync(stream)
コード例 #13
0
ファイル: a2b.py プロジェクト: epfl-cosmo/i-pi-dev
def main(filename, imode, omode):

    ipos = open(filename, "r")
    natoms = 0
    ifr = 0

    # extracts the dimension, its units and the cell_units from the first frame
    ret = read_file_raw(imode, ipos)
    ipos.close()
    comment = ret['comment']
    cell_units = get_cell_units(comment, imode)
    key, dim, dim_units = get_key_dim_units(comment, imode)

    ipos = open(filename, "r")
    while True:
        try:
            ret = read_file(imode, ipos)
            pos = ret["atoms"]
            cell = ret["cell"]

        except EOFError:  # finished reading files
            sys.exit(0)
        print_file(omode, pos, cell, filedesc=sys.stdout, title="", key=key, dimension=dim, units=dim_units, cell_units=cell_units)
        ifr += 1
コード例 #14
0
def contract_trajectory(fns_in, fn_out_template, n_new, cell_units_in,
                        cell_units_out):

    verbosity.level = "low"
    n = len(fns_in)

    # Generate output file names.
    if n_new == 1:
        fns_out = [fn_out_template]
    else:
        fns_out = [fn_out_template.format(i) for i in range(n_new)]

    print("Contracting {:d} beads to {:d} beads.".format(n, n_new))
    print()

    print("input file names:")
    for fn in fns_in:
        print(fn)
    print()

    print("output file names:")
    for fn in fns_out:
        print(fn)
    print()

    # Open input trajectory iterators.
    trjs_in = [iter_file_name_raw(fn) for fn in fns_in]
    mode = os.path.splitext(fn)[-1]

    # Open output files.
    fs_out = [open_backup(fn, "w") for fn in fns_out]
    mode_out = os.path.splitext(fn_out_template)[-1]

    # prepare ring polymer rescaler
    rescale = nm_rescale(n, n_new)

    # Loop over all frames.
    i_frame = 0
    while True:
        try:
            # Get the frames for all beads.
            frames = [trj.next() for trj in trjs_in]
        except StopIteration:
            # Stop when any of the trajectories runs out of frames.
            break

        # gets units from first frame
        dimension, units, cell_units = auto_units(comment=frames[0]["comment"],
                                                  cell_units=cell_units_in)
        if cell_units_out == "automatic":
            cell_units_out = cell_units  # re-use units unless otherwise specified

        # Consistency check.
        h = frames[0]["cell"]
        natoms = len(frames[0]["data"]) / 3
        for i in range(n):

            # Check that all the cells are the same.
            if (frames[i]["cell"] != h).any():
                msg = "Cell for beads {:d} and {:d} differ in frame {:d}."
                raise ValueError(msg.format(0, i, i_frame))

            # Check that the numbers of atoms are the same.
            if len(frames[i]["data"]) != 3 * natoms:
                msg = "Different numbers of atoms for beads {:d} and {:d} in frame {:d}."
                raise ValueError(msg.format(0, i, i_frame))

        cell = Cell()
        cell.h = frames[0]["cell"]
        atoms = Atoms(natoms)
        atoms.names = frames[0]["names"]

        # Compose the ring polymer.
        q = np.vstack([frame["data"] for frame in frames]) * unit_to_internal(
            dimension, units, 1)  # units transformation

        # Contract the coordinates to `n_new` beads.
        q_c = rescale.b1tob2(q)

        # Save the output data.
        for i, f_out in enumerate(fs_out):
            atoms.q = q_c[i, :]
            print_file(mode_out,
                       atoms,
                       cell,
                       f_out,
                       dimension=dimension,
                       units=units,
                       cell_units=cell_units_out)

        # Count frames and print information on progress.
        i_frame += 1
        if i_frame % 100 == 0:
            print("\rframe {:d}".format(i_frame), end="")
        sys.stdout.flush()

    for f_out in fs_out:
        f_out.close()

    print()
    print()
    print("Processed {:d} frames.".format(i_frame))
コード例 #15
0
ファイル: mux-positions.py プロジェクト: i-pi/i-pi
def main(fns_in, fn_out, begin, end, stride, wrap, unwrap):

    verbosity.level = "low"
    print('Multiplexing {:d} beads into one trajectory.'.format(len(fns_in)))
    print()

    print('input file names:')
    for fn in fns_in:
        print(fn)
    print()

    print('output file name:', fn_out)
    print()

    # Open input trajectory iterators.
    trjs_in = [iter_file_name_raw(fn) for fn in fns_in]
    mode = os.path.splitext(fns_in[0])[-1]

    # Open output file.
    f_out = open_backup(fn_out, 'w')
    mode_out = os.path.splitext(fn_out)[-1]

    # Loop over all frames.
    i_frame = 0
    i_frame_saved = 0

    # There can be multiple trajectories, so we store a frame_last for each trajectory
    frame_last = [None] * len(fns_in)

    while True:

        # Check the endpoint index, exit if we're done.
        if (end > -1) and (i_frame >= end):
            break

        # Should we save output from this frame?
        do_output = (i_frame >= begin) and ((i_frame % stride) == 0)

        try:
            # Get the frames from all trajectories...
            for idx,trj in enumerate(trjs_in):
                frame = trj.next()

                # gets units from first frame
                dimension, units, cell_units = auto_units(comment=frame["comment"])
                frame = process_units(dimension=dimension, units=units, cell_units=cell_units, mode=mode, **frame)

                if wrap:
                    frame = wrap_positions(frame)
                if unwrap:
                    frame = unwrap_positions(frame,frame_last[idx])

                frame_last[idx] = frame.copy()


                # ... and possibly save them in the output trajectory.
                if do_output:
                    print_file(mode_out, frame['atoms'], frame['cell'], f_out, dimension=dimension, units=units, cell_units=cell_units)
            if do_output:
                i_frame_saved += 1
        except StopIteration:
            # Stop when any of the trajectories runs out of frames.
            break

        # Count frames and print information on progress.
        i_frame += 1
        if i_frame % 100 == 0:
            print('\rframe {:d}'.format(i_frame), end='')
        sys.stdout.flush()

    f_out.close()

    print()
    print()
    print('Loaded {:d} frames.'.format(i_frame))
    print('Saved {:d} frames.'.format(i_frame_saved))
コード例 #16
0
ファイル: contract-trajectory.py プロジェクト: i-pi/i-pi
def contract_trajectory(fns_in, fn_out_template, n_new, cell_units_in, cell_units_out):

    verbosity.level = "low"
    n = len(fns_in)

    # Generate output file names.
    if n_new == 1:
        fns_out = [fn_out_template]
    else:
        fns_out = [fn_out_template.format(i) for i in range(n_new)]

    print("Contracting {:d} beads to {:d} beads.".format(n, n_new))
    print()

    print("input file names:")
    for fn in fns_in:
        print(fn)
    print()

    print("output file names:")
    for fn in fns_out:
        print(fn)
    print()

    # Open input trajectory iterators.
    trjs_in = [iter_file_name_raw(fn) for fn in fns_in]
    mode = os.path.splitext(fn)[-1]

    # Open output files.
    fs_out = [open_backup(fn, "w") for fn in fns_out]
    mode_out = os.path.splitext(fn_out_template)[-1]

    # prepare ring polymer rescaler
    rescale = nm_rescale(n, n_new)

    # Loop over all frames.
    i_frame = 0
    while True:
        try:
            # Get the frames for all beads.
            frames = [trj.next() for trj in trjs_in]
        except StopIteration:
            # Stop when any of the trajectories runs out of frames.
            break

        # gets units from first frame
        dimension, units, cell_units = auto_units(comment=frames[0]["comment"], cell_units=cell_units_in)
        if cell_units_out == "automatic": cell_units_out = cell_units  # re-use units unless otherwise specified

        # Consistency check.
        h = frames[0]["cell"]
        natoms = len(frames[0]["data"]) / 3
        for i in range(n):

            # Check that all the cells are the same.
            if (frames[i]["cell"] != h).any():
                msg = "Cell for beads {:d} and {:d} differ in frame {:d}."
                raise ValueError(msg.format(0, i, i_frame))

            # Check that the numbers of atoms are the same.
            if len(frames[i]["data"]) != 3 * natoms:
                msg = "Different numbers of atoms for beads {:d} and {:d} in frame {:d}."
                raise ValueError(msg.format(0, i, i_frame))

        cell = Cell()
        cell.h = frames[0]["cell"]
        atoms = Atoms(natoms)
        atoms.names = frames[0]["names"]

        # Compose the ring polymer.
        q = np.vstack([frame["data"] for frame in frames]) * unit_to_internal(dimension, units, 1)  # units transformation

        # Contract the coordinates to `n_new` beads.
        q_c = rescale.b1tob2(q)

        # Save the output data.
        for i, f_out in enumerate(fs_out):
            atoms.q = q_c[i, :]
            print_file(mode_out, atoms, cell, f_out, dimension=dimension, units=units, cell_units=cell_units_out)

        # Count frames and print information on progress.
        i_frame += 1
        if i_frame % 100 == 0:
            print("\rframe {:d}".format(i_frame), end="")
        sys.stdout.flush()

    for f_out in fs_out:
        f_out.close()

    print()
    print()
    print("Processed {:d} frames.".format(i_frame))
コード例 #17
0
    print 'We will expand the ring polymer to get a half polymer of %i beads.' % nbeadsNew

    # Compose the full ring polymer.
    #q2 = np.concatenate((q, np.flipud(q)), axis=0)

    # Make the rpc step
    #rpc = nm_rescale(2 * nbeads, 2 * nbeadsNew)
    #new_q = rpc.b1tob2(q2)[0:nbeadsNew]
    rpc = nm_rescale(nbeads, nbeadsNew, np.asarray(range(natoms)))  # We use open path RPC
    new_q = rpc.b1tob2(q)

    # Print
    out = open("NEW_INSTANTON.xyz", "w")
    for i in range(nbeadsNew):
        atom.q = new_q[i] / unit_to_internal("length", "angstrom", 1.0)  # Go back to angstrom
        print_file("xyz", atom, cell, out, title='cell{atomic_unit}  Traj: positions{angstrom}')
        # print_file("xyz",pos[0],cell,out,title='cell  }')
    out.close()

    print 'The new Instanton geometry (half polymer) was generated'
    print 'Check NEW_INSTANTON.xyz'
    print ''
    print 'Remeber to change the number of beads (%i) in your input' % nbeadsNew
    print ''

if input_hess != 'None' or chk != 'None':

    if manual:
        if (os.path.exists(input_hess)):
            hess = open(input_hess, "r")
        else:
コード例 #18
0
def main(fns_in, fn_out, begin, end, stride, wrap, unwrap):

    verbosity.level = "low"
    print('Multiplexing {:d} beads into one trajectory.'.format(len(fns_in)))
    print()

    print('input file names:')
    for fn in fns_in:
        print(fn)
    print()

    print('output file name:', fn_out)
    print()

    # Open input trajectory iterators.
    trjs_in = [iter_file_name_raw(fn) for fn in fns_in]
    mode = os.path.splitext(fns_in[0])[-1]

    # Open output file.
    f_out = open_backup(fn_out, 'w')
    mode_out = os.path.splitext(fn_out)[-1]

    # Loop over all frames.
    i_frame = 0
    i_frame_saved = 0

    # There can be multiple trajectories, so we store a frame_last for each trajectory
    frame_last = [None] * len(fns_in)

    while True:

        # Check the endpoint index, exit if we're done.
        if (end > -1) and (i_frame >= end):
            break

        # Should we save output from this frame?
        do_output = (i_frame >= begin) and ((i_frame % stride) == 0)

        try:
            # Get the frames from all trajectories...
            for idx, trj in enumerate(trjs_in):
                frame = next(trj)

                # gets units from first frame
                dimension, units, cell_units = auto_units(
                    comment=frame["comment"])
                frame = process_units(dimension=dimension,
                                      units=units,
                                      cell_units=cell_units,
                                      mode=mode,
                                      **frame)

                if wrap:
                    frame = wrap_positions(frame)
                if unwrap:
                    frame = unwrap_positions(frame, frame_last[idx])

                frame_last[idx] = frame.copy()

                # ... and possibly save them in the output trajectory.
                if do_output:
                    print_file(mode_out,
                               frame['atoms'],
                               frame['cell'],
                               f_out,
                               dimension=dimension,
                               units=units,
                               cell_units=cell_units)
            if do_output:
                i_frame_saved += 1
        except StopIteration:
            # Stop when any of the trajectories runs out of frames.
            break

        # Count frames and print information on progress.
        i_frame += 1
        if i_frame % 100 == 0:
            print('\rframe {:d}'.format(i_frame), end='')
        sys.stdout.flush()

    f_out.close()

    print()
    print()
    print('Loaded {:d} frames.'.format(i_frame))
    print('Saved {:d} frames.'.format(i_frame_saved))
コード例 #19
0
    def write_traj(
        self,
        data,
        what,
        stream,
        b=0,
        format="xyz",
        dimension="",
        units="automatic",
        cell_units="automatic",
        flush=True,
    ):
        """Prints out a frame of a trajectory for the specified quantity and bead.

        Args:
           what: A string specifying what to print.
           b: The bead index. Defaults to 0.
           stream: A reference to the stream on which data will be printed.
           format: The output file format.
           cell_units: The units used to specify the cell parameters.
           flush: A boolean which specifies whether to flush the output buffer
              after each write to file or not.
        """

        key = getkey(what)
        if key in ["extras", "extras_component"]:
            stream.write(" #*EXTRAS*# Step:  %10d  Bead:  %5d  \n" %
                         (self.system.simul.step + 1, b))
            if self.extra_type in data:
                if np.array(data[self.extra_type][b]).ndim == 2:
                    stream.write("\n".join([
                        "      ".join(
                            ["{:15.8f}".format(item) for item in row])
                        for row in data[self.extra_type][b]
                    ]))
                elif np.array(data[self.extra_type][b]).ndim == 1:
                    stream.write("      ".join(
                        "%15.8f" % el
                        for el in np.asarray(data[self.extra_type][b])))
                else:
                    stream.write("%s" % data[self.extra_type][b])
                stream.write("\n")
            else:
                raise KeyError(
                    "Extra type '" + self.extra_type +
                    "' is not among the quantities returned by any of the forcefields."
                )
            if flush:
                stream.flush()
                os.fsync(stream)
            return
        elif getkey(what) in [
                "positions",
                "velocities",
                "forces",
                "forces_sc",
                "momenta",
        ]:
            fatom = Atoms(self.system.beads.natoms)
            fatom.names[:] = self.system.beads.names
            fatom.q[:] = data[b]
        else:
            fatom = Atoms(self.system.beads.natoms)
            fatom.names[:] = self.system.beads.names
            fatom.q[:] = data

        fcell = Cell()
        fcell.h = self.system.cell.h

        if units == "":
            units = "automatic"
        if cell_units == "":
            cell_units = "automatic"
        io.print_file(
            format,
            fatom,
            fcell,
            stream,
            title=("Step:  %10d  Bead:   %5d " %
                   (self.system.simul.step + 1, b)),
            key=key,
            dimension=dimension,
            units=units,
            cell_units=cell_units,
        )
        if flush:
            stream.flush()
            os.fsync(stream)
コード例 #20
0
    # Make the rpc step
    #rpc = nm_rescale(2 * nbeads, 2 * nbeadsNew)
    #new_q = rpc.b1tob2(q2)[0:nbeadsNew]
    rpc = nm_rescale(nbeads, nbeadsNew,
                     np.asarray(range(natoms)))  # We use open path RPC
    new_q = rpc.b1tob2(q)

    # Print
    out = open("NEW_INSTANTON.xyz", "w")
    for i in range(nbeadsNew):
        atom.q = new_q[i] / unit_to_internal("length", "angstrom",
                                             1.0)  # Go back to angstrom
        print_file("xyz",
                   atom,
                   cell,
                   out,
                   title='cell{atomic_unit}  Traj: positions{angstrom}')
        # print_file("xyz",pos[0],cell,out,title='cell  }')
    out.close()

    print 'The new Instanton geometry (half polymer) was generated'
    print 'Check NEW_INSTANTON.xyz'
    print ''
    print 'Remeber to change the number of beads (%i) in your input' % nbeadsNew
    print ''

if input_hess != 'None' or chk != 'None':

    if manual:
        if (os.path.exists(input_hess)):
コード例 #21
0
def contract_trajectory(fns_in, fn_out_template, n_new):

    n = len(fns_in)

    # Generate output file names.
    if n_new == 1:
        fns_out = [fn_out_template]
    else:
        fns_out = [fn_out_template.format(i) for i in range(n_new)]

    print "Contracting {:d} beads to {:d} beads.".format(n, n_new)
    print

    print "input file names:"
    for fn in fns_in:
        print fn
    print

    print "output file names:"
    for fn in fns_out:
        print fn
    print

    # Open input trajectory iterators.
    trjs_in = [iter_file_name(fn) for fn in fns_in]

    # Open output files.
    fs_out = [open_backup(fn, "w") for fn in fns_out]
    mode_out = os.path.splitext(fn_out_template)[1]

    # prepare ring polymer rescaler
    rescale = nm_rescale(n, n_new)

    # Loop over all frames.
    i_frame = 0
    while True:

        try:
            # Get the frames for all beads.
            frames = [trj.next() for trj in trjs_in]
        except StopIteration:
            # Stop when any of the trajectories runs out of frames.
            break

        # Consistency check.
        h = frames[0]["cell"].h
        natoms = frames[0]["atoms"].natoms
        for i in range(n):

            # Check that all the cells are the same.
            if (frames[i]["cell"].h != h).any():
                msg = "Cell for beads {:d} and {:d} differ in frame {:d}."
                raise ValueError(msg.format(0, i, i_frame))

            # Check that the numbers of atoms are the same.
            if frames[i]["atoms"].natoms != natoms:
                msg = "Different numbers fo atoms for beads {:d} and {:d} in frame {:d}."
                raise ValueError(msg.format(0, i, i_frame))

        # Reuse the first frame for output.
        cell = frames[0]["cell"]
        atoms = frames[0]["atoms"]

        # Compose the ring polymer.
        q = np.vstack([frame["atoms"].q for frame in frames])

        # Contract the coordinates to `n_new` beads.
        q_c = rescale.b1tob2(q)

        # Save the output data.
        for i, f_out in enumerate(fs_out):
            atoms.q = q_c[i, :]
            print_file(mode_out, atoms, cell, f_out)

        # Count frames and print information on progress.
        i_frame += 1
        if i_frame % 100 == 0:
            print "\rframe {:d}".format(i_frame),
        sys.stdout.flush()

    for f_out in fs_out:
        f_out.close()

    print
    print
    print "Processed {:d} frames.".format(i_frame)
コード例 #22
0
ファイル: outputs.py プロジェクト: eljost/i-pi
    def write_traj(
        self,
        data,
        what,
        stream,
        b=0,
        format="xyz",
        dimension="",
        units="automatic",
        cell_units="automatic",
        flush=True,
    ):
        """Prints out a frame of a trajectory for the specified quantity and bead.

        Args:
           what: A string specifying what to print.
           b: The bead index. Defaults to 0.
           stream: A reference to the stream on which data will be printed.
           format: The output file format.
           cell_units: The units used to specify the cell parameters.
           flush: A boolean which specifies whether to flush the output buffer
              after each write to file or not.
        """

        key = getkey(what)
        if key in ["extras"]:
            stream.write(" #*EXTRAS*# Step:  %10d  Bead:  %5d  \n" %
                         (self.system.simul.step + 1, b))
            try:
                index = 0
                for el, item in enumerate(data):
                    if self.xtratype in item[b].keys():
                        index = el
                    try:
                        if self.xtratype == "friction":
                            fatom = Atoms(self.system.beads.natoms)
                            fatom.names[:] = self.system.beads.names
                            stream.write("#     %s\n" %
                                         "      ".join("%15s" % el for el in [
                                             "xx",
                                             "yy",
                                             "zz",
                                             "xy=yx",
                                             "xz=zx",
                                             "yz=zy",
                                         ]))
                            for na in range(self.system.beads.natoms):
                                stream.write("%3s      %s\n" % (
                                    fatom.names[na],
                                    "      ".join(
                                        "%15.8f" % el for el in data[index][b]
                                        [self.xtratype][na * 6:(na + 1) * 6]),
                                ))
                        else:
                            stream.write("      ".join(
                                "%15.8f" % el
                                for el in data[index][b][self.xtratype]))
                            stream.write("\n")
                    except:
                        stream.write(json.dumps(data[index][b][self.xtratype]))
                        stream.write("\n")
            except:
                try:
                    info(
                        "Sorry, your specified xtratype %s is not among the available options. \n"
                        "The available keys are the following: %s " % (
                            self.xtratype,
                            ",".join("%s" % key for key in data[0][b].keys()),
                        ),
                        verbosity.low,
                    )
                except:
                    info(
                        "Sorry, no extras string has been passed, there are no available options for the xtratype "
                        "attribute. \n",
                        verbosity.low,
                    )

            if flush:
                stream.flush()
                os.fsync(stream)
            return
        elif getkey(what) in [
                "positions",
                "velocities",
                "forces",
                "forces_sc",
                "momenta",
        ]:
            fatom = Atoms(self.system.beads.natoms)
            fatom.names[:] = self.system.beads.names
            fatom.q[:] = data[b]
        else:
            fatom = Atoms(self.system.beads.natoms)
            fatom.names[:] = self.system.beads.names
            fatom.q[:] = data

        fcell = Cell()
        fcell.h = self.system.cell.h

        if units == "":
            units = "automatic"
        if cell_units == "":
            cell_units = "automatic"
        io.print_file(
            format,
            fatom,
            fcell,
            stream,
            title=("Step:  %10d  Bead:   %5d " %
                   (self.system.simul.step + 1, b)),
            key=key,
            dimension=dimension,
            units=units,
            cell_units=cell_units,
        )
        if flush:
            stream.flush()
            os.fsync(stream)