Running simulations in python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

cwf231/running_simulations_in_python

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Running Simulations in Python

Claude Fried — Data Scientist; Cohort Lead, Data Science

08SEP2021

We will talk about Running Simulations using Python for Data Science.

What does it mean to run a Simulation?

Simulate interactions using a board game: Risk

We will be using Python and Python packages for this workshop (Numpy, Pandas, Matplotlib). We will also be writing functions to streamline our processes.

Источник

Simple Simulations in Python

Let’s start writing a simulation in Python! Simulations are used from everything to medical research, fashion, launching rockets, and more, but we’re going to start off with several very basic simulation — but the basic principles are the same! To write a simulation, we must identify all factors that might influence the outcome of the simulation and write Python code to simulate each of these factors.

Simulation

The objective of the code we will develop is to store the results of every run of our simulation in a DataFrame. By storing the data in a DataFrame, you can use all the tools and techniques you already know to select a subset of rows of in a DataFrame, to group data within a DataFrame, to find descriptive statistics about data in the DataFrame, and more!

Almost all simulations will follow a similar «pattern» where we need to only modify the pattern in a few select areas to create a simulation to solve a variety of different problems.

Simulation Pattern

Every simulation we will write will follow a six-step pattern:

  1. We will create a initially empty Python List called data to accumulate each run of our simulation. This will always be data = [] .
  2. We will write a for-loop to run a block of code for each run of our simulation. For a 10,000 run simulation, for i in range(10000): .
  3. Inside of the for-loop, we will simulate all real-world factors. For a simple simulation of a six-sided die roll, roll = random.randint(1, 6) is the only real-world variable.
  4. Inside of the for-loop, we will accumulate all real-world factors we simulated in Python dictionary called d . A dictionary is a list of key-value pairs, enclosed in curly braces, and separated by commas.
    • We will always name the key in our dictionary the same as our real-world factor, except the key must have quotes around it.
    • For example, if you have a single real-world variable roll , our dictionary d is: d = < "roll": roll >.
    • If we have two real world variables red and blue ‘, our dictionary d separates the two variables with a comma: d = < "red": red, "blue": blue >.
    • If the real-world variable is height , our dictionary d is: d = < "height": height >.
    • If we have two real world variables one and two ‘, our dictionary d is: d = < "one": one, "two": two >.
    • We will always refer to our variable by the variable name itself. (The effect of this is that we are creating a column in our DataFrame labeled with the name of our variable.)
  5. Inside of the for-loop, we will append our dictionary to our list data . This will always be: data.append(d) .
  6. Finally, outside of the for-loop, we will save our data as a DataFrame df . This will always be: df = pd.DataFrame(data) , which creates a DataFrame out of data .

Simulate Rolling Die

One of the most simple simulations we can write is to simulate rolling fair, six-sided die.

Example: Simulating Rolling a Six-sided Die

Using the six-sided die example, the full simulation code to simulate rolling a six-sided die 600 times and saving the results will be six lines of code:

data = [] # Step 1, empty list `data`
for i in range(600): # Step 2: for-loop
roll = random.randint(1, 6) # Step 3: simulate real-world factors
d = "roll": roll > # Step 4: accumulate factors in dictionary `d`
data.append(d) # Step 5: append `d` to `data`
df = pd.DataFrame(data) # Step 6: create the DataFrame (outside of the for-loop)
# In a second cell, we'll print out `df` (otherwise we would be re-running the simulation)
df

Example: Simulating Rolling Two Six-sided Dice

If we want to roll two six-sided dice, there are now two real-world factors that happen every simulation. Let’s think of one die as a «white» die (variable white ) and the other as the «black» die (variable black ):

# Step 1, empty list `data`:
data = []

# Step 2: for-loop:
for i in range(600):
# Step 3: simulate all real-world factors:
black = random.randint(1, 6)
white = random.randint(1, 6)

# Step 4: accumulate all factors in dictionary `d`:
d = "white": white, "black": black >

# Step 5: append `d` to `data`
data.append(d)

# Step 6: create the DataFrame (outside of the for-loop)
df = pd.DataFrame(data)
# In a second cell, we'll print out `df` (otherwise we would be re-running the simulation)
df

Example Walk-Throughs with Worksheets

Video 1: Writing Simulations in Python I

Источник

SimPy: Simulating Real-World Processes With Python | Real Python

SimPy: Simulating Real-World Processes With Python | Real Python

The real world is full of systems, like airports and highways, that frequently experience congestion and delay. When these systems are not optimized, their inefficiency can lead to countless unhappy customers and hours of wasted time. In this tutorial, you’ll learn how to use Python’s simpy framework to create virtual simulations that will help you solve problems like these.

In this tutorial, you’ll learn how to:

  • Use a simulation to model a real-world process
  • Create a step-by-step algorithm to approximate a complex system
  • Design and run a real-world simulation in Python with simpy

In this tutorial, you’ll create a simulation for a local movie theater. Your goal is to provide the manager with a script to help find the optimal number of employees to have on staff.

Read it on Real Python

Here’s the source code for this script:

"""Companion code to https://realpython.com/simulation-with-simpy/ 'Simulating Real-World Processes With SimPy' Python version: 3.7.3 SimPy version: 3.0.11 """ import simpy import random import statistics wait_times = [] class Theater(object): def __init__(self, env, num_cashiers, num_servers, num_ushers): self.env = env self.cashier = simpy.Resource(env, num_cashiers) self.server = simpy.Resource(env, num_servers) self.usher = simpy.Resource(env, num_ushers) def purchase_ticket(self, moviegoer): yield self.env.timeout(random.randint(1, 3)) def check_ticket(self, moviegoer): yield self.env.timeout(3 / 60) def sell_food(self, moviegoer): yield self.env.timeout(random.randint(1, 5)) def go_to_movies(env, moviegoer, theater): # Moviegoer arrives at the theater arrival_time = env.now with theater.cashier.request() as request: yield request yield env.process(theater.purchase_ticket(moviegoer)) with theater.usher.request() as request: yield request yield env.process(theater.check_ticket(moviegoer)) if random.choice([True, False]): with theater.server.request() as request: yield request yield env.process(theater.sell_food(moviegoer)) # Moviegoer heads into the theater wait_times.append(env.now - arrival_time) def run_theater(env, num_cashiers, num_servers, num_ushers): theater = Theater(env, num_cashiers, num_servers, num_ushers) for moviegoer in range(3): env.process(go_to_movies(env, moviegoer, theater)) while True: yield env.timeout(0.20) # Wait a bit before generating a new person moviegoer += 1 env.process(go_to_movies(env, moviegoer, theater)) def get_average_wait_time(wait_times): average_wait = statistics.mean(wait_times) # Pretty print the results minutes, frac_minutes = divmod(average_wait, 1) seconds = frac_minutes * 60 return round(minutes), round(seconds) def get_user_input(): num_cashiers = input("Input # of cashiers working: ") num_servers = input("Input # of servers working: ") num_ushers = input("Input # of ushers working: ") params = [num_cashiers, num_servers, num_ushers] if all(str(i).isdigit() for i in params): # Check input is valid params = [int(x) for x in params] else: print( "Could not parse input. Simulation will use default values:", "\n1 cashier, 1 server, 1 usher.", ) params = [1, 1, 1] return params def main(): # Setup random.seed(42) num_cashiers, num_servers, num_ushers = get_user_input() # Run the simulation env = simpy.Environment() env.process(run_theater(env, num_cashiers, num_servers, num_ushers)) env.run(until=90) # View the results mins, secs = get_average_wait_time(wait_times) print( "Running simulation. ", f"\nThe average wait time is minutes and seconds.", ) if __name__ == "__main__": main() 

Generated by Pelican / ✨ © 2020 Jaya Z. Powell

Источник

Читайте также:  Php unicode to bytes
Оцените статью