generated from fastai/nbdev_template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
00_core.py
2706 lines (1869 loc) · 66.6 KB
/
00_core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
---
description: The main simulation functions used for adding, running, and visualizing
ODEs
output-file: core.html
title: Core Simulation
---
# In[ ]:
#| default_exp core
# ## Preliminaries
# In[ ]:
#| export
from scipy.integrate import odeint,ode
from pylab import *
from numpy import *
import pylab
from copy import deepcopy
from matplotlib import rc
size=20
family='sans-serif'
rc('font',size=size,family=family)
rc('axes',titlesize=size,grid=True,labelsize=size)
rc('xtick',labelsize=size)
rc('ytick',labelsize=size)
rc('legend',fontsize=size)
rc('lines',linewidth=2)
rc('figure',figsize=(12,8))
import os
import sys
# In[ ]:
#| export
import functools
from types import FunctionType
def copy_func(f):
"Copy a non-builtin function (NB `copy.copy` does not work for this)"
if not isinstance(f,FunctionType): return copy(f)
fn = FunctionType(f.__code__, f.__globals__, f.__name__, f.__defaults__, f.__closure__)
fn.__dict__.update(f.__dict__)
return fn
def patch_to(cls, as_prop=False):
"Decorator: add `f` to `cls`"
if not isinstance(cls, (tuple,list)): cls=(cls,)
def _inner(f):
for c_ in cls:
nf = copy_func(f)
# `functools.update_wrapper` when passing patched function to `Pipeline`, so we do it manually
for o in functools.WRAPPER_ASSIGNMENTS: setattr(nf, o, getattr(f,o))
nf.__qualname__ = f"{c_.__name__}.{f.__name__}"
setattr(c_, f.__name__, property(nf) if as_prop else nf)
return f
return _inner
def patch(f):
"Decorator: add `f` to the first parameter's class (based on f's type annotations)"
cls = next(iter(f.__annotations__.values()))
return patch_to(cls)(f)
# In[ ]:
#| export
class InterpFunction(object):
def __init__(self,x,y,name):
self.x=x
self.y=y
self.__name__=name
def __call__(self,x):
from numpy import interp
y=interp(x,self.x,self.y)
return y
class RedirectStdStreams(object):
def __init__(self, stdout=None, stderr=None):
self._stdout = stdout or sys.stdout
self._stderr = stderr or sys.stderr
def __enter__(self):
self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
self.old_stdout.flush(); self.old_stderr.flush()
sys.stdout, sys.stderr = self._stdout, self._stderr
def __exit__(self, exc_type, exc_value, traceback):
self._stdout.flush(); self._stderr.flush()
sys.stdout = self.old_stdout
sys.stderr = self.old_stderr
devnull = open(os.devnull, 'w')
# In[ ]:
#| export
def from_values(var,*args):
if len(args)==1:
y=[v[1] for v in args[0]]
x=[v[0] for v in args[0]]
else:
y=[v[1] for v in args]
x=[v[0] for v in args]
if var<x[0]:
return y[0]
if var>x[-1]:
return y[-1]
return interp(var,x,y)
def array_wrap(_f):
# allow a function to be written for float values, but be handed array
# values and return an array
def what(*args,**kw):
try:
val=_f(*args,**kw)
except ValueError: # array treated as float
found=False
for _a in args:
if isinstance(_a,ndarray):
__L=len(_a)
found=True
break
if not found:
print("Leon, you broke my program. ")
print("args",args)
print("kwargs",kw)
raise ValueError()
val=[]
for _i in range(__L):
newargs=[]
for _a in args:
if isinstance(_a,ndarray):
newargs.append(_a[_i])
else:
newargs.append(_a)
newargs=tuple(newargs)
val.append(_f(*newargs,**kw))
val=array(val)
return val
return what
# ## Supporting functions for solving ODE and MAPS
# In[ ]:
#| export
def mapsolve(function,y0,t_mat,*args):
y=array(y0)
y_mat=[]
for t in t_mat:
y_mat.append(y)
newy=array(function(y,t,*args))
y=newy
ret=array(y_mat)
return ret
def euler(function,y0,t_mat,*args,**kwargs):
dt=t_mat.ravel()[1]-t_mat.ravel()[0]
y=array(y0)
y_mat=[]
for t in t_mat:
y_mat.append(y)
dy=array(function(y,t,*args))*dt # call the function
y=y+dy
ret=array(y_mat)
return ret
def rk2(function,y0,t_mat,*args,**kwargs):
dt=t_mat.ravel()[1]-t_mat.ravel()[0]
y=array(y0)
y_mat=[]
for t in t_mat:
y_mat.append(y)
tp=t+dt/2.0
dyp=array(function(y,t,*args))*dt # call the function
yp=y+0.5*dyp
dy=array(function(yp,tp,*args))*dt
y=y+dy
ret=array(y_mat)
return ret
def rk4(function,y0,t_mat,*args,**kwargs):
dt=t_mat.ravel()[1]-t_mat.ravel()[0]
y=array(y0)
y_mat=[]
for t in t_mat:
y_mat.append(y)
y1=y
t1=t
f1=array(function(y1,t1,*args))
y2=y+0.5*f1*dt
t2=t+0.5*dt
f2=array(function(y2,t2,*args))
y3=y+0.5*f2*dt
t3=t+0.5*dt
f3=array(function(y3,t3,*args))
y4=y+f3*dt
t4=t+dt
f4=array(function(y4,t4,*args))
dy=1.0/6.0*(f1+2*f2+2*f3+f4)*dt
y=y+dy
ret=array(y_mat)
return ret
def rkwrapper(function,_self):
def fun(t,y,*args,**kwargs):
return function(y,t,_self,*args,**kwargs)
return fun
def rk45(function,y0,t_mat,_self,*args,**kwargs):
dt=t_mat.ravel()[1]-t_mat.ravel()[0]
t0=t_mat.ravel()[0]
t1=t_mat.ravel()[-1]
function=rkwrapper(function,_self)
r=ode(function).set_integrator('dopri5',nsteps=300)
r.set_initial_value(y0, t0)
y=array(y0)
y_mat=[]
y_mat.append(r.y)
while r.successful() and r.t <= t1:
r.integrate(r.t+dt)
y_mat.append(r.y)
ret=array(y_mat)
return ret
def simfunc(_vec,t,_sim):
if _sim.method=='map':
usemap=True
else:
usemap=False
_l=locals()
for _i,_c in enumerate(_sim.components):
_l[_c.name]=_vec[_i]
_l.update(_sim.myparams)
for _i,_c in enumerate(_sim.assignments):
_s='%s' % _c.diffstr
if _sim.verbose:
print(_s)
try:
_val=eval(_s,_l)
except NameError:
for _j in range(_i+1):
print(_sim.assignments[_j].diffstr)
_val=eval(_s,_l)
_l[_c.name]=_val
_diff=[]
for _i,_c in enumerate(_sim.components):
if not _c.diffstr:
_s='0'
else:
_s='%s' % _c.diffstr
if _sim.verbose:
print(_s)
_val=eval(_s,_l)
if not _c.min is None:
if _vec[_i]<_c.min:
_vec[_i]=_c.min
if _val<0: # stop the change in the variable
_val=0
if not _c.max is None:
if _vec[_i]>_c.max:
_vec[_i]=_c.max
if _val>0: # stop the change in the variable
_val=0
_diff.append(_val)
if usemap:
_l[_c.name]=_val
return _diff
# In[ ]:
#| export
def phase_plot(sim,x,y,z=None,**kwargs):
"""
Make a Phase Plot of two or three variables.
Parameters
----------
sim : Simulation
This is a simulation object.
x : str
Name of the variable to plot on the x-axis
y : str
Name of the variable to plot on the y-axis
z : str, optional
Name of the variable to plot on the (optional) z-axis
Returns
-------
"""
from mpl_toolkits.mplot3d import Axes3D
if not z is None: # 3D!
ax = gcf().add_subplot(111, projection='3d')
ax.plot(sim[x],sim[y],sim[z])
ax.set_xlabel(x)
ax.set_ylabel(y)
ax.set_zlabel(z)
else:
plot(sim[x],sim[y])
xlabel(x)
ylabel(y)
def vector_field(sim,rescale=False,**kwargs):
keys=sorted(kwargs.keys())
tuples=[ kwargs[key] for key in keys ]
if len(tuples)==1:
tuples.append(array([0]))
X,Y=meshgrid(*tuples)
U=zeros_like(X)
V=zeros_like(X)
count=0
for x,y in zip(X.ravel(),Y.ravel()):
vec=[]
for i,c in enumerate(sim.components):
if i==0: # set x
c.initial_value=x
elif i==1: # set y
c.initial_value=y
else:
raise ValueError("Not Implemented for 3D+")
vec.append(c.initial_value)
vec=array(vec)
t=0
df=simfunc(vec,t,sim)
U.ravel()[count]=df[0]
try:
V.ravel()[count]=df[1]
except IndexError:
pass
count+=1
if rescale:
N = sqrt(U**2+V**2) # there may be a faster numpy "normalize" function
U, V = U/N, V/N
figure(figsize=sim.figsize)
Q = quiver( X, Y, U, V)
xlabel(sim.components[0].name)
try:
ylabel(sim.components[1].name)
except IndexError:
pass
# In[ ]:
#| export
class Component(object):
def __init__(self,diffstr,initial_value=0,
min=None,max=None,
plot=False,save=None):
name,rest=diffstr.split('=')
name=name.strip()
self.orig_diffstr=diffstr
if "'" in name:
name=name[:-1]
self.diffeq=True
else:
self.diffeq=False
self.diffstr=rest.strip()
self.diffstr=self.replace_primes(self.diffstr)
self.name=name
self.initial_value=initial_value
try:
self.length=len(initial_value)
if self.length==1:
self.initial_value=initial_value[0]
except TypeError:
self.length=1
self.values=None
self.min=min
self.max=max
self.plot=plot
self.save=save
if name.endswith("_"): # a primed name
ps=name.split('_')
self.label="_".join(ps[:-2])+"'"*len(ps[-2])
else:
self.label=name
self.data={}
def inflow(self,s):
s=s.strip()
s=self.replace_primes(s)
self.diffstr+='+'+s
def outflow(self,s):
s=s.strip()
s=self.replace_primes(s)
self.diffstr+='-('+s+')'
def replace_primes(self,s):
import re
s2=s
if "'" not in s2:
return s2
for i in range(10,0,-1):
s2=re.sub("(\w*)"+"'"*i,"\\1_"+"p"*i+"_",s2)
return s2
def __getitem__(self,s):
"""docstring for __getitem__"""
return self.values[s]
def __repr__(self):
s="%s : %s\n%s" % (self.label,self.orig_diffstr,str(self.values))
return s
# In[ ]:
#| export
numpy_functions=(sin,cos,exp,tan,abs,floor,ceil,radians,degrees,
sinh,cosh,tanh,arccos,arcsin,arctan,arctan2,
min,max,sqrt,log,log10,mean,median)
# ## Examples of Components
# # The `Simulation` class is the primary one to use
# In[ ]:
#| export
class Simulation(object):
def __init__(self,method='odeint',verbose=False,plot_style='.-'):
self.initialized=False
self.components=[]
self.assignments=[]
self.plot_style=plot_style
self.use_delays=False
self.data_delay={}
self.verbose=verbose
self.myparams={}
self.method=method
self.show=True
self.original_params={}
self.initial_value={}
self.extra={}
self.omit=[]
self.figsize=(12,8)
self.myparams.update({'from_values':array_wrap(from_values)})
self.functions(*numpy_functions,omit=True)
self.myparams.update(pi=pi,inf=inf)
self.omit.append('pi')
self.omit.append('inf')
self.use_func=True
self.func=None
self.myfunctions={}
self.initialized=True
self.maximum_data_t=-1e500
self.maximum_t=-1e500
self.noplots=False
self.data_components={}
self.figures=[]
def delay(self,var,t):
return interp(t,self.data_delay[var]['t'],self.data_delay[var]['value'])
def make_func(self):
from numba import jit
all_eq=True
all_diffeq=True
for c in self.components:
if c.diffeq:
all_eq=False
if not c.diffeq:
all_diffeq=False
if not all_eq and not all_diffeq:
components=[]
for c in self.components:
if not c.diffeq:
self.assignments.append(c)
else:
components.append(c)
self.components=components
_sim=self
s="def _simfunc(_vec,t,_sim):\n"
for _f in self.myfunctions:
s=s+" %s=_sim.myfunctions['%s']\n" % (_f,_f)
for _i,_c in enumerate(_sim.components):
s=s+" initial_%s=_sim.initial_value['%s']\n" % (_c.name,_c.name)
s=s+"\n"
for key in _sim.original_params:
s=s+" %s=_sim.original_params['%s']\n" % (key,key)
s=s+"\n"
for _i,_c in enumerate(_sim.components):
s=s+" %s=_vec[%d]\n" % (_c.name,_i)
s=s+"\n"
if _sim.use_delays:
for _i,_c in enumerate(_sim.components):
s+=" _sim.data_delay['%s']['t'].append(t)\n" % (_c.name)
s+=" _sim.data_delay['%s']['value'].append(%s)\n" % (_c.name,_c.name)
for _i,_c in enumerate(_sim.assignments):
s=s+" %s=%s\n" % (_c.name,_c.diffstr)
if _sim.use_delays:
s+=" _sim.data_delay['%s']['t'].append(t)\n" % (_c.name)
s+=" _sim.data_delay['%s']['value'].append(%s)\n" % (_c.name,_c.name)
s=s+"\n"
s=s+" _diff=[]\n"
for _i,_c in enumerate(_sim.components):
s=s+" _val=%s\n" % (_c.diffstr)
if not _c.min is None:
s=s+"""
if _vec[%d]<%s:
_vec[%d]=%s
if _val<0:
_val=0
""" % (_i,_c.min,_i,_c.min)
s=s+"\n"
if not _c.max is None:
s=s+"""
if _vec[%d]>%s:
_vec[%d]=%s
if _val>0:
_val=0
""" % (_i,_c.max,_i,_c.max)
s=s+"\n"
s=s+" _diff.append(_val)\n"
s=s+"\n"
s=s+" return _diff\n"
self.func_str=s
exec(s)
_sim.func=locals()['_simfunc']
return locals()['_simfunc']
def equations(self):
s=""
for c in self.components:
if c.diffstr:
s+="%s'=%s\n" % (c.name,c.diffstr)
else:
s+="%s'=0\n" % (c.name)
for key in self.myparams:
if not key in ['from_values']:
if key in self.omit:
continue
s+="%s=%s\n" % (key,str(self.myparams[key]))
return s
def copy(self):
sim_copy=Simulation()
for c in self.components:
c_copy=Component(c.label+"'="+c.diffstr,c.initial_value,
c.min,c.max,c.plot,c.save)
sim_copy.components.append(c_copy)
for key in self.myparams:
sim_copy.myparams[key]=self.myparams[key]
sim_copy.method=self.method
sim_copy.verbose=self.verbose
return sim_copy
def add(self,diffstr,initial_value=0,
min=None,max=None,
plot=False,save=None):
name,rest=diffstr.split('=')
if 'delay(' in rest or 'delay (' in rest:
self.use_delays=True
if name.count("'")<=1:
name=name.split("'")[0]
if name in [c.name for c in self.components]:
raise ValueError("%s already exists." % name)
c=Component(diffstr,initial_value,min,max,plot,save)
self.components.append(c)
self.data_delay[c.name]={'t':[],'value':[]}
return c
else: # higher order of diffeq
order=name.count("'")
name=name.split("'")[0]
cc=[]
# make the new variables
try:
L=len(plot)
assert L==order
except TypeError:
plot=[plot]*order
for i in range(order-1):
if i==0:
vname1=name
else:
vname1=name+"_"+"p"*i+"_"
vname2=name+"_"+"p"*(i+1)+"_"
ds="%s'=%s" % (vname1,vname2)
c=Component(ds,initial_value[i],min,max,plot[i],save)
self.components.append(c)
cc.append(c)
vname=name+"_"+"p"*(order-1)+"_"
ds="%s'=%s" % (vname,rest)
c=Component(ds,initial_value[order-1],min,max,plot[-1],save)
self.components.append(c)
self.data_delay[c.name]={'t':[],'value':[]}
cc.append(c)
def initial_values(self,**kwargs):
self.initial_value.update(kwargs)
def params(self,**kwargs):
for name in kwargs:
if name in [c.name for c in self.components]:
raise ValueError("Parameter name %s already a variable." % name)
self.myparams.update(kwargs)
self.original_params.update(kwargs)
for key in kwargs:
if 'initial_' in key:
name=key.split('initial_')[1]
_c=self.get_component(name)
_c.initial_value=kwargs[key]
def functions(self,*args,**kwargs):
try:
omit=kwargs['omit']
except KeyError:
omit=False
#self.myparams.update(dict(zip([f.__name__ for f in args],args)))
self.myparams.update(dict(list(zip(
[f.__name__ for f in args],
[array_wrap(a) for a in args],
))))
if self.initialized:
for key in [f.__name__ for f in args]:
self.myfunctions[key]=self.myparams[key]
if omit:
self.omit.extend([f.__name__ for f in args])
def vec2str(self,vec):
s=""
i=0
for c in self.components:
s+="%s=vec[%d]\n" % (c.name,i)
i+=1
return s
def post_process(_sim):
t=_sim.t
try: # assignments with arrays
_l=locals()
for _i,_c in enumerate(_sim.components):
_l[_c.name]=_c.values
_l["initial_"+_c.name]=_c.initial_value
_l.update(_sim.myparams)
for _c in _sim.assignments:
_s='%s' % _c.diffstr
if _sim.verbose:
print(_s)
try:
_val=eval(_s)
except FloatingPointError:
if 'post_process error' not in _sim.extra:
_sim.extra['post_process error']=[]
_sim.extra['post_process error'].append("Floating Point Error on '%s'" % (_s))
_val=-1e500
_l[_c.name]=_val
_c.values=_val
except ValueError:
_l=locals()
_c=_sim.components[0]
_N=len(_c.values)
for _c in _sim.assignments:
_c.values=[]
for _j in range(_N):
for _i,_c in enumerate(_sim.components):
_l[_c.name]=_c.values[_j]
_l.update(_sim.myparams)
for _c in _sim.assignments:
_s='%s' % _c.diffstr
if _sim.verbose:
print(_s)
_val=eval(_s)
_l[_c.name]=_val
_c.values.append(_val)
for _c in _sim.assignments:
_c.values=array(_c.values,float)
def mse(self,name):
svals=self[name]
st=self['t']
c=self.get_component(name)
if not c.data:
raise ValueError('No Data for MSE')
simvals=interp(c.data['t'],self.t,c.values)
mseval=((array(c.data['value'])-simvals)**2).mean()
return mseval
def compare(self,cname,t=None,value=None,
plot=False,transform=None):
if t is None or value is None:
return None
svals=self[cname]
st=self['t']
if transform=='log':
svals=log(svals)
value=log(array(value))
label='log(%s)' % cname
else:
label=cname
simvals=interp(t,st,svals)
mse=((array(value)-simvals)**2).mean()
if plot:
fig=figure(figsize=self.figsize)
self.figures.append(fig)
pylab.plot(st,svals,'-o')
pylab.plot(t,value,'rs')
pylab.grid(True)
xlabel('time')
ylabel(label)
title('MSE : %.3e' % mse)
draw()
if self.show:
show()
return mse
def repeat(self,t_min,t_max=None,num_iterations=1000,**kwargs):
keys=list(kwargs.keys())
name=keys[0]
L=len(kwargs[name])
results=[]
self.noplots=True
for i in range(L):
result={}
params={}
for name in keys:
params[name]=kwargs[name][i]
self.params(**params)
self.run_fast(t_min,t_max,num_iterations)
for c in self.components:
result[c.name]=c.values
results.append(result)
self.noplots=False
return results
def interpolate(self,t,cname=None):
if cname is None:
cnames=[x.name for x in self.components]
result={}
for cname in cnames:
result[cname]=self.interpolate(t,cname)
return result
else:
svals=self[cname]
st=self['t']
# gives a value error if svals is nan
try:
simvals=interp(t,st,svals)
except ValueError:
try:
simvals=-1e500*ones(len(t))
except TypeError: # a float given
simvals=-1e500
return simvals
def run_fast(self,t_min=None,t_max=None,num_iterations=1000,**kwargs):
if t_min is None:
assert self.maximum_data_t>-1e500,"Did you forget to add data to your model?"
t_min=0
t_max=self.maximum_data_t+0.1
if not self.func:
self.make_func()
t=linspace(t_min,t_max,num_iterations)
y0=[c.initial_value for c in self.components]
for c in self.components:
self.initial_value[c.name]=c.initial_value
func=self.func
# I got sick of the ridiculous messages when trying to run fast
with RedirectStdStreams(stdout=devnull, stderr=devnull):
result,extra=odeint(func,y0,t,(self,),full_output=True,printmessg=False,**kwargs)
self.extra=extra
self.t=t