Package SloppyCell :: Module Utility
[hide private]

Source Code for Module SloppyCell.Utility

  1  import cPickle 
  2  import logging 
  3  import smtplib 
  4  import sets 
  5  from email.MIMEText import MIMEText 
  6   
  7  import scipy 
  8   
  9  from scipy import linspace, logspace 
 10   
 11  import random 
 12  import copy 
 13   
14 -def send_email(to_addr, from_addr=None, subject='', message=''):
15 """ 16 Send a plain-text email to a single address. 17 """ 18 if from_addr is None: 19 from_addr = to_addr 20 21 # Create a text/plain message 22 msg = MIMEText(message) 23 msg['Subject'] = subject 24 msg['To'], msg['From'] = to_addr, from_addr 25 26 # From the documentation for email... Not sure what it means. :-) 27 ## Send the message via our own SMTP server, but don't include the 28 ## envelope header. 29 s = smtplib.SMTP() 30 s.connect() 31 s.sendmail(from_addr, [to_addr], msg.as_string()) 32 s.close()
33
34 -def save(obj, filename):
35 """ 36 Save an object to a file 37 """ 38 f = file(filename, 'wb') 39 cPickle.dump(obj, f, 2) 40 f.close()
41
42 -def load(filename):
43 """ 44 Load an object from a file 45 """ 46 f = file(filename, 'rb') 47 obj = cPickle.load(f) 48 f.close() 49 return obj
50
51 -def eig(mat):
52 """ 53 Return the sorted eigenvalues and eigenvectors of mat. 54 """ 55 e, v = scipy.linalg.eig(mat) 56 order = scipy.argsort(abs(e))[::-1] 57 e = scipy.take(e, order) 58 v = scipy.take(v, order, axis=1) 59 60 return e, v
61
62 -def bootstrap(data,num_iterates=100):
63 """ 64 Use sampling with replication to calculate variance in estimates. 65 """ 66 len_data = len(data) 67 sampled_data = [] 68 for ii in range(num_iterates): 69 sampled_data.append([random.choice(data) for ii in range(len_data)]) 70 71 return sampled_data
72
73 -def enable_debugging_msgs(filename=None):
74 """ 75 Enable output of debugging messages. 76 77 If filename is None messages will be sent to stderr. 78 """ 79 logging.root.setLevel(logging.DEBUG) 80 81 if filename is not None: 82 # Remove other handlers 83 for h in logging.root.handlers: 84 logging.root.removeHandler(h) 85 86 # We need to add a file handler 87 handler = logging.FileHandler(filename) 88 # For some reason the default file handler format is different. 89 # Let's change it back to the default 90 formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s') 91 handler.setFormatter(formatter) 92 logging.root.addHandler(handler) 93 logging.debug('Debug messages enabled.')
94
95 -def disable_debugging_msgs():
96 """ 97 Disable output of debugging messages. 98 """ 99 logging.root.setLevel(logging.WARN) 100 # Remove all other handlers 101 for h in logging.root.handlers: 102 logging.root.removeHandler(h) 103 # Restore basic configuration 104 logging.basicConfig()
105
106 -def disable_warnings():
107 scipy.seterr(over='ignore', divide='ignore', invalid='ignore', 108 under='ignore') 109 logging.root.setLevel(logging.CRITICAL)
110
111 -def enable_warnings():
112 logging.root.setLevel(logging.WARNING) 113 scipy.seterr(over='print', divide='print', invalid='print', 114 under='ignore')
115
116 -class SloppyCellException(Exception):
117 pass
118
119 -class ConstraintViolatedException(Exception):
120 """ 121 A ConstraintViolatedException is raised when a the value of a network constraint 122 becomes True. 123 """
124 - def __init__(self, time, constraint, message):
125 self.constraint = constraint 126 self.message = message 127 self.time = time
128 - def __str__(self):
129 return ('Violated constraint: %s at time %g. Additional Information: %s.' \ 130 %(self.constraint, self.time, self.message))
131 132 import Redirector_mod 133 Redirector = Redirector_mod.Redirector 134
135 -def combine_hessians(hesses, key_sets):
136 """ 137 Combine a number of hessians (with possibly different dimensions and 138 orderings) into a single hessian. 139 140 hesses A sequence of hessians to combine 141 key_sets A sequence of sequences containing the parameter keys (in order) 142 for each hessian. 143 """ 144 145 # Get a list of all the possible parameter keys 146 tot_keys = copy.copy(key_sets[0]) 147 keys_seen = sets.Set(tot_keys) 148 for ks in key_sets[1:]: 149 new_keys = [key for key in ks if key not in keys_seen] 150 tot_keys.extend(new_keys) 151 keys_seen.union_update(sets.Set(new_keys)) 152 153 # Add all the appropriate hessian elements together 154 key_to_index = dict(zip(tot_keys, range(len(tot_keys)))) 155 tot_hess = scipy.zeros((len(tot_keys), len(tot_keys)), scipy.float_) 156 for hess, keys in zip(hesses, key_sets): 157 for ii, id1 in enumerate(keys): 158 tot_ii = key_to_index[id1] 159 for jj, id2 in enumerate(keys): 160 tot_jj = key_to_index[id2] 161 tot_hess[tot_ii, tot_jj] += hess[ii, jj] 162 163 return tot_hess, tot_keys
164