Giter Club home page Giter Club logo

modsimpy's Introduction

Modeling and Simulation in Python

Order the book from No Starch Press or Amazon.

Read the book and run the code.

Modeling and Simulation in Python is an introduction to physical modeling using a computational approach. It is organized in three parts:

  • The first part presents discrete models, including a bikeshare system and world population growth.

  • The second part introduces first-order systems, including models of infectious disease, thermal systems, and pharmacokinetics.

  • The third part is about second-order systems, including mechanical systems like projectiles, celestial mechanics, and rotating rigid bodies.

Taking a computational approach makes it possible to work with more realistic models than what you typically see in a first-year physics class, with the option to include features like friction and drag.

Python is an ideal programming language for this material. It is a good first language for people who have not programmed before, and it provides high-level data structures that are well-suited to express solutions to the problems we are interested in.

Modeling and Simulation in Python is a Free Book. It is available under the Creative Commons Attribution-NonCommercial 4.0 Unported License, which means that you are free to copy, distribute, and modify it, as long as you attribute the work and don’t use it for commercial purposes.

This and other Free Books by Allen Downey are available from Green Tea Press.

modsimpy's People

Contributors

abhishekjiitr avatar allendowney avatar bluthej avatar bogidon avatar cjwoodard avatar haeckelk avatar haraldschilly avatar jsieving avatar jzmiller1 avatar mcsmart76 avatar rioj7 avatar truth-quark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

modsimpy's Issues

salmon.ipynb missing from repo

From textbook: Chapter 9 - Case Study - Predicting salmon populations - page 84

  1. In the repository for this book, you’ll find a notebook called salmon.ipynb,
    which contains some data and code to get you started. Read through
    the notebook and run it.

There is no notebook named salmon.ipynb.
salmon_soln is found in the solution folder, but having to filter out exercise-text from the solution is not ideal

Where are the answers? :(

I got this book and I'm going through the exercises but I can't find the answers 🔑 anywhere. Am I missing something obvious? 😢

What is the `show` function?

In chapter 2 of the textbook the show function is used to display the bikeshare state. Where is this function defined? I am trying (fairly successfully) to run the textbook in my local python environment instead of a workbook.

Issue with Pint - Chapter 1

Hi;

I'm going through your book and I'm doing the Computation with units example.

When I run the following line:

t = math.sqrt(2 * h / a)

I get the following error:

image

I'm note sure how to trouble-shoot it.

Am I doing something wrong, or is there an issue with pint?

Thanks!

update_func() with UNITS (Pint) an Frame

When update_func() is set to return State with UNITS, run_simulation() crashes when tryin to enter the update_func() output into ModSimDataFrame().

A simple example : pressure increases with depth $dp = \rho dy g$, I initialize params with
( p = 0 * Pa, dy =0.1 * m , rho = 1000*kg/m**3) etc .....

I (think I) cannot use ode_solver since it is linked with time. So I constrct update_func() that retuns State(p=p,y=y), In run_simulation() I create frame=ModSimDataFrame(), use dimensionless

ts = linrange( 0,100,0.1)
for t in ts:

and when I try to

update frame[ t + dy ] = update_func(...)

it crashes. All is ok, wen I completely remove UNITS. Pitty, isnt it?

Queue case study: can you make a range of UNITS.minutes or any dimensional unit?

The queue case study has instructions to Set duration, which is the number of time steps to simulate, to 10 hours, expressed in minutes.

I did this in the following way

minutes = UNITS.minutes
hours = UNITS.hour
duration=(10*hours).to(minutes)

Later on, there is a prewritten function that uses the system duration to create a range

for t in linrange(0, system.duration):

When that runs, it gives me the following error:


DimensionalityError Traceback (most recent call last)
in ()
1 # Solution goes here
----> 2 results = run_simulation(system, update)
3 plot(results)

in run_simulation(system, update_func)
9 results[0] = x
10
---> 11 for t in linrange(0, system.duration):
12 x = update_func(x, t, system)
13 results[t+1] = x

~/projects/modsim.py in linrange(start, stop, step, **options)
178 n += 1
179
--> 180 array = np.linspace(start, stop, int(n), **options)
181 if units:
182 array = array * units

~/miniconda2/envs/simulation/lib/python3.7/site-packages/pint/quantity.py in int(self)
439 if self.dimensionless:
440 return int(self._convert_magnitude_not_inplace(UnitsContainer()))
--> 441 raise DimensionalityError(self._units, 'dimensionless')
442
443 def long(self):

DimensionalityError: Cannot convert from 'minute' to 'dimensionless'

Should duration not be using units, is there a way do create a range with units, or am I missing something simple?

diff_angle

I had to grab some simple cart2pol code for something,when I came across this repo ,and saw this

#TODO: see http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/

I checked the codes and saw this is going to be tricky as the mag function above it already has the unit bound to it,else it would have just been np.arcos(np.dot(self,other)/self.mag* other.mag)
Just pointing it out.

No Module

Hi, I have been trying to use your repository, however whenever I try to use from modsim import * it returns ModuleNotFoundError: No module named 'modsim' How would I go about fixing that?

round down in chap02.ipynb

Concerning the running simulations section, int() truncates and does not necessarily round down.
Kind of a minor nitpick, but feedback is feedback.

ModSimSeries in the Salmon Population case study

One of the exercises in the case study for the salmon population model (salmon.ipynb) mentions an object type called "ModeSimSeries". I am having trouble finding that type. It is not defined in modsim.py and according to the search function at allendowney.github.io/ModSimPy it is not mentioned in the text.

Am I missing something or is there something missing?

Production Line

Hello,

I've just ordered the printed version of the book: Modeling and Simulation in Python

I would like to ask you if you know any starting example to simulate a simple production line in real time.
Or at least can you point me to a similar example?
I will need to change inputs in real time and use the outputs in a java application.

Thank you so much in advance.
Best,
Nelson

Suggestion for a biological modelling exercise

Hi,
Saw your lightning talk at SciPy, thought I would make a suggestion, as you had invited.

I had to reproduce a bacterial simulation for my bioinformatics class and I think it is a pretty doable example.

The paper is the following:
Counteraction of antibiotic production and degradation stabilizes microbial communities.
Kelsic ED, Zhao J, Vetsigian K, Kishony R.
Nature. 521(7553):516-9.
https://www.nature.com/nature/journal/v521/n7553/full/nature14485.html

The actual panel depicting a visualization of the simulation is Figure 1D.

I could supply the simulation in python, at the moment I only have a pretty version of it in R.

Define generalizing a function in Chapter 2 notebook

In the "Parameters" section where you already have a "%TODO: expand this transition" you use the phrase "it would be better to generalize this function" so it takes the probabilities p1 and p2 as parameters:" and you haven't used this language before in the notebooks or textbook. In the relevant part of the textbook you do say, " The advantage of using parameters is that you can call the same function many times, providing different arguments each time." Perhaps you can explicitly describe this as generalization there and it will make more sense in the notebook.

Vector weirdness

Haven't dived too deeply into this, but I'm getting the feeling it isn't the intended behavior. There's a lot of weirdness that happens when multiplying a Pint Quantity by a modsim Vector(Quantity).

For example, this produces the expected result:
11-29-2017-03 55 13

however accessing x or y produces an error:

distance_vector.x
# -> Neither Quantity object nor its magnitude ([ 0.5547002   0.83205029]) has attribute 'x'

here's a workaround:

acc = 1 * UNITS.m/UNITS.second**2 
acc = (acc.m * Vector(2,3).hat()) * acc.units
acc.x
# -> 0.5547001962252291 meter/second**2 :)

Unrelated, there's a weird edge case that brakes Pint's TeX formatting:
11-29-2017-03 57 09

Looks like there's some kind of superscript formatting going on in the TeX source? Might be a bug on Pint's end.

Installing Pint with Python 3.7

The pint version (0.7.2) in the unidata channel is for Python 3.6. When installing it on the latest version of Anaconda with Python 3.7, this downgrades a large number of packages to Python 3.6. The conda-forge channel has the latest version of pint (0.9) for Python 3.7 and is referenced on the pint website. Unless the older version of pint is required, could you use the conda-forge channel instead?

Can't pip install modsimpy - Error Message

Hey,

I'm trying to begin this book and when following the requirements it says to do pip install modsimpy. When I try to do so, it gives me a really long error message:

ERROR: Command errored out with exit status 1:
     command: 'C:\Users\Brady\Anaconda3\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Brady\\AppData\\Local\\Temp\\pip-install-426xujgr\\modsimpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Brady\\AppData\\Local\\Temp\\pip-install-426xujgr\\modsimpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
         cwd: C:\Users\Brady\AppData\Local\Temp\pip-install-426xujgr\modsimpy\
    Complete output (9 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Brady\AppData\Local\Temp\pip-install-426xujgr\modsimpy\setup.py", line 20, in <module>
        long_description=readme(),
      File "C:\Users\Brady\AppData\Local\Temp\pip-install-426xujgr\modsimpy\setup.py", line 6, in readme
        return f.read()
      File "C:\Users\Brady\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 4990: character maps to <undefined>
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

I have verified that I can install other packages with pip and I tried reinstalling pip using conda as well as restarting my computer.

How can I fix this? Or is there an alternate way of installing modsimpy now? Thanks!

Convert notebooks to LaTeX

I am opening this issue to document my thinking about how to generate the LaTeX version of the book, and to solicit comments.

As of Version 4, the source of the books is the Jupyter notebooks. I use JupyterBook to generate the HTML version, which is hosted here on GitHub.

For publication, I would like to generate a LaTeX version.

I considered using nbconvert to convert from ipynb to tex, but the LaTeX that gets generated would be hard to work with.

A better option seems to be using nbconvert to generate Markdown and then use Pandoc to generate LaTeX.

Pandoc gets pretty close, with these command-line arguments:

--listings --top-level-division=chapter

But I will probably still have to do some post-processing:

  1. The LaTeX files PanDoc generates are complete documents with frontmatter, etc. To convert these files to chapters that can be included in a top-level document, I'll have to strip some lines from the beginning and end.

  2. Currently the images don't survive the translation process.

It seems like it will take some effort to get this working, so before I go too far down this path, I want to consider alternatives.

I welcome comments from anyone who reads this, but I'd like to ask @hamelsmu and @jph00 in particular to take a look. With your experience with fastdoc, you might have suggestions. Thanks!

typo: use to user

In the Contributer List section of chapter 0, the second sentence reads "Or if your are a Git use, send me a pull request!"

Typo in chapter 5 notebook

In the Using a DataFrame section, a global variable sir is defined, but not used. The previously defined system variable is used in it's stead. Apart from confusion, this typo may confuse students when attempting to solve the subsequent exercise.

Errors on importing library

After following the installation instructions, I did import modsim and got the following errors (differentiated by Python 2.7 & 3.6). I'm running these on Anaconda 4.7.5

Python 3.6

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\hsamuel\AppData\Local\Continuum\anaconda2\envs\py36\lib\site-packages\modsim\__init__.py", line 1, in <module>
    from .modsim import *
  File "C:\Users\hsamuel\AppData\Local\Continuum\anaconda2\envs\py36\lib\site-packages\modsim\modsim.py", line 38, in <module>
    from pint.errors import UnitStrippedWarning
ImportError: cannot import name 'UnitStrippedWarning'

Python 2.7

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\hsamuel\AppData\Local\Continuum\anaconda2\lib\site-packages\modsim\__init__.py", line 1, in <module>
    from .modsim import *
  File "C:\Users\hsamuel\AppData\Local\Continuum\anaconda2\lib\site-packages\modsim\modsim.py", line 1668
    def Vector(*args, units=None):
                          ^
SyntaxError: invalid syntax

Ch 01 velocity magnitude

In chapter 01, In [57]:

assert abs(v.magnitude - 86.41527642726142) < 1e7

Shouldn't this be:

assert abs(v.magnitude - 86.41527642726142) < 1e-7

Syntax error uploading Chapter 5 of ModSimPy

I was able to upload the Jupyter notebooks for chapters 1-4 of ModSimPy but attempting Chapter 5 (chap05.ipynb) led to the following error:

error was: SyntaxError: JSON Parse error: Unrecognized token '<'

Installing pint with Python 3.8

Downloaded current version (as of April 2021) Anaconda Python 3.8
UnsatisfiableError when trying conda install -c unidata pint as in book Release 4:

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  • pint -> python[version='2.7.|3.4.|3.5.|3.6.']

Your python: python=3.8

Thanks for looking into it.

Is `modsim/test_modsim.py` still a valid unit test

Viewing modsim/test_modsim.py in VSC with PyLance shows a lot of errors.

A lot of functions are missing.

An object can't be an instance of a function.

pint is not used, and also UnitStrippedWarning

Line 926 Chap04Soln

Hola Profesor Allen,

In this line it should be
for p2 in p2_array:
instead of
for p2 in p1_array:

Have a good day.

Issue: Multiple assignment of State in code

Hi,
Could anyone help me?
I am try to execute examples from chapter 18. I am facing this issue with multiple assignment G, X = state
in slope_func. where G and X assigned randomly to values inside state but not on position basis. which is creating further problem.
I tried to assign G = state.G and X = state.X but that cause problem while running run_ode_solver and shows AttributeError: 'numpy.ndarray' object has no attribute 'G'

For Loop Chap02 - TimeSeries Section.

Hi Allen,

Something is wrong with the "results" after change the range in a for loop from a number to a minor number, for example I run this:

In [47]:
for i in range(10):
step(0.3, 0.2)
results[i] = bikeshare.olin

Displays:

values

0 | 5
1 | 5
2 | 4
3 | 4
4 | 5
5 | 5
6 | 5
7 | 4
8 | 3
9 | 2

But when I changed to this:

In [47]:
for i in range(6):
step(0.3, 0.2)
results[i] = bikeshare.olin

Displays:

values

0 | 2
1 | 1
2 | 1
3 | 0
4 | -1
5 | -1
6 | 5
7 | 4
8 | 3
9 | 2

I dont understand why the values are indexed to 10 positions after run the code with a range of 6 positions.

Thanks in advanced!

Cannot run dir() on ModSimSeries objects

The following code results in a Pandas KeyError:

import modsim
foo = modsim.modsim.ModSimSeries([])
dir(foo)  # KeyError: 'dt'

This seems to be the result of the definition of ModSimSeries, in which the property definitions of dt and T call pandas.Series.loc. As a result, when calling dir(foo), the standard Python library (accessor.py) seems to try to get a nonexistent row.

Oddly, defining only dt as a row index in the series seems to fix this:

import modsim
bar = modsim.modsim.ModSimSeries({'dt': 2})
dir(bar)  # Works as expected

I suspect that this can be handled by overriding the default __getattribute__ or __getattr__ in ModSimSeries.

Bug in fsolve

The documentation for modsim.py's fsolve says that x0 can be a scalar or array, matching scipy's api (well, its defecto one – in the docs it only mentions arrays) . However the sanity check passing x0 into func at the modsim level assumes a scalar type, making arrays not usable.

ModSimPy/code/modsim.py

Lines 336 to 367 in 8054670

def fsolve(func, x0, *args, **kwargs):
"""Return the roots of the (non-linear) equations
defined by func(x) = 0 given a starting estimate.
Uses scipy.optimize.fsolve, with extra error-checking.
func: function to find the roots of
x0: scalar or array, initial guess
args: additional positional arguments are passed along to fsolve,
which passes them along to func
returns: solution as an array
"""
# make sure we can run the given function with x0
try:
func(x0, *args)
except Exception as e:
msg = """Before running scipy.optimize.fsolve, I tried
running the function you provided with the x0
you provided, and I got the following error:"""
logger.error(msg)
raise(e)
# make the tolerance more forgiving than the default
underride(kwargs, xtol=1e-7)
# run fsolve
units_off()
result = scipy.optimize.fsolve(func, x0, args=args, **kwargs)
units_on()
return result

Expected behavior

def func(x):
    return (x-1) * (x-2) * (x-3)

fsolve(func, x0=[0,5])
# -> array([ 1.,  3.])

scipy.optimize.fsolve(func, x0=(0,5))
# -> array([ 1.,  3.])

Actual behavior

def func(x):
    return (x-1) * (x-2) * (x-3)

fsolve(func, x0=[0,5])
# -> TypeError: unsupported operand type(s) for -: 'list' and 'int'

scipy.optimize.fsolve(func, x0=(0,5))
# -> array([ 1.,  3.])

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.