Demo entry 3506299

Simulator

   

Submitted by AmirHossein Rouzbahani on Jan 06, 2016 at 05:12
Language: Python 3. Code size: 2.7 kB.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import math
import scipy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from collections import namedtuple
from simpy import Environment, Store
from sys import argv

Machine = namedtuple('Machine', [
    'service_cost',
    'service_duration'])

REVENUE_PER_USER = 10
MAX_SERVICE_DURATION = 6
EXPECTED_TOTAL_PEOPLE = 200
TOTAL_SIMULATION_TIME = 1000
assert TOTAL_SIMULATION_TIME >= EXPECTED_TOTAL_PEOPLE

def make_machine(quality):
    service_cost_normalizer = 2 * REVENUE_PER_USER / math.pi
    return Machine(
        service_cost=service_cost_normalizer *
        math.asin((quality / 4) ** 1.5),
        service_duration=(1 - quality) * MAX_SERVICE_DURATION)

def simulate(quality, parallelism):
    if quality == 0:
        return 0
    if quality == 1:
        return -np.inf

    machine_spec = make_machine(quality)

    env = Environment()
    store = Store(env)
    cost = parallelism * machine_spec.service_cost * TOTAL_SIMULATION_TIME
    income = 0

    def enter_users():
        p = EXPECTED_TOTAL_PEOPLE / TOTAL_SIMULATION_TIME
        while True:
            if scipy.random.choice([True, False], p=[p, 1 - p]):
                yield store.put(None)
            yield env.timeout(1)

    def run_machine(machine):
        nonlocal cost
        nonlocal income
        while True:
            yield store.get()
            yield env.timeout(machine.service_duration)
            income += REVENUE_PER_USER

    env.process(enter_users())
    for x in range(parallelism):
        env.process(run_machine(machine_spec))
    env.run(TOTAL_SIMULATION_TIME)
    return income - cost


@np.vectorize
def simulate_and_average(quality, parallelism, *, iteration_count):
    return sum(simulate(quality, parallelism) for x in range(iteration_count)) / iteration_count

qs = np.linspace(0.00001, 1, 10)
mc = np.arange(1, 20)
qsg, mcg = np.meshgrid(qs, mc)
pig = simulate_and_average(qsg, mcg, iteration_count=10)

if len(argv) > 2 and argv[1].casefold() == '--to-excel':
    filename = argv[2]
    dataFrame = pd.DataFrame({
        'machine quality': qsg.reshape(qsg.size),
        'machines count': mcg.reshape(mcg.size),
        'total revenue': pig.reshape(pig.size)})
    dataFrame.to_excel(filename)
elif '--plot' in [arg.casefold() for arg in argv]:
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_wireframe(qsg, mcg, pig)
    plt.show()
else:
    print("Args: \n"
          "--plot\n"
          "--to-excel <outfile name>\n")

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).