Skip to content

Commit

Permalink
run script 2to3 for python 3 migration
Browse files Browse the repository at this point in the history
  • Loading branch information
rikigigi committed Jun 24, 2019
1 parent 282868d commit d3d13dc
Show file tree
Hide file tree
Showing 20 changed files with 385 additions and 2,757 deletions.
112 changes: 57 additions & 55 deletions examples/example_cepstrum_doublecomp_NaCl.ipynb

Large diffs are not rendered by default.

2,644 changes: 135 additions & 2,509 deletions examples/example_cepstrum_singlecomp_silica.ipynb

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import absolute_import

from setuptools import setup, find_packages
import json

Expand Down
2 changes: 1 addition & 1 deletion thermocepstrum/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import absolute_import


__all__ = [ 'md', 'i_o', 'heatcurrent', 'utils' ]

Expand Down
46 changes: 23 additions & 23 deletions thermocepstrum/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,11 @@ def main():
selected_keys.extend(j2_keys)

# Write some parameters
print ' Input file ({}): {}'.format(input_format, inputfile)
print(' Input file ({}): {}'.format(input_format, inputfile))
logfile.write(' Input file ({}): {}\n'.format(input_format, inputfile))
print ' Units: {}'.format(units)
print(' Units: {}'.format(units))
logfile.write(' Units: {}\n'.format(units))
print ' Time step: {} fs'.format(DT_FS)
print(' Time step: {} fs'.format(DT_FS))
logfile.write(' Time step: {} fs\n'.format(DT_FS))

## Read data
Expand All @@ -233,7 +233,7 @@ def main():
raise NotImplemented('input format not implemented.')

if (NSPLIT > 1):
print 'Splitting input data time series into {:d} segments...'.format(NSPLIT)
print('Splitting input data time series into {:d} segments...'.format(NSPLIT))
logfile.write('Splitting input data time series into {:d} segments...\n'.format(NSPLIT))
data_size = jdata[selected_keys[0]].shape[0]
n_proc = 1
Expand All @@ -246,15 +246,15 @@ def main():
steps_end = data_size/NSPLIT
if (steps_end%2 == 1):
steps_end = steps_end - 1
for key, value in jdata.iteritems():
for key, value in jdata.items():
if key != 'Temp':
newdata = value[:steps_start].reshape((NSPLIT,data_size/NSPLIT,n_proc)).transpose((1,0,2)).reshape((data_size/NSPLIT,NSPLIT*n_proc))
jdata[key] = newdata[:steps_end]
print 'New shape of input data: {}'.format(jdata[selected_keys[0]].shape)
print('New shape of input data: {}'.format(jdata[selected_keys[0]].shape))
logfile.write('New shape of input data: {}\n'.format(jdata[selected_keys[0]].shape))

if NSTEPS==0:
NSTEPS=jdata[jdata.keys()[0]].shape[0]
NSTEPS=jdata[list(jdata.keys())[0]].shape[0]


## Define Temperature
Expand All @@ -264,41 +264,41 @@ def main():
temperature_std = np.std(jdata['Temp']) # this is wrong (needs block average)
if 'Temp' in selected_keys:
selected_keys.remove('Temp')
print ' Mean Temperature (computed): {} K +/- {}'.format(temperature, temperature_std)
print(' Mean Temperature (computed): {} K +/- {}'.format(temperature, temperature_std))
logfile.write(' Mean Temperature (computed): {} K +/- {}\n'.format(temperature, temperature_std))
elif 'Temp_ave' in jdata:
temperature = jdata['Temp_ave']
if 'Temp_std' in jdata:
temperature_std = jdata['Temp_std']
print ' Mean Temperature (file): {} K +/- {}'.format(temperature, temperature_std)
print(' Mean Temperature (file): {} K +/- {}'.format(temperature, temperature_std))
logfile.write(' Mean Temperature (file): {} K +/- {}\n'.format(temperature, temperature_std))
else:
print ' Mean Temperature (file): {} K'.format(temperature)
print(' Mean Temperature (file): {} K'.format(temperature))
logfile.write(' Mean Temperature (file): {} K\n'.format(temperature))
else:
raise RuntimeError('No Temp key found. Please provide Temperature (-T).')
else:
print ' Mean Temperature (input): {} K'.format(temperature)
print(' Mean Temperature (input): {} K'.format(temperature))
logfile.write(' Mean Temperature (input): {} K\n'.format(temperature))


## Define Volume
if volume is None:
if structurefile is not None:
_, volume= tc.i_o.read_lammps_datafile.get_box(structurefile)
print ' Volume (structure file): {} A^3'.format(volume)
print(' Volume (structure file): {} A^3'.format(volume))
logfile.write(' Volume (structure file): {} A^3'.format(volume))
elif 'Volume' in jdata:
volume = jdata['Volume']
print ' Volume (file): {} A^3'.format(volume)
print(' Volume (file): {} A^3'.format(volume))
logfile.write(' Volume (file): {} A^3\n'.format(volume))
else:
raise RuntimeError('No Volume key found. Please provide Volume (-V) of structure file (--structure).')
else:
print ' Volume (input): {} A^3'.format(volume)
print(' Volume (input): {} A^3'.format(volume))
logfile.write(' Volume (input): {} A^3\n'.format(volume))

print ' Time step (input): {} fs'.format(DT_FS)
print(' Time step (input): {} fs'.format(DT_FS))
logfile.write(' Time step (input): {} fs\n'.format(DT_FS))


Expand All @@ -310,29 +310,29 @@ def main():


## Define currents
print selected_keys, jindex
print(selected_keys, jindex)
if jindex is None:
currents = np.array([jdata[key][START_STEP:(START_STEP+NSTEPS),:] for key in selected_keys])
else:
if sindex is None:
currents = np.array([jdata[key][START_STEP:(START_STEP+NSTEPS),jindex] for key in selected_keys])
else:
currents = np.array([jdata[key][START_STEP:(START_STEP+NSTEPS),jindex]-jdata[key][START_STEP:(START_STEP+NSTEPS),sindex] for key in selected_keys])
print ' currents shape is {}'.format(currents.shape)
print(' currents shape is {}'.format(currents.shape))
logfile.write(' currents shape is {}\n'.format(currents.shape))
print 'snippet:'
print currents
print('snippet:')
print(currents)

# create HeatCurrent object
j = tc.heatcurrent.HeatCurrent(currents, units, DT_FS, temperature, volume, psd_filter_w)

print ' Number of currents = {}'.format(ncurrents)
print(' Number of currents = {}'.format(ncurrents))
logfile.write(' Number of currrents = {}\n'.format(ncurrents))
print ' Number of components = {}'.format(j.N_COMPONENTS)
print(' Number of components = {}'.format(j.N_COMPONENTS))
logfile.write(' Number of components = {}\n'.format(j.N_COMPONENTS))
print ' kappa_scale = {}'.format(j.kappa_scale)
print(' kappa_scale = {}'.format(j.kappa_scale))
logfile.write(' kappa_scale = {}\n'.format(j.kappa_scale))
print ' Nyquist_f = {} THz'.format(j.Nyquist_f_THz)
print(' Nyquist_f = {} THz'.format(j.Nyquist_f_THz))
logfile.write(' Nyquist_f = {} THz\n'.format(j.Nyquist_f_THz))


Expand Down
20 changes: 10 additions & 10 deletions thermocepstrum/heatcurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
################################################################################

import numpy as np
import md
from md.mdsample import MDSample
from . import md
from .md.mdsample import MDSample

#import matplotlib.pyplot as plt
from thermocepstrum.utils.loadAfterPlt import plt

try:
plt
except:
print "Warning: plt undefined"
print("Warning: plt undefined")

def freq_THz_to_red(f, DT_FS):
return f/1000.*DT_FS
Expand Down Expand Up @@ -50,7 +50,7 @@ def __init__(self, j, units, DT_FS, TEMPERATURE, VOLUME, PSD_FILTER_W=None, freq
raise ValueError("Shape of j {} not valid.".format(j.shape))

if self.multicomponent:
print "Using multicomponent code."
print("Using multicomponent code.")
MDSample.__init__(self, traj=j[0], DT_FS=DT_FS)
# initialize other MDSample objects needed to make the work
self.otherMD = []
Expand Down Expand Up @@ -82,7 +82,7 @@ def __init__(self, j, units, DT_FS, TEMPERATURE, VOLUME, PSD_FILTER_W=None, freq
raise ValueError('Freq units not valid.')
self.initialize_cepstral_parameters()
else:
print "Warning: trajectory not initialized. You should manually initialize what you need."
print("Warning: trajectory not initialized. You should manually initialize what you need.")

self.dct = None
return
Expand Down Expand Up @@ -158,7 +158,7 @@ def cepstral_analysis(self, aic_type='aic', Kmin_corrfactor=1.0):
'-----------------------------------------------------\n' +\
' kappa* = {:18f} +/- {:10f} W/mK\n'.format(self.kappa_Kmin, self.kappa_Kmin_std) +\
'-----------------------------------------------------\n'
print self.cepstral_log
print(self.cepstral_log)
return


Expand Down Expand Up @@ -380,8 +380,8 @@ def resample_current(x, TSKIP=None, fstar_THz=None, FILTER_W=None, plot=True, PS
if (freq_units == 'thz') or (freq_units == 'THz'):
xf.plot_periodogram(x.FILTER_WINDOW_WIDTH*1000./x.DT_FS, 'thz', TSKIP, axes=axes)
elif (freq_units == 'red'):
print PSD_FILTER_W
print x.FILTER_WINDOW_WIDTH
print(PSD_FILTER_W)
print(x.FILTER_WINDOW_WIDTH)
xf.plot_periodogram(x.FILTER_WINDOW_WIDTH*TSKIP, 'red', TSKIP, axes=axes)

xf.resample_log = '-----------------------------------------------------\n' +\
Expand All @@ -401,7 +401,7 @@ def resample_current(x, TSKIP=None, fstar_THz=None, FILTER_W=None, plot=True, PS
' min(PSD) (post-filter) = {:12.5f}\n'.format(xf.psd_min) +\
' % of original PSD Power f<f* (pre-filter) = {:5f}\n'.format(np.trapz(x.psd[:fstar_idx+1]) / x.psd_power * 100.) +\
'-----------------------------------------------------\n'
print xf.resample_log
print(xf.resample_log)

if plot:
if (freq_units == 'thz') or (freq_units == 'THz'):
Expand Down Expand Up @@ -436,7 +436,7 @@ def fstar_analysis(x, TSKIP_LIST, aic_type='aic', Kmin_corrfactor=1.0, plot=True

xf = []
for TSKIP in TSKIP_LIST:
print 'TSKIP = {:d}'.format(TSKIP)
print('TSKIP = {:d}'.format(TSKIP))
xff = resample_current(x, TSKIP, plot=False)
xff.cepstral_analysis(aic_type, Kmin_corrfactor)
xf.append( xff )
Expand Down
2 changes: 1 addition & 1 deletion thermocepstrum/i_o/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import absolute_import


__all__ = [ 'read_tablefile', 'read_lammps_dump', 'read_lammps_log', 'read_lammps_datafile' ]

Expand Down
58 changes: 29 additions & 29 deletions thermocepstrum/i_o/read_lammps_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ def get_volume( filename ):
line = f.readline()
while( line ):
if "BOX BOUNDS" in line:
xlo, xhi = map(float, f.readline().split())
ylo, yhi = map(float, f.readline().split())
zlo, zhi = map(float, f.readline().split())
xlo, xhi = list(map(float, f.readline().split()))
ylo, yhi = list(map(float, f.readline().split()))
zlo, zhi = list(map(float, f.readline().split()))
break
line = f.readline()
f.close()
Expand Down Expand Up @@ -152,7 +152,7 @@ def _read_ckeys(self, group_vectors=True, preload_timesteps=True):
zbox = self.file.readline().split()
self.BOX_BOUNDS = np.array([xbox, ybox, zbox], dtype='float')
elif (values[1] == 'ATOMS'):
for i in xrange(2, len(values)):
for i in range(2, len(values)):
if group_vectors:
bracket = is_vector_variable( values[i] ) # get position of left square bracket
else:
Expand Down Expand Up @@ -194,7 +194,7 @@ def _read_ckeys(self, group_vectors=True, preload_timesteps=True):
self.TOT_TIMESTEPS = len(self.all_timesteps)
self.all_timesteps = np.array(self.all_timesteps)
else:
print " ** No timesteps pre-loaded. Be careful in the selection. **"
print(" ** No timesteps pre-loaded. Be careful in the selection. **")
# get the first 2 timesteps
while (len(self.all_timesteps) < 2):
line = self.file.readline()
Expand All @@ -213,12 +213,12 @@ def _read_ckeys(self, group_vectors=True, preload_timesteps=True):
# go back to the first timestep
self.gototimestep(0) # compute_first = True
self._start_byte = 0
print ' all_ckeys = ', self.all_ckeys
print ' TOT_TIMESTEPS = ', self.TOT_TIMESTEPS
print ' FIRST_TIMESTEP = ', self.FIRST_TIMESTEP
print ' DELTA_TIMESTEP = ', self.DELTA_TIMESTEP
print ' LAST_TIMESTEP = ', self.LAST_TIMESTEP
print ' all_timesteps = ', self.all_timesteps
print(' all_ckeys = ', self.all_ckeys)
print(' TOT_TIMESTEPS = ', self.TOT_TIMESTEPS)
print(' FIRST_TIMESTEP = ', self.FIRST_TIMESTEP)
print(' DELTA_TIMESTEP = ', self.DELTA_TIMESTEP)
print(' LAST_TIMESTEP = ', self.LAST_TIMESTEP)
print(' all_timesteps = ', self.all_timesteps)
return


Expand All @@ -237,12 +237,12 @@ def _set_ckey(self, select_ckeys=None):
if value is not None:
self.ckey[key] = value[:] # copy all indexes (up to max dimension for vectors)
else:
print "Warning: ", key, "key not found."
print("Warning: ", key, "key not found.")
if (len(self.ckey) == 0):
raise KeyError("No ckey set. Check selected keys.")
else:
if not self._quiet:
print " ckey = ", self.ckey
print(" ckey = ", self.ckey)
return


Expand Down Expand Up @@ -275,7 +275,7 @@ def _set_timesteps(self, selection, start_step=-1):
if step is None:
step = self.DELTA_TIMESTEP
elif (step%self.DELTA_TIMESTEP != 0):
print "Warning: step is not a multiple of the detected DELTA_TIMESTEP. You may get errors."
print("Warning: step is not a multiple of the detected DELTA_TIMESTEP. You may get errors.")
if (first%step != 0):
first += step - first%step # round first step to the next in the list

Expand All @@ -286,16 +286,16 @@ def _set_timesteps(self, selection, start_step=-1):
if step in self.all_timesteps:
self.timestep.append(step) # make list of available selected-timesteps
else:
print "Warning: timestep # {:d} not found.".format(step)
print("Warning: timestep # {:d} not found.".format(step))
else:
self.timestep = self.select_timesteps # use all the selected (be careful)
self.nsteps = len(self.timestep) # number of available steps
if (self.nsteps == 0):
raise ValueError("No timestep set. Check selected timesteps.")
else:
if not self._quiet:
print " nsteps = ", self.nsteps
print " timestep = ", self.timestep
print(" nsteps = ", self.nsteps)
print(" timestep = ", self.timestep)
return


Expand All @@ -305,9 +305,9 @@ def _initialize_dic(self):
raise ValueError('ckey not set.')
if self.timestep is None:
raise ValueError('timestep not set.')
self.data = [dict() for i in xrange(self.nsteps)]
for istep in xrange(self.nsteps):
for key, idx in self.ckey.iteritems():
self.data = [dict() for i in range(self.nsteps)]
for istep in range(self.nsteps):
for key, idx in self.ckey.items():
if (key == 'element'): # this should be improved
self.data[istep][key] = np.zeros( (self.NATOMS, len(idx)), dtype='S8' )
else:
Expand Down Expand Up @@ -383,36 +383,36 @@ def read_timesteps(self, selection, start_step=-1, select_ckeys=None, fast_check
for istep,step in enumerate(self.timestep):
self._gototimestep(step, fast_check) # jump to the desired step,
self.data[istep]['TIMESTEP'] = step
for nat in xrange(self.NATOMS): # read data (may be unsorted)
for nat in range(self.NATOMS): # read data (may be unsorted)
line = self.file.readline()
if len(line) == 0: # EOF
raise EOFError("Warning: reached EOF.")
values = np.array(line.split())
for key, idx in self.ckey.iteritems(): # save the selected columns
for key, idx in self.ckey.items(): # save the selected columns
atomid = int(values[atomid_col]) - 1 # current atom index (in LAMMPS it starts from 1)
if (key == 'element'): # this should be improved
self.data[istep][key][atomid,:] = np.array(map(str, values[idx]))
self.data[istep][key][atomid,:] = np.array(list(map(str, values[idx])))
else:
self.data[istep][key][atomid,:] = np.array(map(float, values[idx]))
self.data[istep][key][atomid,:] = np.array(list(map(float, values[idx])))
if ( (istep+1)%progbar_step == 0 ):
if self._GUI:
progbar.value = float(istep+1)/self.nsteps*100.;
progbar.description = "%g %%" % progbar.value
else:
print " step = {:9d} - {:6.2f}% completed".format(istep+1, float(istep+1)/self.nsteps*100.)
print(" step = {:9d} - {:6.2f}% completed".format(istep+1, float(istep+1)/self.nsteps*100.))
if self._GUI:
progbar.close()
# check number of steps read, keep an even number of steps
if (istep + 1 < self.nsteps): # (should never happen)
if (istep == 0):
print "WARNING: no step read."
print("WARNING: no step read.")
return
else:
print "Warning: less steps read."
print("Warning: less steps read.")
self.nsteps = istep + 1
if not self._quiet:
print " ( %d ) steps read." % (self.nsteps)
print "DONE. Elapsed time: ", time()-start_time, "seconds"
print(" ( %d ) steps read." % (self.nsteps))
print("DONE. Elapsed time: ", time()-start_time, "seconds")
self._compute_current_step = False # next time do not compute the current_step
return self.data

Loading

0 comments on commit d3d13dc

Please sign in to comment.