RUFAS.routines.animal.ration.ration_optimizer module#

class RUFAS.routines.animal.ration.ration_optimizer.RationOptimizer#

Bases: object

Nonlinear programming methods to optimize a ration by comparing feed supply and animal requirements

Constraints are defined here as the animal requirements subtracted from the feed supply (for a given

attempted ‘solution’)

The difference is then used in scipy.minimize to ensure that the attempted supply meets the requirements If supply meets requirements, then the solution is a ‘success’

Unmet requirements are checked here to report to users

__init__() None#

initializes RationOptimizer object

set_constraints(arguments: Tuple[RationConfig]) None#
static objective(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the objective function in the optimize function for the non-linear program. Whenever the paramert x is used, it refers to the “decision vetor of the NLP” which means it is a list of solutions where each value in the list corresponds to the amount of a given feed (kg) in the formulated diet. The goal of this NLP is to minimize the cost of all feeds while satisfying all “constraints”, which just means the diet fulfills the average nutrient requirements in the pen.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP.

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization.

Returns#

float

static total_energy(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for the sum of the lactation, pregnancy, maintenance, and activity requirements satisfied by the feed. Each equation has a reference to the respective calculation in the pseudo code. The global variables are a temporary measure until the completion of the ration refactor

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is greater than the requirement for total net energy.

static NEmact_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for the maintenance and activity requirements satisfied by the feed. Each equation has a reference to the respective calculation in the pseudo code. The global variables defined in the begining of this function are used in future functions.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float
Non-negative value indicates that supply is greater than the requirement for net energy for maintenance

and activity.

static NEl_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for the lactation and pregnancy requirements satisfied by each feed. Each calculation has a reference to the respective calculation in the pseudocode. Note to eliminate code repetition the global variable MEact is used (calculated in NEmact_constraint).

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float
Non-negative value indicates that supply is greater than the requirement for net energy for pregnancy

and lactation.

static NEgact_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for the growth requirements satisfied by each feed. Each calculation has a reference to the respective calculation in the pseudocode. Note to eliminate code repetition the global variable MEact is used (calculated in NEmact_constraint).

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is greater than the requirement for net energy for growth.

static calcium_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for the calcium requirements satisfied by each feed. Each calculation has a reference to the respective calculation in the pseudocode. Note the calculated calcium requirement ‘C_req’ is in grams and x is in kg thus the divide by 1000.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

static phosphorus_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for the phosphorus requirements satisfied by each feed. Each calculation has a reference to the respective calculation in the pseudocode. Note the calculated phosphorus requirement ‘P_requirement’ is in grams and the formualted ration is reported in kg.

Uses both the requirement value calculated by NRC/NASEM and the one calculated in the phosphorus_rqmts methods in each animal type class (uses suffix _process).

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

static protein_constraint_lower(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the protein requirement constraint in the NLP. Because part of the maintenance requirement for protein contains non-linearity properties, that requirement will be calculated in this function. Each calculation has a reference to the respective calculation in the pseudocode.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is greater than the lower protein limit.

static protein_constraint_upper(decision_vector: ndarray, ration_config: RationConfig) float#

Sets up the upper bound for the protein requirement constraint in the non-linear programming (NLP). Uses MP_supply as calculated in protein_constraint_lower.

This upper limit is calculated by multipling the PROTEIN_UPPER_LIMIT_FACTOR in AnimalModuleConstants

by the protein requirement.

Parameters#

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is below the upper protein limit.

static NDF_constraint_lower(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for each feed to instill an overall NDF percent constraint. This is a lower bound constraint on overall NDF percent. To avoid division by 0 error, returns -1 (fail state) in cases where DMI is equivalent to 0.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that neutral detergent fiber content is greater than 25% of DMI.

static NDF_constraint_upper(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for each feed to instill an overall NDF percent constraint. This is an upper bound constraint on overall NDF percent. To avoid division by 0 error, returns -1 (fail state) in cases where DMI is equivalent to 0.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP.

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization.

Returns#

float

Non-negative value indicates that neutral detergent fiber content is less than 45% of DMI.

static forage_NDF_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for only FORAGES to instill a NDF percent across forages constraint. This is a lower bound constraint on NDF percent across forages. To avoid division by 0 error, returns -1 (fail state) in cases where DMI is equivalent to 0.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP.

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization.

Returns#

float

Non-negative value indicates that NDF supply is greater than 15%.

static fat_constraint(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Sets up the RHS multipliers for each feed to instill an overall fat percent constraint. This is an upper bound constraint on over fat percent. To avoid division by 0 error, returns -1 (fail state) in cases where DMI is equivalent to 0.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is greater than 7%.

static DMI_constraint_lower(decision_vector: ndarray[tuple[int, ...], dtype[float64]], ration_config: RationConfig) float#

Constraint in place to make sure the sum of all the feeds in the ration is greater than the DMI_est + DMI_CONSTRAINT_PERCENT calculated in the requirements

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP.

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization.

Returns#

float

Non-negative value indicates that supply is greater than the DMI minimum.

static DMI_constraint_upper(decision_vector: ndarray[tuple[int, ...], dtype[float64]] | List[float], ration_config: RationConfig) float#

Constraint in place to make sure the sum of all the feeds in the ration is less than the DMI_est + DMI_CONSTRAINT_PERCENT calculated in the requirements.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is less than the DMI maximum.

static get_ration_vals(decision_vector: ndarray[tuple[int, ...], dtype[float64]] | List[float], ration_config: RationConfig) Dict[str, float]#

Function that calculates and retrieves ration values used throughout the ration.

Parameters#

decision_vectornumpy.ndarray

The decision vector of the NLP

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

Dict[str, float]

static make_user_bounds(ration_percents: Dict[str, float], DMIest: float) List[Tuple[float, float]]#

Calculates user bounds for optimize function

Uses udrm object to get tolerance, e.g. the +/- percentage allowed around those. Returns a list of each key/value pair three times, but divided by three

This return in triplicate is necessary for the scipy.minimize function, which requires the decision vector in this shape

Parameters#

ration_percents: Dict[str, float]

keys are feed IDs, values are percent of DMI

DMIest: float

average estimated DMI for pen

Returns#

List

List of each bound, divided by three and reported in triplicate for scipy.minimize function

optimize(animal_combination: AnimalCombination, ration_config: RationConfig, previous_ration: Dict[str, float | str] | None = None) OptimizeResult#

Calls the objective function and constraint functions and formulates the inputs for the minimization function. Returns the optimized solution as a dictionary with feed keys corresponding to their ration (kg).

Parameters#

animal_combinationAnimalCombination

enum of ‘AnimalCombination’, e.g. The animal combination to optimize the ration for.

ration_configRationConfig object

Attributes are animal requirement and feed supply information required for optimization

previous_rationDict[str, float | str] | None

Ration from previous month, if applicable.

Returns#

OptimizeResult object from scipy package

Raises#

ValueError

If the animal combination is invalid.

attempt_optimization(requirements: AnimalRequirements, available_feeds: AvailableFeedsTypedDict, animal_combination: AnimalCombination, previous_ration: Dict[str, float | str] | None = None) Tuple[OptimizeResult | None, Dict[str, float] | None, RationConfig]#

Function that sets up the nutrients and requirements lists into structured inputs for the non-linear program and calls the optimization function.

Parameters#

requirements: AnimalRequirements

Summary of requirements for a group of animals.

available_feedsDict

A DefaultDict of the AvailableFeeds class attributes defined in ration_driver.py

animal_combinationAnimalCombination

Enum of ‘AnimalCombination’, e.g. The animal combination to optimize the ration for.

previous_rationDict[str, float | str] | None

Ration from previous month, if applicable.

Returns#

OptimizeResult

Scipy object with information regarding the minimization attempt.

Dict[str, float]

RationConfig

RationCofig object.

static is_constraint_violated(solution_x: ndarray[tuple[int, ...], dtype[float64]], constraint: Dict[str, Callable[[Any, Any], float] | Tuple[RationConfig] | str], ration_config: RationConfig) bool#
Helper function to check a solution dictionary to see if a given constraint

in a list of constraints was met.

Parameters#

solution_x: numpy nd array, e.g. npt.NDArray

solution.x array from minimize function used in ration_NLP.py

constraint: dict[str, Any]

constraint function as defined in ration_NLP.py

ration_configRationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

bool

True if the constraint method was not met.

static find_failed_constraints(solution_x: ndarray[tuple[int, ...], dtype[float64]], constraints: List[Dict[str, Callable[[Any, Any], float]]], ration_config: RationConfig) List[Dict[str, Callable[[Any, Any], float]]]#

Returns list of constraints that were not met during optmization step.

Parameters#

solution_x: numpy nd array, e.g. npt.NDArray
solution.x is from minimize function used in ration_NLP.py,

solution obj itself is returned as <dict class ‘scipy.optimize._optimize.OptimizeResult’>

constraints: List[dict[str, Callable]]

list of constraint functions as defined in ration_NLP.py

ration_configRationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

List[dict[str,Callable]]
the same type of list as the constraints themselves

just filtered such that the ones that failed are returned