Del modelo lineal al certificado de optimalidad
From the linear model to the optimality certificate
Formulación de mínimo costo para pollo de engorda: método, dualidad, lectura económica, validación con dietas publicadas y reproducibilidad.
Least-cost broiler diet formulation: method, duality, economic reading, validation against published diets and reproducibility.
Guía complementaria del Instructivo del Productor.Companion to the Producer Guide.
Alcance, notación y cómo citar
Scope, notation and citation
Para quién es esta guía, qué supone que ya sabes y cómo están escritas las ecuaciones.
Who this guide is for, what it assumes you know and how equations are written.
Esta guía es para quien necesita entender, verificar o publicar lo que hace RatioAvis: investigadores, docentes de nutrición animal, estudiantes de posgrado y revisores de artículos. Explica el modelo matemático completo, cómo se resuelve, por qué el resultado es demostrablemente óptimo y cómo se validó el programa.
This guide is for those who need to understand, verify or publish what RatioAvis does: researchers, animal-nutrition lecturers, graduate students and journal reviewers. It explains the full mathematical model, how it is solved, why the result is provably optimal and how the program was validated.
Supone nociones de nutrición de aves y de álgebra lineal. El uso paso a paso de la interfaz está en el Instructivo del Productor; aquí se usa la vista Científico y el mismo caso de ejemplo: Ross 308, mixto, iniciación (0–10 d), 2,200 msnm, con el ajuste de −50 kcal/kg de EMAn.
It assumes a working knowledge of poultry nutrition and linear algebra. Step-by-step use of the interface is in the Producer Guide; here we use the Scientist view and the same worked case: Ross 308, as-hatched, starter (0–10 d), 2,200 m a.s.l., with the −50 kcal/kg AMEn adjustment.
NotaciónNotation
| Símbolo | Symbol | Significado | Meaning | Unidad | Unit |
|---|---|---|---|---|---|
| ingrediente seleccionado (variable de decisión) | selected ingredient (decision variable) | — | |||
| nutriente con requerimiento (20 posibles) | nutrient with a requirement (20 possible) | — | |||
| inclusión del ingrediente i en la dieta | inclusion of ingredient i in the diet | % (kg/100 kg) | |||
| precio del ingrediente puesto en granja | delivered ingredient price | $/kg | |||
| contenido del nutriente j en el ingrediente i, tal como se ofrece | content of nutrient j in ingredient i, as fed | %, kcal/kg, mg/kg | |||
| requerimiento mínimo y máximo de j en la dieta | minimum and maximum requirement of j in the diet | unidad de j | unit of j | ||
| límites de inclusión del ingrediente | ingredient inclusion limits | % | |||
| costo de 100 kg de dieta (función objetivo) | cost of 100 kg of diet (objective) | $/100 kg | |||
| variable dual (precio sombra) de la restricción k | dual variable (shadow price) of constraint k | $/100 kg por unidad | $/100 kg per unit | ||
| costo reducido del ingrediente i | reduced cost of ingredient i | $/100 kg por punto % | $/100 kg per % point |
Los vectores van en negritas (, ) y las ecuaciones se numeran a la derecha. Los nombres de botones y pestañas se escriben como aparecen en pantalla: ⚙ Formular, Formulación›Modelo matemático y reproducibilidad.
Vectors are in bold (, ) and equations are numbered on the right. Button and tab names appear as on screen: ⚙ Formulate, Formulation›Mathematical model and reproducibility.
Tipos de recuadroBox types
Un concepto con su significado exacto.
A concept with its exact meaning.
Un teorema o propiedad que el programa aprovecha, con su consecuencia práctica.
A theorem or property the program relies on, with its practical consequence.
Los números reales del caso de ejemplo, tal como los calcula la app.
The real numbers of the worked case, exactly as the app computes them.
Un supuesto o límite del método que puede cambiar una conclusión.
An assumption or limitation that can change a conclusion.
Cómo citarHow to cite
Mojica-Zárate, H. T., Barrera-Guzmán, L. A., y Velázquez-Vázquez, G. (2026). RatioAvis: Guided least-cost diet formulation for broiler chickens (Versión 1.1.1) [Software]. Zenodo. https://doi.org/10.5281/zenodo.23123050
Mojica-Zárate, H. T., Barrera-Guzmán, L. A., & Velázquez-Vázquez, G. (2026). RatioAvis: Guided least-cost diet formulation for broiler chickens (Version 1.1.1) [Software]. Zenodo. https://doi.org/10.5281/zenodo.23123050
Mojica-Zárate, H. T., Barrera-Guzmán, L. A., y Velázquez-Vázquez, G. (2026). RatioAvis. Instructivo del Científico (1.ª ed.). Distribuido con RatioAvis 1.1.1. https://hectortecumshe-ai.github.io/RatioAvis/instructivo-cientifico.html
Mojica-Zárate, H. T., Barrera-Guzmán, L. A., & Velázquez-Vázquez, G. (2026). RatioAvis. Scientist Guide (1st ed.). Distributed with RatioAvis 1.1.1. https://hectortecumshe-ai.github.io/RatioAvis/instructivo-cientifico.html
En la sección R.3 hay un párrafo listo para la sección de Materiales y métodos de un artículo.
Section R.3 provides a ready-made paragraph for a paper’s Materials and methods.
El modelo y su solución
The model and its solution
Qué problema resuelve RatioAvis, cómo lo resuelve y por qué puede garantizar que no existe una dieta más barata.
What problem RatioAvis solves, how it solves it and why it can guarantee that no cheaper diet exists.
El problema de la dietaThe diet problem
Formular una dieta de mínimo costo es uno de los problemas fundacionales de la investigación de operaciones. Stigler (1945) planteó la búsqueda de la dieta humana más barata que cubriera los requerimientos; Dantzig resolvió ese tipo de problemas con el método símplex (1947; Dantzig, 1963), y desde la década de 1950 la industria de alimentos balanceados formula así a diario. RatioAvis implementa ese marco clásico de forma transparente: cada número que entra y sale del modelo está a la vista.
Least-cost diet formulation is one of the founding problems of operations research. Stigler (1945) posed the search for the cheapest human diet meeting requirements; Dantzig solved such problems with the simplex method (1947; Dantzig, 1963), and since the 1950s the feed industry has formulated this way every day. RatioAvis implements that classical framework transparently: every number entering and leaving the model is visible.
Formulación matemáticaMathematical formulation
Con los ingredientes seleccionados y los nutrientes con requerimiento , RatioAvis resuelve el programa lineal:
With the selected ingredients and the nutrients with a requirement , RatioAvis solves the linear program:
La primera restricción cierra la mezcla al 100 %; las siguientes imponen el mínimo y, si lo hay, el máximo de cada nutriente; la última, los límites de inclusión. Como está en kg por cada 100 kg, es el costo de 100 kg y el costo por tonelada es .
The first constraint closes the blend at 100 %; the next ones impose each nutrient’s minimum and, when set, maximum; the last one the inclusion limits. Since is in kg per 100 kg, is the cost of 100 kg and the cost per tonne is .
- Aminoácidos: si la línea genética usa base digestible, se toma la columna digestible estandarizada del ingrediente (
dLys,dMet…); si usa base total (NRC 1994), la total. - Amino acids: if the genetic line uses a digestible basis, the ingredient’s standardized digestible column is used (
dLys,dMet…); on a total basis (NRC 1994), the total one. - Balance electrolítico: se calcula por ingrediente y entra al modelo como un nutriente lineal más (ecuación 6).
- Electrolyte balance: computed per ingredient and entered as one more linear nutrient (equation 6).
- Límites: un mínimo solo genera fila si es mayor que 0, y un máximo solo si es menor que 100 %.
- Limits: a minimum only creates a row if it is above 0, and a maximum only if it is below 100 %.
La geometría del óptimoThe geometry of the optimum
Cada restricción es un semiespacio; su intersección, la región factible, es un poliedro convexo. Las líneas de igual costo son paralelas y el óptimo, si existe, está siempre en un vértice. Con 14 ingredientes el poliedro vive en 14 dimensiones, pero un modelo reducido de tres ingredientes (maíz, pasta de soya y aceite, con el aceite como complemento a 100 %) se puede dibujar en el plano:
Each constraint is a half-space; their intersection, the feasible region, is a convex polyhedron. Iso-cost lines are parallel and the optimum, if it exists, always lies at a vertex. With 14 ingredients the polyhedron lives in 14 dimensions, but a reduced three-ingredient model (corn, soybean meal and oil, with oil completing 100 %) can be drawn on the plane:
El método símplex en dos fasesThe two-phase simplex method
RatioAvis lleva el modelo (1) a forma estándar con variables de holgura y artificiales y lo resuelve con un símplex tabular propio, escrito en JavaScript y ejecutado en el navegador:
RatioAvis brings model (1) to standard form with slack and artificial variables and solves it with its own tableau simplex, written in JavaScript and run in the browser:
- Escalado. Cada fila se divide entre su coeficiente de mayor valor absoluto, de modo que energía (miles de kcal) y aminoácidos (centésimas) quedan en escalas comparables. Los duales se des-escalan al final.
- Scaling. Each row is divided by its largest absolute coefficient, so that energy (thousands of kcal) and amino acids (hundredths) share comparable scales. Duals are unscaled at the end.
- Fase I. Se minimiza la suma de las variables artificiales. Si al terminar no es cero (umbral 10⁻⁷), el problema es infactible y se pasa al diagnóstico (M.7).
- Phase I. The sum of artificial variables is minimized. If it is not zero at the end (threshold 10⁻⁷), the problem is infeasible and the diagnosis runs (M.7).
- Fase II. Desde esa base factible se minimiza el costo real. Entra la primera variable con costo reducido negativo y sale la de menor cociente, con desempate por el menor índice: la regla de Bland (1977), que garantiza que el método no cicle aun con degeneración, frecuente en dietas por los límites fijos (premezcla, colina).
- Phase II. From that feasible basis the real cost is minimized. The first variable with a negative reduced cost enters and the minimum-ratio row leaves, ties broken by lowest index: Bland’s rule (1977), which guarantees no cycling even under degeneracy, common in diets because of fixed limits (premix, choline).
Dualidad y certificado de optimalidadDuality and the optimality certificate
A todo programa lineal le corresponde un problema dual. Si se agrupan las restricciones de (1) como , el dual busca los precios que maximizan el valor de los requerimientos sin que ningún ingrediente quede «subvaluado»:
Every linear program has a corresponding dual problem. Writing the constraints of (1) as , the dual seeks the prices that maximize the value of the requirements without any ingredient being “undervalued”:
Si es factible en el primal, es factible en el dual y , entonces ambos son óptimos. Ninguna dieta factible puede costar menos que , porque toda solución dual factible es una cota inferior del costo (dualidad débil).
If is primal feasible, is dual feasible and , both are optimal. No feasible diet can cost less than , since every dual feasible solution is a lower bound on cost (weak duality).
RatioAvis no se limita a confiar en el símplex: después de cada formulación vuelve a calcular las tres condiciones con los números finales y solo marca la solución como certificada si se cumplen las tolerancias:
RatioAvis does not simply trust the simplex: after every formulation it recomputes the three conditions from the final numbers and only marks the solution as certified if the tolerances are met:
| Comprobación | Check | Qué mide | What it measures | Tolerancia | Tolerance | En el caso | In the case |
|---|---|---|---|---|---|---|---|
| Factibilidad primal | Primal feasibility | mayor violación de una restricción o de x ≥ 0 | largest violation of a constraint or of x ≥ 0 | < 10⁻⁶ | 4.3 × 10⁻¹⁴ | ||
| Factibilidad dual | Dual feasibility | signo de cada y y costos reducidos ≥ 0 | sign of each y and reduced costs ≥ 0 | < 10⁻⁶ | 4.0 × 10⁻¹³ | ||
| Brecha primal–dual | Primal–dual gap | < 10⁻⁷ | 3.9 × 10⁻¹⁶ |
Precios sombra, costos reducidos y precio de entradaShadow prices, reduced costs and entry price
El valor dual de una restricción es la derivada del costo óptimo respecto a su lado derecho, , válida mientras la base óptima no cambie. Solo las restricciones activas (que se cumplen con igualdad) tienen precio sombra distinto de cero: es la holgura complementaria.
The dual value of a constraint is the derivative of the optimal cost with respect to its right-hand side, , valid while the optimal basis does not change. Only binding constraints (met with equality) have a non-zero shadow price: this is complementary slackness.
Como en (1) el lado derecho de un nutriente es y está en $/100 kg, la app reporta en la tabla Precios sombra el cambio del costo por tonelada:
Since the right-hand side of a nutrient in (1) is and is in $/100 kg, the app reports in the Shadow prices table the change in cost per tonne:
a la izquierda, por unidad de requerimiento (1 kcal/kg o 1 punto %); a la derecha, por punto % de un límite de inclusión.
left, per unit of requirement (1 kcal/kg or 1 % point); right, per % point of an inclusion limit.
El costo reducido de un ingrediente fuera de la fórmula es cuánto aumentaría por cada punto % que se le obligara a entrar. Si su precio bajara en , quedaría en el umbral de entrar; por eso la app reporta el precio de entrada:
The reduced cost of an ingredient outside the formula is how much would rise per % point it were forced in. If its price fell by , it would sit at the threshold of entering; hence the app reports the entry price:
Diagnóstico de infactibilidadInfeasibility diagnosis
Cuando la fase I termina con artificiales positivas, la app hace dos pruebas: (a) busca nutrientes con mínimo positivo que ningún ingrediente seleccionado aporta; (b) vuelve a resolver el modelo quitando una restricción a la vez y lista las que, por sí solas, devuelven la factibilidad. Es un diagnóstico de primer orden, rápido y fácil de interpretar.
When phase I ends with positive artificials, the app runs two tests: (a) it looks for nutrients with a positive minimum that no selected ingredient supplies; (b) it re-solves the model removing one constraint at a time and lists those that, on their own, restore feasibility. It is a first-order diagnosis, fast and easy to interpret.
Si ninguna restricción aislada explica la infactibilidad, el conflicto involucra a varias a la vez. La app lo indica, pero no calcula un subsistema irreducible infactible (IIS): hay que relajar requerimientos o añadir ingredientes de manera razonada.
If no single constraint explains the infeasibility, the conflict involves several at once. The app says so, but does not compute an irreducible infeasible subsystem (IIS): requirements must be relaxed or ingredients added in a reasoned way.
Los datos del modelo
The model’s data
De dónde salen b, a, c, l y u, qué ajustes aplica la app y qué supuestos conviene declarar.
Where b, a, c, l and u come from, which adjustments the app applies and which assumptions to declare.
Requerimientos b: fuentes y ajustesRequirements b: sources and adjustments
| Perfil | Profile | Fuente | Source | Base AA | AA basis | Estado | Status |
|---|---|---|---|---|---|---|---|
| Ross 308 · Arbor Acres Plus | Aviagen (2022) | digestible | digestible | oficial vigentecurrent official | |||
| Cobb 500 | Cobb-Vantress (2022) | digestible | digestible | verificarcheck | |||
| Hubbard Efficiency Plus | Hubbard (2022) | digestible | digestible | oficial vigentecurrent official | |||
| Crecimiento lento | Slow-growing | EM y PC de Usturoi et al. (2023); AA por proteína ideal | ME and CP from Usturoi et al. (2023); AA by ideal protein | digestible | digestible | orientativoguideline | |
| NRC | NRC (1994) | total | históricohistorical | ||||
| Personalizado | Custom | NASEM (2025), Rostagno et al. (2024) u otra | NASEM (2025), Rostagno et al. (2024) or other | digestible | digestible | del usuariouser |
Sobre la tabla de la fase, la app aplica ajustes explícitos y documentados:
On top of the phase table, the app applies explicit, documented adjustments:
El primer par de factores es para machos y el segundo para hembras; las aves mixtas usan la tabla tal cual.
The first factor pair is for males and the second for females; as-hatched birds use the table as is.
- % de Lis: el perfil de proteína ideal de la tabla elegida.% of Lys: the ideal-protein profile of the chosen table.
La matriz aThe matrix a
La biblioteca tiene 29 ingredientes en ocho categorías, cada uno con 28 columnas: materia seca, EMAn, proteína, extracto etéreo, fibra, Ca, P disponible, Na, Cl, K, ácido linoleico, ocho aminoácidos totales, sus ocho digestibles estandarizados y xantofilas. Todo está en base tal como se ofrece (≈ 88–90 % de materia seca). Las fuentes son Rostagno et al. (2017), FEDNA (2019) y NRC (1994).
The library holds 29 ingredients in eight categories, each with 28 columns: dry matter, AMEn, protein, ether extract, fibre, Ca, available P, Na, Cl, K, linoleic acid, eight total amino acids, their eight standardized digestible values and xanthophylls. Everything is on an as-fed basis (≈ 88–90 % dry matter). Sources are Rostagno et al. (2017), FEDNA (2019) and NRC (1994).
- Cada aminoácido tiene dos casillas: total · digestible.Each amino acid has two fields: total · digestible.
El balance electrolítico de cada ingrediente (Mongin, 1981) se calcula con las masas atómicas de Na, K y Cl:
Each ingredient’s electrolyte balance (Mongin, 1981) is computed from the atomic masses of Na, K and Cl:
El cálculo es exacto; la incertidumbre está en la composición. Como muestra la validación (capítulo V), las diferencias de 5–10 % en aminoácidos entre tablas son habituales. Para publicar, reporte la matriz usada (el JSON la incluye) y, de ser posible, analice los ingredientes principales.
The calculation is exact; the uncertainty lies in composition. As the validation shows (chapter V), 5–10 % amino-acid differences between tables are common. For publication, report the matrix used (the JSON includes it) and, if possible, analyse the main ingredients.
Precios c y límites l, uPrices c and limits l, u
Los precios precargados son ilustrativos. El Bloque 5 muestra además dos índices de eficiencia de compra:
The preloaded prices are illustrative. Block 5 also shows two purchasing-efficiency indices:
Son útiles para ordenar fuentes, pero no sustituyen al modelo: un ingrediente puede ser la fuente de energía más barata y aun así quedar fuera por su aporte de otros nutrientes. En el caso, el sorgo da la energía a $1.56 frente a $1.63 del maíz y no entra (sección 6.4).
They help rank sources but do not replace the model: an ingredient can be the cheapest energy source and still be left out because of its other nutrients. In the case, sorghum supplies energy at $1.56 versus $1.63 for corn and does not enter (section 6.4).
Lectura científica de una solución
A scientific reading of a solution
El caso de ejemplo resuelto e interpretado: qué restricciones mandan, cuánto vale cada una y qué tan robusta es la fórmula.
The worked case solved and interpreted: which constraints drive it, what each is worth and how robust the formula is.
La solución y su certificadoThe solution and its certificate
- Solución óptima certificada por dualidad fuerte.Certified optimal solution by strong duality.
- Indicadores económicos de la fase.Economic indicators of the phase.
Qué restricciones mandanWhich constraints drive the cost
Quince restricciones quedan activas: la suma a 100 %, nueve mínimos de nutrientes (EMAn, proteína, lisina, Met + Cis, treonina, valina, Ca, P disponible y Na), el máximo de cloro y los cuatro límites que fijan la premezcla y la colina. Los precios sombra por unidad de requerimiento no son comparables entre sí (kcal frente a puntos %); para compararlos se expresan como el costo de subir 1 % relativo cada requerimiento, :
Fifteen constraints are binding: the 100 % sum, nine nutrient minimums (AMEn, protein, lysine, Met + Cys, threonine, valine, Ca, available P and Na), the chloride maximum and the four limits fixing premix and choline. Shadow prices per unit of requirement are not comparable (kcal versus % points); to compare them, they are expressed as the cost of raising each requirement by 1 % relative, :
El precio sombra de la energía es $4.948 por tonelada por kcal/kg. Según (3), bajar el requerimiento 50 kcal debería ahorrar 50 × 4.948 = $247.40/t. Formulando con y sin el ajuste se obtienen $9,052.43 y $8,805.03: una diferencia de $247.40, exactamente la predicha. La base óptima no cambió en ese intervalo, y por eso la derivada vale para un cambio de 50 kcal.
The energy shadow price is $4.948 per tonne per kcal/kg. By (3), lowering the requirement by 50 kcal should save 50 × 4.948 = $247.40/t. Formulating with and without the adjustment gives $9,052.43 and $8,805.03: a difference of $247.40, exactly as predicted. The optimal basis did not change over that interval, which is why the derivative holds for a 50 kcal change.
| Restricción activa | Binding constraint | ∂Z/∂b · $/t | Lectura | Reading |
|---|---|---|---|---|
| EMAn ≥ 2,925 kcal/kg | AMEn ≥ 2,925 kcal/kg | 4.948 | +1 kcal/kg → +$4.95/t | +1 kcal/kg → +$4.95/t |
| Proteína cruda ≥ 23 % | Crude protein ≥ 23 % | 206.432 | +0.1 punto → +$20.64/t | +0.1 point → +$20.64/t |
| Lisina dig. ≥ 1.32 % | Dig. lysine ≥ 1.32 % | 156.583 | +0.01 punto → +$1.57/t | +0.01 point → +$1.57/t |
| Met + Cis ≥ 1.00 % | 522.293 | +0.01 punto → +$5.22/t | +0.01 point → +$5.22/t | |
| Treonina dig. ≥ 0.88 % | Dig. threonine ≥ 0.88 % | 267.642 | +0.01 punto → +$2.68/t | +0.01 point → +$2.68/t |
| Valina dig. ≥ 1.00 % | Dig. valine ≥ 1.00 % | 738.980 | +0.01 punto → +$7.39/t | +0.01 point → +$7.39/t |
| Calcio ≥ 0.95 % | Calcium ≥ 0.95 % | 394.540 | +0.01 punto → +$3.95/t | +0.01 point → +$3.95/t |
| P disponible ≥ 0.50 % | Available P ≥ 0.50 % | 1,378.480 | +0.01 punto → +$13.78/t | +0.01 point → +$13.78/t |
| Sodio ≥ 0.18 % | Sodium ≥ 0.18 % | 944.167 | +0.01 punto → +$9.44/t | +0.01 point → +$9.44/t |
| Cloro ≤ 0.23 % | Chloride ≤ 0.23 % | −326.888 | +0.01 punto de tope → −$3.27/t | +0.01 point of ceiling → −$3.27/t |
El signo del cloro explica una decisión de la fórmula que a primera vista sorprende: la app usa bicarbonato de sodio (0.153 %) además de sal, porque el sodio es limitante y el cloro ya está en su máximo. El bicarbonato aporta sodio sin cloro.
The chloride sign explains a choice that may look surprising at first: the app uses sodium bicarbonate (0.153 %) besides salt, because sodium is binding and chloride is already at its ceiling. Bicarbonate supplies sodium without chloride.
- Modelo y solución (JSON): matriz, precios, límites, requerimientos y solución (capítulo R).Model and solution (JSON): matrix, prices, limits, requirements and solution (chapter R).
Dónde está el costoWhere the cost sits
La fracción de la dieta que ocupa un ingrediente y la fracción del costo que representa pueden diferir mucho. Comparar ambas orienta la negociación de compras mejor que el precio por kilo:
An ingredient’s share of the diet and its share of the cost can differ widely. Comparing both guides purchasing better than price per kilo:
Costos reducidos: el caso del sorgoReduced costs: the sorghum case
De los 14 ingredientes, solo el sorgo queda fuera. Su costo reducido es 1.571 $/t por punto %, es decir, 0.1571 $/kg. Con (4), su precio de entrada es 5.00 − 0.157 = $4.84/kg: si el proveedor lo ofrece a ese precio o menos, conviene volver a formular. Es el número que la vista Productor traduce como «empezaría a convenirte».
Of the 14 ingredients, only sorghum is left out. Its reduced cost is 1.571 $/t per % point, i.e., 0.1571 $/kg. By (4), its entry price is 5.00 − 0.157 = $4.84/kg: if the supplier offers it at that price or less, reformulating pays. This is the number the Producer view translates as “it would start to pay off”.
Calidad de la fórmula: proteína ideal e indicadoresFormula quality: ideal protein and indicators
El óptimo cumple los mínimos, pero conviene verificar relaciones que el modelo no impone como restricción. La app las calcula en Indicadores de calidad:
The optimum meets the minimums, but some ratios the model does not impose as constraints are worth checking. The app computes them under Quality indicators:
| Indicador | Indicator | Caso | Case | Referencia | Reference |
|---|---|---|---|---|---|
| Ca : P disponible | Ca : available P | 1.90 : 1 | 1.8–2.1 : 1 | ||
| Balance electrolítico | Electrolyte balance | 256 mEq/kg | 200–300 (óptimo ≈ 250) | 200–300 (optimum ≈ 250) | |
| EM : PC | ME : CP | 127 kcal/% | informativo | informative | |
| Grasa total (EE) | Total fat (EE) | 4.63 % | < 7 % para buen pellet | < 7 % for good pellets |
Programa multifase e informe
Multiphase program and report
Cómo se construye el programa completo y qué deja el informe para una bitácora o un artículo.
How the full program is built and what the report provides for a log book or a paper.
Programa: un modelo por faseProgram: one model per phase
El Bloque 7 resuelve un modelo (1) independiente para cada fase de la línea, con los mismos ingredientes y precios y con los ajustes de (5) por sexo, pigmentación y calor. El costo del ciclo por ave y por kilo de peso vivo es:
Block 7 solves an independent model (1) for each phase of the line, with the same ingredients and prices and the adjustments of (5) for sex, pigmentation and heat. The cycle cost per bird and per kilo of live weight is:
con el consumo por ave en la fase (kg), el costo óptimo por kg y la ganancia de peso. En el caso: $52.94 por ave y $15.04 por kg de peso vivo.
with the intake per bird in the phase (kg), the optimal cost per kg and the weight gain. In the case: $52.94 per bird and $15.04 per kg of live weight.
Cada fase se optimiza por separado con consumo y ganancia fijos: el programa no modela la respuesta productiva a la densidad de nutrientes. Las ediciones manuales del Bloque 2 y el ajuste por altitud solo valen para la formulación individual; por eso la iniciación aparece aquí a $9,052/t.
Each phase is optimized separately with fixed intake and gain: the program does not model the productive response to nutrient density. Manual edits in Block 2 and the altitude adjustment only apply to the single-phase formulation; hence the starter appears here at $9,052/t.
El informe científicoThe scientific report
En la vista científica, el informe redacta el método (línea, fase, fuente de requerimientos, base de aminoácidos, matrices, costo, aporte y restricciones limitantes) y añade la cita del software. Es un borrador fiel de lo que se hizo, útil para una bitácora o como punto de partida para un artículo.
In the scientist view, the report writes up the method (line, phase, requirement source, amino-acid basis, matrices, cost, supply and binding constraints) and adds the software citation. It is a faithful draft of what was done, useful for a log book or as a starting point for a paper.
Validación
Validation
Tres pruebas independientes: el cálculo del aporte, el optimizador y la matemática del motor.
Three independent tests: supply calculation, the optimizer and the solver’s mathematics.
Diseño de la validaciónValidation design
Se tomaron 8 dietas de 4 artículos revisados por pares (México, Jordania y Estados Unidos; Ross 308, Cobb 500 y Ross 708; base total y digestible). Cada fórmula se introdujo tal como fue publicada, normalizada a 100 % si la tabla no sumaba exactamente, y se analizó con la matriz y los precios de la biblioteca de la app.
Eight diets from 4 peer-reviewed papers were used (Mexico, Jordan and the United States; Ross 308, Cobb 500 and Ross 708; total and digestible basis). Each formula was entered as published, normalized to 100 % when the table did not add up exactly, and analysed with the app’s library matrix and prices.
- Cálculo del aporte. Se compara el análisis calculado que reportan los autores con el que calcula la app, mediante el error absoluto porcentual medio (MAPE).
- Supply calculation. The calculated analysis reported by the authors is compared with the app’s, using the mean absolute percentage error (MAPE).
- Optimizador. Se pide a la app la dieta de mínimo costo que aporte, al menos, lo mismo que calcula para la fórmula publicada, con los mismos ingredientes y sus aditivos fijos. Como la fórmula publicada ya es factible, el óptimo debe igualarla o abaratarla.
- Optimizer. The app is asked for the least-cost diet supplying at least what it computes for the published formula, with the same ingredients and their fixed additives. Since the published formula is already feasible, the optimum must match or beat it.
- Matemática. El símplex se compara con un solucionador de referencia independiente en problemas aleatorios.
- Mathematics. The simplex is compared with an independent reference solver on random problems.
Prueba 1: cálculo del aporteTest 1: supply calculation
La energía y la proteína coinciden dentro de lo normal entre tablas de composición. Las mayores diferencias aparecen en aminoácidos y minerales, y tienen explicaciones concretas: la proteína de la pasta de soya no reportada en dos artículos (se asumieron 46 % y 47 %), la base total frente a digestible y las tablas de origen distintas. El cálculo de la app es una suma ponderada exacta, así que estas diferencias reflejan la matriz, no el algoritmo.
Energy and protein agree within the normal spread between composition tables. The largest differences occur in amino acids and minerals, and have concrete explanations: soybean-meal protein not reported in two papers (46 % and 47 % were assumed), total versus digestible basis, and different source tables. The app’s calculation is an exact weighted sum, so these differences reflect the matrix, not the algorithm.
La comparación sirvió también para detectar dos valores reportados que parecen erratas: metionina 0.47 % en la finalización de Maldonado-Fuentes et al. (2020), cuando el mismo cuadro reporta 0.66 % para dietas con la misma DL-metionina, y valina 1.39 % en la iniciación de Obeidat et al. (2025), imposible con esa fórmula, cuando la fase siguiente reporta 0.35 %.
The comparison also flagged two reported values that look like typos: methionine 0.47 % in the finisher of Maldonado-Fuentes et al. (2020), while the same table reports 0.66 % for diets with the same DL-methionine; and valine 1.39 % in the starter of Obeidat et al. (2025), impossible with that formula, while the next phase reports 0.35 %.
Prueba 2: el optimizadorTest 2: the optimizer
En las 6 dietas con suficientes valores reportados (al menos cuatro nutrientes comparables), la app reencontró exactamente la fórmula publicada, con diferencias menores a 0.005 puntos en cada ingrediente y con certificado de optimalidad. Es decir: con esos ingredientes y ese aporte, cada dieta publicada ya era la de mínimo costo.
In the 6 diets with enough reported values (at least four comparable nutrients), the app recovered exactly the published formula, with differences below 0.005 points for every ingredient and an optimality certificate. In other words, with those ingredients and that supply, each published diet was already the least-cost one.
| Artículo · fase | Paper · phase | Publicada ($/t) | Published ($/t) | App ($/t) | App ($/t) | Igual | Same |
|---|
Costos con los precios de ejemplo de la biblioteca. La app queda 2 centavos por debajo porque la prueba exige el aporte con una tolerancia relativa de 10⁻⁶.
Costs at the library’s example prices. The app comes out 2 cents lower because the test requires the supply with a relative tolerance of 10⁻⁶.
Prueba 3: comparación con HiGHSTest 3: comparison with HiGHS
El símplex de la app se comparó con HiGHS (Huangfu y Hall, 2018), el solucionador de programación lineal que usa SciPy, en 400 problemas generados al azar con las 6 tablas de requerimientos y la biblioteca de ingredientes, variando requerimientos (±8 %), ingredientes disponibles y precios:
The app’s simplex was compared with HiGHS (Huangfu & Hall, 2018), the linear-programming solver used by SciPy, on 400 randomly generated problems built from the 6 requirement tables and the ingredient library, varying requirements (±8 %), available ingredients and prices:
Reproducibilidad y publicación
Reproducibility and publication
Cómo exportar el modelo, verificarlo de forma independiente y describirlo en un artículo.
How to export the model, verify it independently and describe it in a paper.
El archivo del modelo (JSON)The model file (JSON)
El botón ⬇ Modelo y solución (JSON) guarda todo lo necesario para reproducir el cálculo sin la app:
The ⬇ Model and solution (JSON) button saves everything needed to reproduce the calculation without the app:
| Campo | Field | Contenido | Content |
|---|---|---|---|
software, doi, fecha | versión del programa, DOI y fecha del cálculo | program version, DOI and calculation date | |
genetica, sexo, fase, base | contexto; base es dig o total | context; base is dig or total | |
requerimientos | {nutriente: [mín, máx]}, con null si no hay límite | {nutrient: [min, max]}, null when unbounded | |
ingredientes[] | id, nombre, precio, min, max y comp (las 28 columnas de la matriz) | id, nombre, precio, min, max and comp (the 28 matrix columns) | |
solucion | costo por kg, fórmula, aporte, restricciones con duales, certificado y tamaño del modelo | cost per kg, formula, supply, constraints with duals, certificate and model size |
Verificación independiente con SciPyIndependent verification with SciPy
Este script lee el JSON, reconstruye el modelo (1) y lo resuelve con HiGHS. Con el modelo del caso, exportado de la app, imprime $8,805.03 por tonelada y la misma fórmula, ingrediente por ingrediente (probado con Python 3.12, NumPy 2.5 y SciPy 1.18).
This script reads the JSON, rebuilds model (1) and solves it with HiGHS. With the case model exported from the app it prints $8,805.03 per tonne and the same formula, ingredient by ingredient (tested with Python 3.12, NumPy 2.5 and SciPy 1.18).
import json import numpy as np from scipy.optimize import linprog m = json.load(open("dieta_modelo.json", encoding="utf-8")) ings, req = m["ingredientes"], m["requerimientos"] dig = m["base"] == "dig" AA = {"Lys", "Met", "MC", "Thr", "Trp", "Arg", "Ile", "Val"} def valor(c, k): # balance electrolítico (mEq/kg) o columna de la matriz if k == "DEB": return c["Na"]*1e4/22.99 + c["K"]*1e4/39.10 - c["Cl"]*1e4/35.45 return c.get("d" + k if (dig and k in AA) else k, 0) c = np.array([i["precio"] for i in ings]) A_ub, b_ub = [], [] for k, (lo, hi) in req.items(): a = np.array([valor(i["comp"], k) for i in ings]) if lo is not None: A_ub.append(-a); b_ub.append(-100 * lo) if hi is not None: A_ub.append(a); b_ub.append(100 * hi) bounds = [(i["min"] or 0, 100 if i["max"] in (None, "") else i["max"]) for i in ings] r = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=[np.ones(len(ings))], b_eq=[100], bounds=bounds, method="highs") print("Costo por tonelada:", round(r.fun * 10, 2)) for i, x in zip(ings, r.x): if x > 1e-7: print(f"{i['nombre']:<34}{x:9.3f} %")
HiGHS devuelve los duales en r.ineqlin.marginals. Multiplicados por 1000, y con el signo cambiado en las filas de mínimo (que el script escribe como ≤ con signo negativo), coinciden con la columna ∂Z/∂b · $/t de la app. En el caso se verificó con SciPy 1.18: los diez precios sombra de nutrientes coinciden hasta el tercer decimal.
HiGHS returns duals in r.ineqlin.marginals. Multiplied by 1000, and with the sign flipped for minimum rows (which the script writes as ≤ with a negative sign), they match the app’s ∂Z/∂b · $/t column. This was verified for the case with SciPy 1.18: all ten nutrient shadow prices match to the third decimal.
Texto para Materiales y métodosText for Materials and methods
Un párrafo base para describir el uso de RatioAvis en un artículo. Ajuste los datos entre corchetes:
A base paragraph to describe the use of RatioAvis in a paper. Adjust the bracketed data:
Las dietas experimentales se formularon al mínimo costo mediante programación lineal con RatioAvis versión 1.1.1 (Mojica-Zárate et al., 2026), que resuelve el modelo con el método símplex en dos fases y la regla de Bland y verifica la optimalidad de cada solución por dualidad fuerte (brecha primal–dual relativa < 10⁻⁷). Los requerimientos nutricionales correspondieron a [Aviagen (2022), Ross 308, fase de iniciación de 0 a 10 d, aves mixtas], expresando los aminoácidos en base digestible estandarizada. La composición de los ingredientes se tomó de Rostagno et al. (2017) y FEDNA (2019) [o: de análisis de laboratorio de los lotes utilizados], y se impusieron límites de inclusión de [describir]. El modelo y la solución completos se exportaron en formato JSON y se incluyen como material suplementario.
Experimental diets were formulated at least cost by linear programming with RatioAvis version 1.1.1 (Mojica-Zárate et al., 2026), which solves the model with the two-phase simplex method under Bland’s rule and verifies the optimality of every solution by strong duality (relative primal–dual gap < 10⁻⁷). Nutrient requirements followed [Aviagen (2022), Ross 308, starter phase from 0 to 10 d, as-hatched birds], with amino acids on a standardized digestible basis. Ingredient composition was taken from Rostagno et al. (2017) and FEDNA (2019) [or: from laboratory analyses of the batches used], and inclusion limits of [describe] were imposed. The full model and solution were exported in JSON format and are provided as supplementary material.
Ficha técnica del motorSolver technical sheet
Supuestos y limitaciones
Assumptions and limitations
Lo que el modelo supone y lo que no hace, para declararlo con honestidad.
What the model assumes and what it does not do, so it can be stated honestly.
- Linealidad y aditividad. El aporte de la mezcla es la suma ponderada de sus ingredientes. No se modelan interacciones (por ejemplo, la menor EM de la grasa en pollitos se refleja solo si se edita la matriz).
- Linearity and additivity. The blend’s supply is the weighted sum of its ingredients. Interactions are not modelled (for example, the lower ME of fat in chicks is reflected only if the matrix is edited).
- Composición determinista. La matriz se toma como exacta; no hay formulación estocástica ni márgenes de seguridad automáticos por variabilidad. Si los necesita, súmelos al requerimiento.
- Deterministic composition. The matrix is taken as exact; there is no stochastic formulation or automatic safety margin for variability. If needed, add them to the requirement.
- Relaciones no impuestas. Ca:P, EM:PC y las relaciones de proteína ideal se reportan como indicadores, no como restricciones. Se pueden imponer de manera indirecta con mínimos y máximos.
- Ratios not imposed. Ca:P, ME:CP and ideal-protein ratios are reported as indicators, not constraints. They can be imposed indirectly through minimums and maximums.
- Sin modelo de respuesta. Consumo y ganancia son datos, no salidas: la app no predice el desempeño ante cambios de densidad.
- No response model. Intake and gain are inputs, not outputs: the app does not predict performance under density changes.
- Sensibilidad local. Precios sombra y costos reducidos son derivadas en el óptimo; valen mientras la base no cambie. Para cambios grandes, vuelva a formular.
- Local sensitivity. Shadow prices and reduced costs are derivatives at the optimum; they hold while the basis does not change. For large changes, reformulate.
- Herramienta de apoyo. Los resultados deben ser revisados por un profesional en nutrición animal antes de fabricar.
- Decision support. Results should be reviewed by a qualified animal nutritionist before manufacturing.
Apéndices
Appendices
Glosario técnico español–inglés y referencias.
Spanish–English technical glossary and references.
Glosario español–inglésSpanish–English glossary
ReferenciasReferences
- Aviagen. (2022). Ross broiler nutrition specifications; Arbor Acres broiler nutrition specifications. Aviagen.
- Bauer, M. M., Ao, T., Jacob, J. P., et al. (2025). The performance, energy and nutrient utilization, and bone mineralization of broiler chickens fed corn-soybean meal-based diets with reduced metabolizable energy, calcium, and available phosphorus supplemented with exogenous enzymes. Animals, 15(22), 3254. https://doi.org/10.3390/ani15223254
- Bland, R. G. (1977). New finite pivoting rules for the simplex method. Mathematics of Operations Research, 2(2), 103–107.
- Cobb-Vantress. (2022). Cobb500 broiler performance & nutrition supplement. Cobb-Vantress.
- Dantzig, G. B. (1963). Linear programming and extensions. Princeton University Press.
- FEDNA. (2019). Tablas FEDNA de composición y valor nutritivo de alimentos (4.ª ed.). FEDNA.
- Gregg, C. R., Tejeda, O. J., Spencer, L. F., et al. (2022). Effect of dietary choline chloride supplementation on growth performance and carcass characteristics of broiler chickens reared to 32 days of age. Poultry, 1(2), 66–73. https://doi.org/10.3390/poultry1020007
- Huangfu, Q., & Hall, J. A. J. (2018). Parallelizing the dual revised simplex method. Mathematical Programming Computation, 10(1), 119–142.
- Hubbard. (2022). Efficiency Plus broiler guide and nutrient specifications. Hubbard.
- Maldonado-Fuentes, A., Cuca-García, J. M., Pro-Martínez, A., González-Cerón, F., Herrera-Haro, J. G., Sosa-Montes, E., & Domínguez-Martínez, P. A. (2020). Pasta de higuerilla desintoxicada en dietas para pollos de engorda. Revista Mexicana de Ciencias Pecuarias, 11(3), 605–619. https://doi.org/10.22319/rmcp.v11i3.5797
- Mongin, P. (1981). Recent advances in dietary anion-cation balance: Applications in poultry. Proceedings of the Nutrition Society, 40, 285–294.
- National Academies of Sciences, Engineering, and Medicine. (2025). Nutrient requirements of poultry (10th rev. ed.). The National Academies Press. https://doi.org/10.17226/25395
- National Research Council. (1994). Nutrient requirements of poultry (9th rev. ed.). National Academy Press.
- Obeidat, M. D., Alzoubi, S. Q., Nusairat, B. M., Obeidat, B. S., & Riley, D. G. (2025). Effects of fermented soybean meal supplementation on growth, carcass quality, and intestinal morphology in Ross 308 and Indian River broilers. Animals, 15(18), 2659. https://doi.org/10.3390/ani15182659
- Rostagno, H. S., et al. (2017; 2024). Tabelas brasileiras para aves e suínos (4.ª y 5.ª ed.). Universidade Federal de Viçosa.
- Stigler, G. J. (1945). The cost of subsistence. Journal of Farm Economics, 27(2), 303–314.
- Usturoi, M. G., et al. (2023). Impact of different levels of crude protein on production performance and meat quality in broiler selected for slow growth. Agriculture, 13, 427.
- Virtanen, P., Gommers, R., Oliphant, T. E., et al. (2020). SciPy 1.0: Fundamental algorithms for scientific computing in Python. Nature Methods, 17, 261–272.
RatioAvis · Instructivo del Científico, 1.ª edición, octubre de 2026. Describe RatioAvis 1.1.1. Las capturas son de la app real; los gráficos son originales y se generan con los resultados numéricos de la app para el caso descrito. Los precios son ilustrativos.
RatioAvis · Scientist Guide, 1st edition, October 2026. Covers RatioAvis 1.1.1. Screenshots come from the real app; charts are original and generated from the app’s numerical results for the case described. Prices are illustrative.
© 2026 Héctor Tecumshé Mojica-Zárate. El programa se distribuye con licencia MIT.
© 2026 Héctor Tecumshé Mojica-Zárate. The software is distributed under the MIT License.