Skip to content

Repository files navigation

DII Calculator

PyPI versionPython 3.10+License: MITTests

A validated Python implementation of the Dietary Inflammatory Index (DII) for nutritional epidemiology research.


Overview

The Dietary Inflammatory Index (DII) is a literature-derived, population-based scoring system that quantifies the inflammatory potential of an individual's diet. Originally developed by Shivappa et al. (2014), the DII has been used in over 1,000 peer-reviewed studies to examine relationships between diet and chronic disease.

This package provides:

  • Validated calculations matching the original methodology
  • All 45 DII food parameters with global reference values
  • Detailed output showing per-nutrient contributions
  • Visualization tools for research and publication
  • Command-line interface for batch processing

Installation

From PyPI (recommended)

pip install dii-calculator

Development installation

git clone https://github.com/strathlab-data/DII.git
cd DII
pip install -e ".[dev]"

Quick Start

importpandasaspdfromdiiimportcalculate_dii# Load your nutrient intake datanutrients=pd.read_csv("your_data.csv")
# Calculate DII scoresresults=calculate_dii(nutrients, id_column="participant_id")
print(results)

Output:

 participant_id DII_score
0 1 -2.34
1 2 0.87
2 3 3.12

Methodology

The DII calculation follows a standardized four-step process for each nutrient:

Step 1: Z-score

z = (intake - global_mean) / global_sd

Where global_mean and global_sd are population-level statistics derived from 11 worldwide dietary datasets.

Step 2: Centered Percentile

percentile = 2 × Φ(z) - 1

Where Φ is the cumulative distribution function of the standard normal distribution. This transforms z-scores to the range [-1, +1].

Step 3: Weighted Contribution

contribution = percentile × inflammatory_weight

The inflammatory weight (range: -0.785 to +0.373) was derived from a systematic review of 1,943 peer-reviewed articles examining relationships between dietary factors and six inflammatory biomarkers: IL-1β, IL-4, IL-6, IL-10, TNF-α, and CRP.

Step 4: Total DII Score

DII = Σ contributions

Sum all nutrient contributions. Missing nutrients are excluded (not imputed).


Interpretation

DII Score RangeCategoryInterpretation
< -4Strongly anti-inflammatoryDiet rich in anti-inflammatory foods
-4 to -1Anti-inflammatoryGenerally healthy dietary pattern
-1 to +1NeutralMixed dietary pattern
+1 to +4Pro-inflammatoryDiet may promote inflammation
> +4Strongly pro-inflammatoryDiet dominated by pro-inflammatory foods

Theoretical range: approximately -8.87 (maximally anti-inflammatory) to +7.98 (maximally pro-inflammatory) when all 45 nutrients are available.


Input Requirements

Data Format

Your input should be a pandas DataFrame with:

  • One row per participant/observation
  • Columns named to match the DII nutrient names exactly
  • Numeric values representing daily intake

Data Types

All nutrient values should be numeric. The package uses float64 precision internally for reproducibility. Non-numeric values are coerced to NaN with a warning.

Units Reference

⚠️Units are critical for accurate DII calculation. Common errors include using mg instead of g for caffeine.

Macronutrients

NutrientColumn NameUnitGlobal MeanGlobal SD
EnergyEnergykcal/day2056338
CarbohydrateCarbohydrateg/day272.240
ProteinProteing/day79.413.9
Total fatTotal fatg/day71.419.4
FiberFiberg/day18.84.9

Fatty Acids

NutrientColumn NameUnitGlobal MeanGlobal SD
Saturated fatSaturated fatg/day28.68
MUFAMUFAg/day276.1
PUFAPUFAg/day13.883.76
Trans fatTrans fatg/day3.153.75
n-3 fatty acidn-3 fatty acidg/day1.061.06
n-6 fatty acidn-6 fatty acidg/day10.87.5
CholesterolCholesterolmg/day279.451.2

Vitamins

NutrientColumn NameUnitGlobal MeanGlobal SD
Vitamin AVitamin ARE/day983.9518.6
Vitamin B6vitamin B6mg/day1.470.74
Vitamin B12vitamin B12µg/day5.152.7
Vitamin CVitamin Cmg/day118.243.46
Vitamin DVitamin Dµg/day6.262.21
Vitamin EVitamin Emg/day8.731.49
ThiaminThiaminmg/day1.70.66
RiboflavinRiboflavinmg/day1.70.79
NiacinNiacinmg/day25.911.77
Folic acidFolic acidµg/day27370.7
Beta-caroteneBeta-caroteneµg/day37181720

Minerals

NutrientColumn NameUnitGlobal MeanGlobal SD
IronIronmg/day13.353.71
MagnesiumMagnesiummg/day310.1139.4
SeleniumSeleniumµg/day6725.1
ZincZincmg/day9.842.19

Other Components

NutrientColumn NameUnitGlobal MeanGlobal SD
AlcoholAlcoholg/day13.983.72
CaffeineCaffeineg/day⚠️8.056.67
Green/black teaGreen/black teag/day1.691.53

Flavonoids

NutrientColumn NameUnitGlobal MeanGlobal SD
Flavan-3-olFlavan-3-olmg/day95.885.9
FlavonesFlavonesmg/day1.550.07
FlavonolsFlavonolsmg/day17.76.79
FlavononesFlavononesmg/day11.73.82
AnthocyanidinsAnthocyanidinsmg/day18.0521.14
IsoflavonesIsoflavonesmg/day1.20.2

Spices & Herbs

NutrientColumn NameUnitGlobal MeanGlobal SD
GarlicGarlicg/day4.352.9
GingerGingerg/day5963.2
OnionOniong/day35.918.4
PepperPepperg/day107.07
TurmericTurmericmg/day533.6754.3
SaffronSaffrong/day0.371.78
EugenolEugenolmg/day0.010.08
Thyme/oreganoThyme/oreganomg/day0.330.99
RosemaryRosemarymg/day115

Missing Data

  • Nutrients not in your data are automatically excluded from the DII sum
  • Individual missing values (NaN) for specific participants are excluded for that participant
  • A warning is issued if less than 25% of nutrients (11/45) are available
  • More nutrients = more accurate DII scores

Features

Detailed Output

Get per-nutrient contributions to understand what's driving each score:

detailed=calculate_dii(nutrients, detailed=True)
# View all columnsprint(detailed.columns.tolist())
# ['Fiber', 'Fiber_zscore', 'Fiber_percentile', 'Fiber_contribution', # 'Alcohol', 'Alcohol_zscore', ... , 'DII_score']# Examine contributionscontrib_cols= [cforcindetailed.columnsifc.endswith('_contribution')]
print(detailed[contrib_cols].describe())

Visualization

Three turn-key visualization functions are included in the package (using matplotlib):

fromdiiimport (
plot_dii_distribution,
plot_nutrient_contributions,
plot_dii_categories_pie,
)
# Distribution histogram with category coloringplot_dii_distribution(results, save_path="dii_distribution.png")
# Horizontal bar chart of nutrient contributionsplot_nutrient_contributions(detailed.iloc[0], save_path="contributions.png")
# Pie chart of DII categoriesplot_dii_categories_pie(results, save_path="categories.png")

DII Score Distribution

Nutrient Contributions

DII Categories

Command-Line Interface

# Basic usage
dii input.csv -o results.csv
# With detailed output
dii input.csv -o results.csv --detailed
# Specify ID column
dii input.csv -o results.csv --id-column participant_id
# List all supported nutrients with units
dii --nutrients
# Show help
dii --help

Templates

Ready-to-use templates are provided in the templates/ folder:

FileDescription
input_template.csvEmpty CSV with all 45 nutrient columns
analysis_template.ipynbJupyter notebook workflow
TEMPLATE_README.mdComplete unit reference guide

Validation

Methodology

This implementation was validated against three independent sources:

  1. Original R code from study statistician Jeanette M. Andrade, PhD, RDN (University of Florida)
  2. Independent verification by Jiyan Aslan Ceylan (University of Florida, June 2025)
  3. Cross-validation with the dietaryindex R package by Jiada (James) Zhan

Results

MetricValue
Sample size13,580 NHANES participants
Mean absolute error< 1×10⁻¹⁰
Maximum absolute error< 1×10⁻⁹
Pearson correlation1.000000

Synthetic Test Cases

Three validation rows with mathematically-derived expected values are included in the sample data:

SEQNDescriptionExpected DIICalculated DIIAbsolute Error
1All nutrients at global mean0.0000000.000000< 1×10⁻¹⁰
2Maximally anti-inflammatory-7.004394-7.004394< 1×10⁻⁹
3Maximally pro-inflammatory+7.004394+7.004394< 1×10⁻⁹

Precision

  • All calculations use IEEE 754 double precision (numpy.float64)
  • Infinity values from edge cases are converted to NaN
  • Validation tolerance: 1×10⁻¹⁰

For detailed validation results, see examples/validation.ipynb.


API Reference

Core Functions

calculate_dii(nutrient_data, reference_df=None, id_column=None, detailed=False, validate_bounds=True)

Calculate DII scores for a DataFrame of nutrient intakes.

Parameters:

  • nutrient_data (pd.DataFrame): Input data with nutrient columns
  • reference_df (pd.DataFrame, optional): Custom reference table
  • id_column (str, optional): Column name for participant IDs
  • detailed (bool): Return per-nutrient breakdown
  • validate_bounds (bool): Warn about extreme values

Returns: pd.DataFrame with DII scores

get_available_nutrients()

Returns a list of all 45 DII nutrient names.

load_reference_table(custom_path=None)

Load the DII reference table with weights and global statistics.

Visualization Functions

plot_dii_distribution(dii_scores, title=..., save_path=None, show=True)

Create a histogram of DII scores colored by inflammatory category.

plot_nutrient_contributions(detailed_row, save_path=None, show=True)

Create a horizontal bar chart showing each nutrient's contribution.

plot_dii_categories_pie(dii_scores, save_path=None, show=True)

Create a pie chart of anti-inflammatory, neutral, and pro-inflammatory categories.


Citation

If you use this package in your research, please cite both the software and the original methodology:

Software Citation

@software{clark_strath_2025_dii,
author = {Clark, Ted and Strath, Larissa},
title = {{dii-calculator: Dietary Inflammatory Index Calculator for Python}},
year = {2025},
version = {1.0.12},
url = {https://github.com/strathlab-data/DII},
note = {Python package validated against dietaryindex R package}
}

Methodology Citation

@article{shivappa2014dii,
author = {Shivappa, Nitin and Steck, Susan E. and Hurley, Thomas G. and  Hussey, James R. and H{\'e}bert, James R.},
title = {Designing and developing a literature-derived, population-based  dietary inflammatory index},
journal = {Public Health Nutrition},
year = {2014},
volume = {17},
number = {8},
pages = {1689--1696},
doi = {10.1017/S1368980013002115}
}

See also CITATION.cff for machine-readable citation information.


References

  1. Shivappa N, Steck SE, Hurley TG, Hussey JR, Hébert JR. Designing and developing a literature-derived, population-based dietary inflammatory index. Public Health Nutr. 2014;17(8):1689-1696. doi:10.1017/S1368980013002115

  2. Zhan J, Hodge RA, Dunlop AL, et al. Dietaryindex: a user-friendly and versatile R package for standardizing dietary pattern analysis in epidemiological and clinical studies. Am J Clin Nutr. 2024. doi:10.1016/j.ajcnut.2024.08.021


License

MIT License — see LICENSE for details.


Authors

Department of Health Outcomes and Biomedical Informatics, College of Medicine


Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.


Acknowledgments

  • Dr. Jeanette M. Andrade (University of Florida) for providing the original R validation code
  • Jiyan Aslan Ceylan (University of Florida) for independent validation review
  • Jiada (James) Zhan for the dietaryindex R package

Releases

Packages

Contributors

Languages