forked from AllenDowney/ModSimPy
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodsim.py
More file actions
Latest commit
887 lines (641 loc) · 22.8 KB
/
Copy pathmodsim.py
File metadata and controls
887 lines (641 loc) · 22.8 KB
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
"""
Code from Modeling and Simulation in Python.
Copyright 2020 Allen Downey
MIT License: https://opensource.org/licenses/MIT
"""
importlogging
logger=logging.getLogger(name="modsim.py")
# make sure we have Python 3.6 or better
importsys
ifsys.version_info< (3, 6):
logger.warning("modsim.py depends on Python 3.6 features.")
importinspect
importmatplotlib.pyplotasplt
plt.rcParams['figure.dpi'] =75
plt.rcParams['savefig.dpi'] =300
plt.rcParams['figure.figsize'] =6, 4
importnumpyasnp
importpandasaspd
importscipy
importscipy.optimizeasspo
fromscipy.interpolateimportinterp1d
fromscipy.interpolateimportInterpolatedUnivariateSpline
fromscipy.integrateimportsolve_ivp
fromtypesimportSimpleNamespace
fromcopyimportcopy
defflip(p=0.5):
"""Flips a coin with the given probability.
p: float 0-1
returns: boolean (True or False)
"""
returnnp.random.random() <p
defcart2pol(x, y, z=None):
"""Convert Cartesian coordinates to polar.
x: number or sequence
y: number or sequence
z: number or sequence (optional)
returns: theta, rho OR theta, rho, z
"""
x=np.asarray(x)
y=np.asarray(y)
rho=np.hypot(x, y)
theta=np.arctan2(y, x)
ifzisNone:
returntheta, rho
else:
returntheta, rho, z
defpol2cart(theta, rho, z=None):
"""Convert polar coordinates to Cartesian.
theta: number or sequence in radians
rho: number or sequence
z: number or sequence (optional)
returns: x, y OR x, y, z
"""
x=rho*np.cos(theta)
y=rho*np.sin(theta)
ifzisNone:
returnx, y
else:
returnx, y, z
fromnumpyimportlinspace
deflinrange(start, stop=None, step=1):
"""Make an array of equally spaced values.
start: first value
stop: last value (might be approximate)
step: difference between elements (should be consistent)
returns: NumPy array
"""
ifstopisNone:
stop=start
start=0
n=int(round((stop-start) /step))
returnlinspace(start, stop, n+1)
def__check_kwargs(kwargs, param_name, param_len, func, func_name):
"""Check if `kwargs` has a parameter that is a sequence of a particular length
param_len: sequence enumerating possible lengths
"""
param_val=kwargs.get(param_name, None)
ifparam_valisNoneorlen(param_val) notinparam_len:
msg= ("To run `{}`, you have to provide a "
"`{}` keyword argument with a sequence of length {}.")
raiseValueError(msg.format(func_name, param_name, ' or '.join(map(str, param_len))))
try:
func(param_val[0])
exceptExceptionase:
msg= ("In `{}` I tried running the function you provided "
"with `{}[0]`, and I got the following error:")
logger.error(msg.format(func_name, param_name))
raise (e)
defroot_scalar(func, *args, **kwargs):
"""Find the input value that is a root of `func`.
Wrapper for
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root_scalar.html
func: computes the function to find a root of
bracket: sequence of two values, lower and upper bounds of the range to be searched
args: any additional positional arguments are passed to `func`
kwargs: any keyword arguments are passed to `root_scalar`
returns: RootResults object
"""
underride(kwargs, rtol=1e-4)
__check_kwargs(kwargs, 'bracket', [2], lambdax: func(x, *args), 'root_scalar')
res=spo.root_scalar(func, *args, **kwargs)
ifnotres.converged:
msg= ("scipy.optimize.root_scalar did not converge. "
"The message it returned is:\n"+res.flag)
raiseValueError(msg)
returnres
defminimize_scalar(func, *args, **kwargs):
"""Find the input value that minimizes `func`.
Wrapper for
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html
func: computes the function to be minimized
bracket: (`method` is `brent` or `golden`) sequence of two or three values, the range to be searched
bounds: (`method` is `bounded`) sequence of two values, the range to be searched
args: any additional positional arguments are passed to `func`
kwargs: any keyword arguments are passed to `minimize_scalar`
returns: OptimizeResult object
"""
underride(kwargs, __func_name='minimize_scalar')
method=kwargs.get('method', None)
ifmethodisNone:
method='bounded'ifkwargs.get('bounds', None) else'brent'
kwargs['method'] =method
ifmethod=='bounded':
param_name='bounds'
param_len= [2]
else:
param_name='bracket'
param_len= [2, 3]
func_name=kwargs.pop('__func_name')
__check_kwargs(kwargs, param_name, param_len, lambdax: func(x, *args), func_name)
res=spo.minimize_scalar(func, args=args, **kwargs)
ifnotres.success:
msg= ("minimize_scalar did not succeed."
"The message it returned is: \n"+
res.message)
raiseException(msg)
returnres
defmaximize_scalar(func, *args, **kwargs):
"""Find the input value that maximizes `func`.
Wrapper for https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html
func: computes the function to be maximized
bracket: (`method` is `brent` or `golden`) sequence of two or three values, the range to be searched
bounds: (`method` is `bounded`) sequence of two values, the range to be searched
args: any additional positional arguments are passed to `func`
kwargs: any keyword arguments are passed as options to `minimize_scalar`
returns: OptimizeResult object
"""
defmin_func(*args):
return-func(*args)
underride(kwargs, __func_name='maximize_scalar')
res=minimize_scalar(min_func, *args, **kwargs)
# we have to negate the function value before returning res
res.fun=-res.fun
returnres
defrun_solve_ivp(system, slope_func, **options):
"""Computes a numerical solution to a differential equation.
`system` must contain `init` with initial conditions,
`t_end` with the end time. Optionally, it can contain
`t_0` with the start time.
It should contain any other parameters required by the
slope function.
`options` can be any legal options of `scipy.integrate.solve_ivp`
system: System object
slope_func: function that computes slopes
returns: TimeFrame
"""
system=remove_units(system)
# make sure `system` contains `init`
ifnothasattr(system, "init"):
msg="""It looks like `system` does not contain `init`
as a system variable. `init` should be a State
object that specifies the initial condition:"""
raiseValueError(msg)
# make sure `system` contains `t_end`
ifnothasattr(system, "t_end"):
msg="""It looks like `system` does not contain `t_end`
as a system variable. `t_end` should be the
final time:"""
raiseValueError(msg)
# the default value for t_0 is 0
t_0=getattr(system, "t_0", 0)
# try running the slope function with the initial conditions
try:
slope_func(t_0, system.init, system)
exceptExceptionase:
msg="""Before running scipy.integrate.solve_ivp, I tried
running the slope function you provided with the
initial conditions in `system` and `t=t_0` and I got
the following error:"""
logger.error(msg)
raise (e)
# get the list of event functions
events=options.get('events', [])
# if there's only one event function, put it in a list
try:
iter(events)
exceptTypeError:
events= [events]
forevent_funcinevents:
# make events terminal unless otherwise specified
ifnothasattr(event_func, 'terminal'):
event_func.terminal=True
# test the event function with the initial conditions
try:
event_func(t_0, system.init, system)
exceptExceptionase:
msg="""Before running scipy.integrate.solve_ivp, I tried
running the event function you provided with the
initial conditions in `system` and `t=t_0` and I got
the following error:"""
logger.error(msg)
raise (e)
# get dense output unless otherwise specified
ifnot't_eval'inoptions:
underride(options, dense_output=True)
# run the solver
bunch=solve_ivp(slope_func, [t_0, system.t_end], system.init,
args=[system], **options)
# separate the results from the details
y=bunch.pop("y")
t=bunch.pop("t")
# get the column names from `init`, if possible
ifhasattr(system.init, 'index'):
columns=system.init.index
else:
columns=range(len(system.init))
# evaluate the results at equally-spaced points
ifoptions.get('dense_output', False):
try:
num=system.num
exceptAttributeError:
num=101
t_final=t[-1]
t_array=linspace(t_0, t_final, num)
y_array=bunch.sol(t_array)
# pack the results into a TimeFrame
results=TimeFrame(y_array.T, index=t_array,
columns=columns)
else:
results=TimeFrame(y.T, index=t,
columns=columns)
returnresults, bunch
defleastsq(error_func, x0, *args, **options):
"""Find the parameters that yield the best fit for the data.
`x0` can be a sequence, array, Series, or Params
Positional arguments are passed along to `error_func`.
Keyword arguments are passed to `scipy.optimize.leastsq`
error_func: function that computes a sequence of errors
x0: initial guess for the best parameters
args: passed to error_func
options: passed to leastsq
:returns: Params object with best_params and ModSimSeries with details
"""
# override `full_output` so we get a message if something goes wrong
options["full_output"] =True
# run leastsq
t=scipy.optimize.leastsq(error_func, x0=x0, args=args, **options)
best_params, cov_x, infodict, mesg, ier=t
# pack the results into a ModSimSeries object
details=SimpleNamespace(cov_x=cov_x,
mesg=mesg,
ier=ier,
**infodict)
details.success=details.ierin [1,2,3,4]
# if we got a Params object, we should return a Params object
ifisinstance(x0, Params):
best_params=Params(pd.Series(best_params, x0.index))
# return the best parameters and details
returnbest_params, details
defcrossings(series, value):
"""Find the labels where the series passes through value.
The labels in series must be increasing numerical values.
series: Series
value: number
returns: sequence of labels
"""
values=series.values-value
interp=InterpolatedUnivariateSpline(series.index, values)
returninterp.roots()
defhas_nan(a):
"""Checks whether the an array contains any NaNs.
:param a: NumPy array or Pandas Series
:return: boolean
"""
returnnp.any(np.isnan(a))
defis_strictly_increasing(a):
"""Checks whether the elements of an array are strictly increasing.
:param a: NumPy array or Pandas Series
:return: boolean
"""
returnnp.all(np.diff(a) >0)
definterpolate(series, **options):
"""Creates an interpolation function.
series: Series object
options: any legal options to scipy.interpolate.interp1d
returns: function that maps from the index to the values
"""
ifhas_nan(series.index):
msg="""The Series you passed to interpolate contains
NaN values in the index, which would result in
undefined behavior. So I'm putting a stop to that."""
raiseValueError(msg)
ifnotis_strictly_increasing(series.index):
msg="""The Series you passed to interpolate has an index
that is not strictly increasing, which would result in
undefined behavior. So I'm putting a stop to that."""
raiseValueError(msg)
# make the interpolate function extrapolate past the ends of
# the range, unless `options` already specifies a value for `fill_value`
underride(options, fill_value="extrapolate")
# call interp1d, which returns a new function object
x=series.index
y=series.values
interp_func=interp1d(x, y, **options)
returninterp_func
definterpolate_inverse(series, **options):
"""Interpolate the inverse function of a Series.
series: Series object, represents a mapping from `a` to `b`
options: any legal options to scipy.interpolate.interp1d
returns: interpolation object, can be used as a function
from `b` to `a`
"""
inverse=pd.Series(series.index, index=series.values)
interp_func=interpolate(inverse, **options)
returninterp_func
defgradient(series, **options):
"""Computes the numerical derivative of a series.
If the elements of series have units, they are dropped.
series: Series object
options: any legal options to np.gradient
returns: Series, same subclass as series
"""
x=series.index
y=series.values
a=np.gradient(y, x, **options)
returnseries.__class__(a, series.index)
defsource_code(obj):
"""Prints the source code for a given object.
obj: function or method object
"""
print(inspect.getsource(obj))
defunderride(d, **options):
"""Add key-value pairs to d only if key is not in d.
If d is None, create a new dictionary.
d: dictionary
options: keyword args to add to d
"""
ifdisNone:
d= {}
forkey, valinoptions.items():
d.setdefault(key, val)
returnd
defcontour(df, **options):
"""Makes a contour plot from a DataFrame.
Wrapper for plt.contour
https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.contour.html
Note: columns and index must be numerical
df: DataFrame
options: passed to plt.contour
"""
fontsize=options.pop("fontsize", 12)
underride(options, cmap="viridis")
x=df.columns
y=df.index
X, Y=np.meshgrid(x, y)
cs=plt.contour(X, Y, df, **options)
plt.clabel(cs, inline=1, fontsize=fontsize)
defsavefig(filename, **options):
"""Save the current figure.
Keyword arguments are passed along to plt.savefig
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html
filename: string
"""
print("Saving figure to file", filename)
plt.savefig(filename, **options)
defdecorate(**options):
"""Decorate the current axes.
Call decorate with keyword arguments like
decorate(title='Title',
xlabel='x',
ylabel='y')
The keyword arguments can be any of the axis properties
https://matplotlib.org/api/axes_api.html
"""
ax=plt.gca()
ax.set(**options)
handles, labels=ax.get_legend_handles_labels()
ifhandles:
ax.legend(handles, labels)
plt.tight_layout()
defremove_from_legend(bad_labels):
"""Removes some labels from the legend.
bad_labels: sequence of strings
"""
ax=plt.gca()
handles, labels=ax.get_legend_handles_labels()
handle_list, label_list= [], []
forhandle, labelinzip(handles, labels):
iflabelnotinbad_labels:
handle_list.append(handle)
label_list.append(label)
ax.legend(handle_list, label_list)
classSettableNamespace(SimpleNamespace):
"""Contains a collection of parameters.
Used to make a System object.
Takes keyword arguments and stores them as attributes.
"""
def__init__(self, namespace=None, **kwargs):
super().__init__()
ifnamespace:
self.__dict__.update(namespace.__dict__)
self.__dict__.update(kwargs)
defget(self, name, default=None):
"""Look up a variable.
name: string varname
default: value returned if `name` is not present
"""
try:
returnself.__getattribute__(name, default)
exceptAttributeError:
returndefault
defset(self, **variables):
"""Make a copy and update the given variables.
returns: Params
"""
new=copy(self)
new.__dict__.update(variables)
returnnew
defmagnitude(x):
"""Returns the magnitude of a Quantity or number.
x: Quantity or number
returns: number
"""
returnx.magnitudeifhasattr(x, 'magnitude') elsex
defremove_units(namespace):
"""Removes units from the values in a Namespace.
Only removes units from top-level values;
does not traverse nested values.
returns: new Namespace object
"""
res=copy(namespace)
forlabel, valueinres.__dict__.items():
ifisinstance(value, pd.Series):
value=remove_units_series(value)
res.__dict__[label] =magnitude(value)
returnres
defremove_units_series(series):
"""Removes units from the values in a Series.
Only removes units from top-level values;
does not traverse nested values.
returns: new Series object
"""
res=copy(series)
forlabel, valueinres.items():
res[label] =magnitude(value)
returnres
classSystem(SettableNamespace):
"""Contains system parameters and their values.
Takes keyword arguments and stores them as attributes.
"""
pass
classParams(SettableNamespace):
"""Contains system parameters and their values.
Takes keyword arguments and stores them as attributes.
"""
pass
defState(**variables):
"""Contains the values of state variables."""
returnpd.Series(variables, name='state')
defmake_series(x, y, **options):
"""Make a Pandas Series.
x: sequence used as the index
y: sequence used as the values
returns: Pandas Series
"""
underride(options, name='values')
ifisinstance(y, pd.Series):
y=y.values
series=pd.Series(y, index=x, **options)
series.index.name='index'
returnseries
defTimeSeries(*args, **kwargs):
"""Make a pd.Series object to represent a time series.
"""
ifargsorkwargs:
underride(kwargs, dtype=float)
series=pd.Series(*args, **kwargs)
else:
series=pd.Series([], dtype=float)
series.index.name='Time'
if'name'notinkwargs:
series.name='Quantity'
returnseries
defSweepSeries(*args, **kwargs):
"""Make a pd.Series object to store results from a parameter sweep.
"""
ifargsorkwargs:
underride(kwargs, dtype=float)
series=pd.Series(*args, **kwargs)
else:
series=pd.Series([], dtype=np.float64)
series.index.name='Parameter'
if'name'notinkwargs:
series.name='Metric'
returnseries
defshow(obj):
"""Display a Series or Namespace as a DataFrame."""
ifisinstance(obj, pd.Series):
df=pd.DataFrame(obj)
returndf
elifhasattr(obj, '__dict__'):
returnpd.DataFrame(pd.Series(obj.__dict__),
columns=['value'])
else:
returnobj
defTimeFrame(*args, **kwargs):
"""DataFrame that maps from time to State.
"""
underride(kwargs, dtype=float)
returnpd.DataFrame(*args, **kwargs)
defSweepFrame(*args, **kwargs):
"""DataFrame that maps from parameter value to SweepSeries.
"""
underride(kwargs, dtype=float)
returnpd.DataFrame(*args, **kwargs)
defVector(x, y, z=None, **options):
"""
"""
underride(options, name='component')
ifzisNone:
returnpd.Series(dict(x=x, y=y), **options)
else:
returnpd.Series(dict(x=x, y=y, z=z), **options)
## Vector functions (should work with any sequence)
defvector_mag(v):
"""Vector magnitude."""
returnnp.sqrt(np.dot(v, v))
defvector_mag2(v):
"""Vector magnitude squared."""
returnnp.dot(v, v)
defvector_angle(v):
"""Angle between v and the positive x axis.
Only works with 2-D vectors.
returns: angle in radians
"""
assertlen(v) ==2
x, y=v
returnnp.arctan2(y, x)
defvector_polar(v):
"""Vector magnitude and angle.
returns: (number, angle in radians)
"""
returnvector_mag(v), vector_angle(v)
defvector_hat(v):
"""Unit vector in the direction of v.
returns: Vector or array
"""
# check if the magnitude of the Quantity is 0
mag=vector_mag(v)
ifmag==0:
returnv
else:
returnv/mag
defvector_perp(v):
"""Perpendicular Vector (rotated left).
Only works with 2-D Vectors.
returns: Vector
"""
assertlen(v) ==2
x, y=v
returnVector(-y, x)
defvector_dot(v, w):
"""Dot product of v and w.
returns: number or Quantity
"""
returnnp.dot(v, w)
defvector_cross(v, w):
"""Cross product of v and w.
returns: number or Quantity for 2-D, Vector for 3-D
"""
res=np.cross(v, w)
iflen(v) ==3:
returnVector(*res)
else:
returnres
defvector_proj(v, w):
"""Projection of v onto w.
returns: array or Vector with direction of w and units of v.
"""
w_hat=vector_hat(w)
returnvector_dot(v, w_hat) *w_hat
defscalar_proj(v, w):
"""Returns the scalar projection of v onto w.
Which is the magnitude of the projection of v onto w.
returns: scalar with units of v.
"""
returnvector_dot(v, vector_hat(w))
defvector_dist(v, w):
"""Euclidean distance from v to w, with units."""
ifisinstance(v, list):
v=np.asarray(v)
returnvector_mag(v-w)
defvector_diff_angle(v, w):
"""Angular difference between two vectors, in radians.
"""
iflen(v) ==2:
returnvector_angle(v) -vector_angle(w)
else:
# TODO: see http://www.euclideanspace.com/maths/algebra/
# vectors/angleBetween/
raiseNotImplementedError()
defplot_segment(A, B, **options):
"""Plots a line segment between two Vectors.
For 3-D vectors, the z axis is ignored.
Additional options are passed along to plot().
A: Vector
B: Vector
"""
xs=A.x, B.x
ys=A.y, B.y
plt.plot(xs, ys, **options)
fromtimeimportsleep
fromIPython.displayimportclear_output
defanimate(results, draw_func, *args, interval=None):
"""Animate results from a simulation.
results: TimeFrame
draw_func: function that draws state
interval: time between frames in seconds
"""
plt.figure()
try:
fort, stateinresults.iterrows():
draw_func(t, state, *args)
plt.show()
ifinterval:
sleep(interval)
clear_output(wait=True)
draw_func(t, state, *args)
plt.show()
exceptKeyboardInterrupt:
pass