def testVersion(self): """ Test the LatticeTrajectory file version number string. """ # Setup input. sites = [[1.0,1.0,2.3], [3.4,4.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") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Construct. t = LatticeTrajectory(trajectory_filename, Config(sites)) # Open the trajectory file and check that we can read the meta # information and sites. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) # Get the version and check. read_version = local_dict["version"] ref_version = "2013.1.0" self.assertEqual( read_version, ref_version )
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 = []
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 = []
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()
def testPrettyPrint(self): """ Test that we can call the pretty print function. """ # Print to stdout. original_sys_stdout = sys.stdout try: stream_1 = StringIO.StringIO() sys.stdout = stream_1 # Print to stdout. ref_str = "This is what we print" prettyPrint(ref_str) # Check. if MPICommons.myRank() == 0: ref_str = ref_str + "\n" else: ref_str = "" self.assertEqual(stream_1.getvalue(), ref_str) finally: # Put the original stdout back. sys.stdout = original_sys_stdout # Print to another stream. stream_2 = StringIO.StringIO() ref_str = "This is what we print next time." prettyPrint(ref_str, output=stream_2) # Check. if MPICommons.myRank() == 0: ref_str = ref_str + "\n" else: ref_str = "" self.assertEqual(stream_2.getvalue(), ref_str)
def testConstruction(self): """ Test the LatticeTrajectory object can be constructed. """ # Setup input. sites = [[1.0,1.0,2.3], [3.4,4.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") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Construct with default values. dt = LatticeTrajectory(trajectory_filename, Config(sites)) # Check the defaults. self.assertAlmostEqual( dt._Trajectory__max_buffer_time, 60*30 ) self.assertEqual( dt._Trajectory__max_buffer_size, 1024*1024*10 ) # Construct. t = LatticeTrajectory(trajectory_filename, Config(sites), max_buffer_time=100.0, max_buffer_size=100000) # Check the stored values. self.assertEqual( t._Trajectory__max_buffer_time, 100.0 ) self.assertEqual( t._Trajectory__max_buffer_size, 100000 ) self.assertEqual( t._trajectory_filename, trajectory_filename ) # Open the trajectory file and check that we can read the meta # information and sites. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) # Get the version and creation time. read_version = local_dict["version"] read_creation = local_dict["creation_time"] # Check that they are of corect type. self.assertTrue( isinstance(read_version, str) ) self.assertTrue( isinstance(read_creation, str) ) # Check the sites. read_sites = numpy.array(local_dict["sites"]) ref_sites = numpy.array(sites) self.assertAlmostEqual( numpy.linalg.norm(read_sites - ref_sites), 0.0, 10 ) # Check the empty lists. read_times = local_dict["times"] read_steps = local_dict["steps"] read_types = local_dict["types"] empty_list = [] self.assertEqual( read_times, empty_list ) self.assertEqual( read_steps, empty_list ) self.assertEqual( read_types, empty_list )
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()
def testVersion(self): """ Test the LatticeTrajectory file version number string. """ # Setup input. sites = [[1.0, 1.0, 2.3], [3.4, 4.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") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Construct. t = LatticeTrajectory(trajectory_filename, Config(sites)) # Open the trajectory file and check that we can read the meta # information and sites. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) # Get the version and check. read_version = local_dict["version"] ref_version = "2013.1.0" self.assertEqual(read_version, ref_version)
def testConstruction(self): """ Test the LatticeTrajectory object can be constructed. """ # Setup input. sites = [[1.0, 1.0, 2.3], [3.4, 4.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") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Construct with default values. dt = LatticeTrajectory(trajectory_filename, Config(sites)) # Check the defaults. self.assertAlmostEqual(dt._Trajectory__max_buffer_time, 60 * 30) self.assertEqual(dt._Trajectory__max_buffer_size, 1024 * 1024 * 10) # Construct. t = LatticeTrajectory(trajectory_filename, Config(sites), max_buffer_time=100.0, max_buffer_size=100000) # Check the stored values. self.assertEqual(t._Trajectory__max_buffer_time, 100.0) self.assertEqual(t._Trajectory__max_buffer_size, 100000) self.assertEqual(t._trajectory_filename, trajectory_filename) # Open the trajectory file and check that we can read the meta # information and sites. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) # Get the version and creation time. read_version = local_dict["version"] read_creation = local_dict["creation_time"] # Check that they are of corect type. self.assertTrue(isinstance(read_version, str)) self.assertTrue(isinstance(read_creation, str)) # Check the sites. read_sites = numpy.array(local_dict["sites"]) ref_sites = numpy.array(sites) self.assertAlmostEqual(numpy.linalg.norm(read_sites - ref_sites), 0.0, 10) # Check the empty lists. read_times = local_dict["times"] read_steps = local_dict["steps"] read_types = local_dict["types"] empty_list = [] self.assertEqual(read_times, empty_list) self.assertEqual(read_steps, empty_list) self.assertEqual(read_types, empty_list)
def testWriteToFileBuckets(self): """ Test writing buffers in buckets format 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_bucktes_traj.py") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Construct. t = LatticeTrajectory(trajectory_filename, Config(sites)) # Write times, steps and typers. times = [1.10045, 2.334156, 3.4516410] steps = [12, 25, 52] site_types = [[["A"], [(3, "A"), "A", "B", "B"], ["A", "B", "C"]], [[], ["A", (3, "A"), "A", "B", "B"], ["A", "B", "C"]], [[(2, "C")], ["B", "B", "A"], ["A", "B"]]] # Check that the time is zero before we start. if MPICommons.isMaster(): self.assertAlmostEqual(t._Trajectory__time_last_dump, 0.0, 10) # This function should be MPI safe. t._LatticeTrajectory__writeToFile(times, steps, site_types) # Check the info stored in the file. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) # Check the types. ret_types = local_dict['types'] ref_types = [[[(1, "A")], [(4, "A"), (2, "B")], [(1, "A"), (1, "B"), (1, "C")]], [[], [(5, "A"), (2, "B")], [(1, "A"), (1, "B"), (1, "C")]], [[(2, "C")], [(2, "B"), (1, "A")], [(1, "A"), (1, "B")]]] 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)
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()
def testWriteHeader(self): """ Test the header output. """ # Get a file name. 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.xyz") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Setup the trajectory object. unit_cell = KMCUnitCell(cell_vectors=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], basis_points=[[0.0, 0.0, 0.0]]) lattice = KMCLattice(unit_cell=unit_cell, periodic=(True, True, True), repetitions=(4,2,3)) config = KMCConfiguration(lattice=lattice, types=["A","B","C"]*8) t = XYZTrajectory(trajectory_filename=trajectory_filename, configuration=config, max_buffer_size=12345, max_buffer_time=123.0) if MPICommons.isMaster(): # Check that the header was written. self.assertTrue(os.path.exists(trajectory_filename)) # Check the content of the header. with open(trajectory_filename, "r") as f: content = f.read() ref_content = """KMCLib XYZ FORMAT VERSION 2013.10.15 CELL VECTORS a: 1.0000000000e+00 0.0000000000e+00 0.0000000000e+00 b: 0.0000000000e+00 1.0000000000e+00 0.0000000000e+00 c: 0.0000000000e+00 0.0000000000e+00 1.0000000000e+00 REPETITIONS 4 2 3 PERIODICITY True True True """ self.assertEqual( content, ref_content )
def printResults(self, stream=sys.stdout): """ Print the results to a stream. :param stream: The stream to print to. Defaults to 'sys.stdout'. """ # Only master writes. if MPICommons.isMaster(): # Bunch the results together and cutoff. cutoff_bin = self.safeCutoff() all_results = zip(self.__time_steps, self.__results[0], self.__results[1], self.__results[2], self.__results[3], self.__results[4], self.__results[5], self.__results[6], self.__std_dev[0], self.__std_dev[1], self.__std_dev[2], self.__std_dev[3], self.__std_dev[4], self.__std_dev[5], self.__std_dev[6], self.__n_eff)[:cutoff_bin] stream.write("%11s %11s %11s %11s %11s %11s %11s %11s %11s %11s %11s %11s %11s %11s %11s %11s\n"%("TIME ", "MSD_x ", "DSD_y ", "MSD_z ", "MSD_xy ", "MSD_xz ", "MSD_yz ", "MSD_xyz ", "STD_x ", "STD_y ", "STD_z ", "STD_xy ", "STD_xz ", "STD_yz ", "STD_xyz ", "N_eff")) for t, x, y, z, xy, xz, yz, xyz, sx, sy, sz, sxy, sxz, syz, sxyz, nf in all_results: stream.write("%11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e %11.5e\n"%(t, x, y, z, xy, xz, yz, xyz, sx, sy, sz, sxy, sxz, syz, sxyz, nf))
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): stream.write("%15s %15s %15s %12s\n"%(" time (t)", " count (n)", "(dn/dt) ", "stdErr")) n_tot = 0 actualTot = 0 t = 0.0 for i,n in enumerate(self.__data): # Calculate the values to present. t = i * self.__time_interval actualTot += n dt = self.__time_interval n_tot += n dn = n rateEst = self.__floatAnalInterval*dn/dt stdErr = self.__floatAnalInterval*math.sqrt(dn)/dt # Only for times != zero. if (i > 0): stream.write("%15.5f %15i"%(t, n_tot) +" "+ "{:.6E}".format(rateEst) +" "+"{:.3E}".format(stdErr) +"\n") eqTime = self.__finalTime - self.__initialTime stream.write("\nOverall we counted the following number of counts in the following amount of time: " + "%6i"%(actualTot) + " " + "{:.6E}".format(eqTime))
def testConstruction(self): """ Test that the XYZTrajectory object can be constructed. """ filename = "abc123.xyz" name = os.path.abspath(os.path.dirname(__file__)) name = os.path.join(name, "..", "..") name = os.path.join(name, "TestUtilities", "Scratch") filename = os.path.join(name, filename) if MPICommons.isMaster(): self.__files_to_remove.append(filename) unit_cell = KMCUnitCell(cell_vectors=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], basis_points=[[0.0, 0.0, 0.0]]) lattice = KMCLattice(unit_cell=unit_cell, periodic=(True, True, True), repetitions=(4,4,4)) config = KMCConfiguration(lattice=lattice, types=["A","B","C","D"]*16) t = XYZTrajectory(trajectory_filename=filename, configuration=config, max_buffer_size=12345, max_buffer_time=123.0) # Check that the internal memory buffers have been initiated. self.assertEqual(t._XYZTrajectory__atom_id_types, []) self.assertEqual(t._XYZTrajectory__atom_id_coordinates, []) self.assertEqual(t._XYZTrajectory__time, []) self.assertEqual(t._XYZTrajectory__step, [])
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): stream.write("%15s %15s %15s %12s\n"%(" time (t)", " count (n)", "(dn/dt) ", "stdErr")) n_tot = 0 actualTot = 0 t = 0.0 for i,n in enumerate(self.__data): # Calculate the values to present. t = i * self.__time_interval if t>=self.__transientTime: actualTot += n dt = self.__time_interval n_tot += n dn = n rateEst = self.__floatAnalInterval*dn/dt stdErr = self.__floatAnalInterval*math.sqrt(dn)/dt # Only for times != zero. if (i > 0): stream.write("%15.5f %15i"%(t, n_tot) +" "+ "{:.6E}".format(rateEst) +" "+"{:.3E}".format(stdErr) +"\n") eqTime = t - self.__transientTime eqRate = self.__floatAnalInterval*actualTot/eqTime eqStdErr = self.__floatAnalInterval*math.sqrt(actualTot)/eqTime stream.write("\nThere were " + "%6i"%(actualTot) + " counts after equilibration. Therefore, the equilibrium rate estimate is " + "{:.6E}".format(eqRate) + "+/-" + "{:.3E}".format(eqStdErr))
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): stream.write("%15s %15s %15s %12s %12s\n"%(" time (t)", " count (n)", "(dn/dt) ", "stdErr", "relErr")) n_tot = 0 actualTot = 0 t = 0.0 for i,n in enumerate(self.__data): # Calculate the values to present. t = i * self.__time_interval if t>=self.__transientTime: actualTot += n dt = self.__time_interval n_tot += n dn = n rateEst = dn/dt stdErr = math.sqrt(dn)/t # Only for times != zero. if i > 0: stream.write("%15.5f %15i %15.5f %15.5f 15.5f\n"%(t, n_tot, rateEst, stdErr, 100.0*(stdErr/rateEst))) eqTime = t - self.__transientTime eqRate = actualTot/eqTime eqStdErr = math.sqrt(actualTot)/eqTime stream.write("\nThere were " + "%15i"%(actualTot) + " counts after equilibration. Therefore, the equilibrium rate estimate is " + "%15.5f"%(actualTot/eqTime) + "+/-" + "%15.5f"%(eqStdErr) + ".")
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): # The format string for the values. format_str = " %15.3e"*(len(self.__empty_count)) format_str += "\n" # The format string for the counts. format_str_1 = " %15s"*(len(self.__empty_count)) format_str_1 += "\n" types_str = ["time"] for t in self.__type_names[1:]: types_str.append(t) stream.write(format_str_1%tuple(types_str)) for i,d in enumerate(self.__data): # Calculate the time. t = i * self.__time_interval + (self.__time_interval / 2.0) # Append the values. tt = [t] for dd in d[1:]: tt.append(dd) # Print. stream.write(format_str%tuple(tt))
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()
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): for item in self.__histogram: stream.write(str(item[0]) + " " + str(item[1]) + "\n")
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): for item in self.__histogram: stream.write(str(item[0])+" "+str(item[1])+"\n")
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()
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): all_results = zip(self.__time_steps, self.__histogram, self.__normalized_histogram) for t, v, n in all_results: stream.write("%10.5f %10i %20.15f\n"%(t, v, n))
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()
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): all_results = zip(self.__time_steps, self.__histogram, self.__normalized_histogram) for t, v, n in all_results: stream.write("%10.5f %10i %20.15f\n" % (t, v, n))
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()
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()
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): for i in range(0, self.__maxExp): if self.__vars[i] < 0.0: stdDev = 0.0 else: stdDev = math.sqrt(self.__vars[i]) stream.write( str(2**(i + 1)) + " " + str(self.__means[i]) + " " + str(stdDev) + "\n")
def testPrintHeader(self): """ Test the print header function. """ # Print to stdout. original_sys_stdout = sys.stdout try: stream_1 = StringIO.StringIO() sys.stdout = stream_1 # Print to stdout. printHeader() # Check. if MPICommons.myRank() == 0: ref_str = """# ----------------------------------------------------------------------------- # KMCLib version 1.1.01 # Distributed under the GPLv3 license # Copyright (C) 2012-2015 Mikael Leetmaa # Developed by Mikael Leetmaa <*****@*****.**> # # This program is distributed in the hope that it will be useful # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # LICENSE and README files, and the source code, for details. # # You should have received a copy of the GNU General Public License version 3 # (GPLv3) along with this program. If not, see <http://www.gnu.org/licenses/>. # ----------------------------------------------------------------------------- """ else: ref_str = "" # Check. self.assertEqual(ref_str, stream_1.getvalue()) finally: # Put the original stdout back. sys.stdout = original_sys_stdout # Print to another stream. stream_2 = StringIO.StringIO() prettyPrint(ref_str, output=stream_2) # Check. self.assertTrue(ref_str in stream_2.getvalue())
def testPrintResults(self): """ Test that we can print the results """ cc = Composition(time_interval=2.0) # Get a proxy config. class DummyConfig: def _backendTypeNames(self): return ("a", "b", "c", "d", "e") def particlesPerType(self): return (1, 2, 3, 4, 5) class DummyConfig2: def _backendTypeNames(self): return ("a", "b", "c", "d", "e") def particlesPerType(self): return (5, 4, 3, 2, 1) config = DummyConfig() config2 = DummyConfig2() # Call setup. cc.setup("dummy_step", 2.0, config) cc.registerStep(4, 5.0, config2) cc.registerStep(5, 10.0, config) cc.registerStep(6, 12.0, config2) cc.registerStep(7, 20.0, config2) stream = StringIO.StringIO() cc.printResults(stream) ref_str = \ """ time b c d e 1.000e+00 2.000e+00 3.000e+00 4.000e+00 5.000e+00 3.000e+00 4.000e+00 3.000e+00 2.000e+00 1.000e+00 5.000e+00 3.000e+00 3.000e+00 3.000e+00 3.000e+00 """ # Reference checked by hand. if MPICommons.isMaster(): self.assertEqual(stream.getvalue(), ref_str) else: self.assertEqual(stream.getvalue(), "")
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): stream.write("%15s %15s %15s %12s\n"%(" time (t)", " count (n)", "(dn/dt) ", "(n/t)")) n_tot = 0 for i,n in enumerate(self.__data): # Calculate the values to present. t = i * self.__time_interval dt = self.__time_interval n_tot += n dn = n # Only for times != zero. if i > 0: stream.write("%15.5f %15i %15.5f %15.5f\n"%(t, n_tot, dn/dt, n_tot/t))
def testPrintResults(self): """ Test that we can print the results """ cc = Composition(time_interval=2.0) # Get a proxy config. class DummyConfig: def _backendTypeNames(self): return ("a","b","c","d","e") def particlesPerType(self): return (1,2,3,4,5) class DummyConfig2: def _backendTypeNames(self): return ("a","b","c","d","e") def particlesPerType(self): return (5,4,3,2,1) config = DummyConfig() config2 = DummyConfig2() # Call setup. cc.setup("dummy_step", 2.0, config) cc.registerStep(4, 5.0, config2) cc.registerStep(5, 10.0, config) cc.registerStep(6, 12.0, config2) cc.registerStep(7, 20.0, config2) stream = StringIO.StringIO() cc.printResults(stream) ref_str = \ """ time b c d e 1.000e+00 2.000e+00 3.000e+00 4.000e+00 5.000e+00 3.000e+00 4.000e+00 3.000e+00 2.000e+00 1.000e+00 5.000e+00 3.000e+00 3.000e+00 3.000e+00 3.000e+00 """ # Reference checked by hand. if MPICommons.isMaster(): self.assertEqual(stream.getvalue(), ref_str) else: self.assertEqual(stream.getvalue(), "")
def testPrintResults(self): """ Test the time step distribution print result function. """ tsd = TimeStepDistribution() # Set the member data. histogram = numpy.array([12,41,55, 23,43,12, 11,19,98, 97,95,93]) normalized_histogram = histogram / float(numpy.sum(histogram)) binsize = 2.13 tsd._TimeStepDistribution__binsize = binsize tsd._TimeStepDistribution__histogram = histogram # Call the finalize function. tsd.finalize() # Print the results to a stream. stream = StringIO.StringIO() tsd.printResults(stream) ref_value = """ 1.06500 12 0.020033388981636 3.19500 41 0.068447412353923 5.32500 55 0.091819699499165 7.45500 23 0.038397328881469 9.58500 43 0.071786310517529 11.71500 12 0.020033388981636 13.84500 11 0.018363939899833 15.97500 19 0.031719532554257 18.10500 98 0.163606010016695 20.23500 97 0.161936560934891 22.36500 95 0.158597662771285 24.49500 93 0.155258764607679 """ # Check the values. if MPICommons.isMaster(): self.assertEqual(stream.getvalue(), ref_value) else: self.assertEqual(stream.getvalue(), "")
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): stream.write("%15s %15s %15s %12s\n" % (" time (t)", " count (n)", "(dn/dt) ", "(n/t)")) n_tot = 0 for i, n in enumerate(self.__data): # Calculate the values to present. t = i * self.__time_interval dt = self.__time_interval n_tot += n dn = n # Only for times != zero. if i > 0: stream.write("%15.5f %15i %15.5f %15.5f\n" % (t, n_tot, dn / dt, n_tot / t))
def printResults(self, stream=sys.stdout): """ Print the results to the stream. :param stream: The stream to print to. """ # Only master writes. if MPICommons.isMaster(): stream.write( "%15s %15s %15s %12s %12s\n" % (" time (t)", " count (n)", "(dn/dt) ", "stdErr", "relErr")) n_tot = 0 actualTot = 0 t = 0.0 for i, n in enumerate(self.__data): # Calculate the values to present. t = i * self.__time_interval if t >= self.__transientTime: actualTot += n dt = self.__time_interval n_tot += n dn = n rateEst = dn / dt stdErr = math.sqrt(dn) / t # Only for times != zero. if i > 0: stream.write("%15.5f %15i %15.5f %15.5f 15.5f\n" % (t, n_tot, rateEst, stdErr, 100.0 * (stdErr / rateEst))) eqTime = t - self.__transientTime eqRate = actualTot / eqTime eqStdErr = math.sqrt(actualTot) / eqTime stream.write( "\nThere were " + "%15i" % (actualTot) + " counts after equilibration. Therefore, the equilibrium rate estimate is " + "%15.5f" % (actualTot / eqTime) + "+/-" + "%15.5f" % (eqStdErr) + ".")
def testPrintResults(self): """ Test that we can print the results """ # Setup. ps = ProcessStatistics(processes=[0], time_interval=0.3) # Add data on the class. ps._ProcessStatistics__data = [0, 12, 245, 1435] stream = StringIO.StringIO() ps.printResults(stream) # Reference checked by hand. ref_value = \ """ time (t) count (n) (dn/dt) (n/t) 0.30000 12 40.00000 40.00000 0.60000 257 816.66667 428.33333 0.90000 1692 4783.33333 1880.00000 """ if MPICommons.isMaster(): self.assertEqual(stream.getvalue(), ref_value) else: self.assertEqual(stream.getvalue(), "")
def testPrintResults(self): """ Test the time step distribution print result function. """ tsd = TimeStepDistribution() # Set the member data. histogram = numpy.array( [12, 41, 55, 23, 43, 12, 11, 19, 98, 97, 95, 93]) normalized_histogram = histogram / float(numpy.sum(histogram)) binsize = 2.13 tsd._TimeStepDistribution__binsize = binsize tsd._TimeStepDistribution__histogram = histogram # Call the finalize function. tsd.finalize() # Print the results to a stream. stream = StringIO.StringIO() tsd.printResults(stream) ref_value = """ 1.06500 12 0.020033388981636 3.19500 41 0.068447412353923 5.32500 55 0.091819699499165 7.45500 23 0.038397328881469 9.58500 43 0.071786310517529 11.71500 12 0.020033388981636 13.84500 11 0.018363939899833 15.97500 19 0.031719532554257 18.10500 98 0.163606010016695 20.23500 97 0.161936560934891 22.36500 95 0.158597662771285 24.49500 93 0.155258764607679 """ # Check the values. if MPICommons.isMaster(): self.assertEqual(stream.getvalue(), ref_value) else: self.assertEqual(stream.getvalue(), "")
def testFlush2(self): """ Test the file output. """ # Get a file name. 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.xyz") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Setup the trajectory object. unit_cell = KMCUnitCell(cell_vectors=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], basis_points=[[0.0, 0.0, 0.0]]) lattice = KMCLattice(unit_cell=unit_cell, periodic=(True, False, True), repetitions=(4,4,4)) config = KMCConfiguration(lattice=lattice, types=["A","B","C","D"]*16) t = XYZTrajectory(trajectory_filename=trajectory_filename, configuration=config, max_buffer_size=12345, max_buffer_time=123.0) # Set data directly on the class. t._XYZTrajectory__atom_id_types = [("A","B","C","D","E"), ("This","is","the","next","step")] t._XYZTrajectory__atom_id_coordinates = [numpy.zeros((5,3)), numpy.ones((5,3))*1.234] t._XYZTrajectory__step = [0, 12] t._XYZTrajectory__time = [12.123,75.43] # Flush. t.flush() ref_content = """KMCLib XYZ FORMAT VERSION 2013.10.15 CELL VECTORS a: 1.0000000000e+00 0.0000000000e+00 0.0000000000e+00 b: 0.0000000000e+00 1.0000000000e+00 0.0000000000e+00 c: 0.0000000000e+00 0.0000000000e+00 1.0000000000e+00 REPETITIONS 4 4 4 PERIODICITY True False True STEP 0 5 TIME 1.2123000000e+01 A 0.0000000000e+00 0.0000000000e+00 0.0000000000e+00 0 B 0.0000000000e+00 0.0000000000e+00 0.0000000000e+00 1 C 0.0000000000e+00 0.0000000000e+00 0.0000000000e+00 2 D 0.0000000000e+00 0.0000000000e+00 0.0000000000e+00 3 E 0.0000000000e+00 0.0000000000e+00 0.0000000000e+00 4 STEP 12 5 TIME 7.5430000000e+01 This 1.2340000000e+00 1.2340000000e+00 1.2340000000e+00 0 is 1.2340000000e+00 1.2340000000e+00 1.2340000000e+00 1 the 1.2340000000e+00 1.2340000000e+00 1.2340000000e+00 2 next 1.2340000000e+00 1.2340000000e+00 1.2340000000e+00 3 step 1.2340000000e+00 1.2340000000e+00 1.2340000000e+00 4 """ if MPICommons.isMaster(): with open(trajectory_filename, "r") as f: content = f.read() self.assertEqual( content, ref_content ) # Check that the buffers are empty. self.assertEqual(t._XYZTrajectory__atom_id_types, []) self.assertEqual(t._XYZTrajectory__atom_id_coordinates, []) self.assertEqual(t._XYZTrajectory__time, []) self.assertEqual(t._XYZTrajectory__step, [])
def printResults(self, stream=sys.stdout): if MPICommons.isMaster(): for index in range(0, self.__histSize): stream.write(str(index)+" "+"{:.6E}".format(self.__finalHist[index])+"\n")
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
def testStoreData(self): """ Test the data storage function. """ # Get a file name. 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.xyz") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Setup the trajectory object. unit_cell = KMCUnitCell(cell_vectors=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], basis_points=[[0.0, 0.0, 0.0]]) lattice = KMCLattice(unit_cell=unit_cell, periodic=(True, True, True), repetitions=(4,4,4)) config = KMCConfiguration(lattice=lattice, types=["A","B","C","D"]*16) t = XYZTrajectory(trajectory_filename=trajectory_filename, configuration=config, max_buffer_size=12345, max_buffer_time=123.0) # Construct data to store. simulation_time = 1.234 step = 123 configuration = config # Store. t._storeData(simulation_time, step, configuration) # Check that the member data was updated. self.assertEqual(len(t._XYZTrajectory__atom_id_types), 1) self.assertEqual(len(t._XYZTrajectory__atom_id_coordinates), 1) self.assertEqual(len(t._XYZTrajectory__time), 1) self.assertEqual(len(t._XYZTrajectory__step), 1) # store again. simulation_time = 1.999 step = 4444 t._storeData(simulation_time, step, configuration) # Check that the member data was updated. self.assertEqual(len(t._XYZTrajectory__atom_id_types), 2) self.assertEqual(len(t._XYZTrajectory__atom_id_coordinates), 2) self.assertEqual(len(t._XYZTrajectory__time), 2) self.assertEqual(len(t._XYZTrajectory__step), 2) # Check the values of the stored data. self.assertAlmostEqual(t._XYZTrajectory__time[0], 1.234, 10) self.assertAlmostEqual(t._XYZTrajectory__time[1], 1.999, 10) self.assertEqual(t._XYZTrajectory__step[0], 123) self.assertEqual(t._XYZTrajectory__step[1], 4444) diff = numpy.linalg.norm(config.atomIDCoordinates() - t._XYZTrajectory__atom_id_coordinates[0]) self.assertAlmostEqual(diff, 0.0, 10) diff = numpy.linalg.norm(config.atomIDCoordinates() - t._XYZTrajectory__atom_id_coordinates[1]) self.assertAlmostEqual(diff, 0.0, 10) self.assertEqual(t._XYZTrajectory__atom_id_types[0], config.atomIDTypes()) self.assertEqual(t._XYZTrajectory__atom_id_types[1], config.atomIDTypes())
def testPrintResults(self): """ Test that the results gets printed as expected. """ # Fill an object with data. ref_results = numpy.array([[ 2.83900934, 8.52281124, 14.09108351, 20.00585490, 25.26096208, 30.09109804, 36.62202664, 43.47434981, 50.79520993, 58.25866865], [ 2.88482657, 8.20673616, 13.39956335, 17.50176483, 22.89894945, 29.46099902, 36.60734674, 44.33478009, 52.14399436, 59.49159482], [ 22.88482657, 48.20673616, 53.39956335, 67.50176483, 72.89894945, 39.46099902, 56.60734674, 54.33478009, 62.14399436, 79.49159482], [ 3.12507672, 8.84431286, 13.83414102, 18.58819987, 24.03051120, 29.05110007, 77.65539622, 40.08318015, 46.38807125, 54.56025293], [ 13.83900934, 66.52281124, 14.09108351, 20.00585490, 25.26096208, 24.09109804, 88.62202664, 43.47434981, 30.79520993, 78.25866865], [ 35.88482657, 5.20673616, 13.39956335, 37.50176483, 82.89894945, 45.46099902, 34.60734674, 44.33478009, 42.14399436, 99.49159482], [ 56.12507672, 1.84431286, 13.83414102, 58.58819987, 84.03051120, 29.05110007, 33.65539622, 40.08318015, 56.38807125, 74.56025293]]) ref_time_steps = numpy.array([ 1.25, 3.75, 6.25, 8.75, 11.25, 13.75, 16.25, 18.75, 21.25, 23.75]) ref_std_dev = numpy.array([[ 0.02008562, 0.05432052, 0.08833069, 0.11053417, 0.12584537, 0.14901027, 0.18265464, 0.20891115, 0.24045901, 0.27834904], [ 0.01911933, 0.04761810, 0.07830592, 0.10414501, 0.14034533, 0.18069990, 0.23416218, 0.28725392, 0.34211121, 0.39464802], [ 0.02198474, 0.05167655, 0.08130953, 0.10885342, 0.14397243, 0.16894787, 0.19585331, 0.22369909, 0.25162530, 0.29321875], [ 3.02198474, 4.05167655, 5.08130953, 5.10885342, 0.14397243, 4.16894787, 3.19585331, 4.22369909, 50.25162530, 10.29321875], [ 1.02008562, 3.05432052, 0.08833069, 0.11053417, 44.12584537, 3.14901027, 3.18265464, 4.20891115, 0.24045901, 0.27834904], [ 4.01911933, 5.04761810, 4.07830592, 0.10414501, 0.14034533, 1.18069990, 5.23416218, 6.28725392, 4.34211121, 0.39464802], [ 6.02198474, 7.05167655, 3.08130953, 2.10885342, 4.14397243, 1.16894787, 7.19585331, 8.22369909, 0.25162530, 0.29321875]]) ref_bin_counters = (60283, 60628, 60461, 59779, 59683, 59178, 58856, 58752, 58162, 57881) ref_history_bin_counters = [(0, 0, 0, 0, 0, 1, 87, 58752, 58162, 57881)] msd = OnTheFlyMSD.__new__(OnTheFlyMSD) msd._OnTheFlyMSD__results = ref_results msd._OnTheFlyMSD__time_steps = ref_time_steps msd._OnTheFlyMSD__std_dev = ref_std_dev msd._OnTheFlyMSD__bin_counters = ref_bin_counters msd._OnTheFlyMSD__history_bin_counters = ref_history_bin_counters msd._OnTheFlyMSD__n_eff = [0.1, 1.2, 3.4, 5.5, 6.6, 7.7, 0.8, 9.9, 4.3, 2.1] # Print the results to a stream. stream = StringIO.StringIO() msd.printResults(stream) # Check against reference. ref_value = """ TIME MSD_x DSD_y MSD_z MSD_xy MSD_xz MSD_yz MSD_xyz STD_x STD_y STD_z STD_xy STD_xz STD_yz STD_xyz N_eff 1.25000e+00 2.83901e+00 2.88483e+00 2.28848e+01 3.12508e+00 1.38390e+01 3.58848e+01 5.61251e+01 2.00856e-02 1.91193e-02 2.19847e-02 3.02198e+00 1.02009e+00 4.01912e+00 6.02198e+00 1.00000e-01 3.75000e+00 8.52281e+00 8.20674e+00 4.82067e+01 8.84431e+00 6.65228e+01 5.20674e+00 1.84431e+00 5.43205e-02 4.76181e-02 5.16766e-02 4.05168e+00 3.05432e+00 5.04762e+00 7.05168e+00 1.20000e+00 6.25000e+00 1.40911e+01 1.33996e+01 5.33996e+01 1.38341e+01 1.40911e+01 1.33996e+01 1.38341e+01 8.83307e-02 7.83059e-02 8.13095e-02 5.08131e+00 8.83307e-02 4.07831e+00 3.08131e+00 3.40000e+00 8.75000e+00 2.00059e+01 1.75018e+01 6.75018e+01 1.85882e+01 2.00059e+01 3.75018e+01 5.85882e+01 1.10534e-01 1.04145e-01 1.08853e-01 5.10885e+00 1.10534e-01 1.04145e-01 2.10885e+00 5.50000e+00 1.12500e+01 2.52610e+01 2.28989e+01 7.28989e+01 2.40305e+01 2.52610e+01 8.28989e+01 8.40305e+01 1.25845e-01 1.40345e-01 1.43972e-01 1.43972e-01 4.41258e+01 1.40345e-01 4.14397e+00 6.60000e+00 1.37500e+01 3.00911e+01 2.94610e+01 3.94610e+01 2.90511e+01 2.40911e+01 4.54610e+01 2.90511e+01 1.49010e-01 1.80700e-01 1.68948e-01 4.16895e+00 3.14901e+00 1.18070e+00 1.16895e+00 7.70000e+00 1.62500e+01 3.66220e+01 3.66073e+01 5.66073e+01 7.76554e+01 8.86220e+01 3.46073e+01 3.36554e+01 1.82655e-01 2.34162e-01 1.95853e-01 3.19585e+00 3.18265e+00 5.23416e+00 7.19585e+00 8.00000e-01 """ if MPICommons.isMaster(): self.assertEqual(stream.getvalue(), ref_value) else: self.assertEqual(stream.getvalue(), "")
def testFlush(self): """ Make sure we can flush the buffer as expected. """ # Get a filename. 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") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Construct the trajecctory object. 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]] # Construct. t = LatticeTrajectory(trajectory_filename, Config(sites)) # To check against. empty_list = [] # Check that the file is created but only with meta information. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) ret_types = local_dict['types'] self.assertEqual( ret_types, empty_list ) ret_times = local_dict['times'] self.assertEqual( ret_times, empty_list ) ret_steps = local_dict['steps'] self.assertEqual( ret_steps, empty_list ) # Fill the buffers. t._LatticeTrajectory__types_buffer = [["ABC", "123"],["123", "ABC"]] t._LatticeTrajectory__simulation_time_buffer = [1.234, 5.678] t._LatticeTrajectory__step_buffer = [1, 99] # Flush the buffers. t.flush() # Check that the buffers are empty. self.assertEqual( t._LatticeTrajectory__types_buffer, empty_list ) self.assertEqual( t._LatticeTrajectory__simulation_time_buffer, empty_list ) self.assertEqual( t._LatticeTrajectory__step_buffer, empty_list ) # Check that the file has the flushed values. if MPICommons.isMaster(): global_dict = {} local_dict = {} execfile(trajectory_filename, global_dict, local_dict) ret_types = local_dict['types'] self.assertEqual( ret_types, [["ABC", "123"],["123", "ABC"]] ) ret_times = local_dict['times'] self.assertAlmostEqual( ret_times, [1.234, 5.678], 10 ) ret_steps = local_dict['steps'] self.assertEqual( ret_steps, [1, 99] )
def testFlush(self): """ Test the file output. """ # Get a file name. 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.xyz") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Setup the trajectory object. unit_cell = KMCUnitCell(cell_vectors=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], basis_points=[[0.0, 0.0, 0.0]]) lattice = KMCLattice(unit_cell=unit_cell, periodic=(True, False, True), repetitions=(4,4,4)) config = KMCConfiguration(lattice=lattice, types=["A","B","C","D"]*16) t = XYZTrajectory(trajectory_filename=trajectory_filename, configuration=config, max_buffer_size=12345, max_buffer_time=123.0) # Store data. simulation_time = 1.234 step = 123 t._storeData(simulation_time, step, config) # Flush. t.flush() # Check the file. ref_content = """KMCLib XYZ FORMAT VERSION 2013.10.15 CELL VECTORS a: 1.0000000000e+00 0.0000000000e+00 0.0000000000e+00 b: 0.0000000000e+00 1.0000000000e+00 0.0000000000e+00 c: 0.0000000000e+00 0.0000000000e+00 1.0000000000e+00 REPETITIONS 4 4 4 PERIODICITY True False True STEP 123 64 TIME 1.2340000000e+00 A 0.0000000000e+00 0.0000000000e+00 0.0000000000e+00 0 B 0.0000000000e+00 0.0000000000e+00 1.0000000000e+00 1 C 0.0000000000e+00 0.0000000000e+00 2.0000000000e+00 2 D 0.0000000000e+00 0.0000000000e+00 3.0000000000e+00 3 A 0.0000000000e+00 1.0000000000e+00 0.0000000000e+00 4 B 0.0000000000e+00 1.0000000000e+00 1.0000000000e+00 5 C 0.0000000000e+00 1.0000000000e+00 2.0000000000e+00 6 D 0.0000000000e+00 1.0000000000e+00 3.0000000000e+00 7 A 0.0000000000e+00 2.0000000000e+00 0.0000000000e+00 8 B 0.0000000000e+00 2.0000000000e+00 1.0000000000e+00 9 C 0.0000000000e+00 2.0000000000e+00 2.0000000000e+00 10 D 0.0000000000e+00 2.0000000000e+00 3.0000000000e+00 11 A 0.0000000000e+00 3.0000000000e+00 0.0000000000e+00 12 B 0.0000000000e+00 3.0000000000e+00 1.0000000000e+00 13 C 0.0000000000e+00 3.0000000000e+00 2.0000000000e+00 14 D 0.0000000000e+00 3.0000000000e+00 3.0000000000e+00 15 A 1.0000000000e+00 0.0000000000e+00 0.0000000000e+00 16 B 1.0000000000e+00 0.0000000000e+00 1.0000000000e+00 17 C 1.0000000000e+00 0.0000000000e+00 2.0000000000e+00 18 D 1.0000000000e+00 0.0000000000e+00 3.0000000000e+00 19 A 1.0000000000e+00 1.0000000000e+00 0.0000000000e+00 20 B 1.0000000000e+00 1.0000000000e+00 1.0000000000e+00 21 C 1.0000000000e+00 1.0000000000e+00 2.0000000000e+00 22 D 1.0000000000e+00 1.0000000000e+00 3.0000000000e+00 23 A 1.0000000000e+00 2.0000000000e+00 0.0000000000e+00 24 B 1.0000000000e+00 2.0000000000e+00 1.0000000000e+00 25 C 1.0000000000e+00 2.0000000000e+00 2.0000000000e+00 26 D 1.0000000000e+00 2.0000000000e+00 3.0000000000e+00 27 A 1.0000000000e+00 3.0000000000e+00 0.0000000000e+00 28 B 1.0000000000e+00 3.0000000000e+00 1.0000000000e+00 29 C 1.0000000000e+00 3.0000000000e+00 2.0000000000e+00 30 D 1.0000000000e+00 3.0000000000e+00 3.0000000000e+00 31 A 2.0000000000e+00 0.0000000000e+00 0.0000000000e+00 32 B 2.0000000000e+00 0.0000000000e+00 1.0000000000e+00 33 C 2.0000000000e+00 0.0000000000e+00 2.0000000000e+00 34 D 2.0000000000e+00 0.0000000000e+00 3.0000000000e+00 35 A 2.0000000000e+00 1.0000000000e+00 0.0000000000e+00 36 B 2.0000000000e+00 1.0000000000e+00 1.0000000000e+00 37 C 2.0000000000e+00 1.0000000000e+00 2.0000000000e+00 38 D 2.0000000000e+00 1.0000000000e+00 3.0000000000e+00 39 A 2.0000000000e+00 2.0000000000e+00 0.0000000000e+00 40 B 2.0000000000e+00 2.0000000000e+00 1.0000000000e+00 41 C 2.0000000000e+00 2.0000000000e+00 2.0000000000e+00 42 D 2.0000000000e+00 2.0000000000e+00 3.0000000000e+00 43 A 2.0000000000e+00 3.0000000000e+00 0.0000000000e+00 44 B 2.0000000000e+00 3.0000000000e+00 1.0000000000e+00 45 C 2.0000000000e+00 3.0000000000e+00 2.0000000000e+00 46 D 2.0000000000e+00 3.0000000000e+00 3.0000000000e+00 47 A 3.0000000000e+00 0.0000000000e+00 0.0000000000e+00 48 B 3.0000000000e+00 0.0000000000e+00 1.0000000000e+00 49 C 3.0000000000e+00 0.0000000000e+00 2.0000000000e+00 50 D 3.0000000000e+00 0.0000000000e+00 3.0000000000e+00 51 A 3.0000000000e+00 1.0000000000e+00 0.0000000000e+00 52 B 3.0000000000e+00 1.0000000000e+00 1.0000000000e+00 53 C 3.0000000000e+00 1.0000000000e+00 2.0000000000e+00 54 D 3.0000000000e+00 1.0000000000e+00 3.0000000000e+00 55 A 3.0000000000e+00 2.0000000000e+00 0.0000000000e+00 56 B 3.0000000000e+00 2.0000000000e+00 1.0000000000e+00 57 C 3.0000000000e+00 2.0000000000e+00 2.0000000000e+00 58 D 3.0000000000e+00 2.0000000000e+00 3.0000000000e+00 59 A 3.0000000000e+00 3.0000000000e+00 0.0000000000e+00 60 B 3.0000000000e+00 3.0000000000e+00 1.0000000000e+00 61 C 3.0000000000e+00 3.0000000000e+00 2.0000000000e+00 62 D 3.0000000000e+00 3.0000000000e+00 3.0000000000e+00 63 """ if MPICommons.isMaster(): with open(trajectory_filename, "r") as f: content = f.read() self.assertEqual( content, ref_content ) # Check that the buffers are empty. self.assertEqual(t._XYZTrajectory__atom_id_types, []) self.assertEqual(t._XYZTrajectory__atom_id_coordinates, []) self.assertEqual(t._XYZTrajectory__time, []) self.assertEqual(t._XYZTrajectory__step, [])
def testBufferSize(self): """ Test the buffer size function. """ # Get a file name. 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.xyz") if MPICommons.isMaster(): self.__files_to_remove.append(trajectory_filename) # Setup the trajectory object. unit_cell = KMCUnitCell(cell_vectors=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], basis_points=[[0.0, 0.0, 0.0]]) lattice = KMCLattice(unit_cell=unit_cell, periodic=(True, True, True), repetitions=(4,4,4)) config = KMCConfiguration(lattice=lattice, types=["A","B","C","D"]*16) t = XYZTrajectory(trajectory_filename=trajectory_filename, configuration=config, max_buffer_size=12345, max_buffer_time=123.0) # Store a bunch of data. simulation_time = 1.234 step = 123 t._storeData(simulation_time, step, config) buffer_size = t._bufferSize() # Check the size again. ref_size = sys.getsizeof(t._XYZTrajectory__atom_id_coordinates) ref_size += sys.getsizeof(t._XYZTrajectory__atom_id_coordinates[0])*len(t._XYZTrajectory__atom_id_coordinates) ref_size += sys.getsizeof(t._XYZTrajectory__atom_id_types) ref_size += sys.getsizeof(t._XYZTrajectory__atom_id_types[0])*len(t._XYZTrajectory__atom_id_types) ref_size += sys.getsizeof(t._XYZTrajectory__time) ref_size += sys.getsizeof(t._XYZTrajectory__time[0])*len(t._XYZTrajectory__time) ref_size += sys.getsizeof(t._XYZTrajectory__step) ref_size += sys.getsizeof(t._XYZTrajectory__step[0])*len(t._XYZTrajectory__step) self.assertEqual(buffer_size, ref_size) # Store more data. t._storeData(simulation_time, step, config) # Check the size again. t._storeData(simulation_time, step, config) t._storeData(simulation_time, step, config) t._storeData(simulation_time, step, config) t._storeData(simulation_time, step, config) t._storeData(simulation_time, step, config) ref_size = sys.getsizeof(t._XYZTrajectory__atom_id_coordinates) ref_size += sys.getsizeof(t._XYZTrajectory__atom_id_coordinates[0])*len(t._XYZTrajectory__atom_id_coordinates) ref_size += sys.getsizeof(t._XYZTrajectory__atom_id_types) ref_size += sys.getsizeof(t._XYZTrajectory__atom_id_types[0])*len(t._XYZTrajectory__atom_id_types) ref_size += sys.getsizeof(t._XYZTrajectory__time) ref_size += sys.getsizeof(t._XYZTrajectory__time[0])*len(t._XYZTrajectory__time) ref_size += sys.getsizeof(t._XYZTrajectory__step) ref_size += sys.getsizeof(t._XYZTrajectory__step[0])*len(t._XYZTrajectory__step) buffer_size = t._bufferSize() self.assertEqual(buffer_size, ref_size)
def printResults(self, stream=sys.stdout): rateEst = float(self.__current_count)/(self.__lastTime - self.__initTime) if MPICommons.isMaster() and not math.isnan(rateEst): stream.write("{:.6E}".format(rateEst)+"\n")