1 """PyDSTool initialization script.
2
3 Copyright (C) 2007-2012 Georgia State University
4
5 print PyDSTool.__LICENSE__ for the terms of use.
6 """
7
8 __LICENSE__ = """\
9 Copyright (C) 2007-2012, Georgia State University
10 All rights reserved.
11
12 Parts of this distribution that originate from different authors are
13 individually marked as such. Copyright and licensing of those parts remains
14 with the original authors.
15
16 Redistribution and use in source and binary forms, with or without
17 modification, are permitted provided that the following conditions are met:
18
19 1. Redistributions of source code must retain the above copyright
20 notice, this list of conditions and the following disclaimer.
21
22 2. Redistributions in binary form must reproduce the above
23 copyright notice, this list of conditions and the following
24 disclaimer in the documentation and/or other materials provided
25 with the distribution.
26
27 3. The name of Georgia State University and its representatives may not
28 be used to endorse or promote products derived from this
29 software without specific prior written permission.
30
31 THIS SOFTWARE IS PROVIDED BY GEORGIA STATE UNIVERSITY ``AS IS'' AND ANY
32 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
34 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGIA STATE UNIVERSITY BE LIABLE
35 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
38 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
39 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
40 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
41 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42
43 """
44
45 vernum = '0.88'
46 __version__ = vernum
47 __revision__ = '$Revision: 121202 $'
48 __date__ = '$Date: 2012/12/02 23:30:00 $'
49
50 import sys, os, gc
51
52 try:
53 import scipy
54 except ImportError:
55 raise RuntimeError("SciPy is required")
56 try:
57 verstr_parts = scipy.__version__.split('.')
58 except AttributeError:
59 verstr_parts = scipy.__scipy_version__.split('.')
60 digits = [str(n) for n in range(10)]
61 vernums = []
62
63
64 temp_str = ''
65 for s in verstr_parts:
66 for t in s:
67 if t in digits:
68 temp_str += t
69 else:
70 break
71 try:
72 vernums.append(int(temp_str))
73 except ValueError:
74
75 pass
76 temp_str = ''
77 assert len(vernums) > 0
78 if vernums[1] < 5:
79 raise RuntimeError("SciPy v0.5.1 or above is required")
80 del digits, vernums, temp_str
81
82 import math, random
83 import types, time
84
85
86 from Events import *
87 from Interval import *
88 from Points import *
89 from Variable import *
90 from Trajectory import *
91 from FuncSpec import *
92
93 import Generator as GenModule
94 from Generator import Generator as Generator_
95 from Generator import *
96 Generator = GenModule
97 import Model as ModelModule
98 from Model import Model as Model_
99 from Model import *
100 Model = ModelModule
101
102 from ModelConstructor import *
103 from Toolbox.ParamEst import ParamEst
104 from Toolbox.ModelEst import ModelEst
105 from MProject import *
106 from Symbolic import *
107 from ModelSpec import *
108 from parseUtils import auxfnDBclass, protected_allnames, protected_auxnamesDB, \
109 convertPowers
110 from PyCont import *
111 import numpy
112 import numpy as npy
113
114 import scipy as spy
115 from math import *
116 from matplotlib import pyplot as plt
117 from matplotlib.pyplot import figure, plot, show, draw, hold
118 from numpy import *
119
120 __version__ = vernum
121 del vernum
122
123
124 from copy import copy
125
126
127
128 from common import Verbose, Continuous, Discrete, targetLangs, _seq_types, \
129 _num_types, _int_types, _float_types, _complex_types, \
130 _real_types, _all_numpy_int, _all_numpy_float, \
131 _all_numpy_complex, _all_int, _all_float, _all_complex, \
132 LargestInt32, diff, diff2
133 from scipy import who as scipy_who
134 from utils import *
135
136
137
138 major, minor1, minor2, s, tmp = sys.version_info
139 _validpython = major==2 and minor1>=4
140
141 if not _validpython:
142 raise RuntimeError("Python 2.4 or later is required to run PyDSTool")
143 del _validpython, major, minor1, minor2, s, tmp
144
145 _pyDSToolTypes = [ndarray, Generator_, Variable, Trajectory, Event,
146 EventStruct, Point, Pointset, Interval, ParamEst,
147 Model_, Quantity, ModelSpec, QuantSpec, ModelEst,
148 ModelConstructor, auxfnDBclass, nameResolverClass,
149 ContClass, GeneratorConstructor, condition, feature,
150 GeneratorInterface, ModelInterface, ModelManager,
151 ModelTransform, GDescriptor, MDescriptor, context,
152 ModelLibrary]
153
154 -def who(typelist=None, objdict=None, verboselevel=0, returnlevel=0,
155 deepSearch=False, _localCall=False):
156 """Information about the PyDSTool user-created objects of types
157 specified by typelist (defaults to all PyDSTool types and
158 numpy arrays), from the objdict dictionary (or from globals() if this
159 is not given).
160
161 returnlevel > 0 puts who() into silent mode, and it just returns
162 either (1) a list of the objects found, or (2) a dictionary of object
163 names -> objects found.
164
165 deepSearch = True causes a shallow search of list, tuple and dictionary
166 objects defined at the topmost level of objdict. Otherwise only
167 PyDSTool objects visible at the topmost level will be seen.
168 """
169 objdict_out = {}
170 if objdict is None:
171 if _localCall:
172
173
174 frame = sys._getframe().f_back.f_back
175 else:
176 frame = sys._getframe().f_back
177 objdict = frame.f_globals
178
179
180 if typelist is None:
181 typelist_actual = _pyDSToolTypes
182 elif isinstance(typelist, list):
183
184 typelist_actual = []
185 for t in typelist:
186 if t == Model:
187
188 typelist_actual.append(Model_)
189 elif t == Generator:
190
191 typelist_actual.append(Generator_)
192 elif t == array:
193
194 typelist_actual.append(numpy.ndarray)
195 else:
196 typelist_actual.append(t)
197
198
199
200
201 else:
202
203
204 if typelist == Model:
205
206 typelist_actual = [Model_]
207 elif typelist == Generator:
208
209 typelist_actual = [Generator_]
210 elif typelist == array:
211 typelist_actual = [numpy.ndarray]
212 else:
213 typelist_actual = [typelist]
214
215
216
217
218 for objname, obj in objdict.iteritems():
219 if type(obj) not in [type, types.ClassType, types.ModuleType]:
220 if compareClassAndBases(obj, typelist_actual):
221 if isinstance(obj, QuantSpec) and objname in protected_allnames:
222
223
224 continue
225 objdict_out[objname] = obj
226 elif deepSearch:
227 if isinstance(obj, (list, tuple)):
228 if any([compareClassAndBases(x, typelist_actual) \
229 for x in obj]):
230 objdict_out[objname] = obj
231 elif isinstance(obj, dict):
232 if any([compareClassAndBases(x, typelist_actual) \
233 for x in obj.values()]):
234 objdict_out[objname] = obj
235 if returnlevel == 1:
236
237 return objdict_out.values()
238 elif returnlevel == 2:
239
240 return objdict_out
241 else:
242 for objname, obj in objdict_out.iteritems():
243
244 if verboselevel > 0:
245 print "\n"*(verboselevel-1)
246 if hasattr(obj, '_infostr') and not isinstance(obj, type):
247 try:
248 print objname + ": " + obj._infostr(verboselevel)
249 except:
250 print "Problem with: ", objname, className(obj), \
251 obj.info
252 raise
253 else:
254 print objname + " (Class " + className(obj) + ")" \
255 + (verboselevel > 0)*":"
256 if verboselevel > 0:
257 info(obj, objname, recurseDepthLimit=verboselevel-1)
258
259
260 __session_ext = 'ses'
261 __symbolic_ext = 'sym'
262
263 -def saveSession(sessionName=None, force=False, silent=False, deepSearch=False):
264 if sessionName is None:
265 datestr = time.strftime("%Y %m %d _ %Hh%Mm").replace(" ","")[2:]
266 sessionName = "Session_" + datestr
267 objdict = who(returnlevel=2, _localCall=True, deepSearch=deepSearch)
268 objnamelist, objlist = sortedDictLists(objdict, byvalue=False)
269
270
271 objlist.append(objnamelist)
272 saveObjects(objlist, sessionName+'.'+__session_ext, force)
273 if not silent:
274 print "Important!"
275 print "If you used any user-defined classes for ModelSpec, these need to "
276 print "be recreated by running their definition scripts when you restore "
277 print "the session. saveSession only saves class _instances_."
278
279
280
282 """Use tolocals boolean option if loading a session into the local
283 namespace of the caller (i.e. if calling this from within a function
284 rather than interactively at the prompt)"""
285
286 sessionName_split = sessionName.split('.')
287 if sessionName_split[-1] != __session_ext:
288 sessionName = sessionName + '.' + __session_ext
289 try:
290 loadlist = loadObjects(sessionName)
291 except:
292 print "Problem loading session " + sessionName
293 raise
294 numobjs = len(loadlist) - 1
295 if len(loadlist) <= 0:
296 raise ValueError, "Session was empty!"
297 objnamelist = loadlist[-1]
298 objlist = loadlist[:-1]
299 frame = sys._getframe().f_back
300 if tolocals:
301 nspace = frame.f_locals
302 else:
303 nspace = frame.f_globals
304
305 try:
306 for i in xrange(numobjs):
307 nspace[objnamelist[i]] = objlist[i]
308 except:
309 print "Problem recreating objects"
310 print "Debug info: ", len(objnamelist), len(objlist), numobjs
311 raise
312
313
314
315
317 """restart clears out global databases of PyDSTool objects,
318 and with the optional argument delall=1 will delete all PyDSTool
319 objects found at the top-level of the caller's namespace (not including
320 numpy arrays).
321
322 delall=2 will cause a one-level deeper search of lists, tuples, and
323 dictionaries for PyDSTool objects, and the lists etc. will be deleted.
324 Additionally, numpy arrays will be deleted.
325 """
326 nameResolver.clearall()
327 genDB.clearall()
328 protected_auxnamesDB.clearall()
329 if delall>0:
330 deep = delall==2
331 objdict = who(returnlevel=2, _localCall=True, deepSearch=deep)
332 frame = sys._getframe().f_back
333 nspace = frame.f_globals
334 for objname, obj in objdict.iteritems():
335 if objname not in ['nameResolver', 'protected_auxnamesDB'] and \
336 (not isinstance(obj, ndarray) or delall==2):
337
338 del nspace[objname]
339 del objdict, frame, nspace
340 gc.collect()
341