INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Update |QFactor| based on |Area| and the current simulation step size.
def update(self): """Update |QFactor| based on |Area| and the current simulation step size. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> area(50.0) >>> derived.qfactor.update() >>> derived.qfactor qfac...
Number of neurons of the hidden layers.
def nmb_neurons(self) -> Tuple[int, ...]: """Number of neurons of the hidden layers. >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=2, nmb_neurons=(2, 1), nmb_outputs=3) >>> ann.nmb_neurons (2, 1) >>> ann.nmb_neurons = (3,) >>> ann.nmb_n...
Shape of the array containing the activation of the hidden neurons.
def shape_weights_hidden(self) -> Tuple[int, int, int]: """Shape of the array containing the activation of the hidden neurons. The first integer value is the number of connection between the hidden layers, the second integer value is maximum number of neurons of all hidden layers feedin...
Number of hidden weights.
def nmb_weights_hidden(self) -> int: """Number of hidden weights. >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3) >>> ann.nmb_weights_hidden 18 """ nmb = 0 for idx_layer in range(self.nmb_l...
Raise a |RuntimeError| if the network s shape is not defined completely.
def verify(self) -> None: """Raise a |RuntimeError| if the network's shape is not defined completely. >>> from hydpy import ANN >>> ANN(None).verify() Traceback (most recent call last): ... RuntimeError: The shape of the the artificial neural network \ parameter ...
Return a string representation of the actual |anntools. ANN| object that is prefixed with the given string.
def assignrepr(self, prefix) -> str: """Return a string representation of the actual |anntools.ANN| object that is prefixed with the given string.""" prefix = '%s%s(' % (prefix, self.name) blanks = len(prefix)*' ' lines = [ objecttools.assignrepr_value( ...
Plot the relationship between a certain input ( idx_input ) and a certain output ( idx_output ) variable described by the actual |anntools. ANN| object.
def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100, **kwargs) -> None: """Plot the relationship between a certain input (`idx_input`) and a certain output (`idx_output`) variable described by the actual |anntools.ANN| object. Define the lower and the upper bou...
Prepare the actual |anntools. SeasonalANN| object for calculations.
def refresh(self) -> None: """Prepare the actual |anntools.SeasonalANN| object for calculations. Dispite all automated refreshings explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| in...
Raise a |RuntimeError| and removes all handled neural networks if the they are defined inconsistently.
def verify(self) -> None: """Raise a |RuntimeError| and removes all handled neural networks, if the they are defined inconsistently. Dispite all automated safety checks explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the in...
The shape of array |anntools. SeasonalANN. ratios|.
def shape(self) -> Tuple[int, ...]: """The shape of array |anntools.SeasonalANN.ratios|.""" return tuple(int(sub) for sub in self.ratios.shape)
Private on purpose.
def _set_shape(self, shape): """Private on purpose.""" try: shape = (int(shape),) except TypeError: pass shp = list(shape) shp[0] = timetools.Period('366d')/self.simulationstep shp[0] = int(numpy.ceil(round(shp[0], 10))) getattr(self.fastac...
A sorted |tuple| of all contained |TOY| objects.
def toys(self) -> Tuple[timetools.TOY, ...]: """A sorted |tuple| of all contained |TOY| objects.""" return tuple(toy for (toy, _) in self)
Call method |anntools. ANN. plot| of all |anntools. ANN| objects handled by the actual |anntools. SeasonalANN| object.
def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100, **kwargs) -> None: """Call method |anntools.ANN.plot| of all |anntools.ANN| objects handled by the actual |anntools.SeasonalANN| object. """ for toy, ann_ in self: ann_.plot(xmin, xmax, ...
The string corresponding to the current values of subgroup state and variable.
def specstring(self): """The string corresponding to the current values of `subgroup`, `state`, and `variable`. >>> from hydpy.core.itemtools import ExchangeSpecification >>> spec = ExchangeSpecification('hland_v1', 'fluxes.qt') >>> spec.specstring 'fluxes.qt' >>...
Apply method |ExchangeItem. insert_variables| to collect the relevant target variables handled by the devices of the given |Selections| object.
def collect_variables(self, selections) -> None: """Apply method |ExchangeItem.insert_variables| to collect the relevant target variables handled by the devices of the given |Selections| object. We prepare the `LahnH` example project to be able to use its |Selections| object: ...
Determine the relevant target or base variables ( as defined by the given |ExchangeSpecification| object ) handled by the given |Selections| object and insert them into the given device2variable dictionary.
def insert_variables( self, device2variable, exchangespec, selections) -> None: """Determine the relevant target or base variables (as defined by the given |ExchangeSpecification| object ) handled by the given |Selections| object and insert them into the given `device2variable` ...
Assign the given value ( s ) to the given target or base variable.
def update_variable(self, variable, value) -> None: """Assign the given value(s) to the given target or base variable. If the assignment fails, |ChangeItem.update_variable| raises an error like the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pu...
Assign the current objects |ChangeItem. value| to the values of the target variables.
def update_variables(self) -> None: """Assign the current objects |ChangeItem.value| to the values of the target variables. We use the `LahnH` project in the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() ...
Apply method |ChangeItem. collect_variables| of the base class |ChangeItem| and also apply method |ExchangeItem. insert_variables| of class |ExchangeItem| to collect the relevant base variables handled by the devices of the given |Selections| object.
def collect_variables(self, selections) -> None: """Apply method |ChangeItem.collect_variables| of the base class |ChangeItem| and also apply method |ExchangeItem.insert_variables| of class |ExchangeItem| to collect the relevant base variables handled by the devices of the given |Selecti...
Add the general |ChangeItem. value| with the |Device| specific base variable and assign the result to the respective target variable.
def update_variables(self) -> None: """Add the general |ChangeItem.value| with the |Device| specific base variable and assign the result to the respective target variable. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >...
Apply method |ExchangeItem. collect_variables| of the base class |ExchangeItem| and determine the ndim attribute of the current |ChangeItem| object afterwards.
def collect_variables(self, selections) -> None: """Apply method |ExchangeItem.collect_variables| of the base class |ExchangeItem| and determine the `ndim` attribute of the current |ChangeItem| object afterwards. The value of `ndim` depends on whether the values of the target va...
Sequentially return name - value - pairs describing the current state of the target variables.
def yield_name2value(self, idx1=None, idx2=None) \ -> Iterator[Tuple[str, str]]: """Sequentially return name-value-pairs describing the current state of the target variables. The names are automatically generated and contain both the name of the |Device| of the respective |V...
Returns the weekday s name given a ISO weekday number ; today if today is the same weekday.
def iso_day_to_weekday(d): """ Returns the weekday's name given a ISO weekday number; "today" if today is the same weekday. """ if int(d) == utils.get_now().isoweekday(): return _("today") for w in WEEKDAYS: if w[0] == int(d): return w[1]
Returns False if the location is closed or the OpeningHours object to show the location is currently open.
def is_open(location=None, attr=None): """ Returns False if the location is closed, or the OpeningHours object to show the location is currently open. """ obj = utils.is_open(location) if obj is False: return False if attr is not None: return getattr(obj, attr) return obj
Returns False if the location is closed or the OpeningHours object to show the location is currently open. Same as is_open but passes now to utils. is_open to bypass get_now ().
def is_open_now(location=None, attr=None): """ Returns False if the location is closed, or the OpeningHours object to show the location is currently open. Same as `is_open` but passes `now` to `utils.is_open` to bypass `get_now()`. """ obj = utils.is_open(location, now=datetime.datetime.now()) ...
Creates a rendered listing of hours.
def opening_hours(location=None, concise=False): """ Creates a rendered listing of hours. """ template_name = 'openinghours/opening_hours_list.html' days = [] # [{'hours': '9:00am to 5:00pm', 'name': u'Monday'}, {'hours... # Without `location`, choose the first company. if location: ...
Convenience method to make the actual |HydPy| instance runable.
def prepare_everything(self): """Convenience method to make the actual |HydPy| instance runable.""" self.prepare_network() self.init_models() self.load_conditions() with hydpy.pub.options.warnmissingobsfile(False): self.prepare_nodeseries() self.prepare_models...
Load all network files as |Selections| ( stored in module |pub| ) and assign the complete selection to the |HydPy| object.
def prepare_network(self): """Load all network files as |Selections| (stored in module |pub|) and assign the "complete" selection to the |HydPy| object.""" hydpy.pub.selections = selectiontools.Selections() hydpy.pub.selections += hydpy.pub.networkmanager.load_files() self.update...
Call method |Elements. save_controls| of the |Elements| object currently handled by the |HydPy| object.
def save_controls(self, parameterstep=None, simulationstep=None, auxfiler=None): """Call method |Elements.save_controls| of the |Elements| object currently handled by the |HydPy| object. We use the `LahnH` example project to demonstrate how to write a complete set ...
Print out some properties of the network defined by the |Node| and |Element| objects currently handled by the |HydPy| object.
def networkproperties(self): """Print out some properties of the network defined by the |Node| and |Element| objects currently handled by the |HydPy| object.""" print('Number of nodes: %d' % len(self.nodes)) print('Number of elements: %d' % len(self.elements)) print('Number of en...
The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object.
def numberofnetworks(self): """The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object.""" sels1 = selectiontools.Selections() sels2 = selectiontools.Selections() complete = selectiontools.Selection('complete', ...
|Nodes| object containing all |Node| objects currently handled by the |HydPy| object which define a downstream end point of a network.
def endnodes(self): """|Nodes| object containing all |Node| objects currently handled by the |HydPy| object which define a downstream end point of a network.""" endnodes = devicetools.Nodes() for node in self.nodes: for element in node.exits: if ((element in s...
Sorted list of strings summarizing all variables handled by the |Node| objects
def variables(self): """Sorted list of strings summarizing all variables handled by the |Node| objects""" variables = set([]) for node in self.nodes: variables.add(node.variable) return sorted(variables)
Tuple containing the start and end index of the simulation period regarding the initialization period defined by the |Timegrids| object stored in module |pub|.
def simindices(self): """Tuple containing the start and end index of the simulation period regarding the initialization period defined by the |Timegrids| object stored in module |pub|.""" return (hydpy.pub.timegrids.init[hydpy.pub.timegrids.sim.firstdate], hydpy.pub.timeg...
Call method |Devices. open_files| of the |Nodes| and |Elements| objects currently handled by the |HydPy| object.
def open_files(self, idx=0): """Call method |Devices.open_files| of the |Nodes| and |Elements| objects currently handled by the |HydPy| object.""" self.elements.open_files(idx=idx) self.nodes.open_files(idx=idx)
Determines the order in which the |Node| and |Element| objects currently handled by the |HydPy| objects need to be processed during a simulation time step. Optionally a |Selection| object for defining new |Node| and |Element| objects can be passed.
def update_devices(self, selection=None): """Determines the order, in which the |Node| and |Element| objects currently handled by the |HydPy| objects need to be processed during a simulation time step. Optionally, a |Selection| object for defining new |Node| and |Element| objects can be...
A list containing all methods of all |Node| and |Element| objects that need to be processed during a simulation time step in the order they must be called.
def methodorder(self): """A list containing all methods of all |Node| and |Element| objects that need to be processed during a simulation time step in the order they must be called.""" funcs = [] for node in self.nodes: if node.deploymode == 'oldsim': ...
Perform a simulation run over the actual simulation time period defined by the |Timegrids| object stored in module |pub|.
def doit(self): """Perform a simulation run over the actual simulation time period defined by the |Timegrids| object stored in module |pub|.""" idx_start, idx_end = self.simindices self.open_files(idx_start) methodorder = self.methodorder for idx in printtools.progressbar...
Update the inlet link sequence.
def pic_inflow_v1(self): """Update the inlet link sequence. Required inlet sequence: |dam_inlets.Q| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q` """ flu = self.sequences.fluxes.fastaccess inl = self.sequences.inlets.fastaccess flu.inflow = in...
Update the inlet link sequences.
def pic_inflow_v2(self): """Update the inlet link sequences. Required inlet sequences: |dam_inlets.Q| |dam_inlets.S| |dam_inlets.R| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q + S + R` """ flu = self.sequences.fluxes.fastaccess inl = ...
Update the receiver link sequence.
def pic_totalremotedischarge_v1(self): """Update the receiver link sequence.""" flu = self.sequences.fluxes.fastaccess rec = self.sequences.receivers.fastaccess flu.totalremotedischarge = rec.q[0]
Update the receiver link sequence.
def pic_loggedrequiredremoterelease_v1(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.d[0]
Update the receiver link sequence.
def pic_loggedrequiredremoterelease_v2(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.s[0]
Update the receiver link sequence.
def pic_loggedallowedremoterelieve_v1(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedallowedremoterelieve[0] = rec.r[0]
Log a new entry of discharge at a cross section far downstream.
def update_loggedtotalremotedischarge_v1(self): """Log a new entry of discharge at a cross section far downstream. Required control parameter: |NmbLogEntries| Required flux sequence: |TotalRemoteDischarge| Calculated flux sequence: |LoggedTotalRemoteDischarge| Example: ...
Determine the water level based on an artificial neural network describing the relationship between water level and water stage.
def calc_waterlevel_v1(self): """Determine the water level based on an artificial neural network describing the relationship between water level and water stage. Required control parameter: |WaterVolume2WaterLevel| Required state sequence: |WaterVolume| Calculated aide sequence: ...
Calculate the allowed maximum relieve another location is allowed to discharge into the dam.
def calc_allowedremoterelieve_v2(self): """Calculate the allowed maximum relieve another location is allowed to discharge into the dam. Required control parameters: |HighestRemoteRelieve| |WaterLevelRelieveThreshold| Required derived parameter: |WaterLevelRelieveSmoothPar| Requi...
Calculate the required maximum supply from another location that can be discharged into the dam.
def calc_requiredremotesupply_v1(self): """Calculate the required maximum supply from another location that can be discharged into the dam. Required control parameters: |HighestRemoteSupply| |WaterLevelSupplyThreshold| Required derived parameter: |WaterLevelSupplySmoothPar| Requ...
Try to estimate the natural discharge of a cross section far downstream based on the last few simulation steps.
def calc_naturalremotedischarge_v1(self): """Try to estimate the natural discharge of a cross section far downstream based on the last few simulation steps. Required control parameter: |NmbLogEntries| Required log sequences: |LoggedTotalRemoteDischarge| |LoggedOutflow| Calculate...
Estimate the discharge demand of a cross section far downstream.
def calc_remotedemand_v1(self): """Estimate the discharge demand of a cross section far downstream. Required control parameter: |RemoteDischargeMinimum| Required derived parameters: |dam_derived.TOY| Required flux sequence: |dam_derived.TOY| Calculated flux sequence: |Rem...
Estimate the shortfall of actual discharge under the required discharge of a cross section far downstream.
def calc_remotefailure_v1(self): """Estimate the shortfall of actual discharge under the required discharge of a cross section far downstream. Required control parameters: |NmbLogEntries| |RemoteDischargeMinimum| Required derived parameters: |dam_derived.TOY| Required log sequen...
Guess the required release necessary to not fall below the threshold value at a cross section far downstream with a certain level of certainty.
def calc_requiredremoterelease_v1(self): """Guess the required release necessary to not fall below the threshold value at a cross section far downstream with a certain level of certainty. Required control parameter: |RemoteDischargeSafety| Required derived parameters: |RemoteDischargeSmoot...
Get the required remote release of the last simulation step.
def calc_requiredremoterelease_v2(self): """Get the required remote release of the last simulation step. Required log sequence: |LoggedRequiredRemoteRelease| Calculated flux sequence: |RequiredRemoteRelease| Basic equation: :math:`RequiredRemoteRelease = LoggedRequiredRemoteRelease`...
Get the allowed remote relieve of the last simulation step.
def calc_allowedremoterelieve_v1(self): """Get the allowed remote relieve of the last simulation step. Required log sequence: |LoggedAllowedRemoteRelieve| Calculated flux sequence: |AllowedRemoteRelieve| Basic equation: :math:`AllowedRemoteRelieve = LoggedAllowedRemoteRelieve` ...
Calculate the total water release ( immediately and far downstream ) required for reducing drought events.
def calc_requiredrelease_v1(self): """Calculate the total water release (immediately and far downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameters: |NearDischargeMinimumSmoothPar2| |dam_derived.TOY| ...
Calculate the water release ( immediately downstream ) required for reducing drought events.
def calc_requiredrelease_v2(self): """Calculate the water release (immediately downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameter: |dam_derived.TOY| Calculated flux sequence: |RequiredRelease| ...
Calculate the highest possible water release that can be routed to a remote location based on an artificial neural network describing the relationship between possible release and water stage.
def calc_possibleremoterelieve_v1(self): """Calculate the highest possible water release that can be routed to a remote location based on an artificial neural network describing the relationship between possible release and water stage. Required control parameter: |WaterLevel2PossibleRemoteReliev...
Calculate the actual amount of water released to a remote location to relieve the dam during high flow conditions.
def calc_actualremoterelieve_v1(self): """Calculate the actual amount of water released to a remote location to relieve the dam during high flow conditions. Required control parameter: |RemoteRelieveTolerance| Required flux sequences: |AllowedRemoteRelieve| |PossibleRemoteRelieve| ...
Calculate the targeted water release for reducing drought events taking into account both the required water release and the actual inflow into the dam.
def calc_targetedrelease_v1(self): """Calculate the targeted water release for reducing drought events, taking into account both the required water release and the actual inflow into the dam. Some dams are supposed to maintain a certain degree of low flow variability downstream. In case parameter ...
Calculate the actual water release that can be supplied by the dam considering the targeted release and the given water level.
def calc_actualrelease_v1(self): """Calculate the actual water release that can be supplied by the dam considering the targeted release and the given water level. Required control parameter: |WaterLevelMinimumThreshold| Required derived parameters: |WaterLevelMinimumSmoothPar| Require...
Calculate the portion of the required remote demand that could not be met by the actual discharge release.
def calc_missingremoterelease_v1(self): """Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation:...
Calculate the actual remote water release that can be supplied by the dam considering the required remote release and the given water level.
def calc_actualremoterelease_v1(self): """Calculate the actual remote water release that can be supplied by the dam considering the required remote release and the given water level. Required control parameter: |WaterLevelMinimumRemoteThreshold| Required derived parameters: |WaterLevelMini...
Constrain the actual relieve discharge to a remote location.
def update_actualremoterelieve_v1(self): """Constrain the actual relieve discharge to a remote location. Required control parameter: |HighestRemoteDischarge| Required derived parameter: |HighestRemoteSmoothPar| Updated flux sequence: |ActualRemoteRelieve| Basic equation - disco...
Calculate the discharge during and after a flood event based on an |anntools. SeasonalANN| describing the relationship ( s ) between discharge and water stage.
def calc_flooddischarge_v1(self): """Calculate the discharge during and after a flood event based on an |anntools.SeasonalANN| describing the relationship(s) between discharge and water stage. Required control parameter: |WaterLevel2FloodDischarge| Required derived parameter: |dam_deri...
Calculate the total outflow of the dam.
def calc_outflow_v1(self): """Calculate the total outflow of the dam. Note that the maximum function is used to prevent from negative outflow values, which could otherwise occur within the required level of numerical accuracy. Required flux sequences: |ActualRelease| |FloodDischarge| ...
Update the actual water volume.
def update_watervolume_v1(self): """Update the actual water volume. Required derived parameter: |Seconds| Required flux sequences: |Inflow| |Outflow| Updated state sequence: |WaterVolume| Basic equation: :math:`\\frac{d}{dt}WaterVolume = 1e-6 \\cdot (Inflow-Outflow)...
Update the outlet link sequence |dam_outlets. Q|.
def pass_outflow_v1(self): """Update the outlet link sequence |dam_outlets.Q|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.q[0] += flu.outflow
Update the outlet link sequence |dam_outlets. S|.
def pass_actualremoterelease_v1(self): """Update the outlet link sequence |dam_outlets.S|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.s[0] += flu.actualremoterelease
Update the outlet link sequence |dam_outlets. R|.
def pass_actualremoterelieve_v1(self): """Update the outlet link sequence |dam_outlets.R|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.r[0] += flu.actualremoterelieve
Update the outlet link sequence |dam_senders. D|.
def pass_missingremoterelease_v1(self): """Update the outlet link sequence |dam_senders.D|.""" flu = self.sequences.fluxes.fastaccess sen = self.sequences.senders.fastaccess sen.d[0] += flu.missingremoterelease
Update the outlet link sequence |dam_outlets. R|.
def pass_allowedremoterelieve_v1(self): """Update the outlet link sequence |dam_outlets.R|.""" flu = self.sequences.fluxes.fastaccess sen = self.sequences.senders.fastaccess sen.r[0] += flu.allowedremoterelieve
Update the outlet link sequence |dam_outlets. S|.
def pass_requiredremotesupply_v1(self): """Update the outlet link sequence |dam_outlets.S|.""" flu = self.sequences.fluxes.fastaccess sen = self.sequences.senders.fastaccess sen.s[0] += flu.requiredremotesupply
Log a new entry of discharge at a cross section far downstream.
def update_loggedoutflow_v1(self): """Log a new entry of discharge at a cross section far downstream. Required control parameter: |NmbLogEntries| Required flux sequence: |Outflow| Calculated flux sequence: |LoggedOutflow| Example: The following example shows that, with...
( Re ) calculate the MA coefficients based on the instantaneous unit hydrograph.
def update_coefs(self): """(Re)calculate the MA coefficients based on the instantaneous unit hydrograph.""" coefs = [] sum_coefs = 0. moment1 = self.iuh.moment1 for t in itertools.count(0., 1.): points = (moment1 % 1,) if t <= moment1 <= (t+2.) else () ...
Turning point ( index and value tuple ) in the recession part of the MA approximation of the instantaneous unit hydrograph.
def turningpoint(self): """Turning point (index and value tuple) in the recession part of the MA approximation of the instantaneous unit hydrograph.""" coefs = self.coefs old_dc = coefs[1]-coefs[0] for idx in range(self.order-2): new_dc = coefs[idx+2]-coefs[idx+1] ...
The first two time delay weighted statistical moments of the MA coefficients.
def moments(self): """The first two time delay weighted statistical moments of the MA coefficients.""" moment1 = statstools.calc_mean_time(self.delays, self.coefs) moment2 = statstools.calc_mean_time_deviation( self.delays, self.coefs, moment1) return numpy.array([mom...
The maximum number of AR coefficients that shall or can be determined.
def effective_max_ar_order(self): """The maximum number of AR coefficients that shall or can be determined. It is the minimum of |ARMA.max_ar_order| and the number of coefficients of the pure |MA| after their turning point. """ return min(self.max_ar_order, self.ma.order...
Determine the AR coefficients.
def update_ar_coefs(self): """Determine the AR coefficients. The number of AR coefficients is subsequently increased until the required precision |ARMA.max_rel_rmse| is reached. Otherwise, a |RuntimeError| is raised. """ del self.ar_coefs for ar_order in range(1...
Sum of the absolute deviations between the central moments of the instantaneous unit hydrograph and the ARMA approximation.
def dev_moments(self): """Sum of the absolute deviations between the central moments of the instantaneous unit hydrograph and the ARMA approximation.""" return numpy.sum(numpy.abs(self.moments-self.ma.moments))
Multiply all coefficients by the same factor so that their sum becomes one.
def norm_coefs(self): """Multiply all coefficients by the same factor, so that their sum becomes one.""" sum_coefs = self.sum_coefs self.ar_coefs /= sum_coefs self.ma_coefs /= sum_coefs
The sum of all AR and MA coefficients
def sum_coefs(self): """The sum of all AR and MA coefficients""" return numpy.sum(self.ar_coefs) + numpy.sum(self.ma_coefs)
Determine the AR coeffcients based on a least squares approach.
def calc_all_ar_coefs(self, ar_order, ma_model): """Determine the AR coeffcients based on a least squares approach. The argument `ar_order` defines the number of AR coefficients to be determined. The argument `ma_order` defines a pure |MA| model. The least squares approach is applied o...
Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least squares approach applied in method |ARMA. update_ar_coefs|.
def get_a(values, n): """Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least squares approach applied in method |ARMA.update_ar_coefs|. """ m = len(values)-n a = numpy.empty((m, n), dtype=float)...
Determine the MA coefficients.
def update_ma_coefs(self): """Determine the MA coefficients. The number of MA coefficients is subsequently increased until the required precision |ARMA.max_dev_coefs| is reached. Otherwise, a |RuntimeError| is raised. """ self.ma_coefs = [] for ma_order in range...
Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model.
def calc_next_ma_coef(self, ma_order, ma_model): """Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model. The MA coefficients are determined one at a time, beginning with the first one. Each ARMA...
Return the response to a standard dt impulse.
def response(self): """Return the response to a standard dt impulse.""" values = [] sum_values = 0. ma_coefs = self.ma_coefs ar_coefs = self.ar_coefs ma_order = self.ma_order for idx in range(len(self.ma.delays)): value = 0. if idx < ma_ord...
The first two time delay weighted statistical moments of the ARMA response.
def moments(self): """The first two time delay weighted statistical moments of the ARMA response.""" timepoints = self.ma.delays response = self.response moment1 = statstools.calc_mean_time(timepoints, response) moment2 = statstools.calc_mean_time_deviation( t...
Barplot of the ARMA response.
def plot(self, threshold=None, **kwargs): """Barplot of the ARMA response.""" try: # Works under matplotlib 3. pyplot.bar(x=self.ma.delays+.5, height=self.response, width=1., fill=False, **kwargs) except TypeError: # pragma: no cover #...
Returns the Cython method header for methods without arguments except self.
def method_header(method_name, nogil=False, idx_as_arg=False): """Returns the Cython method header for methods without arguments except `self`.""" if not config.FASTCYTHON: nogil = False header = 'cpdef inline void %s(self' % method_name header += ', int idx)' if idx_as_arg else ')' head...
The decorated method will return a |Lines| object including a method header. However the |Lines| object will be empty if the respective model does not implement a method with the same name as the wrapped method.
def decorate_method(wrapped): """The decorated method will return a |Lines| object including a method header. However, the |Lines| object will be empty if the respective model does not implement a method with the same name as the wrapped method. """ def wrapper(self): lines = Lines() ...
Appends the given text line with prefixed spaces in accordance with the given number of indentation levels.
def add(self, indent, line): """Appends the given text line with prefixed spaces in accordance with the given number of indentation levels. """ if isinstance(line, str): list.append(self, indent*4*' ' + line) else: for subline in line: list...
Name of the compiled module.
def pyname(self): """Name of the compiled module.""" if self.pymodule.endswith('__init__'): return self.pymodule.split('.')[-2] else: return self.pymodule.split('.')[-1]
Update the pyx file.
def pyxwriter(self): """Update the pyx file.""" model = self.Model() if hasattr(self, 'Parameters'): model.parameters = self.Parameters(vars(self)) else: model.parameters = parametertools.Parameters(vars(self)) if hasattr(self, 'Sequences'): mo...
All source files of the actual models Python classes and their respective base classes.
def pysourcefiles(self): """All source files of the actual models Python classes and their respective base classes.""" sourcefiles = set() for (name, child) in vars(self).items(): try: parents = inspect.getmro(child) except AttributeError: ...
True if at least one of the |Cythonizer. pysourcefiles| is newer than the compiled file under |Cythonizer. pyxfilepath| otherwise False.
def outdated(self): """True if at least one of the |Cythonizer.pysourcefiles| is newer than the compiled file under |Cythonizer.pyxfilepath|, otherwise False. """ if hydpy.pub.options.forcecompiling: return True if os.path.split(hydpy.__path__[0])[-2].endswith...
Translate cython code to C code and compile it.
def compile_(self): """Translate cython code to C code and compile it.""" from Cython import Build argv = copy.deepcopy(sys.argv) sys.argv = [sys.argv[0], 'build_ext', '--build-lib='+self.buildpath] exc_modules = [ distutils.extension.Extension( ...
Try to find the resulting dll file and to move it into the cythons package.
def move_dll(self): """Try to find the resulting dll file and to move it into the `cythons` package. Things to be aware of: * The file extension either `pyd` (Window) or `so` (Linux). * The folder containing the dll file is system dependent, but is always a subfo...
Constants declaration lines.
def constants(self): """Constants declaration lines.""" lines = Lines() for (name, member) in vars(self.cythonizer).items(): if (name.isupper() and (not inspect.isclass(member)) and (type(member) in TYPE2STR)): ndim = numpy.arra...
Parameter declaration lines.
def parameters(self): """Parameter declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Parameters(object):') for subpars in self.model.parameters: if subpars: lines.add(1, 'cdef public %s %s' ...
Sequence declaration lines.
def sequences(self): """Sequence declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Sequences(object):') for subseqs in self.model.sequences: lines.add(1, 'cdef public %s %s' % (objecttools.classname(s...