Example #1
0
    def test_graph_and_lines(self):
        """Tests simulation with graph and lines"""
        config_name = get_full_class_name(Config)
        with patch(config_name+'.graph_dict', new_callable=PropertyMock) as mock_graph_dict:
            with patch(config_name+'.lines_dict', new_callable=PropertyMock) as mock_lines_dict:
                with patch(config_name+'.traffic_data_dict',
                           new_callable=PropertyMock) as mock_traffic_dict:
                    mock_graph_dict.return_value = {'A': [('B', 7), ('D', 2)],
                                                    'B': [('A', 7), ('C', 1), ('E', 2)],
                                                    'C': [('B', 1), ('D', 3)],
                                                    'D': [('A', 2), ('C', 3)],
                                                    'E': [('B', 2), ('F', 2)],
                                                    'F': [('E', 2)]}
                    mock_lines_dict.return_value = {
                        0: {'id': 0, 'bus_capacity': 20, 'frequency1': 17, 'frequency2': 17,
                            'route1': ['A', 'D', 'C', 'B', 'E', 'F'],
                            'route2': ['F', 'E', 'B', 'A']}}
                    config = Config(["A", "B", "C", "D", "E", "F"], {}, {}, {}, 1.0)
                    mock_traffic_dict.return_value = {'E': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'F': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'D': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'A': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'C': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'B': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0}}

                    simulation = Simulation(config)

                def mocked_update(mocked_self):
                    """Mocked update """
                    for bus in mocked_self.buses:
                        if bus.route == 0:
                            if bus.id not in mocked_self.mocked_dict.keys():
                                mocked_self.mocked_dict[bus.id] = []
                            if bus.time_to_next_stop == 0:
                                mocked_self.mocked_dict[bus.id].append(bus.current_stop_name)
                            else:
                                mocked_self.mocked_dict[bus.id].append(bus.current_stop_name + bus.next_stop_name)

                def finished(mocked_self):
                    mocked_self.mocked_update()
                    return False

                add_property(simulation, "finished", finished)
                from types import MethodType
                simulation.mocked_update = MethodType(mocked_update, simulation)
                add_variable(simulation, "count_finished", 0)
                add_variable(simulation, "mocked_dict", {})
                count = 0
                while count < 35:
                    count += 1
                    simulation.refresh()
                paths = ['PA', 'A', 'AD', 'AD', 'D', 'DC', 'DC', 'DC', 'C', 'CB', 'B', 'BE', 'BE', 'E', 'EF', 'EF', 'F']
                self.assertEqual(len(simulation.mocked_dict), 2)
                for path in simulation.mocked_dict.values():
                    self.assertEqual(path, paths)
Example #2
0
    def __init__(self, machine_configs, task_configs, algorithm, event_file):
        self.env = simpy.Environment()
        cluster = Cluster()
        cluster.add_machines(machine_configs)

        task_broker = Episode.broker_cls(self.env, task_configs)

        scheduler = Scheduler(self.env, algorithm)

        self.simulation = Simulation(self.env, cluster, task_broker, scheduler,
                                     event_file)
Example #3
0
    def test_graph_and_lines_transfer_3(self):
        """Tests simulation with graph and lines - looong bus stops"""
        config_name = get_full_class_name(Config)
        with patch(config_name+'.graph_dict', new_callable=PropertyMock) as mock_graph_dict:
            with patch(config_name+'.lines_dict', new_callable=PropertyMock) as mock_lines_dict:
                with patch(config_name+'.traffic_data_dict',
                           new_callable=PropertyMock) as mock_traffic_dict:
                    class MockedGenerator:
                        def __init__(self, empty_argument):
                            self.done = False

                        def generate(self, src, dest):
                            if not self.done and src == 'C' and dest == 'F':
                                self.done = True
                                return 1
                            return 0

                    mock_graph_dict.return_value = {'A': [('B', 2), ('D', 2)],
                                                    'B': [('A', 2), ('C', 2), ('E', 2)],
                                                    'C': [('B', 8), ('D', 2)],
                                                    'D': [('A', 2), ('C', 2)],
                                                    'E': [('B', 2), ('F', 2)],
                                                    'F': [('E', 2)]}
                    mock_lines_dict.return_value = {
                        0: {'id': 0, 'bus_capacity': 20, 'frequency1': 1000, 'frequency2': 1000,
                            'route1': ['B', 'A', 'D', 'C'],
                            'route2': ['C', 'D', 'A', 'B']},
                        1: {'id': 1, 'bus_capacity': 20, 'frequency1': 1000, 'frequency2': 1000,
                            'route1': ['C', 'B', 'E', 'F'],
                            'route2': ['F', 'E', 'B', 'C']}}
                    config = Config(["A", "B", "C", "D", "E", "F"], {}, {}, {}, 1.0)
                    mock_traffic_dict.return_value = {'E': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'F': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'D': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'A': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'C': {'E': 0, 'F': 1, 'D': 0, 'A': 0, 'C': 0, 'B': 0},
                                                      'B': {'E': 0, 'F': 0, 'D': 0, 'A': 0, 'C': 0, 'B': 0}}

                    simulation = Simulation(config, MockedGenerator)
                    for _ in range(11):
                        simulation.refresh()
                    k = 0
                    for bus in simulation.buses:
                        if bus.line.number == 1 and bus.route == 0:
                            k += 1
                            self.are_lists_equal(bus.passengers, [PassengersGroup('F', 1)],
                                                 passenger_group_equality)
                    self.are_equal(k, 1)
Example #4
0
 def __init__(self,
              configuration_path: str = global_constants.
              DEFAULT_CONFIGURATION_PATH):
     super(JsbsimGymEnvironmentWrapper, self).__init__()
     self.sim = Simulation(configuration_path=configuration_path)
     self._dimensions = 1
     self.action_space = spaces.Box(low=-0,
                                    high=1,
                                    shape=(self._dimensions, ),
                                    dtype=np.float32)
     self.observation_space = spaces.Box(
         low=np.inf,
         high=np.inf,
         shape=self._getObs().
         shape,  # Passt sich damit automatisch an die Beobachtung an
         dtype=np.float32)
Example #5
0
class Episode(object):
    def __init__(self, machine_configs, task_configs, algorithm, event_file):
        self.env = simpy.Environment()
        cluster = Cluster()
        cluster.add_machines(machine_configs)

        task_broker = Broker(self.env, task_configs)

        scheduler = Scheduler(self.env, algorithm)

        self.simulation = Simulation(self.env, cluster, task_broker, scheduler,
                                     event_file)

    def run(self):
        self.simulation.run()
        self.env.run()
 def __init__(self,
              configuration_file: str = config.DEFAULT_CONFIGURATION_FILE):
     super(JsbsimGymEnvironmentWrapper, self).__init__()
     self.configuration = toml.load(os.path.expanduser(configuration_file))
     self.sim = Simulation(configuration_file=configuration_file)
     self._dimensions = 1
     self.action_space = spaces.Box(low=-0,
                                    high=1,
                                    shape=(self._dimensions, ),
                                    dtype=np.float32)
     self.observation_space = spaces.Box(
         low=np.inf,
         high=np.inf,
         shape=self._getObs().
         shape,  # Passt sich damit automatisch an die Beobachtung an
         dtype=np.float32)
     self.sim_steps = self.configuration['simulation'][
         'agent_interaction_freq']
class JsbsimGymEnvironmentWrapper(gym.Env):
    """Custom Environment that follows gym interface"""
    metadata = {'render.modes': ['human']}

    def __init__(self,
                 configuration_file: str = config.DEFAULT_CONFIGURATION_FILE):
        super(JsbsimGymEnvironmentWrapper, self).__init__()
        self.configuration = toml.load(os.path.expanduser(configuration_file))
        self.sim = Simulation(configuration_file=configuration_file)
        self._dimensions = 1
        self.action_space = spaces.Box(low=-0,
                                       high=1,
                                       shape=(self._dimensions, ),
                                       dtype=np.float32)
        self.observation_space = spaces.Box(
            low=np.inf,
            high=np.inf,
            shape=self._getObs().
            shape,  # Passt sich damit automatisch an die Beobachtung an
            dtype=np.float32)
        self.sim_steps = self.configuration['simulation'][
            'agent_interaction_freq']

    def reset(self):
        self.sim.reset_with_initial_condition()
        observation = self._getObs()
        reward = self._calcRewards(observation)
        return observation, reward, self._calcDones(), {}

    def step(
        self, actions: List[np.ndarray]
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Dict]:
        self.sim.set_properties('fcs/throttle-cmd-norm', actions[0])
        for _ in range(self.sim_steps):
            self.sim.run()
        observation = self._getObs()
        reward = self._calcRewards(observation)
        return observation, reward, self._calcDones(), {}

    def _getObs(self) -> np.ndarray:
        state = self.sim.get_state()
        return np.array(list(state.values()))

    def _calcRewards(self, observation) -> np.ndarray:
        rewAgent0 = 0
        return np.array([rewAgent0], dtype=np.float32)

    def _calcDones(self) -> np.ndarray:
        dones = np.zeros(1)
        return dones

    def render(self, mode='human'):
        pass

    def close(self):
        pass

    def seed(self, seed=None) -> None:
        pass
Example #8
0
def main():
    if len(sys.argv) != 11:
        print(
            "Input parameters must be: 'lambda mu theta C c0 Q L H simulation_time repeats'"
        )
    else:
        start_time = time.time()

        lambd = float(sys.argv[1])
        mu = float(sys.argv[2])
        theta = float(sys.argv[3])
        C = int(sys.argv[4])
        c0 = int(sys.argv[5])
        Q = int(sys.argv[6])
        L = int(sys.argv[7])
        H = int(sys.argv[8])
        simulation_time = int(sys.argv[9])
        repeats = int(sys.argv[10])

        print("Test for M/M/C[c0]/R[L,H]: lambda =", lambd, ", mu =", mu,
              ", theta = ", theta, ", C =", C, ", c0=", c0, ", Q =", Q,
              ", sim time =", simulation_time, ", repeats =", repeats)

        B = 0
        W = 0
        N = 0

        is_debug = False
        simulation = Simulation("m/m/c[c0]/r[l,h]", lambd, mu, theta, C, c0, L,
                                H, simulation_time, Q, is_debug)
        for i in range(0, repeats):
            simulation = Simulation("m/m/c[c0]/r[l,h]", lambd, mu, theta, C,
                                    c0, L, H, simulation_time, Q, is_debug)
            simulation.start_requests(simulation_time)
            B += simulation.queue.blocked / (simulation.queue.blocked +
                                             simulation.served_count)

            w = 0
            for request in simulation.served_requests:
                w += request.w
            for request in simulation.queue.blocked_requests:
                w += request.w
            W += w / (simulation.served_count +
                      len(simulation.queue.blocked_requests))
            N += (w / (simulation.served_count +
                       len(simulation.queue.blocked_requests))) * lambd

        B /= repeats
        W /= repeats
        N /= repeats

        end_time = time.time()

        print("B =", B, "\nW =", W, "\nN =", N)
        print("Execution time = %s seconds" % (end_time - start_time))
Example #9
0
    def generate_statistics(self):
        generated_values = []

        t1 = time.time()
        for lambd in self.range_dict[PARAM.LAMBDA]:
            for mu in self.range_dict[PARAM.MU]:
                for theta in self.range_dict[PARAM.THETA]:
                    for C in self.range_dict[PARAM.C]:
                        for c0 in self.range_dict[PARAM.c0]:
                            for L in self.range_dict[PARAM.L]:
                                for H in self.range_dict[PARAM.H]:
                                    for Q in self.range_dict[PARAM.Q]:
                                        if lambd <= 0: continue
                                        if mu <= 0: continue
                                        if theta <= 0: continue
                                        if C <= 0: continue
                                        if c0 <= 0: continue
                                        if L <= 0: continue
                                        if H <= 0: continue
                                        if Q <= 0: continue
                                        if c0 > C or c0 < 0: continue
                                        if H - L < 2: continue
                                        if Q - H <= 2: continue
                                        if H < L or H > Q: continue
                                        if L > Q: continue

                                        start_time = time.time()
                                        generated_values_storage = Generated_values_storage(
                                        )
                                        for repeats in self.range_dict[
                                                PARAM.REPEATS]:
                                            sim = Simulation(
                                                self.mode, lambd, mu, theta, C,
                                                c0, L, H, self.simulation_time,
                                                Q, self.is_debug)
                                            if (self.strategy == "time"):
                                                sim.start()
                                            else:
                                                sim.start_requests(
                                                    self.simulation_time)
                                            generated_values_storage.add(sim)
                                        end_time = time.time()
                                        generated_values_storage.normalize(
                                            self.parameters[
                                                PARAM.REPEATS].end_value)
                                        generated_values.append(
                                            generated_values_storage)
                                        self.log(lambd, mu, theta, C, c0, L, H,
                                                 Q, start_time, end_time)
        t2 = time.time()
        print("Total simulation time = %.5f" % (t2 - t1))
        return generated_values
    def generate(self):
        """
			Run simulation and collect statistic depending with specified strategy
			strategy = {
					single - run with fixed params
					range - run for specified range
					}
			strategy depends on input_range, if there is no range then single simulation will be executed

		"""
        generated_values = []

        print("Input parameters has range =", self.has_range, "\n")
        if self.has_range:
            for var in np.arange(self.input_range[0], self.input_range[1] + 1,
                                 self.step):
                start_time = time.time()
                generated_values_storage = Generated_values_storage()
                for i in range(0, int(self.repeats)):
                    sim = Simulation("m/m/c[c0]/r[l,h]",
                                     self.lambd if self.lambd != -1 else var,
                                     self.mu if self.mu != -1 else var,
                                     self.theta if self.theta != -1 else var,
                                     int(self.C) if self.C != -1 else var,
                                     int(self.c0) if self.c0 != -1 else var,
                                     int(self.L) if self.L != -1 else var,
                                     int(self.H) if self.H != -1 else var,
                                     int(self.simulation_time),
                                     int(self.Q) if self.Q != -1 else var,
                                     self.is_debug)
                    sim.start()
                    generated_values_storage.add(sim)
                end_time = time.time()
                print("Generated values added to storage for ", self.x_axis,
                      " = ", var, "/", self.input_range[1], ", repeated ",
                      len(range(0, int(self.repeats))), " times, ",
                      "execution time = %s sec" % (end_time - start_time))
                generated_values_storage.normalize(self.repeats)
                generated_values.append(generated_values_storage)
        else:
            for i in range(1, self.repeats):
                print("Repeat #", i)
                generated_values_storage = Generated_values_storage()
                sim = Simulation("m/m/c[c0]/r[l,h]", self.lambd, self.mu,
                                 self.theta, int(self.C), int(self.c0),
                                 int(self.L), int(self.H),
                                 int(self.simulation_time), int(self.Q),
                                 self.is_debug)
                generated_values_storage.add(sim)
            generated_values_storage.normalize(self.repeats)
            generated_values.append(generated_values_storage)
        return generated_values
            ("Name", '$name'),
            ("index", "$index"),
            ("Wert", "$y")]

        p = figure(title="simple line example", x_axis_label='Datapoints', y_axis_label='Data', tooltips=TOOLTIPS)
        p.line(df['phi'].index.values, df['phi'], line_width=2,
               legend_label='phi', name='phi', color="red")
        p.line(df['theta'].index.values, df['theta'], line_width=2,
               legend_label='theta', name='theta', color="green")
        p.line(df['u'].index.values, df['u'], line_width=2,
               legend_label='u', name='u', color="blue")
        output_file("plot.html")
        save(p)


    sim = Simulation()
    result = sim.run()
    sim.set_properties('propulsion/engine/set-running', 1)
    sim.set_properties('fcs/throttle-cmd-norm', 1.0)
    i = 0
    state = ""
    before = datetime.now()
    while result and sim.jsbsim.get_sim_time() <= 50:
        #print(i)
        state = sim.get_state()
        if i%5==0:
            sim.set_properties('fcs/aileron-cmd-norm', pid.innerLoopAileron(np.deg2rad(5), state['phi'], state['p'],
                                                                            sim.jsbsim.get_property_value(
                                                                           'fcs/aileron-cmd-norm')))
            sim.set_properties('fcs/elevator-cmd-norm', pid.innerLoopElevator(np.deg2rad(-10), state['theta'], state['q'],
                                                                              sim.jsbsim.get_property_value(
Example #12
0
        p.line(df['u'].index.values,
               df['u'],
               line_width=2,
               legend_label='u',
               name='u',
               color="blue")
        p.line(df['rpm'].index.values,
               df['rpm'],
               line_width=2,
               legend_label='rpm',
               name='rpm',
               color="black")
        output_file("plot.html")
        save(p)

    sim = Simulation()
    result = sim.run()
    sim.set_properties('propulsion/starter_cmd', 1)
    sim.set_properties('propulsion/engine/set-running', 1)
    sim.set_properties('propulsion/magneto_cmd', 2.0)
    sim.set_properties('fcs/mixture-cmd-norm', 0.87)
    sim.set_properties('fcs/throttle-cmd-norm', 1.0)
    i = 0
    state = ""
    before = datetime.now()
    while result and sim.jsbsim.get_sim_time() <= 50:
        #print(i)
        state = sim.get_state()
        sim.set_properties('fcs/throttle-cmd-norm', 0.99)
        sim.set_properties('fcs/mixture-cmd-norm', 0.87)
        if i % 5 == 0:
    adapters = get_available_adapters(arguments.device,
                                      device_package=arguments.device_package)

    protocols = {adapter.protocol for adapter in adapters.values()}

    for p in protocols:
        print(p)
    exit()

device = device_type(**parameters)
adapter = import_adapter(arguments.device,
                         arguments.protocol,
                         device_package=arguments.device_package)(
                             device, arguments.adapter_args)

simulation = Simulation(device=device, adapter=adapter)

simulation.cycle_delay = arguments.cycle_delay
simulation.speed = arguments.speed

if arguments.rpc_host:
    simulation.control_server = ControlServer(
        {
            'device':
            device,
            'simulation':
            ExposedObject(simulation, exclude=('start', 'control_server'))
        }, *arguments.rpc_host.split(':'))

simulation.start()
Example #14
0
def main():
    lambd = 2
    mu = 1
    theta = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
    C = 5
    c0 = 1
    Q = 10
    L = 3
    H = 6
    simulation_time = 1000
    repeats = 1
    served_requests = [
        10**2, 10**3, 10**4, 10**5, 10**6, 10**7, 10**8, 10**9, 10**10
    ]

    files = []

    for sr in served_requests:
        start_time = time.time()
        theoretical_mmcr = MMCR(lambd, mu, c0, Q)
        theoretical_result = theoretical_mmcr.run()

        B = theoretical_result[0]
        W = theoretical_result[1]
        N = theoretical_result[2]

        ### sim
        B2 = 0
        W2 = 0
        N2 = 0

        served = 0

        is_debug = False
        if is_debug: print("Q=", Q)

        simulation = Simulation("m/m/c/r", lambd, mu, theta, C, c0, L, H,
                                simulation_time, Q, is_debug)
        for i in range(0, repeats):
            simulation = Simulation("m/m/c/r", lambd, mu, theta, C, c0, L, H,
                                    simulation_time, Q, is_debug)
            simulation.start(sr)
            B2 += simulation.queue.blocked / (simulation.queue.blocked +
                                              simulation.served_count)

            w = 0
            for request in simulation.served_requests:
                w += request.w
            for request in simulation.queue.blocked_requests:
                w += request.w
            W2 += w / (simulation.served_count +
                       len(simulation.queue.blocked_requests))
            N2 += (w / (simulation.served_count +
                        len(simulation.queue.blocked_requests))) * lambd

        B2 /= repeats
        W2 /= repeats
        N2 /= repeats

        end_time = time.time()

        abs_path = os.path.abspath(__file__)
        path = 'served_requests_test' + '-(lambda=%s,mu=%s,theta=%s,C=%s,c0=%s,L=%s,H=%s,sim_time=%s, served requests =%s)' % (
            lambd, mu, theta, C, c0, L, H, (end_time - start_time), sr)
        path = path + ".csv"

        outfile = open(path, 'w')
        output = csv.writer(outfile, delimiter=';')
        output.writerow(['Served', 'theor B', 'imit B', 'diff'])
        outrow = []
        outrow.append(B)
        outrow.append(B2)
        outrow.append(abs((B2 - B) / B))
        output.writerow(outrow)
        output.writerow(['Served', 'theor N', 'imit N', 'diff'])
        outrow = []
        outrow.append(N)
        outrow.append(N2)
        outrow.append(abs((N2 - N) / N))
        output.writerow(outrow)
        output.writerow(['Served', 'theor W', 'imit W', 'diff'])
        outrow = []
        outrow.append(W)
        outrow.append(W2)
        outrow.append(abs((W2 - W) / W))
        output.writerow(outrow)
        outfile.close()

        files.append(path)

        print("theoretical B =", B, ", simulation B=", B2, ", Difference = ",
              abs((B2 - B) / B),
              "\ntheoretical W =", W, ", simulation W=", W2, ", Difference = ",
              abs((W2 - W) / W), "\ntheoretical N =", N, ", simulation N=", N2,
              ", Difference = ", abs((N2 - N) / N))
Example #15
0
def main():
    if len(sys.argv) != 9:
        print("Input parameters must be: 'lambda mu theta C c0 Q simulation_time repeats'")
    else:
        start_time = time.time()

        lambd = float(sys.argv[1])
        mu = float(sys.argv[2])
        theta = float(sys.argv[3])
        C = int(sys.argv[4])
        c0 = int(sys.argv[5])
        Q = int(sys.argv[6])
        simulation_time = int(sys.argv[7])
        repeats = int(sys.argv[8])

        # unused parameters
        L = 1
        H = 1
        #

        print("Difference test for M/M/C[c0]/R: lambda =", lambd, ", mu =", mu, ", C =", C, ", c0=", c0,", Q =", Q, ", theta = ", theta, ", sim time =",
                  simulation_time, ", repeats =", repeats)
        print("c0 will be used for theoretical m/m/c/r calculation")

        ### theoretical
        theoretical_mmcr = MMCR(lambd, mu, c0, Q)
        theoretical_result = theoretical_mmcr.run()

        B = theoretical_result[0]
        W = theoretical_result[1]
        N = theoretical_result[2]

        ### sim
        B2 = 0
        W2 = 0
        N2 = 0

        is_debug = False
        if is_debug: print("Q=",Q)
        simulation = Simulation("m/m/c[c0]/r", lambd, mu, theta, C, c0, L, H, simulation_time, Q, is_debug)
        for i in range(0, repeats):
            simulation = Simulation("m/m/c[c0]/r", lambd, mu, theta, C, c0, L, H, simulation_time, Q, is_debug)
            simulation.start()
            B2 += simulation.queue.blocked / (simulation.queue.blocked + simulation.served_count)

            w = 0
            for request in simulation.served_requests:
                w += request.w
            for request in simulation.queue.blocked_requests:
                w += request.w
            W2 += w / (simulation.served_count + len(simulation.queue.blocked_requests))
            N2 += (w / (simulation.served_count + len(simulation.queue.blocked_requests))) * lambd

        B2 /= repeats
        W2 /= repeats
        N2 /= repeats

        end_time = time.time()

        print("theoretical B =", B, ", simulation B=", B2, ", Difference = ", abs((B2 - B) / B),
                  "\ntheoretical W =", W, ", simulation W=", W2, ", Difference = ", abs((W2 - W) / W),
                  "\ntheoretical N =", N, ", simulation N=", N2, ", Difference = ", abs((N2 - N) / N))

        print("Execution time = %s seconds" % (end_time - start_time))
Example #16
0
parser.add_argument('-m', '--metrics', action="extend", nargs="+", type=str,
                    help='Metrics to be calculated after a simulation '\
                        'finishes.')
parser.add_argument('-d',
                    '--discard',
                    action="extend",
                    nargs="+",
                    type=str,
                    help='If set, discards the created .')


def tui(stdscr):
    total_jobs = len(Simulation.instances_status)
    s = screen.SimulationScreen(stdscr, total_jobs)
    s.init()
    s.loop(settings.PARALLEL_INSTANCES)


if __name__ == "__main__":
    options = parser.parse_args()
    settings_module = options.settings or 'settings'
    settings = Settings(settings_module)
    if options.display_stdout:
        setattr(settings, 'STDOUT', None)
    build_simulations(settings, options=options)
    if options.use_tui:
        curses.wrapper(tui)
    else:
        Simulation.dispatch_all(settings.PARALLEL_INSTANCES)
        Simulation.join()
def main():
	"""
	Main method to launch
	"""
	if len(sys.argv) < 12 or len(sys.argv) > 13:
		print("Input parameters must be: 'filename lambda mu C c0 Q theta L H simulation_time is_debug repeats(optionally)'")
	else:
		start_time = time.time()

		file_name = sys.argv[1]
		lambd = float(sys.argv[2])
		mu = float(sys.argv[3])
		C = int(sys.argv[4])
		c0 = int(sys.argv[5])
		Q = int(sys.argv[6])
		theta = float(sys.argv[7])
		L = int(sys.argv[8])
		H = int(sys.argv[9])
		simulation_time = float(sys.argv[10]);
		is_debug = True if sys.argv[11] == "True" else False;
		repeats = int(sys.argv[12]) if len(sys.argv) == 13 else 1;

		print("Simulation started for params: lambda =", lambd,
			                                  ", mu =", mu,
			                                  ", C =", C,
			                                  ", c0 =", c0,
			                                  ", Q =", Q,
			                                  ", theta =", theta,
			                                  ", L =", L,
			                                  ", H =", H,
			                                  ", repeats =", repeats)

		blocked = 0
		served = 0
		generated = 0
		B = 0
		N = 0

		simulation = Simulation("m/m/c[c0]/r[l,h]", lambd, mu, theta, C, c0, L, H, simulation_time, Q, is_debug)
		for i in range(0, repeats):
			simulation = Simulation("m/m/c[c0]/r[l,h]", lambd, mu, theta, C, c0, L, H, simulation_time, Q, is_debug)
			simulation.start()
			blocked += simulation.queue.blocked
			served += simulation.served_count
			generated += simulation.flow.generated_count
			B += simulation.queue.blocked/(simulation.served_count+simulation.queue.blocked)
			N += simulation.served_count/simulation_time
		end_time = time.time()

		blocked = blocked/repeats
		served = served/repeats
		generated = generated/repeats
		B = B/repeats
		N = N/repeats

		print( "")
		print( "Summary results:")
		print( "blocked=", blocked, " served=", served, ", generated=", generated)
		print("B = ", B)
		print("N = ", N)
		print("Execution time = %s seconds" % (end_time - start_time))
		print( "... to be implemented more summary ...")

		# write stats to file
		abs_path = os.path.abspath(__file__)
		path = os.path.relpath('stats', abs_path)
		path = os.path.join(path, file_name + '-(%s,%s,%s,%s,%s,%s,%s,%s).csv' % (lambd,mu,theta,C,c0,L,H,simulation_time))

		outfile=open(path,'w')
		output = csv.writer(outfile, delimiter=';')
		output.writerow(['Request ID','Queue', 'Arrival_Time','Queue_Arrival_time','Server_Arrival_time','alpha','beta'])

		i=0
		for request in simulation.served_requests:
			i=i+1
			outrow=[]
			outrow.append(request.ID)
			outrow.append(request.queue_size_at_serving)
			outrow.append(request.arrival_time)
			outrow.append(request.queue_arrival_time)
			outrow.append(request.server_arrival_time)
			outrow.append(request.alpha)
			outrow.append(request.beta)
			output.writerow(outrow)
		outfile.close()

		return simulation
Example #18
0
def main():
    if len(sys.argv) != 7:
        print(
            "Input parameters must be: 'lambda mu C Q simulation_time repeats'"
        )
    else:
        start_time = time.time()
        print(
            "Difference test for theoretical M/M/C/R model and 'm/m/c/r' imitation mode."
        )

        lambd = float(sys.argv[1])
        mu = float(sys.argv[2])
        C = int(sys.argv[3])
        R = int(sys.argv[4])
        simulation_time = int(sys.argv[5])
        repeats = int(sys.argv[6])

        theoretical_mmcr = MMCR(lambd, mu, C, R)
        theoretical_result = theoretical_mmcr.run()

        B = theoretical_result[0]
        W = theoretical_result[1]
        N = theoretical_result[2]
        Wq = theoretical_result[3]
        Q = theoretical_result[4]

        ### sim
        B2 = 0
        W2 = 0
        N2 = 0
        Wq2 = 0
        Q2 = 0

        theta = 1
        L = 1
        H = 1
        c0 = C
        is_debug = False
        simulation = Simulation("m/m/c/r", lambd, mu, theta, C, c0, L, H,
                                simulation_time, R, is_debug)
        for i in range(0, repeats):
            simulation = Simulation("m/m/c/r", lambd, mu, theta, C, c0, L, H,
                                    simulation_time, R, is_debug)
            simulation.start()
            B2 += simulation.queue.blocked / (simulation.queue.blocked +
                                              simulation.served_count)

            w = 0
            for request in simulation.served_requests:
                w += request.w
            for request in simulation.queue.blocked_requests:
                w += request.w
            W2 += w / (simulation.served_count +
                       len(simulation.queue.blocked_requests))
            N2 += (w / (simulation.served_count +
                        len(simulation.queue.blocked_requests))) * lambd

            wq = 0
            for request in simulation.served_requests:
                wq += request.wq
            for request in simulation.queue.blocked_requests:
                wq += request.wq
            Wq2 += wq / (simulation.served_count +
                         len(simulation.queue.blocked_requests))
            Q2 += (wq / (simulation.served_count +
                         len(simulation.queue.blocked_requests))) * lambd

        B2 /= repeats
        W2 /= repeats
        N2 /= repeats
        Wq2 /= repeats
        Q2 /= repeats

        end_time = time.time()

        print("theoretical B =", B, ", simulation B=", B2, ", Difference = ",
              abs((B2 - B) / B),
              "\ntheoretical W =", W, ", simulation W=", W2, ", Difference = ",
              abs((W2 - W) / W), "\ntheoretical N =", N, ", simulation N=", N2,
              ", Difference = ", abs((N2 - N) / N), "\ntheoretical Wq =",
              Wq, ", simulation Wq=", Wq2, ", Difference = ",
              abs((Wq2 - Wq) / Wq), "\ntheoretical Q =", Q, ", simulation Q=",
              Q2, ", Difference = ", abs((Q2 - Q) / Q))

        print("Execution time = %s seconds" % (end_time - start_time))