Classes hide much of the complexity of code.¶
We can use very simple methods to save data to disk¶
We can create objects and save to disk without have to have detailed knowledge of their internal structure. If we are willing to have a non-human readable file then python allows you to write out a complete object, preserving all information. This uses the pickle
format.
Writing out data¶
In [1]:
import pickle # this is the magic to save an object to disk
from simul import Simul
simul = Simul(L=4, simul_time=0.1, sigma=0.5) # this line calls __init__
print(simul.__doc__) # print the class documentation
simul.md_step() # move forwards sample_time
print(simul) # we have defined the function __str__, so we can print
with open('simul.pickle', 'wb') as file: # this sends all the state to a file
pickle.dump(simul,file)
print("we have saved the data to the file simul.pickle")
This is the prototype of the simulation code It moves the particles with at velocity, using a vector notation: numpy should be used. Simul::md_step pos= [[2.00583194 1.66637062] [5.09271708 2.15617709] [2.24553793 5.47748117] [4.78207456 4.85046322]] vel= [[ 0.05831945 -3.33629383] [ 0.92717077 1.56177092] [ 2.45537932 4.7748117 ] [-2.17925437 -1.49536779]] we have saved the data to the file simul.pickle
simul.pickle
now contains a full copy of the state of the simulation
We can load it back in to memory and read its contents.
Reading in Data¶
In [2]:
with open('simul.pickle', 'rb') as file:
simul_copy = pickle.load(file) # we
print('loaded position' , simul_copy.position)
loaded position [[2.00583194 1.66637062] [5.09271708 2.15617709] [2.24553793 5.47748117] [4.78207456 4.85046322]]
If we want to have human readable output to a file we can also use 'csv' output¶
In [3]:
import csv
with open('simul.csv','w') as file:
writer = csv.writer(file)
writer.writerow(simul.position)
Or we just save a numpy array to a file¶
In [4]:
import numpy as np
np.savetxt("position.txt", simul.position)
In [ ]: