RUFAS.biophysical.animal.ration.ration_optimizer module#

class RUFAS.biophysical.animal.ration.ration_optimizer.RationConfig(animal_requirements: NutritionRequirements = None, pen_available_feeds: List[Feed] = [], pen_average_body_weight: float = 0)#

Bases: object

RationConfig provides a structured way to represent the collection of animal requirements and feed supply information for the ration formulation process.

Attributes#

animal_requirementsNutritionRequirements

Nutrition requirements for pen, used in constraint methods.

pen_average_body_weightfloat

Average body weight in pen, used in constraint methods.

feeds_usedList[Feed]

List of Feeds used in ration formulation.

price_listList[float]

Price for each feed used in ration formulation.

feed_minimum_listList[float]

Minimum amount allowed for each feed used in formulation, kg.

feed_maximum_listList[float]

Maxmimum amount allowed for each feed used in formulation, kg.

TDN_listList[float]

TDN for each feed used in ration formulation.

NDF_list: List[float]

NDF for each feed used in ration formulation.

EE_listList[float]

EE for each feed used in ration formulation.

__init__(animal_requirements: NutritionRequirements = None, pen_available_feeds: List[Feed] = [], pen_average_body_weight: float = 0) None#

Initialize the RationConfig class with the provided feed information. If the input is a list, it should have a length corresponding to the decision vector.

Parameters#

animal_requirementsNutritionRequirements

Nutrition requirements for pen, used in constraint methods.

pen_available_feedsList[Feed]

List of Feeds used in ration formulation.

pen_average_body_weightfloat

Average body weight in pen, used in constraint methods.

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

Bases: object

Nonlinear programming methods to optimally formulate a ration by comparing feed supply and the requirements for animals in a given pen.

This class sets an objective, defines constraints, attempts optimization using scipy’s minimize method, and reports unsuccessful optimization attempts to the user.

Constraint methods compare the supply of an attempted ration to specific limits on a per nutrient/energy basis.

For constraints with lower thresholds, the minimum value is subtracted from the supply.

For constraints with upper thresholds, the supply is subtracted from the maximum value.

In either case, if the difference is non negative, then the solution is considered a ‘success’ in scipy.minimize.

__init__() None#

Initializes RationOptimizer object

set_constraints(arguments: Tuple[RationConfig]) None#

Defines lists of constraint methods to use for different pens.

Parameters#

argumentsTuple[RationConfig]

RationConfig used in constraint methods.

static convert_decision_vec_to_feeds(ration_configuration: RationConfig, decision_vector: ndarray[tuple[int, ...], dtype[float64]]) List[FeedInRation]#

Converts the decision vector to a Feeds object for use in NutritionSupplyCalculator methods.

Parameters#

ration_configuration: RationConfig object

Stored information relevant to ration formulation.

decision_vectornumpy.ndarray

The decision vector used in scipy.minimize.

Returns#

List[FeedInRation]

List of feeds and their attributes used in ration formulation.

classmethod make_ration_from_solution(pen_available_feeds: List[Feed], solution: OptimizeResult) Dict[str, float | str]#

Generates ration from scipy result.

Parameters#

pen_available_feedsList[Feed]

List of Feeds used in ration formulation.

solutionOptimizeResult

Object from scipy package.

Returns#

Dict[str, float | str]

Formulated ration, with keys as feed IDs, values as kg fed per animal.

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

Constraint method for total net energy, as sum of net energy required for lactation, pregnancy, maintenance, growth, and activity. Only applicable to lactating cows. Total energy supply here assumed to be the “largest” supply of net energy available for any individual requirement. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

The difference between supplied and required total net energy. Non-negative value indicates that supply meets or exceeds the requirement for total net energy.

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

Constraint method for maintenance and activity. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 requirements for maintenance and activity.

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

Constraint method for net energy for lactation. Only applicable to lactating cows. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 requirements for lactation.

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

Constraint method for net energy for growth. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 requirements for growth.

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

Constraint method for phosphorus. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 requirements for phosphorus.

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

Constraint method for the lower bound of metabolizable protein. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 requirements for protein.

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

Constraint method for the upper bound of metabolizable protein. This constraint is a simple check that the supply does not exceed the limit. See the upper limit factor as defined in AnimalModuleConstants.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 maximum allowable protein.

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

Constraint method for calcium. This constraint is a simple check that the supply exceeds the requirement.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 requirements for calcium.

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

Constraint method for the minimum amount of NDF in a ration. This constraint is a simple check that the supply exceeds the amount of NDF desired for a formulated ration.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 minimum ration percent value for NDF.

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

Constraint method for the maximum amount of NDF in a ration. This constraint is a simple check that the supply does not exceed the NDF desired for a formulated ration.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 maximum ration percent value for NDF.

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

Constraint method for the minimum amount of forage NDF in a ration. This constraint is a simple check that the supply exceeds the amount of forage NDF desired for a formulated ration.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 minimum ration percent value for forage NDF.

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

Constraint method for fat. This constraint is a simple check that the supply does not exceed the percentage of fat desired for a formulated ration.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 maximum percentage of fat.

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

Constraint method for the minimum amount of dry matter intake. This constraint is a simple check that the formulated ration supplies enough dry matter.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

ration_config: RationConfig object

Attributes are animal requirement and feed supply information required for optimization

Returns#

float

Non-negative value indicates that supply is exceeds the minimum dry matter intake.

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

Constraint method for the maximum amount of dry matter intake. This constraint is a simple check that the formulated ration does not supply too much dry matter.

Parameters#

decision_vectornumpy.ndarray

The decision vector used in the scipy minimize method.

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 maximum dry matter intake.

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

attempt_optimization(pen_average_body_weight: float, requirements: NutritionRequirements, pen_available_feeds: List[Feed], animal_combination: AnimalCombination, previous_ration: Dict[int | str, float | str] | None = None) Tuple[OptimizeResult | None, RationConfig]#
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

static handle_failed_constraints(num_attempts: int, solution: OptimizeResult, ration_config: RationConfig, animal_combination: AnimalCombination, pen_id: int, pen_available_feeds: Any, average_nutrient_requirements: NutritionRequirements, sim_day: int = 9999, info_map: Dict[str, Any] = {}) None#

Handle and log failed constraints during the ration optimization process.

This method identifies and logs the constraints that failed during the optimization process for a specific pen of animals. It gathers relevant information about the failed attempt, including the simulation day, the number of attempts, the failed constraints, the attempted ration, and the pen’s nutrient requirements. This information is then added to the output manager via a variable.

Parameters:#

num_attemptsint

The number of ration formulation attempts made so far.

solutionscipy.optimize.OptimizeResult

The result of the optimization process.

ration_configRationConfig

A RationConfig object.

animal_combinationAnimalCombination

The combination of animals for which the failed constraints are being handled.

pen_idRUFAS_ID

The ID for the pen.

pen_available_feedsAvailableFeedsTypedDict

A dictionary of available feeds for ration formulation.

average_nutrient_requirementsNutritionRequirements

The pen’s average (or other summary statistic) requirements used in ration formulation.

sim_dayint

Day of simulation.

info_mapDict[str, Any]

A dictionary containing additional information to be logged with the failed constraints summary.

Returns:#

None