def load_dens(self): """ Returns multi-dim numpy array containing all density profiles from file self.fname """ try: open(self.fname, "r") except: raise IOError, "File %s could not be opened." % (self.fname, ) return np.array(rxvg.lines_to_list_of_lists(rxvg.read_xvg(self.fname)))
def load_x_q_as_nparray(self): """ loads x and q profile from a xvg file self.fname into self.x,q in-place """ try: open(self.fname,"r") except: print "File %s could not be opened." % (self.fname,) raise IOError try: self.x, self.q_noisy = np.split(np.array( rxvg.lines_to_list_of_lists(rxvg.read_xvg(self.fname)) ).ravel(order="F") , 2 ) except: raise RuntimeError, "File %s could not be loaded, possibly because of wrong formatting." % (self.fname,)
def load_x_q_as_nparray(self): """ loads x and q profile from a xvg file self.fname into self.x,q in-place """ try: open(self.fname, "r") except: print "File %s could not be opened." % (self.fname, ) raise IOError try: self.x, self.q_noisy = np.split( np.array(rxvg.lines_to_list_of_lists(rxvg.read_xvg( self.fname))).ravel(order="F"), 2) except: raise RuntimeError, "File %s could not be loaded, possibly because of wrong formatting." % ( self.fname, )
def read_trajs(self, binwidth): """ Reads in Plumed's Pitch files (3columns) or Gromacs pullx files (8 columns) File format plain (Plumed, also suits pitch-n-roll output with change bias->roll): ------------ 3 columns : floats Time -- PITCH -- bias (roll for PNR) crashes or unexpected behaviour if different format (e.g. more cols) File format pnr_[roll, pitch] (for roll/pitch coordinate from pitch-n-roll code): ------------ 3 columns : floats Time -- PITCH -- ROLL crashes or unexpected behaviour if different format (e.g. more cols) File format plain2 (Plumed): ------------ 2 columns (otherwise same) File format xvg (Gromacs pullx): ------------ 8 columns : float Time -- x,y,z -- length -- dx,dy,dz Returns ------- trajs : list of dictionaries containing arrays with the key convention of pytram dict-key 'm' -- Markov state -- 0-based indexing """ def discretize(in_data, offset=0.0): """ turns data into integers, i.e. discretizes data based on the offset and bin width Discretized data are 0-based indices (shifted with local var smallest) Parameters ---------- data : np.array data to be discretized offset : float starting value for the discretization scheme """ data = np.copy(in_data) if offset != 0.0: data -= offset # binwidth variable taken from the # enclosing scope (at definition time) -- closure if binwidth != 1.0: data /= binwidth return data.astype(int) smallest = None trajs = [] for sim in self.sims: filename = sim['fname'] tmpdict = {} if self.traj_file_format == "plain": # should contain exactly 3 columns tmpdict['time'], tmpdict['x'], tmpdict['b'] = np.hsplit( np.loadtxt(filename), 3) # convert from kJ/mol to kT units tmpdict['b'] /= k_b * sim['temperature'] elif self.traj_file_format == "plain2": # should contain exactly 2 columns tmpdict['time'], tmpdict['x'] = np.hsplit( np.loadtxt(filename), 2) elif self.traj_file_format == "xvg": # create a numpy array with the contents of .xvg file; # should contain exactly 8 columns tmp_arr = np.array( rxvg.lines_to_list_of_lists(rxvg.read_xvg(filename))) tmpdict['time'] = tmp_arr[:, 0] tmpdict['x'] = tmp_arr[:, 4] elif "pnr" in self.traj_file_format: # should contain exactly 3 columns tmpdict['time'], tmpdict['pitch'], tmpdict['roll'] = np.hsplit( np.loadtxt(filename), 3) # convert from kJ/mol to kT units if "roll" in self.traj_file_format: tmpdict['x'] = tmpdict['roll'] elif "pitch" in self.traj_file_format: tmpdict['x'] = tmpdict['pitch'] else: raise RuntimeError, "only pitch -or- roll defined in the file format!" # setting bias to 0, as the file format does not contain it anyway # for the case some other method/procedure might need it tmpdict['b'] = tmpdict['x'] * 0.0 else: print "Given file format undefined: ", self.traj_file_format raise RuntimeError tmpdict['m'] = discretize(tmpdict['x']) # find the smallest state-no if smallest == None or smallest > tmpdict['m'].min(): smallest = tmpdict['m'].min() # thermodynamic state assumed constant during each simulation tmpdict['t'] = np.ones(tmpdict['m'].shape, dtype=int) * sim['t'] trajs.append(tmpdict) # shift the trajs by the smallest state-no (smallest var) for traj in trajs: traj['m'] -= smallest return trajs
def load_dens(self): """ Returns multi-dim numpy array containing all density profiles from file self.fname """ try: open(self.fname,"r") except: raise IOError, "File %s could not be opened." % (self.fname,) return np.array( rxvg.lines_to_list_of_lists(rxvg.read_xvg(self.fname)) )
def get_potential(charge_file, Xref=14.8, crop=0, fcorr_type="cent_plat_zero", field_intensity=0.0, qcorr=True, plot=False, **kwargs): """ Function get_potential returns the voltage drop (in V) across the membrane from simulations with two membranes. It uses function int_q for integration, which starts the integration from the centre, Scales the box length to the reference value Xref (approximate average from the simulations), allows cropping from left/right sides, It returns the absolute (positive) average value of the voltage drop (in V) taken from drops centre-left and centre-right. """ # Xref is in nm, value taken from the average of the longest simulations #create a numpy array with the contents of .xvg file; nested: file -> lines -> list-of-lists(floats) -> np.array -> flatten(ravel) -> split in 2 X, Charge = np.split( np.array(rxvg.lines_to_list_of_lists( rxvg.read_xvg(charge_file))).ravel(order="F"), 2) # V--- list of lists <----------- list of lines # numpy array ----------------------------------------------> flattened ... # .... and split .... ....... in ............. .......... two! #Scale potential to the average Z-length box_fluct_thres = 0.2 if abs(Xref - X.max()) > box_fluct_thres: print "Scaling box length from %4.2f to %4.2f nm (average length from the longest simulation)" % ( X.max(), Xref) print "This is quite a large difference. \n" X *= Xref / X.max() #Crop box ends if crop >= 0: X = X[crop:len(X) - crop] Charge = Charge[crop:len(Charge) - crop] #shift Box-Z centre to 0.0 #assumes that Box starts at z=0 and ends at some z=Length X -= X[int(len(X) / 2)] # total charge and dipole of the system #Qtot = np.trapz(Charge, x=X) #print "Net charge: %5.4f q/nm^2" % (Qtot,) #Ptot = np.trapz(np.multiply(Charge,X), x=X) #print "Net dipole: %5.4f D/nm^2 \n" % (1/0.393456*1.889725989e1*Ptot,) # Magic constants by Stepan (Field, Potential, V) = int_q_twice(Charge, X, fcorr_type, field_intensity, qcorr) if plot: import matplotlib.pyplot as plt #Read-in densities densities_file = kwargs.get("densfile") Xdens, phos, tail, wat = np.genfromtxt(densities_file, comments="#", skip_header=24, unpack=True) #Scaling to the same average Z-length (see above) Xdens *= Xref / Xdens.max() Numdens = len(Xdens) cendens = int(Numdens / 2) Xdens_shift = Xdens - Xdens[cendens] #Plots fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(Xdens_shift, phos / 256, 'b', label="P") ax1.plot(Xdens_shift, tail / 512, 'm', label="Terminal C") ax1.plot(Xdens_shift, wat / 10128, 'c', label="Water") ax1.set_xlabel('Z [nm]') ax1.set_ylabel(r'Number density normalized to unity [nm$^{-3}$]') plt.legend(loc="upper left") ax2 = ax1.twinx() ax2.plot(X, Potential, 'k', label="Electrostatic potential", lw=2) ax2.plot([X[0], X[len(X) - 1]], [0, 0], '--', label="Zero", lw=2) ax2.set_ylabel('Potential [V]') plt.legend(loc="upper center") plt.show() fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(Xdens_shift, phos / 256, 'b', label="P") ax1.plot(Xdens_shift, tail / 512, 'm', label="Terminal C") ax1.plot(Xdens_shift, wat / 10128, 'c', label="Water") ax1.set_xlabel('Z [nm]') ax1.set_ylabel(r'Number density normalized to unity [nm$^{-3}$]') plt.legend(loc="upper left") ax2 = ax1.twinx() ax2.plot(X, Field, 'k', label="Intensity of electric field", lw=2) ax2.set_ylabel('Field [V/nm]') plt.legend(loc="upper center") plt.show() return V
def get_potential(charge_file, Xref=14.8, crop=0, fcorr_type="cent_plat_zero", field_intensity=0.0, qcorr=True, plot=False, **kwargs): """ Function get_potential returns the voltage drop (in V) across the membrane from simulations with two membranes. It uses function int_q for integration, which starts the integration from the centre, Scales the box length to the reference value Xref (approximate average from the simulations), allows cropping from left/right sides, It returns the absolute (positive) average value of the voltage drop (in V) taken from drops centre-left and centre-right. """ # Xref is in nm, value taken from the average of the longest simulations #create a numpy array with the contents of .xvg file; nested: file -> lines -> list-of-lists(floats) -> np.array -> flatten(ravel) -> split in 2 X, Charge = np.split(np.array( rxvg.lines_to_list_of_lists(rxvg.read_xvg(charge_file)) ).ravel(order="F") , 2 ) # V--- list of lists <----------- list of lines # numpy array ----------------------------------------------> flattened ... # .... and split .... ....... in ............. .......... two! #Scale potential to the average Z-length box_fluct_thres=0.2 if abs(Xref-X.max())>box_fluct_thres: print "Scaling box length from %4.2f to %4.2f nm (average length from the longest simulation)" % (X.max(),Xref) print "This is quite a large difference. \n" X *= Xref/X.max() #Crop box ends if crop>=0 : X = X[crop:len(X)-crop] Charge = Charge[crop:len(Charge)-crop] #shift Box-Z centre to 0.0 #assumes that Box starts at z=0 and ends at some z=Length X -= X[int(len(X)/2)] # total charge and dipole of the system #Qtot = np.trapz(Charge, x=X) #print "Net charge: %5.4f q/nm^2" % (Qtot,) #Ptot = np.trapz(np.multiply(Charge,X), x=X) #print "Net dipole: %5.4f D/nm^2 \n" % (1/0.393456*1.889725989e1*Ptot,) # Magic constants by Stepan (Field, Potential, V) = int_q_twice(Charge, X, fcorr_type, field_intensity, qcorr) if plot: import matplotlib.pyplot as plt #Read-in densities densities_file = kwargs.get("densfile") Xdens, phos, tail, wat = np.genfromtxt(densities_file, comments="#", skip_header=24, unpack=True) #Scaling to the same average Z-length (see above) Xdens *= Xref/Xdens.max() Numdens = len(Xdens) cendens = int(Numdens/2) Xdens_shift = Xdens - Xdens[cendens] #Plots fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(Xdens_shift, phos/256, 'b', label="P") ax1.plot(Xdens_shift, tail/512, 'm', label="Terminal C") ax1.plot(Xdens_shift, wat/10128, 'c', label="Water") ax1.set_xlabel('Z [nm]') ax1.set_ylabel(r'Number density normalized to unity [nm$^{-3}$]') plt.legend(loc="upper left") ax2 = ax1.twinx() ax2.plot(X, Potential, 'k', label="Electrostatic potential", lw=2) ax2.plot([X[0],X[len(X)-1]], [0,0], '--', label="Zero", lw=2) ax2.set_ylabel('Potential [V]') plt.legend(loc="upper center") plt.show() fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(Xdens_shift, phos/256, 'b', label="P") ax1.plot(Xdens_shift, tail/512, 'm', label="Terminal C") ax1.plot(Xdens_shift, wat/10128, 'c', label="Water") ax1.set_xlabel('Z [nm]') ax1.set_ylabel(r'Number density normalized to unity [nm$^{-3}$]') plt.legend(loc="upper left") ax2 = ax1.twinx() ax2.plot(X, Field, 'k', label="Intensity of electric field", lw=2) ax2.set_ylabel('Field [V/nm]') plt.legend(loc="upper center") plt.show() return V
def read_trajs(self, binwidth): """ Reads in Plumed's Pitch files (3columns) or Gromacs pullx files (8 columns) File format plain (Plumed, also suits pitch-n-roll output with change bias->roll): ------------ 3 columns : floats Time -- PITCH -- bias (roll for PNR) crashes or unexpected behaviour if different format (e.g. more cols) File format pnr_[roll, pitch] (for roll/pitch coordinate from pitch-n-roll code): ------------ 3 columns : floats Time -- PITCH -- ROLL crashes or unexpected behaviour if different format (e.g. more cols) File format plain2 (Plumed): ------------ 2 columns (otherwise same) File format xvg (Gromacs pullx): ------------ 8 columns : float Time -- x,y,z -- length -- dx,dy,dz Returns ------- trajs : list of dictionaries containing arrays with the key convention of pytram dict-key 'm' -- Markov state -- 0-based indexing """ def discretize(in_data, offset=0.0): """ turns data into integers, i.e. discretizes data based on the offset and bin width Discretized data are 0-based indices (shifted with local var smallest) Parameters ---------- data : np.array data to be discretized offset : float starting value for the discretization scheme """ data = np.copy(in_data) if offset != 0.0: data -= offset # binwidth variable taken from the # enclosing scope (at definition time) -- closure if binwidth != 1.0: data /= binwidth return data.astype(int) smallest = None trajs = [] for sim in self.sims: filename = sim['fname'] tmpdict = {} if self.traj_file_format == "plain" : # should contain exactly 3 columns tmpdict['time'], tmpdict['x'], tmpdict['b'] = np.hsplit(np.loadtxt(filename), 3) # convert from kJ/mol to kT units tmpdict['b'] /= k_b*sim['temperature'] elif self.traj_file_format == "plain2" : # should contain exactly 2 columns tmpdict['time'], tmpdict['x'] = np.hsplit(np.loadtxt(filename), 2) elif self.traj_file_format == "xvg" : # create a numpy array with the contents of .xvg file; # should contain exactly 8 columns tmp_arr = np.array( rxvg.lines_to_list_of_lists(rxvg.read_xvg(filename)) ) tmpdict['time'] = tmp_arr[:,0] tmpdict['x'] = tmp_arr[:,4] elif "pnr" in self.traj_file_format : # should contain exactly 3 columns tmpdict['time'], tmpdict['pitch'], tmpdict['roll'] = np.hsplit(np.loadtxt(filename), 3) # convert from kJ/mol to kT units if "roll" in self.traj_file_format : tmpdict['x'] = tmpdict['roll'] elif "pitch" in self.traj_file_format : tmpdict['x'] = tmpdict['pitch'] else: raise RuntimeError, "only pitch -or- roll defined in the file format!" # setting bias to 0, as the file format does not contain it anyway # for the case some other method/procedure might need it tmpdict['b'] = tmpdict['x']*0.0 else: print "Given file format undefined: ", self.traj_file_format raise RuntimeError tmpdict['m'] = discretize(tmpdict['x']) # find the smallest state-no if smallest == None or smallest > tmpdict['m'].min(): smallest = tmpdict['m'].min() # thermodynamic state assumed constant during each simulation tmpdict['t'] = np.ones(tmpdict['m'].shape, dtype=int) * sim['t'] trajs.append(tmpdict) # shift the trajs by the smallest state-no (smallest var) for traj in trajs: traj['m'] -= smallest return trajs