示例#1
0
    def flush(self):
        """ Write all buffers to file. """
        if not len(self.__step) < 1:

            # Make sure only master writes.
            if MPICommons.isMaster():

                # Write data to file.
                with open(self._trajectory_filename, 'a') as trajectory:
                    for i in range(len(self.__step)):

                        step = self.__step[i]
                        time = self.__time[i]
                        n_atoms = len(self.__atom_id_types[i])

                        trajectory.write("STEP %i\n" % (step))
                        trajectory.write("          %i\n" % (n_atoms))
                        trajectory.write("    TIME %.2f\n" % (time))

                        for j in range(n_atoms):
                            t = self.__atom_id_types[i][j]
                            c = self.__atom_id_coordinates[i][j]
                            trajectory.write(" %16s   %.3f %.3f %.3f  %i\n" %
                                             (t, c[0], c[1], c[2], j))

            # While the other processes wait.
            MPICommons.barrier()

            # Reset the buffers.
            self.__atom_id_types = []
            self.__atom_id_coordinates = []
            self.__time = []
            self.__step = []
示例#2
0
    def __writeHeader(self, configuration):
        """
        Write the header to the file.

        :param configuration: The configuration of the system.
        """
        # Make sure only master writes.
        if MPICommons.isMaster():

            # Open the file and write the meta information.
            with open(self._trajectory_filename, 'w') as trajectory:

                # Version.
                trajectory.write("KMCLib XYZ FORMAT VERSION 2013.10.15\n\n")

                # Cellvectors.
                cell_vectors = configuration.lattice().unitCell().cellVectors()
                trajectory.write("CELL VECTORS\n")
                trajectory.write("a: %15.10e %15.10e %15.10e\n"%(cell_vectors[0][0], cell_vectors[0][1], cell_vectors[0][2]))
                trajectory.write("b: %15.10e %15.10e %15.10e\n"%(cell_vectors[1][0], cell_vectors[1][1], cell_vectors[1][2]))
                trajectory.write("c: %15.10e %15.10e %15.10e\n\n"%(cell_vectors[2][0], cell_vectors[2][1], cell_vectors[2][2]))

                # Repetitions.
                repetitions = configuration.lattice().repetitions()
                trajectory.write("REPETITIONS %i %i %i\n\n"%(repetitions[0], repetitions[2], repetitions[2]))

                # Periodicity.
                periodicity = configuration.lattice().periodic()
                trajectory.write("PERIODICITY %s %s %s\n\n"%(str(periodicity[0]), str(periodicity[1]), str(periodicity[2])))

        # While the other processes wait.
        MPICommons.barrier()
示例#3
0
    def flush(self):
        """ Write all buffers to file. """
        if not len(self.__step) < 1:

            # Make sure only master writes.
            if MPICommons.isMaster():

                # Write data to file.
                with open(self._trajectory_filename, 'a') as trajectory:
                    for i in range(len(self.__step)):

                        step = self.__step[i]
                        time = self.__time[i]
                        n_atoms = len(self.__atom_id_types[i])

                        trajectory.write("STEP %i\n"%(step))
                        trajectory.write("          %i\n"%(n_atoms))
                        trajectory.write("    TIME %15.10e\n"%(time))

                        for j in range(n_atoms):
                            t = self.__atom_id_types[i][j]
                            c = self.__atom_id_coordinates[i][j]
                            trajectory.write(" %16s   %15.10e %15.10e %15.10e  %i\n"%(t, c[0], c[1], c[2], j))

            # While the other processes wait.
            MPICommons.barrier()

            # Reset the buffers.
            self.__atom_id_types = []
            self.__atom_id_coordinates = []
            self.__time = []
            self.__step = []
示例#4
0
    def __writeHeader(self, configuration):
        """
        Write the header to the file.

        :param configuration: The configuration of the system.
        """
        # Make sure only master writes.
        if MPICommons.isMaster():

            # Open the file and write the meta information.
            with open(self._trajectory_filename, 'w') as trajectory:

                # Version.
                trajectory.write("KMCLib XYZ FORMAT VERSION 2013.10.15\n\n")

                # Cellvectors.
                cell_vectors = configuration.lattice().unitCell().cellVectors()
                trajectory.write("CELL VECTORS\n")
                trajectory.write("a: %15.10e %15.10e %15.10e\n"%(cell_vectors[0][0], cell_vectors[0][1], cell_vectors[0][2]))
                trajectory.write("b: %15.10e %15.10e %15.10e\n"%(cell_vectors[1][0], cell_vectors[1][1], cell_vectors[1][2]))
                trajectory.write("c: %15.10e %15.10e %15.10e\n\n"%(cell_vectors[2][0], cell_vectors[2][1], cell_vectors[2][2]))

                # Repetitions.
                repetitions = configuration.lattice().repetitions()
                trajectory.write("REPETITIONS %i %i %i\n\n"%(repetitions[0], repetitions[1], repetitions[2]))

                # Periodicity.
                periodicity = configuration.lattice().periodic()
                trajectory.write("PERIODICITY %s %s %s\n\n"%(str(periodicity[0]), str(periodicity[1]), str(periodicity[2])))

        # While the other processes wait.
        MPICommons.barrier()
示例#5
0
 def tearDown(self):
     """ The tearDown method for test fixtures. """
     # Make sure to stop simultaneously.
     MPICommons.barrier()
     for f in self.__files_to_remove:
         # Make sure only master delets files, while slaves wait.
         if MPICommons.isMaster():
             os.remove(f)
         MPICommons.barrier()
示例#6
0
def prettyPrint(msg, output=None):
    """
    Utility function for printing an output string to screen.

    :param msg: The message to print.
    :type msg: str

    :param out: The stream to write to. Defaults to sys.stdout.
    """
    # Set the default.
    if output is None:
        output = sys.stdout

    # Write.
    if MPICommons.isMaster():
        output.write(msg)
        output.write("\n")
    MPICommons.barrier()
示例#7
0
def prettyPrint(msg, output=None):
    """
    Utility function for printing an output string to screen.

    :param msg: The message to print.
    :type msg: str

    :param out: The stream to write to. Defaults to sys.stdout.
    """
    # Set the default.
    if output is None:
        output = sys.stdout

    # Write.
    if MPICommons.isMaster():
        output.write(msg)
        output.write("\n")
    MPICommons.barrier()
示例#8
0
    def __writeToFile(self, simulation_time_buffer, step_buffer, types_buffer):
        """
        Append the types and time information to the trajectory.
        The trajectory if flushed to file if the flush time limit has passed.

        :param simulation_time_buffer: A list of simulation times to be written to disk.
        :param step_buffer:            A list of step numbers to be written.
        :param types_buffer:           The types buffer given as a list of lists of strings.
        """
        # Save to file.

        # Make sure only master writes.
        if MPICommons.isMaster():
            with open(self.__trajectory_filename, 'a') as trajectory:
                for (sim_time, step, types) in zip(simulation_time_buffer, step_buffer, types_buffer):
                    trajectory.write( "times.append(%f)\n"%sim_time )
                    trajectory.write( "steps.append(%i)\n"%step )

                    # Write the types.
                    types_str = "types.append(["
                    indent = " "*14
                    row_length = len(types_str)
                    for t in types[:-1]:
                        row_length += len(t) + 2
                        types_str += "\"" + t + "\"" + ","

                        # Berak the row if above 70 positions.
                        if row_length >= 70:
                            types_str += "\n" + indent
                            row_length = len(indent)

                    # Add the last type.
                    types_str += "\"" + types[-1] + "\"" + "])\n"

                    # Write it to file.
                    trajectory.write(types_str)

        # While the others wait.
        MPICommons.barrier()

        # Update the time.
        self.__time_last_dump = time.time()
示例#9
0
    def __writeToFile(self, simulation_time_buffer, step_buffer, types_buffer):
        """
        Append the types and time information to the trajectory.
        The trajectory if flushed to file if the flush time limit has passed.

        :param simulation_time_buffer: A list of simulation times to be written to disk.
        :param step_buffer:            A list of step numbers to be written.
        :param types_buffer:           The types buffer given as a list of lists of strings.
        """
        # Save to file.

        # Make sure only master writes.
        if MPICommons.isMaster():
            with open(self._trajectory_filename, 'a') as trajectory:
                for (sim_time, step, types) in zip(simulation_time_buffer,
                                                   step_buffer, types_buffer):
                    trajectory.write("times.append(%18.10e)\n" % sim_time)
                    trajectory.write("steps.append(%i)\n" % step)

                    # Write the types.
                    types_str = "types.append(["
                    indent = " " * 14
                    row_length = len(types_str)
                    for t in types[:-1]:
                        row_length += len(t) + 2
                        types_str += "\"" + t + "\"" + ","

                        # Berak the row if above 70 positions.
                        if row_length >= 70:
                            types_str += "\n" + indent
                            row_length = len(indent)

                    # Add the last type.
                    types_str += "\"" + types[-1] + "\"" + "])\n"

                    # Write it to file.
                    trajectory.write(types_str)

        # While the others wait.
        MPICommons.barrier()
示例#10
0
    def __writeHeader(self, sites):
        """
        Write the header to the file.

        :param sites: The sites in the system.
        """
        # Make sure only master writes.
        if MPICommons.isMaster():

            # Open the file and write the meta information.
            with open(self._trajectory_filename, 'w') as trajectory:
                trajectory.write("# KMCLib Trajectory\n")
                trajectory.write("version=\"2013.1.0\"\n")
                trajectory.write("creation_time=\"%s\"\n" % (time.ctime()))

                # Write the sites.
                sites_str = "sites=["
                indent = " " * 7
                for i, site in enumerate(sites):
                    sites_str += "[%15.6f,%15.6f,%15.6f]" % (site[0], site[1],
                                                             site[2])

                    # Handle the last site differently.
                    if i == len(sites) - 1:
                        sites_str += "]\n"
                    else:
                        sites_str += ",\n" + indent

                trajectory.write(sites_str)

                # Write the empty lists.
                trajectory.write("times=[]\n")
                trajectory.write("steps=[]\n")
                trajectory.write("types=[]\n")

        # While the other processes wait.
        MPICommons.barrier()
示例#11
0
    def __writeHeader(self, sites):
        """
        Write the header to the file.

        :param sites: The sites in the system.
        """
        # Make sure only master writes.
        if MPICommons.isMaster():

            # Open the file and write the meta information.
            with open(self._trajectory_filename, 'w') as trajectory:
                trajectory.write( "# KMCLib Trajectory\n" )
                trajectory.write( "version=\"2013.1.0\"\n" )
                trajectory.write( "creation_time=\"%s\"\n"%(time.ctime()) )

                # Write the sites.
                sites_str = "sites=["
                indent    = " "*7
                for i,site in enumerate(sites):
                    sites_str += "[%15.6f,%15.6f,%15.6f]"%(site[0],site[1],site[2])

                    # Handle the last site differently.
                    if i == len(sites)-1:
                        sites_str += "]\n"
                    else:
                        sites_str += ",\n" + indent

                trajectory.write( sites_str )

                # Write the empty lists.
                trajectory.write("times=[]\n")
                trajectory.write("steps=[]\n")
                trajectory.write("types=[]\n")

        # While the other processes wait.
        MPICommons.barrier()
示例#12
0
    def __writeToFile(self, simulation_time_buffer, step_buffer, types_buffer):
        """
        Append the types and time information to the trajectory.
        The trajectory if flushed to file if the flush time limit has passed.

        :param simulation_time_buffer: A list of simulation times to be written to disk.
        :param step_buffer:            A list of step numbers to be written.
        :param types_buffer:           The types buffer given as a list of lists of strings.
        """
        # Save to file.

        # Make sure only master writes.
        if MPICommons.isMaster():
            with open(self._trajectory_filename, 'a') as trajectory:
                for (sim_time, step, types) in zip(simulation_time_buffer,
                                                   step_buffer, types_buffer):
                    trajectory.write("times.append(%18.10e)\n" % sim_time)
                    trajectory.write("steps.append(%i)\n" % step)

                    # Write the types.
                    types_str = "types.append(["
                    indent = " " * 14
                    row_length = len(types_str)

                    if isinstance(types[:-1][0], str):
                        for t in types[:-1]:
                            row_length += len(t) + 2
                            types_str += "\"" + t + "\"" + ","

                            # Berak the row if above 70 positions.
                            if row_length >= 70:
                                types_str += "\n" + indent
                                row_length = len(indent)

                        # Add the last type.
                        types_str += "\"" + types[-1] + "\"" + "])\n"

                    # With bucket types.
                    else:
                        bucket_types = toShortBucketsFormat(types)

                        # For all sites except the last.
                        for bt in bucket_types[:-1]:

                            # Start the types for this site.
                            types_str += "["
                            for t in bt[:-1]:
                                types_str += "(" + str(
                                    t[0]) + ",\"" + t[1] + "\"),"
                            if len(bt) > 0:
                                t = bt[-1]
                                types_str += "(" + str(
                                    t[0]) + ",\"" + t[1] + "\")"
                                types_str += "],\n" + indent

                            else:
                                types_str += "],\n" + indent

                        # For the last site.
                        bt = bucket_types[-1]
                        types_str += "["
                        for t in bt[:-1]:
                            types_str += "(" + str(
                                t[0]) + ",\"" + t[1] + "\"),"
                        if len(bt) > 0:
                            t = bt[-1]
                            types_str += "(" + str(
                                t[0]) + ",\"" + t[1] + "\")]"
                        else:
                            types_str += "]"

                        types_str += "])\n"

                    # Write it to file.
                    trajectory.write(types_str)

        # While the others wait.
        MPICommons.barrier()
示例#13
0
    def testAppend(self):
        """ Test appending to the trajectory. """
        # Setup input.
        sites = [[0.0,1.0,2.3],
                 [1.0,0.0,2.3],
                 [1.0,1.0,0.3],
                 [1.0,1.0,2.3],
                 [3.4,4.5,4.3],
                 [3.4,4.3,4.3],
                 [3.4,5.5,4.3],
                 [3.7,7.5,6.5]]
        name = os.path.abspath(os.path.dirname(__file__))
        name = os.path.join(name, "..", "..")
        name = os.path.join(name, "TestUtilities", "Scratch")
        trajectory_filename = os.path.join(name, "tmp_trajectory_file.py")
        self.__files_to_remove.append(trajectory_filename)

        # Construct.
        t = Trajectory(trajectory_filename, sites)

        # Append times, steps and typers.
        t.append(1.10045, 12,
                 ["A", "A", "A", "A", "A", "A"] )

        # Since this was the first time it should have triggered a dump to file.
        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        # Needed to prevent test failure.
        MPICommons.barrier()

        # Check the types.
        ret_types = local_dict['types']
        ref_types = [["A", "A", "A", "A", "A", "A"]]
        self.assertEqual( ret_types, ref_types )

        # Check the steps.
        ret_steps = local_dict['steps']
        ref_steps = [12]
        self.assertEqual( ret_steps, ref_steps )

        # Check the times.
        ret_times = local_dict['times']
        ref_times = [1.10045]
        self.assertEqual( ret_times, ref_times )

        # Appending again directly makes no dump.
        t.append(1.1993, 14,
                 ["B", "B", "B", "B", "B", "B"] )

        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        # Needed to prevent test failure.
        MPICommons.barrier()

        # Check.
        ret_types = local_dict['types']
        self.assertEqual( ret_types, ref_types )
        ret_steps = local_dict['steps']
        self.assertEqual( ret_steps, ref_steps )
        ret_times = local_dict['times']
        self.assertEqual( ret_times, ref_times )

        # But if we dump again and set the time limit to zero we will trigger a dump.
        t._Trajectory__max_buffer_time = 0.0
        t.append(1.199, 19,
                 ["C", "C", "C", "C", "C", "C"] )

        # Reset the time to some thing large.
        t._Trajectory__max_buffer_time = 100000000000.0

        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        # Check the types.
        ret_types = local_dict['types']
        ref_types = [["A","A","A","A","A","A"],
                     ["B","B","B","B","B","B"],
                     ["C","C","C","C","C","C"]]

        # Needed to prevent test failure.
        MPICommons.barrier()

        self.assertEqual( ret_types, ref_types )

        # Check the steps.
        ret_steps = local_dict['steps']
        ref_steps = [12,14,19]
        self.assertEqual( ret_steps, ref_steps )

        # Check the times.
        ret_times = local_dict['times']
        ref_times = [1.10045, 1.1993, 1.199]
        self.assertEqual( ret_times, ref_times )

        # The buffers are reset after each dump. If we make the
        # max size limit smaller than the size of the appended types
        # list this must trigger a dump.
        types = ["A","A","A","A","A","B"]
        size = sys.getsizeof(types)
        t._Trajectory__max_buffer_size = size

        # Append.
        t.append(1.1995, 43, types )

        # Check.
        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        ret_types = local_dict['types']
        ref_types = [["A","A","A","A","A","A"],
                     ["B","B","B","B","B","B"],
                     ["C","C","C","C","C","C"]]

        # Needed to prevent test failure.
        MPICommons.barrier()

        self.assertEqual( ret_types, ref_types )

        # Append.
        t.append(1.1995, 43, types )
        t.append(1.1995, 43, types )
        t.append(1.1995, 43, types )
        # This last one triggers the dump.
        t.append(1.1995, 43, types )

        # Check.
        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        ret_types = local_dict['types']
        ref_types = [["A","A","A","A","A","A"],
                     ["B","B","B","B","B","B"],
                     ["C","C","C","C","C","C"],
                     ["A","A","A","A","A","B"],
                     ["A","A","A","A","A","B"],
                     ["A","A","A","A","A","B"],
                     ["A","A","A","A","A","B"],
                     ["A","A","A","A","A","B"]]

        # Needed to prevent test failure.
        MPICommons.barrier()

        self.assertEqual( ret_types, ref_types )
示例#14
0
 def setUp(self):
     """ The setUp method for test fixtures. """
     self.__files_to_remove = []
     # Make sure to start simultaneously.
     MPICommons.barrier()
示例#15
0
 def tearDown(self):
     """ The tearDown method for test fixtures. """
     for f in self.__files_to_remove:
         if MPICommons.isMaster():
             os.remove(f)
     MPICommons.barrier()
示例#16
0
    def flush(self):
        """ Write all buffers to file. """
        if not len(self.__step) < 1:

            # Make sure only master writes.
            if MPICommons.isMaster():

                # Write data to file.
                with open(self._trajectory_filename, 'a') as trajectory:
                    for i in range(len(self.__step)):

                        step = self.__step[i]
                        time = self.__time[i]
                        n_atoms = len(self.__atom_id_types[i])

                        # calculate the super-cell length
                        H = 5.0

                        #supercell headers for CFG file for atomeye
                        trajectory.write("Number of particles = %i\n\n" %
                                         (n_atoms))
                        trajectory.write("A = 1 Angstrom\n")
                        trajectory.write("H0(1,1) = %f A\n" % (H))
                        trajectory.write("H0(1,2) = 0 . 0 A\n")
                        trajectory.write("H0(1,3) = 0 . 0 A\n")
                        trajectory.write("H0(2,1) = 0 . 0 A\n")
                        trajectory.write("H0(2,2) = %f A\n" % (H))
                        trajectory.write("H0(2,3) = 0 . 0 A\n")
                        trajectory.write("H0(3,1) = 0 . 0 A\n")
                        trajectory.write("H0(3,2) = 0 . 0 A\n")
                        trajectory.write("H0(3,3) = %f A\n" % (H))
                        trajectory.write("#\n")

                        for j in range(n_atoms):
                            t = self.__atom_id_types[i][j]
                            c = self.__atom_id_coordinates[i][j]
                            #reduce the coordinates
                            """if c[0] < 0.0:
                                s1 = 1- (c[0] - math.floor(c[0]))
                                print ("reduced<: %.2f"%(s1)
                            elif c[0] > 5.0:
                                s1 = c[0] - math.floor(c[0])
                                print ("reduced>: %.2f"%(s1)
                            """
                            s1 = c[0] / H
                            s2 = c[1] / H
                            s3 = c[2] / H
                            #print("X: %f Y: %f Z: %f"%(s1, s2, s3))

                            #change the mass atomic number depending on type of atoms there
                            if t == 'Fe':
                                mass = 55.845

                            elif t == 'V':
                                mass = 1.0

                            # write the cfg file with reduced coordinates
                            trajectory.write(
                                "%.2f %s %.2f %.2f %.2f 0.0 0.0 0.0\n" %
                                (mass, t, s1, s2, s3))

            # While the other processes wait.
            MPICommons.barrier()

            # Reset the buffers.
            self.__atom_id_types = []
            self.__atom_id_coordinates = []
            self.__time = []
            self.__step = []
示例#17
0
    def __writeToFile(self, simulation_time_buffer, step_buffer, types_buffer):
        """
        Append the types and time information to the trajectory.
        The trajectory if flushed to file if the flush time limit has passed.

        :param simulation_time_buffer: A list of simulation times to be written to disk.
        :param step_buffer:            A list of step numbers to be written.
        :param types_buffer:           The types buffer given as a list of lists of strings.
        """
        # Save to file.

        # Make sure only master writes.
        if MPICommons.isMaster():
            with open(self._trajectory_filename, 'a') as trajectory:
                for (sim_time, step, types) in zip(simulation_time_buffer, step_buffer, types_buffer):
                    trajectory.write( "times.append(%18.10e)\n"%sim_time )
                    trajectory.write( "steps.append(%i)\n"%step )

                    # Write the types.
                    types_str = "types.append(["
                    indent = " "*14
                    row_length = len(types_str)

                    if isinstance(types[:-1][0], str):
                        for t in types[:-1]:
                            row_length += len(t) + 2
                            types_str += "\"" + t + "\"" + ","

                            # Berak the row if above 70 positions.
                            if row_length >= 70:
                                types_str += "\n" + indent
                                row_length = len(indent)

                        # Add the last type.
                        types_str += "\"" + types[-1] + "\"" + "])\n"

                    # With bucket types.
                    else:
                        bucket_types = toShortBucketsFormat(types)

                        # For all sites except the last.
                        for bt in bucket_types[:-1]:

                            # Start the types for this site.
                            types_str += "["
                            for t in bt[:-1]:
                                types_str += "(" + str(t[0]) + ",\"" + t[1] + "\"),"
                            if len(bt) > 0:
                                t = bt[-1]
                                types_str += "(" + str(t[0]) + ",\"" + t[1] + "\")"
                                types_str += "],\n" + indent

                            else:
                                types_str += "],\n" + indent

                        # For the last site.
                        bt = bucket_types[-1]
                        types_str += "["
                        for t in bt[:-1]:
                            types_str += "(" + str(t[0]) + ",\"" + t[1] + "\"),"
                        if len(bt) > 0:
                            t = bt[-1]
                            types_str += "(" + str(t[0]) + ",\"" + t[1] + "\")]"
                        else:
                            types_str += "]"

                        types_str += "])\n"

                    # Write it to file.
                    trajectory.write(types_str)

        # While the others wait.
        MPICommons.barrier()
示例#18
0
    def __init__(self,
                 trajectory_filename,
                 sites,
                 max_buffer_size=None,
                 max_buffer_time=None):
        """
        Constructor for the Trajectory.

        :param trajectory_filename: The file name to write trajectory information to.
        :type trajectory_filename: str

        :param sites: The lattice sites of the configuration as an Nx3 list.

        :param max_buffer_size: The max size of the the buffer in memory
                                before writing to file.
        :type max_buffer_size: int

        :param max_buffer_time: The max time limit between dumps to file.
        :type max_buffer_time: float
        """
        # Set the defaults.
        if max_buffer_size is None:
            self.__max_buffer_size = 1024*1024*10    #   <- Max buffer size in bytes (10 MB)
        else:
            self.__max_buffer_size = max_buffer_size

        if max_buffer_time is None:
            self.__max_buffer_time = 30*60.0           #   <- Max time in seconds (30 min)
        else:
            self.__max_buffer_time = max_buffer_time

        # Note that this object is not in the interface, so input is allready checked.
        self.__trajectory_filename = trajectory_filename

        # Open the file and write the meta information.

        # Make sure only master writes.
        if MPICommons.isMaster():
            with open(self.__trajectory_filename, 'w') as trajectory:
                trajectory.write( "# KMCLib Trajectory\n" )
                trajectory.write( "version=\"2013.1.0\"\n" )
                trajectory.write( "creation_time=\"%s\"\n"%(time.ctime()) )

                # Write the sites.
                sites_str = "sites=["
                indent    = " "*7
                for i,site in enumerate(sites):
                    sites_str += "[%15.6f,%15.6f,%15.6f]"%(site[0],site[1],site[2])

                    # Handle the last site differently.
                    if i == len(sites)-1:
                        sites_str += "]\n"
                    else:
                        sites_str += ",\n" + indent

                trajectory.write( sites_str )

                # Write the empty lists.
                trajectory.write("times=[]\n")
                trajectory.write("steps=[]\n")
                trajectory.write("types=[]\n")

        # While the other processes wait.
        MPICommons.barrier()

        # Init the member data.
        self.__types_buffer = []
        self.__simulation_time_buffer = []
        self.__step_buffer = []

        # Set the time counter to zero.
        self.__time_last_dump = 0.0
示例#19
0
    def testWriteToFile(self):
        """ Test writing the buffers to file. """
        # Setup input.
        sites = [[0.0,1.0,2.3],
                 [1.0,0.0,2.3],
                 [1.0,1.0,0.3],
                 [1.0,1.0,2.3],
                 [3.4,4.5,4.3],
                 [3.4,4.3,4.3],
                 [3.4,5.5,4.3],
                 [3.7,7.5,6.5]]
        name = os.path.abspath(os.path.dirname(__file__))
        name = os.path.join(name, "..", "..")
        name = os.path.join(name, "TestUtilities", "Scratch")
        trajectory_filename = os.path.join(name, "tmp_trajectory_file.py")
        self.__files_to_remove.append(trajectory_filename)

        # Construct.
        t = Trajectory(trajectory_filename, sites)

        # Write times, steps and typers.
        times = [1.10045, 2.334156, 3.4516410]
        steps = [12, 25, 52]
        types = [["ThisIsTheLongestTypeNameIHaveEverEncounteredPerhaps",
                  "here", "is", "Next", "Long", "List", "Offffffff", "Names", "now", "this", "one", "is", "longer", "still"],
                 ["A", "B", "C", "D", "E", "F", "G", "H"],
                 ["1", "2", "4", "5", "6", "5" ,"43", "243r2424"]]

        # Needed to prevent test failure.
        MPICommons.barrier()

        # Check that the time is zero before we start.
        self.assertAlmostEqual( t._Trajectory__time_last_dump, 0.0, 10 )

        t._Trajectory__writeToFile(times, steps, types)

        # Needed to prevent test failure.
        MPICommons.barrier()

        # Check that the time stamp was updated.
        self.assertTrue( 1357651850 < t._Trajectory__time_last_dump )
        last_time = t._Trajectory__time_last_dump

        # Check the info stored in the file.
        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        # Check the types.
        ret_types = local_dict['types']
        ref_types = [['ThisIsTheLongestTypeNameIHaveEverEncounteredPerhaps',
                      'here', 'is', 'Next', 'Long', 'List', 'Offffffff',
                      'Names', 'now', 'this', 'one', 'is', 'longer', 'still'],
                     ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                     ['1', '2', '4', '5', '6', '5', '43', '243r2424']]

        # Needed to prevent test failure.
        MPICommons.barrier()

        self.assertEqual( ret_types, ref_types )

        # Check the steps.
        ret_steps = local_dict['steps']
        ref_steps = [12, 25, 52]
        self.assertEqual( ret_steps, ref_steps )

        # Check the times.
        ret_times = local_dict['times']
        ref_times = [1.10045, 2.334156, 3.451641]
        self.assertEqual( ret_times, ref_times )

        # Sleep for two seconds before we add again.
        time.sleep(1)
        t._Trajectory__writeToFile(times, steps, types)

        # Check the time.
        self.assertTrue( (t._Trajectory__time_last_dump - last_time > 1) )

        # Now, check the file again.
        global_dict = {}
        local_dict  = {}
        execfile(trajectory_filename, global_dict, local_dict)

        # Check the types.
        ret_types = local_dict['types']
        ref_types = [['ThisIsTheLongestTypeNameIHaveEverEncounteredPerhaps',
                      'here', 'is', 'Next', 'Long', 'List', 'Offffffff',
                      'Names', 'now', 'this', 'one', 'is', 'longer', 'still'],
                     ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                     ['1', '2', '4', '5', '6', '5', '43', '243r2424'],
                     ['ThisIsTheLongestTypeNameIHaveEverEncounteredPerhaps',
                      'here', 'is', 'Next', 'Long', 'List', 'Offffffff',
                      'Names', 'now', 'this', 'one', 'is', 'longer', 'still'],
                     ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                     ['1', '2', '4', '5', '6', '5', '43', '243r2424']]

        # Needed to prevent test failure.
        MPICommons.barrier()

        self.assertEqual( ret_types, ref_types )

        # Check the steps.
        ret_steps = local_dict['steps']
        ref_steps = [12, 25, 52, 12, 25, 52]
        self.assertEqual( ret_steps, ref_steps )

        # Check the times.
        ret_times = local_dict['times']
        ref_times = [1.10045, 2.334156, 3.451641, 1.10045, 2.334156, 3.451641]
        self.assertEqual( ret_times, ref_times )