示例#1
0
    def __init__(self, charge_values: Sequence[ChargeValues] = ()) -> None:
        """
        The constructor of the RandomNodeCreator class.

        Parameters
        ----------
        charge_values : Sequence[input_output_handler.input_handler.charge_values.ChargeValues], optional
            The sequence of charge values.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the charge values does not contain a charge for each child node within a root node.
        base.exceptions.ConfigurationError:
            If in the sequence of charge values a charge name appears more than once.
        """
        # Check that per charge value there is a charge given for every particle
        for charge_value in charge_values:
            if not len(charge_value) == self.number_of_nodes_per_root_node:
                raise ConfigurationError(
                    "Charge {0} is not given for every child of a composite point object."
                    .format(charge_value.charge_name))
        # Check that each charge value has a different name
        if not len(
                set(charge_value.charge_name
                    for charge_value in charge_values)) == len(charge_values):
            raise ConfigurationError(
                "Please choose a unique charge name for all the charges used.")
        self._charge_values = charge_values
示例#2
0
    def initialize(self, extracted_global_state: Sequence[Node],
                   internal_states: Sequence[InternalState]) -> None:
        """
        Initialize the taggers based on the full extracted global state and all initialized internal states.

        Extends the initialize method of the Tagger class. Use this method once in the beginning of the run to
        initialize the tagger. Only after a call of this method, other public methods of this class can be called
        without raising an error.
        This method extracts the internal state corresponding to the internal state label out of the sequence of
        internal states. If a tagger also need to initialize their event handlers, it should further extend this method.
        The full extracted global state is given as a sequence of cnodes of all root nodes stored in the global state.

        Parameters
        ----------
        extracted_global_state : Sequence[base.node.Node]
            The full extracted global state from the state handler.
        internal_states : Sequence[activator.internal_state.InternalState]
            Sequence of all initialized internal states in the activator.
        """
        super().initialize(extracted_global_state, internal_states)
        relevant_internal_state = [
            state for state in internal_states
            if to_snake_case(get_alias(state.__class__.__name__)) ==
            self._internal_state_label
        ]
        if len(relevant_internal_state) == 0:
            raise ConfigurationError(
                "The given internal state label '{0}' does not exist!".format(
                    self._internal_state_label))
        if len(relevant_internal_state) > 1:
            raise ConfigurationError(
                "The given internal state label '{0}' exists more than once!".
                format(self._internal_state_label))
        self._internal_state = relevant_internal_state[0]
    def __init__(self, potential: Potential, bounding_potential: InvertiblePotential, charge: str = None) -> None:
        """
        The constructor of the RootUnitActiveTwoCompositeObjectSummedBoundingPotentialEventHandler class.

        Parameters
        ----------
        potential : potential.Potential
            The potential between the leaf units.
        bounding_potential : potential.InvertiblePotential
            The invertible bounding potential between the leaf units.
        charge : str or None, optional
            The relevant charge for this event handler.

        Raises
        ------
        base.exceptions.ConfigurationError:
            If the bounding potential does not expect exactly one separation.
        base.exceptions.ConfigurationError:
            If the potential does not expect exactly one separation.
        base.exceptions.ConfigurationError:
            If the charge is not None but the potential or the bounding potential expects more than two charges.
        base.exceptions.ConfigurationError
            If the number of nodes per root node is one and therefore no composite objects are present in the run.
        """
        log_init_arguments(logging.getLogger(__name__).debug, self.__class__.__name__,
                           potential=potential.__class__.__name__,
                           bounding_potential=bounding_potential.__class__.__name__, charge=charge)
        super().__init__()
        self._potential = potential
        self._bounding_potential = bounding_potential
        if self._bounding_potential.number_separation_arguments != 1:
            raise ConfigurationError("The event handler {0} expects a potential and a bounding potential "
                                     "which handles exactly one separation!".format(self.__class__.__name__))
        if not setting.number_of_nodes_per_root_node > 1:
            raise ConfigurationError("The class {0} can only be "
                                     "used when composite point objects are present!".format(self.__class__.__name__))
        if self._potential.number_separation_arguments != 1:
            raise ConfigurationError("The event handler {0} expects a potential "
                                     "which handles exactly one separation!".format(self.__class__.__name__))

        if charge is None:
            self._potential_charges = (lambda unit_one, unit_two:
                                       tuple(1.0 for _ in range(self._potential.number_charge_arguments)))
            self._bounding_potential_charges = (lambda unit_one, unit_two:
                                                tuple(1.0 for _ in
                                                      range(self._bounding_potential.number_charge_arguments)))
        else:
            if self._potential.number_charge_arguments == 2 and self._bounding_potential.number_charge_arguments == 2:
                self._potential_charges = lambda unit_one, unit_two: (unit_one.charge[charge], unit_two.charge[charge])
                self._bounding_potential_charges = self._potential_charges
            else:
                raise ConfigurationError("The event handler {0} was initialized with a charge which is not None,"
                                         " but its potential {1} and/or its bounding potential {2}"
                                         "expects not exactly 2 charges."
                                         .format(self.__class__.__name__, self._potential.__class__.__name__,
                                                 self._bounding_potential.__class__.__name__))

        self._direction_of_motion = None
        self._speed = None
示例#4
0
    def __init__(self,
                 potential: Potential,
                 bounding_potential: CellBoundingPotential,
                 charge: str = None) -> None:
        """
        The constructor of the TwoLeafUnitCellBoundingPotentialEventHandler class.

        Parameters
        ----------
        potential : potential.Potential
            The potential between the leaf units.
        bounding_potential : potential.cell_bounding_potential.CellBoundingPotential
            The invertible cell bounding potential between the leaf units.
        charge : str or None, optional
            The relevant charge for this event handler.

        Raises
        ------
        base.exceptions.ConfigurationError:
            If the cell bounding potential does not expect exactly one separation.
        base.exceptions.ConfigurationError:
            If the charge is not None but the potential or the cell bounding potential expects more than two charges.
        """
        log_init_arguments(
            logging.getLogger(__name__).debug,
            self.__class__.__name__,
            potential=potential.__class__.__name__,
            bounding_potential=bounding_potential.__class__.__name__,
            charge=charge)
        super().__init__(potential=potential,
                         bounding_potential=bounding_potential)
        self._charge = charge

        if self._bounding_potential.number_separation_arguments != 1:
            raise ConfigurationError(
                "The event handler {0} expects a cell bounding potential "
                "which handles exactly one separation!".format(
                    self.__class__.__name__))

        if charge is None:
            self._potential_charges = (lambda unit_one, unit_two: tuple(
                1.0 for _ in range(self._potential.number_charge_arguments)))
            self._bounding_potential_charges = (
                lambda unit_one, unit_two: tuple(1.0 for _ in range(
                    self._bounding_potential.number_charge_arguments)))
        else:
            if self._potential.number_charge_arguments == 2 and self._bounding_potential.number_charge_arguments == 2:
                self._potential_charges = lambda unit_one, unit_two: (
                    unit_one.charge[charge], unit_two.charge[charge])
                self._bounding_potential_charges = self._potential_charges
            else:
                raise ConfigurationError(
                    "The event handler {0} was initialized with a charge which is not None,"
                    " but its potential {1} and/or its bounding potential {2}"
                    "expects not exactly 2 charges.".format(
                        self.__class__.__name__,
                        self._potential.__class__.__name__,
                        self._bounding_potential.__class__.__name__))
    def __init__(self,
                 potential: Potential,
                 lifting: Lifting,
                 charge: str = None,
                 **kwargs: Any) -> None:
        """
        The constructor of the TwoCompositeObjectBoundingPotentialEventHandler class.

        This class is designed for cooperative inheritance, meaning that it passes through all unused kwargs in the
        init to the next class in the MRO via super.

        Parameters
        ----------
        potential : potential.Potential
            The potential between all pairs of units in different composite objects.
        lifting : lifting.Lifting
            The lifting scheme.
        charge : str or None, optional
            The charge this event handler passes to the potential. If None, the potential just gets one as the charges.
        kwargs : Any
            Additional kwargs which are passed to the __init__ method of the next class in the MRO.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the number of nodes per root node is one and therefore no composite objects are present in the run.
        base.exceptions.ConfigurationError
            If the potential expects more than one separation.
        base.exceptions.ConfigurationError
            If the charge is not None but the potential expects more than two charges.
        """
        super().__init__(potential=potential, **kwargs)
        self._lifting = lifting
        if not setting.number_of_nodes_per_root_node > 1:
            raise ConfigurationError(
                "Class {0} can only be used when composite point objects are present!"
                .format(self.__class__.__name__))
        if self._potential.number_separation_arguments != 1:
            raise ConfigurationError(
                "The event handler {0} expects a potential "
                "which handles exactly one separation!".format(
                    self.__class__.__name__))
        if charge is None:
            self._potential_charges = (lambda unit_one, unit_two: tuple(
                1.0 for _ in range(self._potential.number_charge_arguments)))
        else:
            if self._potential.number_charge_arguments == 2:
                self._potential_charges = lambda unit_one, unit_two: (
                    unit_one.charge[charge], unit_two.charge[charge])
            else:
                raise ConfigurationError(
                    "The event handler {0} was initialized with a charge which is not None,"
                    " but its potential {1} "
                    "expects not exactly 2 charges.".format(
                        self.__class__.__name__,
                        self._potential.__class__.__name__))
    def __init__(self,
                 potential: Potential,
                 offset: float,
                 max_displacement: float,
                 charge: str = None) -> None:
        """
        The constructor of the TwoLeafUnitEventHandlerWithPiecewiseConstantBoundingPotential class.

        Parameters
        ----------
        potential : potential.Potential
            The potential between the leaf units.
        offset : float
            The offset used to create piecewise constant bounding potential.
        max_displacement :
            The maximum displacement used to create piecewise constant bounding potential.
        charge : str or None, optional
            The relevant charge for this event handler.

        Raises
        ------
        base.exceptions.ConfigurationError:
            If the potential does not expect exactly one separation.
        base.exceptions.ConfigurationError:
            If the charge is not None but the potential expects more than two charges.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           potential=potential.__class__.__name__,
                           offset=offset,
                           max_displacement=max_displacement,
                           charge=charge)
        super().__init__(potential=potential,
                         offset=offset,
                         max_displacement=max_displacement)
        if self._potential.number_separation_arguments != 1:
            raise ConfigurationError(
                "The event handler {0} expects a potential "
                "which handles exactly one separation!".format(
                    self.__class__.__name__))

        if charge is None:
            self._charges = lambda unit_one, unit_two: tuple(
                1.0 for _ in range(self._potential.number_charge_arguments))
        else:
            if self._potential.number_charge_arguments == 2:
                self._charges = lambda unit_one, unit_two: (unit_one.charge[
                    charge], unit_two.charge[charge])
            else:
                raise ConfigurationError(
                    "The event handler {0} was initialized with a charge which is not None,"
                    " but its potential {1} expects not exactly 2 charges.".
                    format(self.__class__.__name__,
                           self._potential.__class__.__name__))
    def __init__(self, power: float, prefactor: float) -> None:
        """
        The constructor of the InversePowerPotential.

        Parameters
        ----------
        power : float
            The power p of the potential.
        prefactor : float
            The prefactor k of the potential.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the power p is not larger than 0.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           power=power,
                           prefactor=prefactor)
        super().__init__(prefactor=prefactor)
        if not power > 0.0:
            raise ConfigurationError(
                "Give a power > 0.0 as the power for the potential {0}.".
                format(self.__class__.__name__))
        self._power = power
        self._two_over_power = 2.0 / self._power
        self._power_over_two = self._power / 2.0
        self._power_plus_two = self._power + 2
        self._infinity = float('inf')
示例#8
0
    def initialize(self, cells: PeriodicCells,
                   extracted_global_state: Sequence[Node]) -> None:
        """
        Initialize the cell bounding potential event handler base class.

        This is done by handing over the cells, the extracted global state and the charge to the base class. This event
        handler requires the cells to be an instance of PeriodicCells.
        Extends the initialize method of the abstract Initializer class. This method is called once in the beginning of
        the run by the activator. Only after a call of this method, other public methods of this class can be called
        without raising an error.

        Parameters
        ----------
        cells : activator.internal_state.cell_occupancy.cells.Cells
            The cell system.
        extracted_global_state : Sequence[base.node.Node]
            The extracted global state of the tree state handler.

        Raises
        ------
        AssertionError
            If the cell system is not an instance of PeriodicCells.
        """
        if not isinstance(cells, PeriodicCells):
            raise ConfigurationError(
                "The event handler {0} needs an instance of PeriodicCells!".
                format(self.__class__.__name__))
        super().initialize(cells, extracted_global_state, self._charge)
    def initialize(self, extracted_global_state: Sequence[Node],
                   internal_states: Sequence[InternalState]) -> None:
        """
        Initialize the taggers based on the full extracted global state and all initialized internal states.

        Extends the initialize method of the TaggerWithInternalState class. Use this method once in the beginning of the
        run to initialize the tagger. Only after a call of this method, other public methods of this class can be called
        without raising an error.
        This method checks if the internal state of this label is a cell-occupancy system.
        The full extracted global state is given as a sequence of cnodes of all root nodes stored in the global state.

        Parameters
        ----------
        extracted_global_state : Sequence[base.node.Node]
            The full extracted global state from the state handler.
        internal_states : Sequence[activator.internal_state.InternalState]
            Sequence of all initialized internal states in the activator.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the internal state is not an instance of CellOccupancy.
        """
        super().initialize(extracted_global_state, internal_states)
        if not isinstance(self._internal_state, CellOccupancy):
            raise ConfigurationError(
                "Class ExcludedCellsTagger can only be used with an instance of CellOccupancy "
                "as the internal state!")
示例#10
0
    def __init__(self, filename: str) -> None:
        """
        The constructor of the OxygenOxygenSeparationOutputHandler class.

        This class uses a HardBufferedTextWriter to first write the separations to a temporary file.

        Parameters
        ----------
        filename : str
            The filename of the file this output handler is connected to.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the number of node levels is not two or the number of nodes per root node is not three.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           filename=filename)
        super().__init__(filename)
        self._file = HardBufferedTextWriter(filename)
        if setting.number_of_node_levels != 2 or setting.number_of_nodes_per_root_node != 3:
            raise ConfigurationError(
                "The output handler {0} can only be used if each root node has 3 child nodes."
                .format(self.__class__.__name__))
示例#11
0
    def __init__(self, potential: Potential, empirical_bound: float = float('inf'), prefactor: float = 1.5,
                 points_per_side: int = 10) -> None:
        """
        The constructor of the InnerPointEstimator class.

        If the given region has the dimension D, then the total number of compared points is simply
        points_per_side ** D.

        Parameters
        ----------
        potential : potential.Potential
            Potential whose derivative is to be bounded.
        prefactor : float, optional
            A constant which gets multiplied to the bounds.
        empirical_bound : float, optional
            If a bound exceeds this value, this value will be returned instead.
        points_per_side : int, optional
            Specifies, into how many parts in each direction the given region for the separations in the
            derivative_bound method  is cut.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the potential derivative method does not expect exactly one separation.
        """
        log_init_arguments(logging.getLogger(__name__).debug, self.__class__.__name__,
                           potential=potential.__class__.__name__, empirical_bound=empirical_bound, prefactor=prefactor,
                           points_per_side=points_per_side)
        super().__init__(potential=potential, empirical_bound=empirical_bound, prefactor=prefactor)
        self._points_per_side = points_per_side
        if self._potential.number_separation_arguments != 1:
            raise ConfigurationError("The estimator {0} expects a potential "
                                     "which handles exactly one separation!".format(self.__class__.__name__))
示例#12
0
    def __init__(self, sampling_interval: float, output_handler: str) -> None:
        """
        The constructor of the FixedIntervalSamplingEventHandler class.

        Parameters
        ----------
        sampling_interval : float
            The time interval of the sampling.
        output_handler : str
            The name of the output handler.

        Raises
        ------
        base.exceptions.ConfigurationError:
            If the sampling interval is not greater than zero.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           sampling_interval=sampling_interval,
                           output_handler=output_handler)
        super().__init__(output_handler=output_handler)
        if not sampling_interval > 0.0:
            raise ConfigurationError(
                "The sampling_interval in the event handler {0} has to be > 0.0."
                .format(self.__class__.__name__))
        self._sampling_interval = sampling_interval
        self._event_time = 0.0
    def __init__(self, potential: Potential, offset: float,
                 max_displacement: float, **kwargs: Any):
        """
        The constructor of the EventHandlerWithPiecewiseConstantBoundingPotential class.

        This class is designed for cooperative inheritance, meaning that it passes through all unused kwargs in the
        init to the next class in the MRO via super.

        Parameters
        ----------
        potential : potential.Potential
            The potential between the leaf units.
        offset : float
            The offset.
        max_displacement : float
            The maximum displacement by which the active unit is displaced to determine the bounding event rate.
        kwargs : Any
            Additional kwargs which are passed to the __init__ method of the next class in the MRO.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the maximum displacement is not larger than zero.
        """
        super().__init__(**kwargs)
        self._potential = potential
        self._offset = offset
        if not max_displacement > 0.0:
            raise ConfigurationError(
                "Please use a value for max_displacement > 0.0 in the class {0}."
                .format(self.__class__.__name__))
        self._max_displacement = max_displacement
        self._bounding_event_rate = None
    def __init__(self, filename: str) -> None:
        """
        The constructor of the DumpingOutputHandler class.

        Parameters
        ----------
        filename : str
            The filename of the file this output handler is connected to.

        Raises
        ------
        AssertionError
            If the filename does not contain a file format.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           filename=filename)
        split_filename = filename.split(".")
        if len(split_filename) != 2:
            raise ConfigurationError(
                "The given filename {0} contains more than one '.'.".format(
                    filename))
        # Include python implementation and version (implementation_major_minor_macro in filename)
        dumping_filename = (
            split_filename[0] + "_" + sys.implementation.name + "_" +
            "_".join([str(sys.version_info[i])
                      for i in range(3)]) + "." + split_filename[1])

        super().__init__(dumping_filename)
    def __init__(self, potential: InvertiblePotential, charge: str = None):
        """
        The constructor of the RootUnitActiveTwoLeafUnitEventHandler class.

        Parameters
        ----------
        potential : potential.InvertiblePotential
            The invertible potential.
        charge : str or None, optional
            The relevant charge for this event handler.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the number of nodes per root node is one and therefore no composite objects are present in the run.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           potential=potential.__class__.__name__,
                           charge=charge)
        super().__init__(potential=potential, charge=charge)
        if not setting.number_of_node_levels > 1:
            raise ConfigurationError(
                "The event handler {0} should only be used when composite point objects are "
                "involved!".format(self.__class__.__name__))
    def __init__(self, potential: Potential, **kwargs: Any):
        """
        The constructor of the EventHandlerWithBoundingPotential class.

        This class is designed for cooperative inheritance, meaning that it passes through all unused kwargs in the
        init to the next class in the MRO via super.

        Parameters
        ----------
        potential : potential.Potential
            The potential between the active and target leaf unit.
        kwargs : Any
            Additional kwargs which are passed to the __init__ method of the next class in the MRO.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the potential expects more than one separation.
        """
        super().__init__(**kwargs)
        self._bounding_event_rate = None
        self._potential = potential
        if self._potential.number_separation_arguments != 1:
            raise ConfigurationError(
                "The event handler {0} expects a potential "
                "which handles exactly one separation!".format(
                    self.__class__.__name__))
示例#17
0
    def __init__(self,
                 end_of_run_time: float,
                 output_handler: str = None) -> None:
        """
        The constructor of the FinalTimeEndOfRunEventHandler class.

        Parameters
        ----------
        end_of_run_time : float
            The event time at which the run is ended.
        output_handler : str or None, optional
            The name of the output handler.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the end of run time is not greater than zero.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           end_of_run_time=end_of_run_time,
                           output_handler=output_handler)
        super().__init__(output_handler=output_handler)
        if not end_of_run_time > 0.0:
            raise ConfigurationError(
                "The end_of_run_time in the event handler {0} has to be > 0.0."
                .format(self.__class__.__name__))
        self._event_time = end_of_run_time
    def __init__(self, estimator: Estimator, charge: str = None) -> None:
        """
        The constructor of the CompositeObjectCellVetoEventHandler class.

        Parameters
        ----------
        estimator : estimator.Estimator
            The estimator used to determine bounds for the derivatives.
        charge : str or None, optional
            The relevant charge for this event handler.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the charge is not None but the potential expects more than two charges.
        """
        log_init_arguments(logging.getLogger(__name__).debug, self.__class__.__name__,
                           estimator=estimator.__class__.__name__, charge=charge)
        super().__init__(estimator=estimator)
        self._charge = charge
        if charge is None:
            self._charges = lambda unit_one, unit_two: tuple(1.0 for _ in
                                                             range(self._potential.number_charge_arguments))
        else:
            if self._potential.number_charge_arguments == 2:
                self._charges = lambda unit_one, unit_two: (unit_one.charge[charge], unit_two.charge[charge])
            else:
                raise ConfigurationError("The event handler {0} was initialized with a charge which is not None,"
                                         " but its potential {1} expects not exactly 2 charges."
                                         .format(self.__class__.__name__, self._potential.__class__.__name__))
示例#19
0
    def write(self, output_handler: str, *args: Any) -> None:
        """
        Pass the arguments to the output handler.

        The arguments could be for example the full global state so that the output handler can start its sampling.
        This method is called in the mediating methods of event handlers in the mediator. There, each event handler
        defines itself, which methods should be passed to its output handler.
        When the output handlers were built using the JF factory, their names can include an alias. Then the output
        handler name should be this alias.

        Parameters
        ----------
        output_handler : str
            The name of the output handler which should receive the arguments.
        args : Any
            The arguments passed to output handler.

        Raises
        ------
        base.exceptions.ConfigurationError
            If no output handler with the given name exists.
        """
        try:
            self._output_handlers_dictionary[output_handler].write(*args)
        except KeyError:
            raise ConfigurationError(
                "The given output handler {0} does not exist.".format(
                    output_handler))
    def __init__(self, filename: str):
        """
        The constructor of the BondLengthAndAngleOutputHandler class.

        This class uses a HardBufferedTextWriter to first write the bond lengths and angles to temporary files.

        Parameters
        ----------
        filename : str
            The filename of the file this output handler is connected to.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the number of node levels is not two or the number of nodes per root node is not three.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           filename=filename)
        super().__init__(filename)
        filename_dot_position = self._output_filename.rfind('.')
        bond_length_filename = (self._output_filename[:filename_dot_position] +
                                '_Length' +
                                self._output_filename[filename_dot_position:])
        bond_angle_filename = (self._output_filename[:filename_dot_position] +
                               '_Angle' +
                               self._output_filename[filename_dot_position:])
        self._file_bond_lengths = HardBufferedTextWriter(bond_length_filename)
        self._file_bond_angles = HardBufferedTextWriter(bond_angle_filename)
        if setting.number_of_node_levels != 2 or setting.number_of_nodes_per_root_node != 3:
            raise ConfigurationError(
                "The output handler {0} can only be used if each root node has 3 child nodes."
                .format(self.__class__.__name__))
    def __init__(self, potential: Potential, lifting: Lifting, offset: float, max_displacement: float,
                 separations: Sequence[int]) -> None:
        """
        The constructor of the FixedSeparationsEventHandlerWithPiecewiseConstantBoundingPotential class.

        Parameters
        ----------
        potential : potential.Potential
            The potential between the leaf units.
        lifting : lifting.Lifting
            The lifting scheme.
        offset : float
            The offset used to create piecewise constant bounding potential.
        max_displacement : float
            The maximum displacement used to create piecewise constant bounding potential.
        separations : Sequence[int]
            A sequence of integers in the format [i1, j1, i2, j2...in, jn]. The separations passed to the potential
            will be [r_j1 - r_i1, r_j2 - r_i2, ..., r_jn - r_in].

        Raises
        ------
        base.exceptions.ConfigurationError:
            If the separations sequence is not divisible by two.
        base.exceptions.ConfigurationError:
            If the number of separations which can be constructed from the separations sequence does not equal the
            number of separation arguments of the potential.
        """
        log_init_arguments(logging.getLogger(__name__).debug, self.__class__.__name__,
                           potential=potential.__class__.__name__,
                           lifting=lifting.__class__.__name__, offset=offset, max_displacement=max_displacement,
                           separations=separations)
        super().__init__(potential=potential, offset=offset, max_displacement=max_displacement)
        self._lifting = lifting
        self._separations = separations
        if len(self._separations) % 2 != 0:
            raise ConfigurationError("The given array of indices {0} which should be used to calculate the separations"
                                     " handed over to the potential is not divisible by two!".format(separations))
        if self._potential.number_separation_arguments != len(self._separations) // 2:
            raise ConfigurationError("The event handler {0} expects a potential "
                                     "which handles exactly the number of separations specified"
                                     " by the list of identifiers {1} used to calculate these separations"
                                     " (length of the list divided by 2)!"
                                     .format(self.__class__.__name__, self._separations))
        # The charges the potential expects will always be set to 1.0
        self._number_charges = self._potential.number_charge_arguments
示例#22
0
    def __init__(
        self,
        input_output_handler: InputOutputHandler,
        state_handler: StateHandler,
        scheduler: Scheduler,
        activator: Activator,
        number_cores: int = os.cpu_count()) -> None:
        """
        The constructor of the MultiProcessMediator class.

        Parameters
        ----------
        input_output_handler : input_output_handler.InputOutputHandler
            The input-output handler.
        state_handler : state_handler.StateHandler
            The state handler.
        scheduler : scheduler.Scheduler
            The scheduler.
        activator : activator.Activator
            The activator.
        number_cores : int, optional
            The number of cores to use.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the number of cores is not larger than one.
        """
        self._logger = logging.getLogger(__name__)
        self._logger_enabled_for_debug = self._logger.isEnabledFor(
            logging.DEBUG)
        log_init_arguments(
            self._logger.debug,
            self.__class__.__name__,
            input_output_handler=input_output_handler.__class__.__name__,
            state_handler=state_handler.__class__.__name__,
            scheduler=scheduler.__class__.__name__,
            activator=activator.__class__.__name__)
        if not number_cores > 1:
            raise ConfigurationError(
                "The multi processing mediator should only be used "
                "when more than one processor is available.")
        state_handler.initialize(input_output_handler.read())
        super().__init__(input_output_handler, state_handler, scheduler,
                         activator)
        self._event_storage = EventStorage()
        self._number_cores = number_cores
        self._pipes = {}
        self._event_handlers = {}
        self._os_processes = []
        self._start_events = {}
        self._send_out_state_events = {}
        self._event_handlers_state = {}
        for event_handler in self._event_handlers_list:
            event_handler.run_in_process = types.MethodType(
                run_in_process, event_handler)
        self._start_processes()
    def __init__(self, initial_direction_of_motion: int, speed: float,
                 initial_active_identifier: Sequence[int]) -> None:
        """
        The constructor of the InitialChainStartOfRunEventHandler class.

        Parameters
        ----------
        initial_direction_of_motion : int
            The initial direction of motion.
        speed : float
            The initial absolute value of the velocity.
        initial_active_identifier : List[int]
            The global state identifier of the initially active leaf unit.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the initial direction of motion exceeds the dimension.
        base.exceptions.ConfigurationError
            If the speed is not larger than zero.
        """
        log_init_arguments(
            logging.getLogger(__name__).debug,
            self.__class__.__name__,
            initial_direction_of_motion=initial_direction_of_motion,
            speed=speed,
            initial_active_identifier=initial_active_identifier)
        super().__init__()
        if initial_direction_of_motion >= setting.dimension:
            raise ConfigurationError(
                "The index of the initial direction of motion {0} "
                "has to be smaller than the dimension {1} "
                "in the event handler {2}.".format(initial_direction_of_motion,
                                                   setting.dimension,
                                                   self.__class__.__name__))
        if speed <= 0.0:
            raise ConfigurationError(
                "The speed in the event handler {0} should be larger than 0.0."
                .format(self.__class__.__name__))
        self._initial_velocity = [0.0] * setting.dimension
        self._initial_velocity[initial_direction_of_motion] = speed
        self._initial_active_identifier = tuple(initial_active_identifier)
示例#24
0
    def __init__(self, chain_length: float, aim_mode: str) -> None:
        """
        The constructor of the RootLeafUnitActiveSwitcher class.

        The aim mode can have two values:
        1. leaf_unit_active: Switches from the composite object motion to the motion of a single leaf unit.
        2. root_unit_active: Switches from the motion of a single leaf unit to the composite object motion.

        Parameters
        ----------
        chain_length : float
            The time interval of the switching of the modes.
        aim_mode : str
            The aim mode.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the number of nodes per root node is one and therefore no composite objects are present in the run.
        base.exceptions.ConfigurationError:
            If the chain length is not greater than zero.
        base.exceptions.ConfigurationError:
            If the aim_mode was not one of the allowed options.
        """
        log_init_arguments(logging.getLogger(__name__).debug, self.__class__.__name__, chain_length=chain_length,
                           aim_mode=aim_mode)
        super().__init__()
        if not setting.number_of_node_levels > 1:
            raise ConfigurationError("Event handler {0} should only be used when composite point objects are involved."
                                     .format(self.__class__.__name__))
        if not chain_length > 0.0:
            raise ConfigurationError("The chain_length in the event handler {0} has to be > 0.0."
                                     .format(self.__class__.__name__))
        self._chain_length = chain_length
        try:
            self._aim_mode = _Modes[aim_mode]
        except KeyError:
            raise ConfigurationError("Invalid aim mode {0} given in event handler {1}. "
                                     "Only supported aim modes are {2}".format(aim_mode, self.__class__.__name__,
                                                                               [i for i in _Modes]))
        self.send_out_state = getattr(self, "_send_out_state_" + self._aim_mode.name)
示例#25
0
    def __init__(self,
                 create: Sequence[str],
                 trash: Sequence[str],
                 event_handler: CellBoundaryEventHandler,
                 internal_state_label: str,
                 tag: str = None) -> None:
        """
        The constructor of the CellBoundaryTagger class.

        This class uses an internal state and therefore inherits from the TaggerWithInternalState class.
        The internal_state_label should refer to a cell-occupancy system.
        Note that the activate and deactivate sequences are always empty for a tagger of this kind.
        Also there is only one event handler instance in this tagger, since we need to calculate only a single event
        per cell-occupancy system.
        Finally the event handler should be an instance of a CellBoundaryEventHandler.

        Parameters
        ----------
        create : Sequence[str]
            Sequence of tags to create after an event handler of this tagger has committed an event to the global state.
        trash : Sequence[str]
            Sequence of tags to trash after an event handler of this tagger has committed an event to the global state.
        event_handler : event_handler.cell_boundary_event_handler.CellBoundaryEventHandler
            A single event handler instance.
        internal_state_label : str
            The label of the internal state this tagger wants to use.
        tag : str or None, optional
            Tag used in all four lists (also of other taggers). If None, the class name (or the alias set in the
            factory) will be used as the tag.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the event handler is not an instance of a CellBoundaryEventHandler.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           event_handler=event_handler.__class__.__name__,
                           internal_state_label=internal_state_label,
                           create=create,
                           trash=trash,
                           tag=tag)
        if not isinstance(event_handler, CellBoundaryEventHandler):
            raise ConfigurationError(
                "The class {0} can only be used "
                "with the class CellBoundaryEventHandler!".format(
                    self.__class__.__name__))
        super().__init__(create,
                         trash,
                         event_handler,
                         number_event_handlers=1,
                         internal_state_label=internal_state_label,
                         tag=tag)
示例#26
0
    def __init__(self, prefactor: float, equilibrium_separation: float,
                 **kwargs: Any) -> None:
        """
        The constructor of the MexicanHatPotential class.

        This class is designed for cooperative inheritance, meaning that it passes through all unused kwargs in the
        init to the next class in the MRO via super.

        Parameters
        ----------
        prefactor : float
            A general multiplicative prefactor of the potential.
        equilibrium_separation : float
            The absolute value of the separation r_0 where the potential has a minimum.
        kwargs : Any
            Additional kwargs which are passed to the __init__ method of the next class in the MRO.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the general multiplicative prefactor is smaller than or equal to zero.
        base.exceptions.ConfigurationError
            If the equilibrium separation is smaller than or equal to zero.
        """
        super().__init__(prefactor=prefactor, **kwargs)
        self._equilibrium_separation = equilibrium_separation
        self._equilibrium_separation_squared = equilibrium_separation**2
        if not self._prefactor > 0.0:
            raise ConfigurationError(
                "The potential {0} can only be used for cases "
                "where the prefactor"
                " is greater than 0.0!".format(self.__class__.__name__))
        if not self._equilibrium_separation > 0.0:
            raise ConfigurationError(
                "The potential {0} can only be used for an equilibrium separation which is greater"
                " than 0.0!".format(self.__class__.__name__))
示例#27
0
 def _build_tagger_dictionary(
         self, list_attribute: str) -> Dict[Tagger, List[Tagger]]:
     tag_to_tagger_dictionary = {
         tagger.tag: tagger
         for tagger in self._taggers
     }
     tagger_dictionary = {tagger: [] for tagger in self._taggers}
     for tagger in self._taggers:
         for tag in getattr(tagger, list_attribute):
             if tag not in tag_to_tagger_dictionary.keys():
                 raise ConfigurationError(
                     "Given tag '{0}' in the list attribute '{1}'"
                     " of the tagger '{2}' does not exist as a tagger!".
                     format(tag, list_attribute, tagger.tag))
             tagger_dictionary[tagger].append(tag_to_tagger_dictionary[tag])
     return tagger_dictionary
示例#28
0
    def __init__(self, prefactor: float = 1.0, **kwargs: Any) -> None:
        """
        The constructor of the Potential class.

        This constructor tries to initialize the number of separation and charge arguments the derivative method
        gets by inspecting the argument names of this method. For this to work, each separation argument should begin
        with 'separation' and similarly each charge argument should begin with 'charge'. When using a different
        convention in an inhering class, the attributes self._number_separation_arguments and
        self._number_charges_arguments should be set accordingly on initialization.

        This class is designed for cooperative inheritance, meaning that it passes through all unused kwargs in the
        init to the next class in the MRO via super.

        Parameters
        ----------
        prefactor : float, optional
            A general multiplicative prefactor of the potential.
        kwargs : Any
            Additional kwargs which are passed to the __init__ method of the next class in the MRO.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the prefactor equals 0.
        """
        if prefactor == 0.0:
            raise ConfigurationError(
                "Give a prefactor unequal 0.0 as the prefactor for the potential {0}."
                .format(self.__class__.__name__))
        self._prefactor = prefactor
        derivative_signature = inspect.signature(self.derivative)
        number_derivative_arguments = len(derivative_signature.parameters)
        self._number_separation_arguments = len([
            parameter_name
            for parameter_name in derivative_signature.parameters
            if "separation" in parameter_name
        ])
        self._number_charges_arguments = len([
            parameter_name
            for parameter_name in derivative_signature.parameters
            if "charge" in parameter_name
        ])
        if self._number_separation_arguments + self._number_charges_arguments + 1 != number_derivative_arguments:
            # The number of separation and charges arguments is not enough to fill all arguments of derivative method
            self._number_separation_arguments = None
            self._number_charges_arguments = None
        super().__init__(**kwargs)
    def __init__(self,
                 potential: Potential,
                 prefactor: float = 1.5,
                 empirical_bound: float = float('inf'),
                 number_trials: int = 10000,
                 dipole_separation: float = 0.05) -> None:
        """
        The constructor of the InnerPointEstimator class.

        Parameters
        ----------
        potential : potential.Potential
            Potential whose derivative is to be bounded.
        prefactor : float, optional
            A constant which gets multiplied to the bounds.
        empirical_bound : float, optional
            If a bound exceeds this value, this value will be returned instead.
        number_trials : int, optional
            The number of separation samples taken.
        dipole_separation : float, optional
            Separation of the two point masses within the constructed dipole.

        Raises
        ------
        base.exceptions.ConfigurationError
            If the potential derivative method does not expect exactly one separation.
        """
        log_init_arguments(logging.getLogger(__name__).debug,
                           self.__class__.__name__,
                           potential=potential.__class__.__name__,
                           prefactor=prefactor,
                           empirical_bound=empirical_bound,
                           number_trials=number_trials,
                           dipole_separation=dipole_separation)
        super().__init__(potential=potential,
                         prefactor=prefactor,
                         empirical_bound=empirical_bound)
        self._number_trials = number_trials
        self._dipole_separation = dipole_separation
        self._dipole_separation_over_two = dipole_separation / 2
        if self._potential.number_separation_arguments != 1:
            raise ConfigurationError(
                "The estimator {0} expects a potential "
                "which handles exactly one separation!".format(
                    self.__class__.__name__))
示例#30
0
    def __init__(self, input_output_handler: InputOutputHandler, state_handler: StateHandler, scheduler: Scheduler,
                 activator: Activator) -> None:
        """
        The constructor of the MediatorAbstractClass class.

        This method checks for all event handlers which are connected to an output handler (by inheriting from the
        class EventHandlerWithOutputHandler) if the output handler exists in the input-output handler.

        Parameters
        ----------
        input_output_handler : input_output_handler.InputOutputHandler
            The input-output handler.
        state_handler : state_handler.StateHandler
            The state handler.
        scheduler : scheduler.Scheduler
            The scheduler.
        activator : activator.Activator
            The activator.

        Raises
        ------
        base.exceptions.ConfigurationError
            If an output handler of an event handler does not exist in the input-output handler.
        """
        activator.initialize(state_handler.extract_global_state())
        self._input_output_handler = input_output_handler
        self._state_handler = state_handler
        self._scheduler = scheduler
        self._activator = activator
        self._event_handlers_list = activator.event_handlers
        used_output_handlers = []
        for event_handler in self._event_handlers_list:
            if isinstance(event_handler, EventHandlerWithOutputHandler):
                if event_handler.output_handler is None:
                    continue
                if event_handler.output_handler not in self._input_output_handler.output_handlers:
                    raise ConfigurationError("The output handler '{0}' in event handler {1} is not existing."
                                             .format(event_handler.output_handler, event_handler.__class__.__name__))
                used_output_handlers.append(event_handler.output_handler)
        for output_handler in self._input_output_handler.output_handlers:
            if output_handler not in used_output_handlers:
                logging.getLogger(__name__).warning("Created output handler {0} was not used in any event handler."
                                                    .format(output_handler))