Example #1
0
 def setUp(self):
     # create simulator
     self.simulator = SimulationEngine()
     self.out_dir = tempfile.mkdtemp()
     self.log_names = ['de_sim.debug.file', 'de_sim.plot.file']
     measurements_file = core.get_config()['de_sim']['measurements_file']
     self.measurements_pathname = os.path.join(self.out_dir,
                                               measurements_file)
Example #2
0
    def simulate(self, time_max=None, sim_config=None, config_dict=None, author_metadata=None):
        """ Run a simulation

        See `_get_sim_config` for constraints on arguments

        Args:
            time_max (:obj:`float`, optional): the time of the end of the simulation
            sim_config (:obj:`SimulationConfig`, optional): the simulation run's configuration
            config_dict (:obj:`dict`, optional): a dictionary with keys chosen from
                the field names in :obj:`SimulationConfig`
            author_metadata (:obj:`AuthorMetadata`, optional): information about the person who runs the simulation

        Returns:
            :obj:`SimulationReturnValue`: a :obj:`namedtuple` which contains a) the number of times any
                simulation object executes `_handle_event()`, which may
                be smaller than the number of events sent, because simultaneous events at one
                simulation object are handled together, and b), if `sim_config.profile` is set,
                a :obj:`pstats.Stats` instance containing the profiling statistics

        Raises:
            :obj:`SimulatorError`: if the simulation has not been initialized, or has no objects,
                or has no initial events, or attempts to execute an event that violates non-decreasing time
                order
        """
        self.sim_config = self._get_sim_config(time_max=time_max, sim_config=sim_config,
                                               config_dict=config_dict)
        self.author_metadata = author_metadata
        if self.sim_config.output_dir:
            measurements_file = core.get_config()['de_sim']['measurements_file']
            self.measurements_fh = open(os.path.join(self.sim_config.output_dir, measurements_file), 'w')
            print(f"de_sim measurements: {datetime.now().isoformat(' ')}", file=self.measurements_fh)

        profile = None
        if self.sim_config.profile:
            # profile the simulation and return the profile object
            with tempfile.NamedTemporaryFile() as file_like_obj:
                out_file = file_like_obj.name
                locals = {'self': self}
                cProfile.runctx('self._simulate()', {}, locals, filename=out_file)
                if self.sim_config.output_dir:
                    profile = pstats.Stats(out_file, stream=self.measurements_fh)
                else:
                    profile = pstats.Stats(out_file)
                profile.sort_stats('tottime').print_stats(self.NUM_PROFILE_ROWS)
        else:
            self._simulate()
        if self.sim_config.output_dir:
            self.measurements_fh.close()
        return self.SimulationReturnValue(self.num_events_handled, profile)
Example #3
0
 def test_get_config(self):
     config = core.get_config()
     self.assertEqual(config['de_sim']['copy_event_bodies'], False)
     config = core.get_config(extra={'de_sim': {'copy_event_bodies': True}})
     self.assertEqual(config['de_sim']['copy_event_bodies'], True)
Example #4
0
from collections import namedtuple
from numpy import random
import numpy
import os
import shutil
import tempfile
import unittest
import copy

from de_sim.checkpoint import Checkpoint, AccessCheckpoints
from de_sim.config import core
from de_sim.errors import SimulatorError
from wc_utils.util.uniform_seq import UniformSequence
import wc_utils.util.types

MAX_TIME_PRECISION = core.get_config()['de_sim']['max_time_precision']


class TestCheckpoint(unittest.TestCase):
    def setUp(self):
        self.empty_checkpoint1 = Checkpoint(None, None, None)
        self.empty_checkpoint2 = Checkpoint(None, None, None)

        # Checkpoint(time, state, random_state)
        time = 2
        state = [[1, 2], 3]
        random_state = random.RandomState(seed=0)
        attrs = dict(time=time, state=state, random_state=random_state)
        self.non_empty_checkpoint1 = Checkpoint(time, state, random_state)
        self.non_empty_checkpoint2 = self.non_empty_checkpoint1
Example #5
0
from copy import deepcopy
from enum import IntEnum
import abc
import heapq
import math
import warnings

from de_sim.config import core
from de_sim.errors import SimulatorError
from de_sim.event import Event
from de_sim.simulation_message import SimulationMessage
from de_sim.utilities import ConcreteABCMeta, FastLogger
from wc_utils.util.list import elements_to_str
from wc_utils.util.misc import most_qual_cls_name, round_direct

config = core.get_config()


# TODO(Arthur): move to engine
class EventQueue(object):
    """ A simulation's event queue

    Stores a `SimulationEngine`'s events in a heap (also known as a priority queue).
    The heap is a 'min heap', which keeps the event with the smallest
    `(event_time, sending_object.name)` at the root in heap[0].
    This is implemented via comparison operations in `Event`.
    Thus, all entries with equal `(event_time, sending_object.name)` will be popped from the heap
    adjacently. `schedule_event()` costs `O(log(n))`, where `n` is the size of the heap,
    while `next_events()`, which returns all events with the minimum
    `(event_time, sending_object.name)`, costs `O(mlog(n))`, where `m` is the number of events
    returned.