1 """@namespace IMP.isd.utils
2 Miscellaneous utilities.
29 from threading
import Thread
58 return sum(x) / float(len(x))
61 def atexit_register(*args):
63 atexit.register(*args)
66 def atexit_unregister(func):
68 exit_funcs = [x[0]
for x
in atexit._exithandlers]
71 i = exit_funcs.index(func)
75 atexit._exithandlers.pop(i)
78 class WatchDog(Thread):
80 def __init__(self, timeout, debug=False, logfile=None):
87 self.timeout = timeout * 60.
89 self._last_ping =
None
92 if logfile
is not None:
93 logfile = os.path.expanduser(logfile)
95 self.logfile = logfile
103 "set the _last_ping variable of the WatchDog instance"
106 print(
'Watchdog: set(%s) called.' % str(x))
111 """run the Watchdog thread, which sits in a loop sleeping for
112 timeout/4. at each iteration, and
113 if abs(time() - _last_ping) > timeout, exits.
116 while not self._stop:
118 if self._last_ping
is not None:
119 delta = abs(self._last_ping - time.time())
128 val =
'%.0f s' % delta
130 print(
'Watchdog: last life sign %s ago; timeout is %d min(s).'
131 % (val, self.timeout / 60.))
133 if self._last_ping
is not None and delta > self.timeout:
135 s =
'No life sign for > %d minute(s)' % (self.timeout / 60.)
137 print(s +
', exiting...')
139 if self.logfile
is not None:
141 if os.path.exists(self.logfile):
147 f = open(self.logfile, mode)
149 s +
'; host %s, %s\n' %
150 (socket.gethostname(), time.ctime()))
159 print(
'Watchdog: keeping Python interpreter alive.')
162 time.sleep(self.timeout / 4.)
167 symbols = (
'-',
'/',
'|',
'\')
172 def update(self, s=''):
173 sys.stdout.write(
'\r%s%s' % (s, self.symbols[self.state]))
176 self.state = (self.state + 1) % len(self.symbols)
181 """implements a FIFO pipe that merges lists (see self.put)"""
183 def __init__(self, length=-1):
189 """If x is subscriptable, insert its contents at the beginning of
190 the pipe. Else insert the element itself.
191 If the pipe is full, drop the oldest element.
196 self.pipe = list(x) + self.pipe
199 self.pipe.insert(0, x)
201 if self.length > 0
and len(self.pipe) > self.length:
202 self.pipe = self.pipe[:-1]
205 """x must be a list and will be appended to the end of the pipe,
206 dropping rightmost elements if necessary
209 self.pipe = (list(x) + self.pipe)[:self.length]
212 """returns the oldest element, without popping it out of the pipe.
213 Popping occurs in the put() method
217 def __getitem__(self, index):
218 return self.pipe.__getitem__(index)
221 return len(self.pipe)
224 return str(self.pipe)
227 return len(self.pipe) == self.length
232 def load_pdb(filename):
236 from Scientific.IO.PDB
import Structure
238 return Structure(os.path.expanduser(filename))
241 def copyfiles(src_path, dest_path, pattern=None, verbose=False):
243 from glob
import glob
244 from shutil
import copyfile
250 file_list = glob(os.path.join(src_path, pattern))
253 copyfile(f, os.path.join(dest_path, os.path.basename(f)))
262 f = open(filename,
'w')
265 except IOError
as error:
267 if os.path.isdir(filename):
276 """read sequence of ONE chain, 1-letter or 3-letter, returns dict of
277 no:3-letter code. Fails on unknown amino acids.
280 filename = os.path.abspath(filename)
284 raise IOError(
'Could not open sequence file "%s".' % filename)
285 seq = f.read().upper()
287 if seq.startswith(
'>'):
288 print(
"Detected FASTA 1-letter sequence")
291 seq =
''.join(seq[pos + 1:].split())
292 names = [code[i]
for i
in seq]
293 numbers = list(range(first_residue_number,
294 first_residue_number + len(seq)))
295 return dict(list(zip(numbers, names)))
299 if x
not in code.values():
300 print(
'Warning: unknown 3-letter code: %s' % x)
301 numbers = list(range(first_residue_number,
302 first_residue_number + len(spl)))
303 return dict(list(zip(numbers, spl)))
309 """checks whether residue codes a and b are the same, doing necessary
315 print(
'Warning: unknown 1-letter code: %s' % a)
320 print(
'Warning: unknown 1-letter code: %s' % b)
324 print(
'Unknown residue code %s' % a)
327 print(
'Unknown residue code %s' % b)
330 print(
'Residues %s and %s are not the same' % (a, b))
336 def my_glob(x, do_touch=False):
338 from glob
import glob
344 path, name = os.path.split(x)
352 def Dump(this, filename, gzip=0, mode='w', bin=1):
354 Dump(this, filename, gzip = 0)
355 Supports also '~' or '~user'.
361 filename = os.path.expanduser(filename)
363 if mode
not in [
'w',
'a']:
364 raise ValueError(
"mode has to be 'w' (write) or 'a' (append)")
368 f = gzip.GzipFile(filename, mode)
370 f = open(filename, mode)
372 pickle.dump(this, f, bin)
377 def Load(filename, gzip=0, force=0):
379 Load(filename, gzip=0, force=0)
381 force: returns all objects that could be unpickled. Useful
382 when unpickling of sequential objects fails at some point.
387 filename = os.path.expanduser(filename)
392 f = gzip.GzipFile(filename)
396 f = open(filename,
'rb')
406 object = pickle.load(f)
420 print(
'Could not load chunk %d. Stopped.' % n)
425 object = pickle.load(f)
432 def get_pdb(pdb_entry, dest='.', verbose_level=0):
437 url =
'ftp.ebi.ac.uk'
438 path =
'pub/databases/rcsb/pdb-remediated/data/structures/all/pdb'
439 filename_template =
'pdb%s.ent.gz'
441 dest = os.path.expanduser(dest)
443 ftp = ftplib.FTP(url)
445 ftp.set_debuglevel(verbose_level)
449 filename = os.path.join(dest,
'%s.pdb.gz' % pdb_entry)
451 f = open(filename,
'wb')
454 ftp.retrbinary(
'RETR %s' % filename_template % pdb_entry.lower(),
461 except ftplib.error_perm:
462 raise IOError(
'File %s not found on server' % filename)
464 os.system(
'gunzip -f %s' % filename)
467 def compile_index_list(chain, atom_names, residue_index_list=None):
469 if residue_index_list
is None:
470 residue_index_list = list(range(len(chain)))
480 for res_index
in residue_index_list:
482 if atom_names
is None:
483 names = sorted(chain[res_index].keys())
487 if n
in chain[res_index]:
488 index = chain[res_index][n].index
489 index_list.append(index)
493 return index_list, index_map
496 def get_coordinates(universe, E, indices=None, atom_names=(
'CA',),
497 residue_index_list=
None, atom_index_list=
None):
499 from numpy.oldnumeric
import array, take
502 indices = list(range(len(E)))
504 chain = universe.get_polymer()
506 if atom_index_list
is None:
507 atom_index_list, index_map = compile_index_list(chain, atom_names,
514 chain.set_torsions(E.torsion_angles[i], 1)
516 X = array(take(universe.X, atom_index_list))
525 maps angles into interval [-pi,pi]
528 from numpy.oldnumeric
import fmod, greater, logical_not
531 from numpy.oldnumeric
import pi
as period
533 mask = greater(angles, 0.)
535 return mask * (fmod(angles + period, 2 * period) - period) + \
536 logical_not(mask) * (fmod(angles - period, 2 * period) + period)
539 def remove_from_dict(d, items):
546 def myrange(a, b, n):
548 from numpy.oldnumeric
import arange
550 step = (b - a) / (n - 1)
552 x = arange(a, b + step, step)
557 def indent(lines, prefix):
559 tag =
' ' * len(str(prefix))
561 lines[0] = prefix + lines[0]
562 lines = [lines[0]] + list(map(
lambda s, t=tag: t + s, lines[1:]))
564 return '\n'.join(lines)
567 def make_block(s, length=80, tol=10):
568 blocks = s.split(
'\n')
571 spl += _make_block(block, length, tol)
576 def _make_block(s, length, tol):
579 spl = [(w,
' ')
for w
in spl]
584 g = [w +
'/' for w
in g]
585 g[-1] = g[-1][:-1] +
' '
592 for i
in range(len(words)):
595 if len(line + word) <= length:
599 if length - len(line) > tol:
600 m = length - len(line)
604 if len(line) > 1
and line[0] ==
' ' and \
612 if len(line) > 1
and line[0] ==
' ' and \
621 def _save_dump(x, filename, err_msg=None, delay=10, show_io_err=True,
622 gzip=
False, bin=
True):
625 Dump(x, filename, gzip=gzip, bin=bin)
627 except IOError
as msg:
632 print(
'IOError: %s' % str(msg))
636 print(
'%s. %s' % (str(msg), err_msg))
644 time.sleep(60. * delay)
647 Dump(x, filename, gzip=gzip, bin=bin)
654 def save_dump(x, filename, err_msg=None, delay=10, show_io_err=True,
655 gzip=
False, mode=
'w', bin=
True):
660 path, _filename = os.path.split(filename)
662 temp_path, temp_filename = os.path.split(tempfile.mktemp())
663 temp_filename = os.path.join(path, temp_filename)
665 _save_dump(x, temp_filename, err_msg, delay, show_io_err,
671 os.rename(temp_filename, filename)
674 os.unlink(temp_filename)
675 Dump(x, filename, mode=
'a', gzip=gzip, bin=bin)
678 raise Exception(
'Mode "%s" invalid.' % mode)
def map_angles
maps angles into interval [-pi,pi]
def put
If x is subscriptable, insert its contents at the beginning of the pipe.
implements a FIFO pipe that merges lists (see self.put)
def get
returns the oldest element, without popping it out of the pipe.
def read_sequence_file
read sequence of ONE chain, 1-letter or 3-letter, returns dict of no:3-letter code.
def append
x must be a list and will be appended to the end of the pipe, dropping rightmost elements if necessar...
The general base class for IMP exceptions.
def check_residue
checks whether residue codes a and b are the same, doing necessary conversions