27 from Queue
import Queue
28 from threading
import Thread
57 return sum(x)/float(len(x))
59 def atexit_register(*args):
61 atexit.register(*args)
63 def atexit_unregister(func):
65 exit_funcs= [x[0]
for x
in atexit._exithandlers]
68 i = exit_funcs.index(func)
72 atexit._exithandlers.pop( i )
74 class WatchDog(Thread):
76 def __init__(self, timeout, debug=False, logfile=None):
84 self.timeout = timeout*60.
86 self._last_ping =
None
89 if logfile
is not None:
90 logfile = os.path.expanduser(logfile)
92 self.logfile = logfile
100 "set the _last_ping variable of the WatchDog instance"
103 print 'Watchdog: set(%s) called.' % str(x)
108 """run the Watchdog thread, which sits in a loop sleeping for timeout/4. at
109 each iteration, and if abs(time() - _last_ping) > timeout, exits.
112 while not self._stop:
114 if self._last_ping
is not None:
115 delta = abs(self._last_ping - time.time())
124 val =
'%.0f s' % delta
126 print 'Watchdog: last life sign %s ago; timeout is %d min(s).' % \
127 (val, self.timeout/60.)
129 if self._last_ping
is not None and delta > self.timeout:
131 s =
'No life sign for > %d minute(s)' % (self.timeout/60.)
133 print s +
', exiting...'
135 if self.logfile
is not None:
137 if os.path.exists(self.logfile):
143 f = open(self.logfile, mode)
144 f.write(s+
'; host %s, %s\n' % (socket.gethostname(), time.ctime()))
153 print 'Watchdog: keeping Python interpreter alive.'
156 time.sleep(self.timeout/4.)
160 symbols = (
'-',
'/',
'|',
'\\')
165 def update(self, s=''):
169 sys.stdout.write(
'\r%s%s' % (s, self.symbols[self.state]))
172 self.state = (self.state + 1) % len(self.symbols)
175 """implements a FIFO pipe that merges lists (see self.put)"""
177 def __init__(self, length = -1):
183 """if x is subscriptable, insert its contents at the beginning of the pipe.
184 Else insert the element itself.
185 If the pipe is full, drop the oldest element.
190 self.pipe = list(x) + self.pipe
193 self.pipe.insert(0, x)
195 if self.length > 0
and len(self.pipe) > self.length:
196 self.pipe = self.pipe[:-1]
199 """ x must be a list and will be appended to the end of the pipe, dropping
200 rightmost elements if necessary
203 self.pipe = (list(x) + self.pipe)[:self.length]
206 """returns the oldest element, without popping it out of the pipe.
207 Popping occurs in the put() method
211 def __getitem__(self, index):
212 return self.pipe.__getitem__(index)
215 return len(self.pipe)
218 return str(self.pipe)
221 return len(self.pipe) == self.length
225 class SortedQueue(Queue):
229 from numpy.oldnumeric
import array
230 from Isd.misc.mathutils
import average
232 self.queue.sort(
lambda a, b: cmp(average(a.time), average(b.time)))
234 self.times = array([average(x.time)
for x
in self.queue])
236 def _put(self, item):
238 Queue._put(self, item)
243 from numpy.oldnumeric
import power
244 from Isd.misc.mathutils
import draw_dirichlet, rescale_uniform
248 p = 1. - rescale_uniform(self.times)
251 index = draw_dirichlet(p)
253 val = self.queue[index]
255 self.queue = self.queue[:index] + self.queue[index + 1:]
262 def load_pdb(filename):
266 from Scientific.IO.PDB
import Structure
268 return Structure(os.path.expanduser(filename))
270 def copyfiles(src_path, dest_path, pattern=None, verbose=False):
272 from glob
import glob
273 from shutil
import copyfile
279 file_list = glob(os.path.join(src_path,pattern))
282 copyfile(f, os.path.join(dest_path, os.path.basename(f)))
290 f = open(filename,
'w')
293 except IOError, error:
295 if os.path.isdir(filename):
301 def read_sequence_file(filename, first_residue_number=1):
302 """read sequence of ONE chain, 1-letter or 3-letter, returns dict of
303 no:3-letter code. Fails on unknown amino acids.
306 filename = os.path.abspath(filename)
310 raise IOError,
'Could not open sequence file "%s".' % filename
311 seq = f.read().upper()
313 if seq.startswith(
'>'):
314 print "Detected FASTA 1-letter sequence"
317 seq=
''.join(seq[pos+1:].split())
318 names = [code[i]
for i
in seq]
319 numbers = range(first_residue_number, first_residue_number+len(seq))
320 return dict(zip(numbers,names))
324 if not x
in code.values():
325 print 'Warning: unknown 3-letter code: %s' % x
326 numbers = range(first_residue_number, first_residue_number+len(l))
327 return dict(zip(numbers,l))
330 def check_residue(a,b):
331 "checks whether residue codes a and b are the same, doing necessary conversions"
336 print 'Warning: unknown 1-letter code: %s' % a
341 print 'Warning: unknown 1-letter code: %s' % b
345 print 'Unknown residue code %s' % a
348 print 'Unknown residue code %s' % b
351 print 'Residues %s and %s are not the same' % (a,b)
358 def my_glob(x, do_touch=False):
360 from glob
import glob
366 path, name = os.path.split(x)
373 def Dump(this, filename, gzip = 0, mode = 'w', bin=1):
375 Dump(this, filename, gzip = 0)
376 Supports also '~' or '~user'.
381 filename = os.path.expanduser(filename)
383 if not mode
in [
'w',
'a']:
384 raise "mode has to be 'w' (write) or 'a' (append)"
388 f = gzip.GzipFile(filename, mode)
390 f = open(filename, mode)
392 cPickle.dump(this, f, bin)
396 def Load(filename, gzip = 0, force=0):
398 Load(filename, gzip=0, force=0)
400 force: returns all objects that could be unpickled. Useful
401 when unpickling of sequential objects fails at some point.
405 filename = os.path.expanduser(filename)
410 f = gzip.GzipFile(filename)
424 object = cPickle.load(f)
438 print 'Could not load chunk %d. Stopped.' % n
443 object = cPickle.load(f)
449 def get_pdb(pdb_entry, dest='.', verbose_level=0):
452 from tempfile
import mktemp
455 url =
'ftp.ebi.ac.uk'
456 path =
'pub/databases/rcsb/pdb-remediated/data/structures/all/pdb'
457 filename_template =
'pdb%s.ent.gz'
459 dest = os.path.expanduser(dest)
461 ftp = ftplib.FTP(url)
463 ftp.set_debuglevel(verbose_level)
467 filename = os.path.join(dest,
'%s.pdb.gz' % pdb_entry)
469 f = open(filename,
'wb')
472 ftp.retrbinary(
'RETR %s' % filename_template % pdb_entry.lower(),
479 except ftplib.error_perm:
480 raise IOError,
'File %s not found on server' % filename
482 os.system(
'gunzip -f %s' % filename)
484 def compile_index_list(chain, atom_names, residue_index_list=None):
486 if residue_index_list
is None:
487 residue_index_list = range(len(chain))
497 for res_index
in residue_index_list:
499 if atom_names
is None:
500 names = chain[res_index].keys()
505 if n
in chain[res_index]:
506 index = chain[res_index][n].index
507 index_list.append(index)
511 return index_list, index_map
513 def get_coordinates(universe, E, indices=None, atom_names=(
'CA',),
514 residue_index_list=
None, atom_index_list=
None):
516 from numpy.oldnumeric
import array, take
519 indices = range(len(E))
521 chain = universe.get_polymer()
523 if atom_index_list
is None:
524 atom_index_list, index_map = compile_index_list(chain, atom_names,
531 chain.set_torsions(E.torsion_angles[i], 1)
533 X = array(take(universe.X, atom_index_list))
539 def map_angles(angles, period=None):
541 maps angles into interval [-pi,pi]
544 from numpy.oldnumeric
import fmod, greater, logical_not
547 from numpy.oldnumeric
import pi
as period
549 mask = greater(angles, 0.)
551 return mask * (fmod(angles+period, 2*period)-period) + \
552 logical_not(mask) * (fmod(angles-period, 2*period)+period)
554 def remove_from_dict(d, items):
560 def myrange(a, b, n):
562 from numpy.oldnumeric
import arange
564 step = (b - a) / (n - 1)
566 x = arange(a, b + step, step)
570 def indent(lines, prefix):
572 tag =
' ' * len(str(prefix))
574 lines[0] = prefix + lines[0]
575 lines = [lines[0]] + map(
lambda s, t = tag: t + s, lines[1:])
577 return '\n'.join(lines)
579 def make_block(s, length = 80, tol = 10):
580 blocks = s.split(
'\n')
583 l += _make_block(block, length, tol)
587 def _make_block(s, length, tol):
590 l = [(w,
' ')
for w
in l]
595 g = [w+
'/' for w
in g]
596 g[-1] = g[-1][:-1] +
' '
603 for i
in range(len(words)):
606 if len(line + word) <= length:
610 if length - len(line) > tol:
611 m = length - len(line)
615 if len(line) > 1
and line[0] ==
' ' and \
623 if len(line) > 1
and line[0] ==
' ' and \
631 def _save_dump(x, filename, err_msg=None, delay=10, show_io_err=True,
632 gzip=
False, bin=
True):
635 Dump(x, filename, gzip=gzip, bin=bin)
642 print 'IOError: %s' % str(msg)
646 print '%s. %s' % (str(msg), err_msg)
654 time.sleep(60. * delay)
657 Dump(x, filename, gzip=gzip, bin=bin)
663 def save_dump(x, filename, err_msg=None, delay=10, show_io_err=True,
664 gzip=
False, mode=
'w', bin=
True):
668 path, _filename = os.path.split(filename)
670 temp_path, temp_filename = os.path.split(tempfile.mktemp())
671 temp_filename = os.path.join(path, temp_filename)
673 _save_dump(x, temp_filename, err_msg, delay, show_io_err,
679 os.rename(temp_filename, filename)
682 os.unlink(temp_filename)
683 Dump(x, filename, mode=
'a', gzip=gzip, bin=bin)
686 raise StandardError,
'Mode "%s" invalid.' % mode