<commit_before>"""
Name:        simulator

Author:      <NAME> <<EMAIL>>
Created:     23/04/2012
Copyright:   (c) <NAME> 2012

"""
#!/usr/bin/env python
from cps.misc import IndexedPriorityQueue
from cps.exception import ZeroPopulationError, SimulationError
import random

NORMAL = 0
CONSTANT_NUMBER = 1


class BaseSimulator(object):
    """
    Base class for simulators.

    Attributes:
        num_agents       (int)
        num_agents_max   (int)
        world            (cps.entity.World)
        agents           (list-of-cps.entity.Agent)
        agent_queue      (cps.misc.AgentQueue)
        loggers          (list-of-cps.state.LoggerNode)
        recorders        (list-of-cps.state.Recorder)

    """
    def __init__(self, model, tstart):
        """
        Initialize a simulator according to the specification of the provided
        model.

        """
        from cps.model import create_world, create_agents

        # keep count of agents
        self.num_agents = model.n0
        self.num_agents_max = model.nmax

        # create world entity
        self.world = create_world(model, self, tstart)

        # create agent entities
        self.agents = create_agents(model, self, tstart)

        # loggers
        self.loggers = []
        for i in sorted(model.logged):
            self.loggers.append(self.agents[i]._logger)

        # recorders
        self.recorders = model.recorders

        # initialization routine
        self.state_initializer = model.initializer

        # create queue
        self.agent_queue = model.AgentQueueType()

        self._do_sync = any([entry.sync for entry in model.agent_channel_table.values()])

        self.initialize()

    def initialize(self):
        raise NotImplementedError

    def runSimulation(self, tstop):
        raise NotImplementedError

    def finalize(self):
        raise NotImplementedError



#-------------------------------------------------------------------------------
# First-Entity (synchronous) Method

class FMSimulator(BaseSimulator):

    def initialize(self):
        self._mode = NORMAL if self.num_agents < self.num_agents_max else CONSTANT_NUMBER
        self._processAgent = {NORMAL:self._processAgentNormalMode,
                              CONSTANT_NUMBER:self._processAgentConstantNumberMode}
        self.sizethresh_hi = self.num_agents_max
        self.sizethresh_lo = -1
        self.world._ts = [self.world._time]
        self.world._size = [self.num_agents]
        self.nbirths = 0
        self.ndeaths = 0

        # initialize state variables with user-defined function
        self.state_initializer(self.world, self.agents)

        # schedule simulation channels
        self.world._scheduleAllChannels()
        for agent in self.agents:
            agent._scheduleAllChannels()

        # set up global timetable
        event_times = [agent._next_event_time for agent in self.agents]
        self.timetable = IndexedPriorityQueue(zip(self.agents, event_times))

    def runSimulation(self, tstop):
        world = self.world
        agents = self.agents
        timetable = self.timetable

        emin, tmin = self._earliestItem() #TODO:should force it to pick agent over world

        while (tmin <= tstop):
            if emin is world:
                # fire agent sync channels
                if self._do_sync:
                    for agent in agents:
                        agent._synchronize(tmin)
                        if agent in timetable:
                            timetable.updateitem(agent, agent._next_event_time)
                    emin, tmin = self._earliestItem()
                    if emin is not world:<commit_msg>Record snapshot at start time<commit_after>"""
Name:        simulator

Author:      <NAME> <<EMAIL>>
Created:     23/04/2012
Copyright:   (c) <NAME> 2012

"""
#!/usr/bin/env python
from cps.misc import IndexedPriorityQueue
from cps.exception import ZeroPopulationError, SimulationError
import random

NORMAL = 0
CONSTANT_NUMBER = 1


class BaseSimulator(object):
    """
    Base class for simulators.

    Attributes:
        num_agents       (int)
        num_agents_max   (int)
        world            (cps.entity.World)
        agents           (list-of-cps.entity.Agent)
        agent_queue      (cps.misc.AgentQueue)
        loggers          (list-of-cps.state.LoggerNode)
        recorders        (list-of-cps.state.Recorder)

    """
    def __init__(self, model, tstart):
        """
        Initialize a simulator according to the specification of the provided
        model.

        """
        from cps.model import create_world, create_agents

        # keep count of agents
        self.num_agents = model.n0
        self.num_agents_max = model.nmax

        # create world entity
        self.world = create_world(model, self, tstart)

        # create agent entities
        self.agents = create_agents(model, self, tstart)

        # loggers
        self.loggers = []
        for i in sorted(model.logged):
            self.loggers.append(self.agents[i]._logger)

        # recorders
        self.recorders = model.recorders

        # initialization routine
        self.state_initializer = model.initializer

        # create queue
        self.agent_queue = model.AgentQueueType()

        self._do_sync = any([entry.sync for entry in model.agent_channel_table.values()])

        self.initialize()

    def initialize(self):
        raise NotImplementedError

    def runSimulation(self, tstop):
        raise NotImplementedError

    def finalize(self):
        raise NotImplementedError



#-------------------------------------------------------------------------------
# First-Entity (synchronous) Method

class FMSimulator(BaseSimulator):

    def initialize(self):
        self._mode = NORMAL if self.num_agents < self.num_agents_max else CONSTANT_NUMBER
        self._processAgent = {NORMAL:self._processAgentNormalMode,
                              CONSTANT_NUMBER:self._processAgentConstantNumberMode}
        self.sizethresh_hi = self.num_agents_max
        self.sizethresh_lo = -1
        self.world._ts = [self.world._time]
        self.world._size = [self.num_agents]
        self.nbirths = 0
        self.ndeaths = 0

        # initialize state variables with user-defined function
        self.state_initializer(self.world, self.agents)

        # schedule simulation channels
        self.world._scheduleAllChannels()
        for agent in self.agents:
            agent._scheduleAllChannels()

        # set up global timetable
        event_times = [agent._next_event_time for agent in self.agents]
        self.timetable = IndexedPriorityQueue(zip(self.agents, event_times))

        # TODO: make this better
        for recorder in self.recorders:
            recorder.record(self.world._time, self.world, self.agents)

    def runSimulation(self, tstop):
        world = self.world
        agents = self.agents
        timetable = self.timetable

        emin, tmin = self._earliestItem() #TODO:should force it to pick agent over world

        while (tmin <= tstop):
            if emin is world:
                # fire agent sync channels
                if self._do_sync:
                    for agent in agents:
                        agent._synchronize(tmin)
                        if agent in timetable:
                            timetable.updateitem(agent, agent._next_event_time)
                    emin, tmin = self._earliestItem()
                    if emin is not world:
{'fraction_non_alphanumeric': 0.09958672177043061, 'fraction_numerical': 0.004799360085321957, 'mean_word_length': 1.9145299145299146, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '866887', 'n_tokens_mistral': 2165, 'n_tokens_neox': 2011, 'n_words': 496}