示例#1
0
文件: outputs.py 项目: i-pi/i-pi
    def open_stream(self, mode):
        """Opens the output stream(s)."""

        # prepare format string for zero-padded number of beads,
        # including underscpre
        fmt_bead = "{0:0" + str(int(1 + np.floor(np.log(self.system.beads.nbeads) / np.log(10)))) + "d}"

        if getkey(self.what) in ["positions", "velocities", "forces", "extras", "forces_sc", "momenta"]:

            # must write out trajectories for each bead, so must create b streams

            # prepare format string for file name
            if getkey(self.what) == "extras":
                fmt_fn = self.filename + "_" + fmt_bead
            else:
                fmt_fn = self.filename + "_" + fmt_bead + "." + self.format

            # open all files
            self.out = []
            for b in range(self.system.beads.nbeads):
                if (self.ibead < 0 and (b % (-self.ibead) == 0)) or (self.ibead == b):
                    self.out.append(open_backup(fmt_fn.format(b), mode))
                else:
                    # Create null outputs if a single bead output is chosen.
                    self.out.append(None)

        else:

            # open one file
            filename = self.filename + "." + self.format
            self.out = open_backup(filename, mode)
示例#2
0
    def open_stream(self):
        """Opens the output stream."""

        # Is this the start of the simulation?
        is_start = self.system.simul.step == 0

        # Only open a new file if this is a new run, otherwise append.
        if is_start:
            mode = "w"
        else:
            mode = "a"

        self.out = open_backup(self.filename, mode)

        # print nice header if information is available on the properties
        if is_start:
            icol = 1
            for what in self.outlist:
                ohead = "# "
                key = getkey(what)
                prop = self.system.properties.property_dict[key]

                if "size" in prop and prop["size"] > 1:
                    ohead += "cols.  %3d-%-3d" % (icol,
                                                  icol + prop["size"] - 1)
                    icol += prop["size"]
                else:
                    ohead += "column %3d    " % (icol)
                    icol += 1
                ohead += " --> %s " % (what)
                if "help" in prop:
                    ohead += ": " + prop["help"]
                self.out.write(ohead + "\n")
示例#3
0
    def open_stream(self):
        """Opens the output stream."""

        # Is this the start of the simulation?
        is_start = self.system.simul.step == 0

        # Only open a new file if this is a new run, otherwise append.
        if is_start:
            mode = "w"
        else:
            mode = "a"

        self.out = open_backup(self.filename, mode)

        # print nice header if information is available on the properties
        if is_start:
            icol = 1
            for what in self.outlist:
                ohead = "# "
                key = getkey(what)
                prop = self.system.properties.property_dict[key]

                if "size" in prop and prop["size"] > 1:
                    ohead += "cols.  %3d-%-3d" % (icol, icol + prop["size"] - 1)
                    icol += prop["size"]
                else:
                    ohead += "column %3d    " % (icol)
                    icol += 1
                ohead += " --> %s " % (what)
                if "help" in prop:
                    ohead += ": " + prop["help"]
                self.out.write(ohead + "\n")
示例#4
0
    def open_stream(self):
        """Opens the output stream(s)."""

        # Is this the start of the simulation?
        is_start = self.system.simul.step == 0

        # Only open a new file if this is a new run, otherwise append.
        if is_start:
            mode = "w"
        else:
            mode = "a"

        # prepare format string for zero-padded number of beads,
        # including underscpre
        fmt_bead = "{0:0" + str(
            int(1 + np.floor(np.log(self.system.beads.nbeads) /
                             np.log(10)))) + "d}"

        if getkey(self.what) in [
                "positions", "velocities", "forces", "extras", "forces_sc",
                "momenta"
        ]:

            # must write out trajectories for each bead, so must create b streams

            # prepare format string for file name
            if getkey(self.what) == "extras":
                fmt_fn = self.filename + "_" + fmt_bead
            else:
                fmt_fn = self.filename + "_" + fmt_bead + "." + self.format

            # open all files
            self.out = []
            for b in range(self.system.beads.nbeads):
                if (self.ibead < 0 and
                    (b % (-self.ibead) == 0)) or (self.ibead == b):
                    self.out.append(open_backup(fmt_fn.format(b), mode))
                else:
                    # Create null outputs if a single bead output is chosen.
                    self.out.append(None)

        else:

            # open one file
            filename = self.filename + "." + self.format
            self.out = open_backup(filename, mode)
示例#5
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))
示例#6
0
    def open_stream(self, mode):
        """Opens the output stream(s)."""

        # prepare format string for zero-padded number of beads,
        # including underscore
        fmt_bead = ("{0:0" + str(
            int(1 + np.floor(np.log(self.system.beads.nbeads) / np.log(10)))) +
                    "d}")

        if getkey(self.what) in [
                "positions",
                "velocities",
                "forces",
                "extras",
                "extras_component",
                "forces_sc",
                "momenta",
        ]:

            # must write out trajectories for each bead, so must create b streams

            # prepare format string for file name
            if getkey(self.what) == "extras" or getkey(
                    self.what) == "extras_component":
                fmt_fn = self.filename + "_" + fmt_bead
            else:
                fmt_fn = self.filename + "_" + fmt_bead + "." + self.format

            # open all files
            self.out = []
            for b in range(self.system.beads.nbeads):
                if (self.ibead < 0 and
                    (b % (-self.ibead) == 0)) or (self.ibead == b):
                    self.out.append(open_backup(fmt_fn.format(b), mode))
                else:
                    # Create null outputs if a single bead output is chosen.
                    self.out.append(None)
        else:
            # open one file
            filename = self.filename + "." + self.format
            self.out = open_backup(filename, mode)
示例#7
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)
示例#8
0
    def open_stream(self, mode="w"):
        """Opens the output stream"""

        # Only open a new file if this is a new run, otherwise append.
        self.mode = mode
        self.out = open_backup(self.filename, self.mode)
示例#9
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))
示例#10
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))
示例#11
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))
示例#12
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 = 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))
示例#13
0
文件: outputs.py 项目: i-pi/i-pi
    def open_stream(self, mode="w"):
        """Opens the output stream."""

        # Only open a new file if this is a new run, otherwise append.
        self.mode = mode
        self.out = open_backup(self.filename, self.mode)