<commit_before>import os
import copy
import numpy
import pickle
import textwrap
from lxml import etree
from pysb.bng import generate_equations
from pysb.simulator import ScipyOdeSimulator

class BMIModel(object):
    def __init__(self, model):
        self.model = model
        generate_equations(model)
        self.dt = 1.0
        self.units = 'seconds'
        self.sim = None
        self.attributes = copy.copy(default_attributes)
        self.species_name_map = {}
        for idx, species in enumerate(self.model.species):
            monomer = species.monomer_patterns[0].monomer
            self.species_name_map[monomer.name] = idx
        self.input_vars = self._get_input_vars()
        # These attributes are related to the simulation state
        self.time = 0.0
        self.status = 'start'

    def _get_input_vars(self):
        species_is_obj = {s: False for s in self.species_name_map.keys()}
        for ann in self.model.annotations:
            if ann.predicate == 'rule_has_object':
                species_is_obj[ann.object] = True
        # Return all the variables that aren't objects in a rule
        input_vars = [s for s, tf in species_is_obj.items() if not tf]
        if 'rainfall' in input_vars:
            idx = input_vars.index('rainfall')
            del(input_vars[idx])
        return input_vars


    # Simulation functions
    def initialize(self, cfg_file=None, mode=None):
        """Initialize the model for simulation, possibly given a config file.

        Parameters
        ----------
        cfg_file : Optional[str]
            The name of the configuration file to load, optional.
        """
        self.sim = ScipyOdeSimulator(self.model)
        self.state = copy.copy(self.sim.initials)[0]
        self.time = 0.0
        self.status = 'initialized'

    def update(self, dt=None):
        """Simulate the model for a given time interval.

        Parameters
        ----------
        dt : Optional[float]
            The time step to simulate, if None, the default built-in time step
            is used.
        """
        dt = dt if dt else self.dt
        tspan = [0, dt]
        # Run simulaton with initials set to current state
        res = self.sim.run(tspan=tspan, initials=self.state)
        # Set the state based on the result here
        self.state  = res.species[-1]
        self.time += dt

    def finalize(self):
        """Finish the simulation and clean up resources as needed."""
        self.status = 'finalized'

    # Setter functions for state variables
    def set_value(self, var_name, value):
        """Set the value of a given variable to a given value.

        Parameters
        ----------
        var_name : str
            The name of the variable in the model whose value should be set.

        value : float
            The value the variable should be set to
        """
        species_idx = self.species_name_map[var_name]
        self.state[species_idx] = value

    # Getter functions for state
    def get_value(self, var_name):
        """Return the value of a given variable.

        Parameters
        ----------
        var_name : str
            The name of the variable whose value should be returned

        Returns
        -------
        value : float
            The value of the given variable in the current state
        """
        species_idx = self.species_name_map[var_name]
        return self.state[species_idx]

    def get_values(self, var_name):
        return self.get_value(var_name)

    def set_values(self, var_name, value):
        self.set_value(var_name, value)

    def get_status(self):
        return self.status

    # Getter functions for basic properties
    def get_attribute(self, att_name):
        """Return the value of a given attribute.

        Atrributes include: model_name, version, author_name, grid_type,
        time_step_type, step_method, time_units

        Parameters
        ----------
        att_name : str<commit_msg>Fixes in numpy usage and more documentation<commit_after>import os
import copy
import numpy
import pickle
import textwrap
from lxml import etree
from pysb.bng import generate_equations
from pysb.simulator import ScipyOdeSimulator

class BMIModel(object):
    def __init__(self, model):
        self.model = model
        generate_equations(model)
        self.dt = numpy.array(1.0)
        self.units = 'seconds'
        self.sim = None
        self.attributes = copy.copy(default_attributes)
        self.species_name_map = {}
        for idx, species in enumerate(self.model.species):
            monomer = species.monomer_patterns[0].monomer
            self.species_name_map[monomer.name] = idx
        self.input_vars = self._get_input_vars()
        # These attributes are related to the simulation state
        self.state = numpy.array([0.0 for s in self.species_name_map.keys()])
        self.time = numpy.array(0.0)
        self.status = 'start'
        # EMELI needs a DONE attribute
        self.DONE = False

    def _get_input_vars(self):
        species_is_obj = {s: False for s in self.species_name_map.keys()}
        for ann in self.model.annotations:
            if ann.predicate == 'rule_has_object':
                species_is_obj[ann.object] = True
        # Return all the variables that aren't objects in a rule
        input_vars = [s for s, tf in species_is_obj.items() if not tf]
        return input_vars


    # Simulation functions
    def initialize(self, cfg_file=None, mode=None):
        """Initialize the model for simulation, possibly given a config file.

        Parameters
        ----------
        cfg_file : Optional[str]
            The name of the configuration file to load, optional.
        """
        self.sim = ScipyOdeSimulator(self.model)
        self.state = numpy.array(copy.copy(self.sim.initials)[0])
        self.time = numpy.array(0.0)
        self.status = 'initialized'

    def update(self, dt=None):
        """Simulate the model for a given time interval.

        Parameters
        ----------
        dt : Optional[float]
            The time step to simulate, if None, the default built-in time step
            is used.
        """
        # EMELI passes dt = -1 so we need to handle that here
        dt = dt if (dt is not None and dt > 0) else self.dt
        tspan = [0, dt]
        # Run simulaton with initials set to current state
        res = self.sim.run(tspan=tspan, initials=self.state)
        # Set the state based on the result here
        self.state  = res.species[-1]
        self.time += dt

    def finalize(self):
        """Finish the simulation and clean up resources as needed."""
        self.status = 'finalized'

    # Setter functions for state variables
    def set_value(self, var_name, value):
        """Set the value of a given variable to a given value.

        Parameters
        ----------
        var_name : str
            The name of the variable in the model whose value should be set.

        value : float
            The value the variable should be set to
        """
        species_idx = self.species_name_map[var_name]
        self.state[species_idx] = value

    def set_values(self, var_name, value):
        """Set the value of a given variable to a given value.

        Parameters
        ----------
        var_name : str
            The name of the variable in the model whose value should be set.

        value : float
            The value the variable should be set to
        """
        self.set_value(var_name, value)

    # Getter functions for state
    def get_value(self, var_name):
        """Return the value of a given variable.

        Parameters
        ----------
        var_name : str
            The name of the variable whose value should be returned

        Returns
        -------
        value : float
            The value of the given variable in the current state
        """
        species_idx = self.species_name_map[var_name]
        return self.state[species_idx]

    def get_values(self, var_name):
        """Return the value of a given variable.

        Parameters
        ----------
        var_name : str
            The name of the variable whose value should be returned

        Returns
        -------
        value : float
            The value of the given variable in the current state
        """
        return self.get_value(var_name)

    def get_status(self):
        """Return the current status of the model."""
        return self.status

    # Getter functions for basic properties
    def get_attribute(self, att_name):
        """Return the value of a given attribute.

        Atrributes include: model_name, version, author_name, grid_type,
        time_step_type, step_method, time_units

        Parameters
        ----------
        att_name : str
{'fraction_non_alphanumeric': 0.0874447090847227, 'fraction_numerical': 0.0027220142905750254, 'mean_word_length': 1.9770425388251183, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '6589616', 'n_tokens_mistral': 2447, 'n_tokens_neox': 2375, 'n_words': 813}