Nutrition_modelling_toolbox¶
- calculateFoodScore(originalFood, vmhLabelMacros, vmhMetaboliteMacros, translation)[source]¶
Calculate a similarity score between the macros of each original food item and its VMH alternative and add the score to the food macro structure
A cosine-style distance is computed between the reported macros of the original food and the macros of the matched VMH food. Weights supplied in the template file let the user prioritise or deprioritise certain macros; it is suggested to keep the weight for fiber, starch and minerals set to 0.
- USAGE:
[outputMacros] = calculateFoodScore (originalFood, vmhLabelMacros, vmhMetaboliteMacros, translation)
- INPUTS:
originalFood – The filled-in template table with the original food items; food names are in the first column and macro values from the seventh column onward
vmhLabelMacros – Structure with one field per VMH food item, each holding a table of reported (label) macros
vmhMetaboliteMacros – Structure with one field per VMH food item, each holding a table of macros computed from measured metabolite levels
- OPTIONAL INPUTS:
translation – Cell array translating original food names to their alias (the field names in vmhLabelMacros), used to match the correct original food values. Defaults to NaN when not provided
- OUTPUT:
outputMacros – Updated structure where, for each food item, the original food macros, the percentage of reported macros captured by measured metabolites and the similarity score are added to the macro table
Note
It is important that the template file is used, as otherwise issues could arise with finding the values (starting in the 6th column), the weights (the 2nd row) and calculating the differences between the original and VMH macros.
- calculateMacroOriginalDiet(diet, originalMacroTable)[source]¶
Calculate the macro composition of a diet from the original macros given in the template file used to choose VMH food item alternatives
- USAGE:
orgMacroDiet = calculateMacroOriginalDiet (diet, originalMacroTable)
- INPUTS:
diet – An n x 2 cell array; column one holds the original food names and column two the respective amounts eaten (in grams)
originalMacroTable – The filled-in template table. Macro values are read from columns 6-15 and normalised per gram using the “WeightEaten (g)” column, food items are matched on the OriginalFoodName column, and the table .Properties.VariableNames provide the macro names
- OUTPUT:
orgMacroDiet – Table with the total macro composition of the given diet based on the original food item macros:
.macroNames - names of the macronutrients
.values_g - total amount of each macro (grams)
Note
It is important that the template file base structure is not altered as the basic structure is assumed here to perform the calculations.
- collectFoodItemInfo(foods2Check, foodNames, varargin)[source]¶
Collect the macro and flux values for the VMH food suggestions found by vmhFoodFinder
- USAGE:
[allFluxes, allMacros] = collectFoodItemInfo (foods2Check, foodNames, varargin)
- INPUTS:
foods2Check – Structure with one field per original food item, each holding a table whose first column lists the suggested VMH food items and whose second column holds the amount of food eaten
foodNames – Names of the original food items associated with the fields of foods2Check (passed to the input parser)
- OPTIONAL INPUTS:
varargin – Name-value pairs:
addStarch - boolean indicating if additional starch should be added based on the VMH food macros (default false)
macroType - char selecting how macros are computed: ‘metabolites’ from the calculated flux vectors or ‘usda’ from the USDA FoodData database (default ‘metabolites’)
databaseType - char selecting which database is used; currently only ‘usda’ (USDA FoodData) is supported (default ‘usda’)
- OUTPUTS:
allFluxes – Structure with one field per food item, each holding a table of flux values for every suggested VMH food item
allMacros – Structure with one field per food item, each holding a table of macros for every suggested VMH food item
- compareDietPerformance(model, diets, rois, varargin)[source]¶
Check the effect of different diets on the possible flux range for a set of specified reactions
- USAGE:
[dietPerformance] = compareDietPerformance (model, diets, rois, varargin)
- INPUTS:
model – COBRA model in which the reactions of interest are present
diets – Cell array where each cell holds a cell array with the metabolite composition of a diet as {‘met’, value}
rois – Cell array of reactions to investigate under the different diets
- OPTIONAL INPUTS:
varargin – Name-value pairs:
optPercentage - percentage of the objective used by fluxVariability when solving FVA (default 99)
microbiotaExcretionBound - value used to constrain both bounds of Excretion_EX_microbiota_LI_biomass (default 1)
dietNames - cell array of names for the diets used in the output (default Diet1, Diet2, …)
- OUTPUT:
dietPerformance – Table giving, for each diet, the minimum and maximum flux of each reaction of interest
- compareDiets(diet1, diet2, one2Two)[source]¶
Calculate the changes in metabolite flux composition between two diets and the metabolites unique to each diet
By default the differences in diet2 relative to diet1 are calculated.
- USAGE:
[fluxChanges, uniqueDiet1, uniqueDiet2] = compareDiets (diet1, diet2, one2Two)
- INPUTS:
diet1 – Cell array with the metabolite identifiers in the first column and flux values (doubles or strings) in the second
diet2 – Cell array with the metabolite identifiers in the first column and flux values (doubles or strings) in the second
- OPTIONAL INPUTS:
one2Two – true(1) or false(0) selecting the comparison direction. When true (default) the differences in diet2 relative to diet1 are calculated; when false the differences in diet1 relative to diet2 are calculated
- OUTPUTS:
fluxChanges – Cell array with the metabolite identifier in the first column and the changed flux value in the second
uniqueDiet1 – Cell array of metabolites unique to diet1 compared to diet2
uniqueDiet2 – Cell array of metabolites unique to diet2 compared to diet1
- createFridaDatabase(path2Files, varargin)[source]¶
Create the flux and macro tables used by the nutrition toolbox from the Frida database (frida.fooddata.dk, National Food Institute, Technical University of Denmark)
- USAGE:
createFridaDatabase (path2Files, varargin)
- INPUTS:
path2Files – Character array; directory where the required Frida input files are stored
- OPTIONAL INPUTS:
varargin – Name-value pairs:
outputDir - char, directory where the results are saved (default [path2Files filesep ‘fluxMacroTables’])
- createUSDAdatabase(path2Files, varargin)[source]¶
Create the files used by the nutrition toolbox from the USDA FoodData Central database (https://fdc.nal.usda.gov/download-datasets.html). This function was written for the April 2024 Full Download of All Data Types
- USAGE:
createUSDAdatabase (path2Files, varargin)
- INPUTS:
path2Files – Path to the directory holding all the USDA FoodData files as well as the usdaNutrientVmhTransl file from the COBRA Toolbox
- OPTIONAL INPUTS:
varargin – Name-value pairs:
brandedFoods - boolean; if true the branded-foods source table is also created. Note that this can take days as it converts almost 2 million items (default false)
outputDir - directory where the individual food source databases are stored (default [path2Files filesep ‘foodSourceNutrientTables’])
finalDatabaseDir - directory where the final flux and macro databases are stored (default [path2Files filesep ‘fluxMacroTables’])
foodSource2Use - cell array of food source tables used to build the final flux and macro databases (default {‘sr_legacy_food’; ‘foundation_food’; ‘survey_fndds_food’})
- extractDietFromModel(model)[source]¶
Analyse a VMH whole-body model and extract the diet based on the lower bound constraints of the food and dietary exchange reactions
- USAGE:
[foodMenu] = extractDietFromModel (model)
- INPUT:
model – A human whole-body model (WBM), with fields:
.rxns - reaction identifiers
.lb - lower flux bounds
- OUTPUT:
foodMenu – An n x 2 cell array containing n dietary metabolites and their corresponding flux
- findViableDiet(model, targetString, varargin)[source]¶
Identify the changes to a diet needed for a model to be viable
If no viable solution exists, viableModel and dietChanges are returned as NaN.
- USAGE:
[viableModel, pointsModel, pointsSln, dietChanges] = findViableDiet (model, targetString, varargin)
- INPUTS:
model – COBRA model to make viable, with fields:
.rxns - reaction identifiers
.mets - metabolite identifiers
.S - stoichiometric matrix
.ub - upper flux bounds
.osenseStr - objective sense (set to ‘min’ internally)
targetString – String identifier for the targeted reactions (e.g. ‘Diet_EX_’)
- OPTIONAL INPUTS:
varargin – Name-value pairs:
supplyScalar - scalar setting the magnitude that metabolites are supplied relative to the minimal necessary; e.g. one returns the minimal flux for a viable diet and ten returns ten times that flux (default 1)
specifiedWeights - cell array used to weight specific nutrients above others; default weights are one (e.g. {‘Diet_EX_glu[d]’, 0.1; ‘Diet_EX_fru[d]’, 10})
tol - numerical threshold assumed to correspond to a zero flux (default 1e-7)
lbValues - maximum (most negative) flux that may be added for a dietary reaction (default -100000)
- OUTPUTS:
viableModel – Copy of the input model with updated diet reaction bounds
pointsModel – Model used to identify the recommended dietary changes; it includes the points reactions and the food added/removed reactions
pointsSln – Solution returned for pointsModel
dietChanges – Table of the recommended dietary changes
- generateInSilicoDiet(toCreateDiet, varargin)[source]¶
Build an in silico diet from an input file and compute its metabolite flux vector for use as dietary constraints on whole-body models (WBMs)
Macros are additionally computed from the metabolite flux vector and retrieved as reported for the food items, so the fraction of the reported macros captured by the measured metabolites can be compared. When the original diet macros are provided they are included in the comparison, together with the percentage of the total energy contributed by carbohydrates, lipids and proteins.
- USAGE:
[dietFlux] = generateInSilicoDiet (toCreateDiet, varargin)
- INPUTS:
toCreateDiet – Path to the file (read with readtable) describing the diets to create. The table has the columns “originalName” (original food names), “databaseID” (food item ID in its database) and “databaseUsed” (which database the alternative was found in); each subsequent column is a diet whose values (in grams) give the amount of each food item consumed. The table .Properties.VariableNames are used as the diet names
- OPTIONAL INPUTS:
varargin – Name-value pairs:
outputDir - path to the directory where the results are stored (default: current directory)
originalDietMacros - path to the file with the original macros for each diet; should contain rows for lipids, carbohydrate, protein and energy (default ‘’)
analyseMacros - boolean, whether the macro analysis is performed (default true)
addStarch - boolean, whether additional starch is added based on the reported macros (default false)
- OUTPUT:
dietFlux – Table with the dietary flux (mmol/person/day) for each diet and the dietary reactions to be set
Note
The tutorial folder in the COBRA Toolbox provides template files showing how the data should be formatted; see there for guidance.
- getDietComposition(input, varargin)[source]¶
Take a diet (or a whole-body model) and identify the food macros
- USAGE:
[dietComposition] = getDietComposition (input, varargin)
- INPUT:
input – Either a whole-body metabolic model (struct) or a diet given as an n x 2 cell array of items and amounts
- OPTIONAL INPUTS:
varargin – Name-value pairs:
macroType - which data are used to compute the macros; accepted values are ‘metabolites’, ‘usda’ and ‘frida’ (default ‘metabolites’)
- OUTPUT:
dietComposition – Table with the breakdown of the diet macros, giving the macro categories and their mass in grams
- getDietEnergy(diet, varargin)[source]¶
Compute the number of calories in a diet given as an n x 2 cell array of diet components and serving sizes, or as a metabolite flux list
- USAGE:
[calories] = getDietEnergy (diet, varargin)
- INPUTS:
diet – An n x 2 cell array of diet components with the grams of food eaten, or the dietary flux names with their flux values
- OPTIONAL INPUTS:
varargin – Name-value pairs:
databaseType - char or cell array selecting how the calories are obtained: ‘metabolites’ (from the flux values) or a cell array with ‘usda’ or ‘frida’ per food item (default ‘usda’)
- OUTPUT:
calories – Total amount of calories from the input
- getMetaboliteFlux(diet, varargin)[source]¶
Take a diet consisting of food items and return the associated metabolite flux
- USAGE:
[metFlux] = getMetaboliteFlux (diet, varargin)
- INPUT:
diet – An n x 2 cell array of n dietary/food components and their corresponding flux in grams (for food items) or mmol (for individual metabolites) per day
- OPTIONAL INPUTS:
varargin – Name-value pairs:
databaseType - char or cell array selecting which database is used (‘usda’ and/or ‘frida’) (default ‘usda’)
addStarch - boolean, whether additional starch is added to the flux vector when it is not measured in the macros (default false)
- OUTPUT:
metFlux – An n x 2 cell array listing all n metabolites in the diet and their corresponding flux
- makeDietFormatConsistant(model, diet)[source]¶
Check a diet input for formatting consistency for use with setFoodConstraints and return it in a consistent format
- USAGE:
[diet] = makeDietFormatConsistant (model, diet)
- INPUTS:
model – A COBRA model, with fields:
.rxns - reaction identifiers
diet – An n x 2 cell array of n dietary components and their corresponding flux
- OUTPUT:
diet – The diet in a format consistent with setFoodConstraints
- normalizeDiet(foodMenu, calories, exceptions)[source]¶
Normalize a diet so that it meets a caloric specification
- USAGE:
[foodMenu] = normalizeDiet (foodMenu, calories, exceptions)
- INPUTS:
foodMenu – An n x 2 cell array of food items and their corresponding flux (n = number of food items)
calories – The number of calories the diet should be renormalized to
exceptions – Cell array of specific food items to exclude from the renormalization; their flux is maintained
- OUTPUT:
foodMenu – The renormalized version of the original foodMenu
- nutritionAlgorithmWBM(model, obj, objMinMax, rois, roisMinMax, options)[source]¶
Identifies the minimal changes to a diet necessary to get a desired change in one or more reactions of interest. One may enter a metabolite of the pointsModel instead of a reaction and the algorithm will optimize the diet with a sink or demand reaction for the corresponding metabolite of interest.
- USAGE:
[newDietModel,pointsModel,slnMin,slnMax,pointsModelSln,itemsRemoved,itemsAdded] = nutritionAlgorithmWBM (pointsModel,obj,objMinMax,rois,roisMinMax,options) – Example: [newDietModel,pointsModel,roiFlux,pointsModelSln,itemsRemoved,itemsAdded] = nutritionAlgorithmWBM(WBmodel,’Whole_body_objective_rxn’,’max’,{},{})
- INPUTS:
model – COBRA whole-body model, with fields:
.rxns - reaction identifiers
.mets - metabolite identifiers
.S - stoichiometric matrix
.lb - lower flux bounds
.ub - upper flux bounds
.osenseStr - objective sense (set internally)
obj – Organism’s objective function (reaction name)
objMinMax – Minimize (‘min’) or maximize (‘max’) the objective
rois – Cell array of all reactions of interest
roisMinMax – Cell array of ‘min’/’max’ entries for the rois
- OPTIONAL INPUTS:
options – Structure containing the optional specifications:
.foodOrMets: dictates if the algorithm adds individual
metabolites to the diet or food items. Default is food items. “Food Cat” adjust algorithm to identify categories of food rather than specific items.”AllMets” allows any dietary metabolite into the solution and “FoodMets” only allows metabolites that are in the fdTable spreadsheet into the solution. Possible inputs are: “Food”, “AllMets”, “FoodMets”.
.roiWeights: a vector of weights for each reaction of interest
default is equal to 1
.weightedFoodItems: A cell vector that specifies any food items
or metabolites that should be weighted and the corresponding weight.
.initObjSln: provide an initial solution for the objective
function. Output from optimizeWBmodel.
.caloricRange: 1x2 vector defining the bounds for the diet calories
.carbohydrateRange: 1x2 vector defining the bounds for the diet
carbohydrate content
.lipidRange: 1x2 vector defining the bounds for the diet lipid
content
.proteinRange: 1x2 vector defining the bounds for the diet protein
content
.sugarsRange: 1x2 vector defining the bounds for the diet sugar
content
- .slnType: Specify if solution should be ‘Detailed’ or ‘Quick’.
Default setting is ‘Detailed’
.roiBound: ‘Unbounded’ or ‘Bounded’. Default is ‘Bounded’.
- .foodAddedLimit: Specify a limit for the units of food that can
be added to the diet
- .foodRemovedLimit: Specify a limit for the units of food that can
be removed from the diet
.freeMets: Specifies any metabolites that should be freely
available to the model.
.graphicalAnalysis: set to ‘True’ include graphical analysis and
‘False’ to not include. Default is ‘False’ if .slnType is set to ‘Quick but is ‘True; if .slnType is ‘Detailed’.
.removeFoodItem: A nx2 cell array with the first column the food
item ID and the second column the name of the database of the food items that should be removed from the analysis
.addPrice: a nx3 cell array with the first column the food item
ID, the second column the name of the database, and in the third column the price (any currency) associated with that food item. Allows for optimizing the price of a diet, but only if enough information is available.
- OUTPUTS:
newDietModel – The input model with diet reaction bounds updated to reflect the recommended dietary changes
pointsModel – The points-tracking model built to compute the optimal dietary changes
roiFlux – Flux solutions of the reactions of interest under the new diet
pointsModelSln – Solution structure returned by optimizing pointsModel
menuChanges – Table of the food items (or metabolites) added to or removed from the diet
macroChanges – Table comparing the original and new macronutrient values of the diet
roiChanges – Table of the original and new flux ranges for each reaction of interest
usda and frida database. Enabled options for constraints with various macronutrients. Removed old/not used code. Added additional outputs for the user to better store and interpret the results. Set up the options and initialise variables
- searcher(keyWords, database, varargin)[source]¶
Search a database for entries matching a set of keywords using one of two search strategies
- USAGE:
[output] = searcher (keyWords, database, varargin)
- INPUTS:
keyWords – Cell array of strings used as the search terms
database – Database to be searched, with fields:
.description - item description text matched against the keywords (used by the cumulative search)
- OPTIONAL INPUTS:
varargin – Name-value pairs:
searchType - method of searching the keywords in the database, either ‘iterative’ or ‘cumulative’ (default ‘iterative’)
notInclude - keywords that exclude items (default empty cell array)
- OUTPUT:
output – Cell array of the matches found in the database
- setFoodRxnsWbm(wbm, database, resetDietBounds, addPrice)[source]¶
Adjust a WBM so that it can exchange food items and break them down into their respective metabolite components, preparing the WBM to accept food item consumed weights as dietary input
- USAGE:
[wbm] = setFoodRxnsWbm (wbm, database, resetDietBounds, addPrice)
- INPUTS:
wbm – A WBM model, with fields:
.rxns - reaction identifiers
database – Cell array naming the databases the food items originate from; ‘usda’, ‘frida’ or both are used to add the food items
- OPTIONAL INPUTS:
resetDietBounds – Boolean; if true all Diet_EX_ reactions are set to 0 (default true)
addPrice – Cell array assigning a price to food items: column one the food item IDs, column two the database (‘usda’ or ‘frida’) and column three the price. Defaults to an empty cell array
- OUTPUT:
wbm – The updated WBM model with food exchange and breakdown reactions
- setInSilicoDiet(dietToSetPath, varargin)[source]¶
Set either the dietary flux vector or the food items themselves as a diet on whole-body models (WBMs)
The WBMs can be the default Harvey/Harvetta models or custom ones. The resulting models are saved in dedicated folders and their feasibility on the given diets can optionally be tested.
- USAGE:
setInSilicoDiet (dietToSetPath, varargin)
- INPUTS:
dietToSetPath – Path to the file with the diets to create. It has the columns “originalName” (original food names), “foodName” (name of the database alternatives), “databaseID” (food item ID in its database) and “databaseUsed” (which database the alternative was found in); each subsequent column is a diet whose values (in grams) give the amount of each food item consumed
- OPTIONAL INPUTS:
varargin – Name-value pairs:
metadataPath - path to the metadata file; should contain the columns “ID”, “sex” and “Diet” (default ‘’)
outputDir - path to the directory where the results are stored (default: current directory)
constrainFoodWBM - boolean; if true food item exchange and breakdown reactions are added to the WBMs and the grams consumed are used as exchange flux (default false)
constrainFluxWBM - boolean; if true the dietary flux vector is set on the WBMs (default true)
checkFeasibility - boolean; if true the WBMs are checked for feasibility (default true)
wbmVersion - version of a specific WBM to use; do not start with ‘_’. Defaults to ‘’ so the latest version is loaded
pathToWbms - directory of non-standard Harvey/Harvetta models; changed general female and male models must contain _male and _female in the filename, otherwise the sample ID matching the metadata must be present (default ‘’)
addStarch - boolean, whether additional starch is added when generating the in silico diet (default false)
Note
The tutorial folder in the COBRA Toolbox provides template files showing how the data should be formatted; see there for guidance.
- vmhFoodFinder(templateFilePath, varargin)[source]¶
Find VMH food alternatives to original food items based on keywords or pre-selected VMH food items
- USAGE:
[scoredFoods, fluxValues] = vmhFoodFinder (templateFilePath, varargin)
- INPUTS:
templateFilePath – Path to the filled-in template file
- OPTIONAL INPUTS:
varargin – Name-value pairs:
searchType - method of searching the keywords in the food database, either ‘iterative’ or ‘cumulative’ (default ‘iterative’)
addStarch - boolean indicating if additional starch is added based on the VMH food macros (default false)
databaseType - char selecting the database: ‘usda’ (USDA FoodData), ‘frida’ (Danish food institute) or ‘mixed’ for both (default ‘mixed’)
maxItems - numeric, maximum number of VMH food alternatives analysed for macros (default 50)
outputDir - path where the output files are stored (default [pwd filesep ‘NT_Result’])
foodSources2Use - cell array of strings selecting which USDA food sources are used to find food items (default {‘sr_legacy_food’; ‘foundation_food’; ‘survey_fndds_food’})
- OUTPUTS:
scoredFoods – Structure with one field per food item, each holding a table with the macro values of the original food items and the VMH alternatives, together with the similarity score relative to the original food item
fluxValues – Structure with one field per food item, each holding the calculated flux vector based on the amount eaten