Skip to content

Commit 1077890

Browse files
committed
Make python 3 compatible
1 parent b91e4f5 commit 1077890

File tree

14 files changed

+214
-182
lines changed

14 files changed

+214
-182
lines changed

quickff/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
error is raised.
3838
'''
3939

40-
40+
from __future__ import absolute_import
4141
import os
4242
from glob import glob
4343

quickff/cost.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
# along with this program; if not, see <http://www.gnu.org/licenses/>
2323
#
2424
#--
25+
26+
from __future__ import absolute_import
27+
2528
from molmod.units import *
2629

2730
from quickff.tools import boxqp

quickff/io.py

Lines changed: 39 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
#
2424
#--
2525

26+
from __future__ import print_function, absolute_import
27+
2628
'''Readers ab initio vibrational calculations.
2729
'''
2830

@@ -84,20 +86,20 @@ def __init__(self, filename, field_labels=[]):
8486
# Read atomic masses for atomtype
8587
masses = np.asarray([float(atom.findall('c')[2].text) for atom in self.root.findall(".//*[@name='atomtypes']/set")[0]])*amu
8688
self.fields['masses'] = np.zeros(self.fields['numbers'].shape)
87-
for iatype in xrange(masses.shape[0]):
89+
for iatype in range(masses.shape[0]):
8890
self.fields['masses'][atomtypes==iatype] = masses[iatype]
8991
# Read SCF energies
9092
self.fields['energies'] = np.array([float(step.find('energy/i[@name="e_fr_energy"]').text)*electronvolt\
9193
for step in self.root.findall('.//calculation')])
9294
# Read all requested arrays
9395
for label in field_labels:
94-
if not label in tag_dictionary.keys():
95-
raise NotImplementedError, "Failed to read %s from xml file" % label
96+
if not label in list(tag_dictionary.keys()):
97+
raise NotImplementedError("Failed to read %s from xml file" % label)
9698
self.fields[label] = self.read_array(tag_dictionary[label][0], unit=tag_dictionary[label][1])
9799
# Convert fractional to Cartesian coordinates
98100
self.fields['pos_init'] = np.dot(self.fields['pos_init'], self.fields['rvecs_init'])
99101
# Hessian is mass-weighted, we want the pure second derivatives
100-
if 'hessian' in self.fields.keys():
102+
if 'hessian' in list(self.fields.keys()):
101103
m3 = np.sqrt(np.array(sum([[m,m,m] for m in self.fields['masses']],[])))
102104
self.fields['hessian'] = m3.reshape((-1,1))*self.fields['hessian']*m3
103105

@@ -154,39 +156,39 @@ def read_abinitio(fn, do_hess=True):
154156
def make_yaff_ei(fn, charges, bcis=None, radii=None):
155157
assert charges is not None or bcis is not None, 'Either charges or bcis should be parsed'
156158
f = open(fn, 'w')
157-
print >> f, '#Fixed charges'
158-
print >> f, '#---------------'
159-
print >> f, ''
160-
print >> f, 'FIXQ:UNIT Q0 e'
161-
print >> f, 'FIXQ:UNIT P e'
162-
print >> f, 'FIXQ:UNIT R angstrom'
163-
print >> f, 'FIXQ:SCALE 1 1.0'
164-
print >> f, 'FIXQ:SCALE 2 1.0'
165-
print >> f, 'FIXQ:SCALE 3 1.0'
166-
print >> f, 'FIXQ:DIELECTRIC 1.0'
167-
print >> f, ''
159+
print('#Fixed charges', file=f)
160+
print('#---------------', file=f)
161+
print('', file=f)
162+
print('FIXQ:UNIT Q0 e', file=f)
163+
print('FIXQ:UNIT P e', file=f)
164+
print('FIXQ:UNIT R angstrom', file=f)
165+
print('FIXQ:SCALE 1 1.0', file=f)
166+
print('FIXQ:SCALE 2 1.0', file=f)
167+
print('FIXQ:SCALE 3 1.0', file=f)
168+
print('FIXQ:DIELECTRIC 1.0', file=f)
169+
print('', file=f)
168170
if charges is not None or radii is not None:
169-
print >> f, '# Atomic parameters'
170-
print >> f, '# ----------------------------------------------------'
171-
print >> f, '# KEY label Q_0A R_A'
172-
print >> f, '# ----------------------------------------------------'
171+
print('# Atomic parameters', file=f)
172+
print('# ----------------------------------------------------', file=f)
173+
print('# KEY label Q_0A R_A', file=f)
174+
print('# ----------------------------------------------------', file=f)
173175
if charges is not None:
174-
ffatypes = charges.keys()
176+
ffatypes = list(charges.keys())
175177
else:
176-
ffatypes = radii.keys()
178+
ffatypes = list(radii.keys())
177179
for ffatype in ffatypes:
178180
charge, radius = 0.0, 0.0
179181
if charges is not None: charge = charges[ffatype]
180182
if radii is not None: radius = radii[ffatype]
181-
print >> f, 'FIXQ:ATOM %8s % 13.10f %12.10f' %(ffatype, charge, radius/angstrom)
183+
print('FIXQ:ATOM %8s % 13.10f %12.10f' %(ffatype, charge, radius/angstrom), file=f)
182184
if bcis is not None:
183-
print >> f, '# Bond parameters'
184-
print >> f, '# ----------------------------------------------------'
185-
print >> f, '# KEY label0 label1 P_AB '
186-
print >> f, '# ----------------------------------------------------'
187-
for key, bci in bcis.iteritems():
185+
print('# Bond parameters', file=f)
186+
print('# ----------------------------------------------------', file=f)
187+
print('# KEY label0 label1 P_AB ', file=f)
188+
print('# ----------------------------------------------------', file=f)
189+
for key, bci in bcis.items():
188190
ffatype1, ffatype2 = key.split('.')
189-
print >> f, 'FIXQ:BOND %8s %8s % 12.10f' %(ffatype1, ffatype2, bci)
191+
print('FIXQ:BOND %8s %8s % 12.10f' %(ffatype1, ffatype2, bci), file=f)
190192
f.close()
191193

192194

@@ -211,7 +213,7 @@ def read_bci_constraints(fn):
211213
master, suffix, sign = line.split(':')
212214
slaves = [(slave.strip(), float(sign)) for slave in suffix.split(',')]
213215
label = master.strip()
214-
if label in constraints.keys():
216+
if label in list(constraints.keys()):
215217
for slave in slaves: constraints[label].append(slave)
216218
else:
217219
constraints[label] = slaves
@@ -413,7 +415,7 @@ def dump_charmm22_prm(valence, fn):
413415

414416
def _atoms_to_charmm22_psf(system):
415417
result = ['{:8d} !NATOM'.format(system.natom)]
416-
for iatom in xrange(system.natom):
418+
for iatom in range(system.natom):
417419
ffatype = system.get_ffatype(iatom)
418420
if len(ffatype) > 4:
419421
log.warning('Atom type too long for CHARMM PSF file: {}'.format(ffatype))
@@ -977,13 +979,13 @@ def dump_yaff(valence, fn):
977979
f = open(fn, 'w')
978980
for section in sections:
979981
if len(section['PARS'].lines)==0: continue
980-
print >> f, '# %s' %section.prefix
981-
print >> f, '#-%s' %('-'*len(section.prefix))
982+
print('# %s' %section.prefix, file=f)
983+
print('#-%s' %('-'*len(section.prefix)), file=f)
982984
for line in section['UNIT'].lines:
983-
print >> f, '%s:UNIT %s' %(section.prefix, line)
984-
print >> f, ''
985+
print('%s:UNIT %s' %(section.prefix, line), file=f)
986+
print('', file=f)
985987
for line in section['PARS'].lines:
986-
print >> f, '%s:PARS %s' %(section.prefix, line)
987-
print >> f, ''
988-
print >> f, ''
988+
print('%s:PARS %s' %(section.prefix, line), file=f)
989+
print('', file=f)
990+
print('', file=f)
989991
f.close()

quickff/log.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
#
2424
#--
2525

26+
from __future__ import print_function, absolute_import, unicode_literals
27+
from io import IOBase
2628
import os, sys, datetime, getpass, atexit
2729
import numpy, scipy, matplotlib
2830

@@ -132,7 +134,7 @@ def set_level(self, level):
132134
def write_to_file(self, f):
133135
if isinstance(f, str):
134136
self._f = open(f, 'w')
135-
elif isinstance(f, file):
137+
elif isinstance(f, IOBase):
136138
self._f = f
137139
else:
138140
raise ValueError('File argument f should be a string representing a filename or a File instance')
@@ -151,16 +153,16 @@ def dump(self, message, new_line=True):
151153
self.print_header()
152154
assert self.label is not None
153155
if new_line and self.add_blank_line:
154-
print >> self._f , ''
156+
print('', file=self._f)
155157
self.add_blank_line = False
156158
line = ''
157159
for piece in splitstring(message, self.ll-self.mll):
158160
line += ' ' + self.label[:self.mll-2] + ' '
159161
line += ' '*(self.mll-2 - len(self.label[:self.mll-2]))
160-
line += piece.encode('utf-8')
162+
line += piece
161163
line += '\n'
162164
line = line.rstrip('\n')
163-
print >> self._f, line
165+
print(line, file=self._f)
164166

165167
def warning(self, message, new_line=True):
166168
'''
@@ -173,7 +175,7 @@ def warning(self, message, new_line=True):
173175
self.print_header()
174176
assert self.label is not None
175177
if new_line and self.add_blank_line:
176-
print >> self._f , ''
178+
print('', file=self._f)
177179
self.add_blank_line = False
178180
line = ''
179181
for piece in splitstring('WARNING: '+message, self.ll-self.mll):
@@ -182,12 +184,12 @@ def warning(self, message, new_line=True):
182184
line += piece.encode('utf-8')
183185
line += '\n'
184186
line = line.rstrip('\n')
185-
print >> self._f, line
187+
print(line, file=self._f)
186188

187189
def print_header(self):
188190
if self.log_level>0:
189-
print >> self._f, header
190-
print >> self._f, ''
191+
print(header, file=self._f)
192+
print('', file=self._f)
191193
mll = self.mll
192194
self.mll = 20
193195
with self.section('USER', 1): self.dump(getpass.getuser(), new_line=False)
@@ -202,8 +204,8 @@ def print_header(self):
202204
with self.section('COMMAND LINE', 1): self.dump(' '.join(sys.argv), new_line=False)
203205
self.mll = mll
204206
if self.log_level>0:
205-
print >> self._f, ''
206-
print >> self._f, '~'*80
207+
print('', file=self._f)
208+
print('~'*80, file=self._f)
207209

208210
def exit(self):
209211
if self._active:
@@ -213,20 +215,20 @@ def exit(self):
213215

214216
def print_footer(self):
215217
if self.log_level>0:
216-
print >> self._f, footer
218+
print(footer, file=self._f)
217219

218220
def print_timetable(self):
219221
if self.log_level>0:
220-
print >> self._f, '~'*80
221-
print >> self._f, ''
222+
print('~'*80, file=self._f)
223+
print('', file=self._f)
222224
with self.section('TIMING', 1):
223225
for label, time in self.timetable:
224226
line = '%30s ' %(label+' '*(30-len(label)))
225227
line += str(time)
226228
self.dump(line)
227229

228230
def close(self):
229-
if isinstance(self._f, file):
231+
if isinstance(self._f, IOBase):
230232
self._f.close()
231233

232234

quickff/paracontext.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
#
2424
#--
2525

26+
from __future__ import print_function, absolute_import
27+
2628
'''
2729
Convenience functions to enable using scoop.
2830
'''
@@ -51,7 +53,7 @@ def my_wait_first(fs):
5153
return fs[:1], fs[1:]
5254
def debug_log(*args):
5355
with open('debug.log', 'a') as f:
54-
print >> f, ' '.join(str(arg) for arg in args)
56+
print(' '.join(str(arg) for arg in args), file=f)
5557
return 0
5658
self.map = my_map
5759
self.wait_first = my_wait_first
@@ -67,7 +69,7 @@ def my_wait_first(fs):
6769
return futures.wait(fs, return_when=futures.FIRST_COMPLETED)
6870
def debug_log(*args):
6971
with open('debug_%s.log' % WORKER_NAME, 'a') as f:
70-
print >> f, ' '.join(str(arg) for arg in args)
72+
print(' '.join(str(arg) for arg in args), file=f)
7173
return 0
7274
self.map = my_map
7375
self.wait_first = my_wait_first

quickff/perturbation.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
#
2424
#--
2525

26+
from __future__ import absolute_import
27+
2628
from molmod.io.xyz import XYZWriter
2729
from molmod.units import *
2830
from molmod.periodic import periodic as pt
@@ -78,7 +80,7 @@ def __init__(self, term, start, end, numbers, nsteps=11):
7880
self.qunit = term.units[1]
7981
self.kunit = term.units[0]
8082
self.step = (end-start)/(nsteps-1)
81-
self.targets = start + (end-start)/(nsteps-1)*np.array(range(nsteps), float)
83+
self.targets = start + (end-start)/(nsteps-1)*np.array(list(range(nsteps)), float)
8284
self.values = np.zeros(nsteps, float)
8385
self.coords = np.zeros([nsteps, len(numbers), 3], float)
8486
self.active = True
@@ -122,7 +124,7 @@ def plot(self, ai, ffrefs=[], valence=None, fn=None, eunit='kjmol', suffix=''):
122124
when fn is specified.
123125
'''
124126
import matplotlib.pyplot as pp
125-
if 'active' in self.__dict__.keys() and not self.active: return
127+
if 'active' in list(self.__dict__.keys()) and not self.active: return
126128
fig, ax = pp.subplots()
127129
def add_plot(xs, ys, prefix, kwargs):
128130
pars = fitpar(xs, ys, rcond=1e-6)
@@ -188,7 +190,7 @@ def to_xyz(self, fn=None):
188190
fn
189191
a string defining the name of the output file
190192
'''
191-
if 'active' in self.__dict__.keys() and not self.active: return
193+
if 'active' in list(self.__dict__.keys()) and not self.active: return
192194
if fn is None:
193195
fn = 'trajectory-%s-%i.xyz' %(self.term.basename.replace('/', '-'),self.term.index)
194196
f = open(fn, 'w')
@@ -331,7 +333,7 @@ def generate(self, trajectory, remove_com=True):
331333
log.dump(' Converged (value=%.3f, lagmult=%.3e)' %(strain.constrain_value,sol[3*natom]))
332334
if remove_com:
333335
com = (x.T*self.system0.masses.copy()).sum(axis=1)/self.system0.masses.sum()
334-
for i in xrange(natom):
336+
for i in range(natom):
335337
x[i,:] -= com
336338
trajectory.coords[iq,:,:] = x
337339
#delete flagged frames
@@ -377,7 +379,7 @@ def estimate(self, trajectory, ai, ffrefs=[], do_valence=False):
377379
term = trajectory.term
378380
index = term.index
379381
basename = term.basename
380-
if 'active' in trajectory.__dict__.keys() and not trajectory.active:
382+
if 'active' in list(trajectory.__dict__.keys()) and not trajectory.active:
381383
log.dump('Trajectory of %s was deactivated: skipping' %(basename))
382384
return
383385
qs = trajectory.values.copy()
@@ -403,7 +405,7 @@ def estimate(self, trajectory, ai, ffrefs=[], do_valence=False):
403405
trajectory.rv = -pars[1]/(2.0*pars[0])
404406
else:
405407
trajectory.fc = 0.0
406-
trajectory.rv = qs[len(qs)/2]
408+
trajectory.rv = qs[len(qs)//2]
407409
log.dump('force constant of %s is zero: rest value set to middle value' %basename)
408410
#no negative rest values for all ics except dihedrals and bendcos
409411
if term.ics[0].kind not in [1,3,4,11]:
@@ -456,7 +458,7 @@ def __init__(self, system, term, other_terms, cart_penalty=1e-3*angstrom):
456458
#set the rest values to the equilibrium values
457459
strain.dlist.forward()
458460
strain.iclist.forward()
459-
for iterm in xrange(strain.vlist.nv):
461+
for iterm in range(strain.vlist.nv):
460462
vterm = strain.vlist.vtab[iterm]
461463
ic = strain.iclist.ictab[vterm['ic0']]
462464
vterm['par1'] = ic['value']
@@ -490,7 +492,7 @@ def gradient(self, X):
490492
grad[:self.ndof] = gstrain.reshape((-1,)) + X[self.ndof]*gconstraint.reshape((-1,))
491493
grad[self.ndof] = self.constrain_value - self.constrain_target
492494
#cartesian penalty, i.e. extra penalty for deviation w.r.t. cartesian equilibrium coords
493-
indices = np.array([[3*i,3*i+1,3*i+2] for i in xrange(self.ndof/3) if i not in self.cons_ic_atindexes]).ravel()
495+
indices = np.array([[3*i,3*i+1,3*i+2] for i in range(self.ndof//3) if i not in self.cons_ic_atindexes]).ravel()
494496
if len(indices)>0:
495497
grad[indices] += X[indices]/(self.ndof*self.cart_penalty**2)
496498
with log.section('PTGEN', 4, timer='PT Generate'):

0 commit comments

Comments
 (0)