grafs_e package#
Submodules#
grafs_e.N_class module#
- class grafs_e.N_class.CultureData(data_loader, year, region, categories_mapping={'Alfalfa and clover': 'temporary meadows', 'Barley': 'cereals (excluding rice)', 'Cabbage': 'fruits and vegetables', 'Citrus': 'fruits and vegetables', 'Dry beans': 'leguminous', 'Dry fruits': 'fruits and vegetables', 'Dry vegetables': 'fruits and vegetables', 'Flax': 'oleaginous', 'Forage cabbages': 'forages', 'Forage maize': 'forages', 'Fruits': 'fruits and vegetables', 'Grain maize': 'cereals (excluding rice)', 'Green beans': 'leguminous', 'Green peas': 'leguminous', 'Hemp': 'oleaginous', 'Horse beans and faba beans': 'leguminous', 'Leaves vegetables': 'fruits and vegetables', 'Natural meadow ': 'natural meadows ', 'Non-legume temporary meadow': 'temporary meadows', 'Oat': 'cereals (excluding rice)', 'Olives': 'fruits and vegetables', 'Other cereals': 'cereals (excluding rice)', 'Other oil crops': 'leguminous', 'Other protein crops': 'leguminous', 'Other roots': 'roots', 'Peas': 'leguminous', 'Potatoes': 'roots', 'Rapeseed': 'oleaginous', 'Rice': 'rice', 'Rye': 'cereals (excluding rice)', 'Soybean': 'leguminous', 'Squash and melons': 'fruits and vegetables', 'Straw': 'forages', 'Sugar beet': 'roots', 'Sunflower': 'oleaginous', 'Wheat': 'cereals (excluding rice)'})[source]#
Bases:
object
This class processes and creates a dataframe with crop data for a specific year and region.
The class uses the provided DataLoader instance to load and preprocess the data. It extracts relevant crop-related information such as surface area, crop production, nitrogen production, and fertilization needs, and combines them into a comprehensive dataframe.
- Args:
data_loader (DataLoader): An instance of the DataLoader class used to load and preprocess the data. region (str): The region for which to create the crop dataframe. year (str): The year for which to create the crop dataframe. categories_mapping (dict): A dictionary used to classify each crop, mapping crop names to categories.
- Attributes:
region (str): The region for which the crop data is processed. year (str): The year for which the crop data is processed. df (pandas.DataFrame): A dataframe containing the preprocessed data for the specified year and region. data_path (str): The path to the directory containing the data files. categories_mapping (dict): A dictionary mapping crop names to their respective categories. df_cultures (pandas.DataFrame): The final dataframe containing the processed crop data, including surface area,
crop production, nitrogen production, yield, and fertilization needs.
- Methods:
- create_culture_dataframe():
Processes the raw data to create the crop dataframe. This dataframe includes: - Crop surface area (in hectares). - Crop production (in kton DFW). - Nitrogen production (in kton N). - Yield per hectare (in qtl/ha). - Fertilization needs per hectare (in kgN/ha). The method performs various data transformations and calculations, including filling missing values with zero.
- create_culture_dataframe()[source]#
Processes the raw data to create the crop dataframe.
The dataframe includes: - Crop surface area (in hectares). - Crop production (in kton DFW). - Nitrogen production (in kton N). - Yield per hectare (in qtl/ha). - Fertilization needs per hectare (in kgN/ha).
This method performs the following steps: - Extracts crop surface and production data from the main dataframe. - Reads additional crop-specific data (fertilization and nitrogen content) from an external Excel file. - Calculates the nitrogen production and yield based on crop production and surface area. - Computes fertilization needs per hectare based on crop yield. - Fills missing values with zero.
- Returns:
pandas.DataFrame: A dataframe containing the processed crop data.
- class grafs_e.N_class.DataLoader[source]#
Bases:
object
Load the GRAFS Excel file (written by Julia Le Noë).
This class makes it possible to access all the data stored in the Excel file. Currently, only yearly data (area, production, etc.) are accessed. Stable data is stored in the ‘GRAFS_data.xlsx’ file.
This class will become obsolete once a proper database is built.
No arguments are required; the script automatically finds the Excel sheet. Loading time: approximately 40 seconds.
- class grafs_e.N_class.ElevageData(data_loader, year, region)[source]#
Bases:
object
This class processes and creates a dataframe containing livestock data for a specific year and region.
The class uses data from the provided DataLoader instance, filters and processes it to generate a dataframe containing livestock production and emissions data.
- Args:
data_loader (DataLoader): An instance of the DataLoader class used to load and preprocess the data. year (str): The year for which to generate the livestock dataframe. region (str): The region for which to generate the livestock dataframe.
- Attributes:
region (str): The region for which the livestock data is processed. year (str): The year for which the livestock data is processed. df (pandas.DataFrame): A dataframe containing the preprocessed data for the specified year and region. data_path (str): The path to the directory containing the data files. dataloader (DataLoader): The instance of the DataLoader used to load the data. df_elevage (pandas.DataFrame): The final dataframe containing livestock production and emissions data.
- Methods:
- create_elevage_dataframe():
Processes the pre-loaded data to create the livestock dataframe, which includes both production data and associated emission data. The production data is filtered and matched with gas emission data for the specified region, and missing values are filled with zero.
- create_elevage_dataframe()[source]#
Processes the raw data to create the livestock dataframe.
The dataframe includes the following: - Livestock production data (in kton carcass) for the specified region. - Gas emissions data related to livestock (volatilisation) linked by the ‘Elevage’ index.
- Returns:
pandas.DataFrame: A dataframe containing the processed livestock production data and gas emissions data.
- class grafs_e.N_class.FluxGenerator(labels)[source]#
Bases:
object
This class generates and manages the transition matrix of fluxes between various sectors (e.g., agriculture, livestock, industry, trade).
The transition matrix is used to model the flow of resources or interactions between sectors, where each entry in the matrix represents the relationship or flow between a source sector and a target sector.
- Args:
labels (list): A list of labels representing the sectors (e.g., [‘agriculture’, ‘livestock’, ‘industry’, ‘trade’]) in the model. These labels are used to index the transition matrix and identify the sectors in the flux calculations.
- Attributes:
labels (list): The list of labels (sectors) that are used to define the transition matrix. label_to_index (dict): A dictionary mapping each label (sector) to its corresponding index in the adjacency matrix. n (int): The number of sectors (i.e., the length of the labels list). adjacency_matrix (numpy.ndarray): A square matrix of size n x n representing the fluxes between sectors. Each element in the matrix holds the transition coefficient between a source and a target sector.
- Methods:
- generate_flux(source, target):
Generates and updates the transition matrix by calculating flux coefficients between the source and target sectors. The coefficients are based on the provided source and target dictionaries.
- get_coef(source_label, target_label):
Retrieves the transition coefficient for the flux between two sectors (identified by their labels) from the transition matrix.
- generate_flux(source, target)[source]#
Generates and updates the transition matrix by calculating the flux coefficients between the source and target sectors.
- Args:
source (dict): A dictionary representing the source sector, where keys are sector labels and values are the corresponding flux values. target (dict): A dictionary representing the target sector, where keys are sector labels and values are the corresponding flux values.
This method updates the adjacency matrix by computing the flux between all pairs of source and target sectors. A flux coefficient is calculated as the product of the corresponding values from the source and target dictionaries. If the coefficient exceeds a small threshold (10^-7), it is added to the matrix at the corresponding position.
- get_coef(source_label, target_label)[source]#
Retrieves the transition coefficient between two sectors from the adjacency matrix.
- Args:
source_label (str): The label of the source sector. target_label (str): The label of the target sector.
- Returns:
float or None: The transition coefficient between the source and target sectors. Returns None if either sector is not found in the matrix.
- class grafs_e.N_class.NitrogenFlowModel(data, year, region, categories_mapping={'Alfalfa and clover': 'temporary meadows', 'Barley': 'cereals (excluding rice)', 'Cabbage': 'fruits and vegetables', 'Citrus': 'fruits and vegetables', 'Dry beans': 'leguminous', 'Dry fruits': 'fruits and vegetables', 'Dry vegetables': 'fruits and vegetables', 'Flax': 'oleaginous', 'Forage cabbages': 'forages', 'Forage maize': 'forages', 'Fruits': 'fruits and vegetables', 'Grain maize': 'cereals (excluding rice)', 'Green beans': 'leguminous', 'Green peas': 'leguminous', 'Hemp': 'oleaginous', 'Horse beans and faba beans': 'leguminous', 'Leaves vegetables': 'fruits and vegetables', 'Natural meadow ': 'natural meadows ', 'Non-legume temporary meadow': 'temporary meadows', 'Oat': 'cereals (excluding rice)', 'Olives': 'fruits and vegetables', 'Other cereals': 'cereals (excluding rice)', 'Other oil crops': 'leguminous', 'Other protein crops': 'leguminous', 'Other roots': 'roots', 'Peas': 'leguminous', 'Potatoes': 'roots', 'Rapeseed': 'oleaginous', 'Rice': 'rice', 'Rye': 'cereals (excluding rice)', 'Soybean': 'leguminous', 'Squash and melons': 'fruits and vegetables', 'Straw': 'forages', 'Sugar beet': 'roots', 'Sunflower': 'oleaginous', 'Wheat': 'cereals (excluding rice)'}, labels=['Wheat', 'Rye', 'Barley', 'Oat', 'Grain maize', 'Rice', 'Other cereals', 'Straw', 'Forage maize', 'Forage cabbages', 'Rapeseed', 'Sunflower', 'Other oil crops', 'Sugar beet', 'Potatoes', 'Other roots', 'Dry vegetables', 'Dry fruits', 'Squash and melons', 'Cabbage', 'Leaves vegetables', 'Fruits', 'Olives', 'Citrus', 'Hemp', 'Flax', 'Non-legume temporary meadow', 'Horse beans and faba beans', 'Peas', 'Other protein crops', 'Green peas', 'Dry beans', 'Green beans', 'Soybean', 'Alfalfa and clover', 'Natural meadow ', 'bovines', 'ovines', 'caprines', 'porcines', 'poultry', 'equine', 'urban', 'rural', 'NH3 volatilization', 'N2O emission', 'hydro-system', 'other losses', 'soil stock', 'atmospheric N2', 'Haber-Bosch', 'other sectors', 'animal trade', 'fishery products', 'cereals (excluding rice) food trade', 'fruits and vegetables food trade', 'leguminous food trade', 'oleaginous food trade', 'roots food trade', 'rice food trade', 'cereals (excluding rice) feed trade', 'leguminous feed trade', 'oleaginous feed trade', 'forages feed trade', 'temporary meadows feed trade'], cultures=['Wheat', 'Rye', 'Barley', 'Oat', 'Grain maize', 'Rice', 'Other cereals', 'Straw', 'Forage maize', 'Forage cabbages', 'Rapeseed', 'Sunflower', 'Other oil crops', 'Sugar beet', 'Potatoes', 'Other roots', 'Dry vegetables', 'Dry fruits', 'Squash and melons', 'Cabbage', 'Leaves vegetables', 'Fruits', 'Olives', 'Citrus', 'Hemp', 'Flax', 'Non-legume temporary meadow'], legumineuses=['Horse beans and faba beans', 'Peas', 'Other protein crops', 'Green peas', 'Dry beans', 'Green beans', 'Soybean', 'Alfalfa and clover'], prairies=['Natural meadow '], betail=['bovines', 'ovines', 'caprines', 'porcines', 'poultry', 'equine'], Pop=['urban', 'rural'], ext=['NH3 volatilization', 'N2O emission', 'hydro-system', 'other losses', 'soil stock', 'atmospheric N2', 'Haber-Bosch', 'other sectors', 'animal trade', 'fishery products', 'cereals (excluding rice) food trade', 'fruits and vegetables food trade', 'leguminous food trade', 'oleaginous food trade', 'roots food trade', 'rice food trade', 'cereals (excluding rice) feed trade', 'leguminous feed trade', 'oleaginous feed trade', 'forages feed trade', 'temporary meadows feed trade'])[source]#
Bases:
object
This class models the nitrogen flow in an agricultural system, calculating fluxes and nitrogen dynamics for different sectors (e.g., crops, livestock) over a given year and region.
The model incorporates various processes, including crop production, animal production, nitrogen emissions, and fertilization, and computes the corresponding nitrogen fluxes between sectors using transition matrices.
This class provides methods to compute fluxes, generate heatmaps, and access matrices such as the transition matrix, core matrix, and adjacency matrix.
For a detailed explanation of the model’s methodology and mathematical foundations, please refer to the associated scientific paper: Tracking Nitrogen Dynamics: A Disaggregated Approach for French Agro-Food Systems, 2025, Adrien Fauste-Gay (pre-print).
- Args:
data (DataLoader): An instance of the DataLoader class to load and preprocess the data. year (str): The year for which to compute the nitrogen flow model. region (str): The region for which to compute the nitrogen flow model. categories_mapping (dict, optional): A dictionary used to classify each crop. Defaults to categories_mapping. labels (list, optional): A list of labels representing the sectors in the model. Defaults to labels. cultures (CultureData, optional): An instance of the CultureData class for crop data processing. legumineuses (list, optional): A list representing leguminous crops in the model. prairies (list, optional): A list representing grasslands and prairies in the model. betail (list, optional): A list representing livestock categories in the model. Pop (list, optional): A list representing the population data. ext (list, optional): A list representing external data or processes affecting nitrogen fluxes.
- Attributes:
year (str): The year for which the nitrogen flow model is computed. region (str): The region for which the nitrogen flow model is computed. categories_mapping (dict): The dictionary used to classify crops. labels (list): The list of labels representing the sectors in the model. data_loader (DataLoader): The instance of the DataLoader used to load the data. culture_data (CultureData): An instance of the CultureData class for crop data. elevage_data (ElevageData): An instance of the ElevageData class for livestock data. flux_generator (FluxGenerator): An instance of the FluxGenerator class to generate flux coefficients. df_cultures (pandas.DataFrame): The dataframe containing crop data. df_elevage (pandas.DataFrame): The dataframe containing livestock data. adjacency_matrix (numpy.ndarray): The matrix representing nitrogen fluxes between sectors. label_to_index (dict): A dictionary mapping sector labels to matrix indices.
- Methods:
- compute_fluxes():
Computes the nitrogen fluxes between the sectors of the model. This method populates the adjacency matrix with flux coefficients based on the interactions between crops, livestock, emissions, and fertilization.
- plot_heatmap():
Generates a heatmap visualization of the transition matrix for nitrogen fluxes.
- plot_heatmap_interactive():
Generates an interactive heatmap for the nitrogen fluxes.
- get_df_culture():
Returns the dataframe containing crop data.
- get_df_elevage():
Returns the dataframe containing livestock data.
- get_transition_matrix():
Returns the transition matrix representing nitrogen fluxes between sectors.
- get_core_matrix():
Returns the core matrix representing the primary fluxes in the system.
- get_adjacency_matrix():
Returns the adjacency matrix, which is used to represent the complete set of nitrogen fluxes between sectors.
- extract_input_output_matrixs():
Extracts and returns the input-output matrices of nitrogen fluxes.
- imported_nitrogen():
Returns the total amount of imported nitrogen in the system.
- net_imported_plant():
Returns the net imported nitrogen for plants.
- net_imported_animal():
Returns the net imported nitrogen for livestock.
- total_plant_production():
Returns the total plant production in the model.
- stacked_plant_production():
Returns a stacked representation of plant production data.
- LU_density()[source]#
Calculates the livestock unit density over the agricultural area.
- Returns:
Livestock unit per hectare (LU/ha).
- Return type:
float
- N2O_em()[source]#
Returns the total N₂O emissions in the system.
- Returns:
N₂O emissions in kt.
- Return type:
float
- NH3_vol()[source]#
Returns the total NH₃ volatilization in the system.
- Returns:
NH₃ emissions in kt.
- Return type:
float
- NUE()[source]#
Calculates the crop-level nitrogen use efficiency (NUE).
Defined as the ratio of nitrogen produced by crops over total nitrogen inputs.
- Returns:
NUE of crop systems (%).
- Return type:
float
- NUE_system()[source]#
Calculates system-wide nitrogen use efficiency, including crop and livestock production.
Accounts for feed losses and nitrogen consumed via imported feed.
- Returns:
System-wide NUE (%).
- Return type:
float
- NUE_system_2()[source]#
Alternative NUE computation considering livestock conversion factors and feed inputs.
Includes non-edible nitrogen outputs and imported feed consumption in the calculation.
- Returns:
Adjusted system-wide NUE (%).
- Return type:
float
- N_self_sufficient()[source]#
Estimates nitrogen self-sufficiency of the system.
Defined as the share of atmospheric (biological) nitrogen inputs relative to all external nitrogen sources.
- Returns:
Self-sufficiency ratio (%).
- Return type:
float
- Y(culture)[source]#
Computes the nitrogen yield of a given crop.
Yield is calculated as nitrogen production (kgN) per hectare for the specified crop.
- Parameters:
culture (str) – The name of the crop (index of df_cultures).
- Returns:
Nitrogen yield in kgN/ha.
- Return type:
float
- animal_production()[source]#
Returns the total edible nitrogen produced by livestock sectors.
- Returns:
Total nitrogen in edible animal products (in ktN).
- Return type:
float
- cereals_production()[source]#
Returns the nitrogen production from cereal crops.
- Returns:
Total nitrogen from cereals (in ktN).
- Return type:
float
- cereals_production_r()[source]#
Returns the share of nitrogen production from cereals relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from cereals.
- Return type:
float
- compute_fluxes()[source]#
Computes the nitrogen fluxes for all sectors in the model.
This method populates the adjacency matrix with flux coefficients based on sector interactions. These interactions include crop production, livestock production, nitrogen emissions, and fertilization. The coefficients are used to model the flow of nitrogen between sectors over the specified year and region.
The computation involves complex mathematical processes, which are detailed in the associated scientific methodology paper: Tracking Nitrogen Dynamics: A Disaggregated Approach for French Agro-Food Systems, 2025, Adrien Fauste-Gay (pre-print).
For an in-depth explanation of the model’s functioning, please refer to the accompanying paper.
- emissions()[source]#
Computes the total nitrogen emissions from the system.
Includes N₂O emissions, atmospheric N₂ release, and NH₃ volatilization, with unit conversions.
- Returns:
A pandas Series with nitrogen emission quantities.
- Return type:
pandas.Series
- env_footprint()[source]#
Calculates the land footprint (in ha) of nitrogen flows linked to: - local food and feed production, - imported food and feed, - imported and exported livestock nitrogen, - crop exports for feed and food.
This is expressed as theoretical land areas mobilized by the nitrogen content.
- Returns:
A pandas Series of land footprint values (in ha), positive for imports and local use, negative for exports.
- Return type:
pandas.Series
- extract_input_output_matrixs(clean=True)[source]#
Extracts input and output matrices (C and B blocks) from the full transition matrix.
These matrices represent the nitrogen flows between core and external sectors: - B: Outputs from core to external sectors. - C: Inputs from external to core sectors.
If clean is True, the method removes rows and columns corresponding to inactive sectors.
- Parameters:
clean (bool) – Whether to remove zero-flow sectors from the matrices.
- Returns:
A tuple (B, C) of NumPy arrays.
- Return type:
tuple[numpy.ndarray, numpy.ndarray]
- fruits_and_vegetable_production()[source]#
Returns the nitrogen production from fruits and vegetables crops.
- Returns:
Total nitrogen from fruits and vegetables (in ktN).
- Return type:
float
- fruits_and_vegetable_production_r()[source]#
Returns the share of nitrogen production from fruits and vegetables relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from fruits and vegetables.
- Return type:
float
- get_adjacency_matrix()[source]#
Returns the binary adjacency matrix of nitrogen fluxes.
This matrix has the same dimensions as the core matrix and indicates the presence (1) or absence (0) of nitrogen fluxes between sectors.
- Returns:
A binary adjacency matrix.
- Return type:
numpy.ndarray
- get_core_matrix()[source]#
Extracts and returns the core matrix of nitrogen fluxes between active sectors.
This method filters out rows and columns with no flows and excludes external sectors. The result isolates the central dynamics of the system.
- Returns:
A 2D NumPy array of the filtered core matrix.
- Return type:
numpy.ndarray
- get_df_culture()[source]#
Returns the DataFrame containing crop-related data.
- Returns:
A pandas DataFrame with crop data used in the nitrogen model.
- Return type:
pandas.DataFrame
- get_df_elevage()[source]#
Returns the DataFrame containing livestock-related data.
- Returns:
A pandas DataFrame with livestock data used in the nitrogen model.
- Return type:
pandas.DataFrame
- get_transition_matrix()[source]#
Returns the full nitrogen transition matrix.
This matrix represents all nitrogen fluxes between sectors, including core and external processes.
- Returns:
A 2D NumPy array representing nitrogen fluxes between all sectors.
- Return type:
numpy.ndarray
- grassland_and_forages_production()[source]#
Returns the nitrogen production from grassland and forages crops.
- Returns:
Total nitrogen from grassland and forages (in ktN).
- Return type:
float
- grassland_and_forages_production_r()[source]#
Returns the share of nitrogen production from forages relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from forages.
- Return type:
float
- imported_nitrogen()[source]#
Calculates the total amount of nitrogen imported into the system.
Includes nitrogen in imported food, feed, and excess feed.
- Returns:
Total imported nitrogen (in ktN).
- Return type:
float
- leguminous_production()[source]#
Returns the nitrogen production from leguminous crops.
- Returns:
Total nitrogen from leguminous (in ktN).
- Return type:
float
- leguminous_production_r()[source]#
Returns the share of nitrogen production from leguminous relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from leguminous.
- Return type:
float
- net_footprint()[source]#
Computes the net nitrogen land footprint of the region (in Mha).
Aggregates all imports and exports to yield a net balance of nitrogen-dependent land use.
- Returns:
Net land footprint (in million hectares).
- Return type:
float
- net_imported_animal()[source]#
Returns the net nitrogen export for animal sectors.
- Returns:
Total nitrogen exported via animal products (in ktN).
- Return type:
float
- net_imported_plant()[source]#
Computes the net nitrogen imports for plant sectors.
Calculated as the difference between total nitrogen imports and plant sector availability after local uses (feed and food).
- Returns:
Net nitrogen import for plant-based products (in ktN).
- Return type:
float
- oleaginous_production()[source]#
Returns the nitrogen production from oleaginous crops.
- Returns:
Total nitrogen from oleaginous (in ktN).
- Return type:
float
- oleaginous_production_r()[source]#
Returns the share of nitrogen production from oleaginous relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from oleaginous.
- Return type:
float
- plot_heatmap()[source]#
Generates a static heatmap to visualize the nitrogen flux transition matrix.
The heatmap displays the nitrogen fluxes between sectors using a logarithmic color scale. It provides a visual representation of the relative magnitudes of nitrogen fluxes, where each cell in the matrix corresponds to a transition from one sector (source) to another (target).
Features of the heatmap: - Logarithmic scale for better visualization of fluxes with wide value ranges (LogNorm is used with vmin=10^-4 and vmax set to the maximum value in the adjacency matrix). - Color palette is reversed “plasma” (plasma_r), with the color bar indicating flux magnitudes in kton/year. - Grid: A light gray grid is added for visual separation of cells. - Labels: Axis labels are moved to the top of the heatmap, with tick labels rotated for better readability. - Legend: Each sector is labeled with its corresponding index (e.g., “1: Agriculture”), positioned next to the heatmap.
- Args:
None
- Returns:
None: Displays the heatmap plot on screen.
- Note:
This method uses matplotlib and seaborn for visualization. Make sure these libraries are installed.
- plot_heatmap_interactive()[source]#
Generates an interactive heatmap using Plotly to visualize the nitrogen flux transition matrix.
The heatmap has the following features: - Logarithmic scale (simulated via log10(z)) to handle wide-ranging values. - A horizontal colorbar placed at the bottom of the plot. - A legend that maps matrix indices to sector labels, positioned on the right, ensuring no overlap. - The X-axis is displayed at the top of the plot, and the title is centered above the plot.
This visualization helps to understand the relative magnitudes of the nitrogen fluxes between sectors in a clear and interactive manner.
- Returns:
plotly.graph_objects.Figure: An interactive Plotly figure containing the heatmap.
- primXsec()[source]#
Calculates the percentage of nitrogen from secondary sources (biological or recycled), compared to the total nitrogen inputs.
Secondary sources include: human excretion, animal excretion, atmospheric inputs, seeds, and leguminous fixation.
- Returns:
Share of secondary sources in total nitrogen inputs (%).
- Return type:
float
- rel_fert()[source]#
Computes the relative share (%) of each nitrogen input source.
- Returns:
A pandas Series with nitrogen input sources as percentage of the total.
- Return type:
pandas.Series
- roots_production()[source]#
Returns the nitrogen production from roots crops.
- Returns:
Total nitrogen from roots (in ktN).
- Return type:
float
- roots_production_r()[source]#
Returns the share of nitrogen production from roots relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from roots.
- Return type:
float
- stacked_plant_production()[source]#
Returns the vector of nitrogen production by crop category.
- Returns:
A pandas Series of nitrogen production per crop.
- Return type:
pandas.Series
- surfaces()[source]#
Returns the cultivated area per crop.
- Returns:
A pandas Series with area per crop (in hectares).
- Return type:
pandas.Series
- surfaces_tot()[source]#
Returns the total cultivated area in the model.
- Returns:
Total area (in hectares).
- Return type:
float
grafs_e.app module#
- grafs_e.app.add_color_legend(m, vmin, vmax, cmap, metric_name)[source]#
Ajoute une légende de la colormap à la carte.
- grafs_e.app.get_metric_range(metrics)[source]#
Récupère les valeurs min et max de l’indicateur sélectionné.
grafs_e.donnees module#
grafs_e.graphes_objet module#
- class grafs_e.graphes_objet.GraphAnalyzer(G)[source]#
Bases:
object
- static calculate_Feff(matrix)[source]#
Calcule F à partir d’une matrice NumPy ou d’un graphe NetworkX.
- static calculate_Neff(matrix)[source]#
Calcule N = C.F à partir d’une matrice NumPy ou d’un graphe NetworkX.
- calculer_et_tracer_distribution_distances(nb_bins=50, titre='Distribution des distances entre les nœuds', sauvegarder=False, nom_fichier='histogramme_distances.png')[source]#
Calcule les plus courts chemins entre toutes les paires de nœuds dans un graphe pondéré dirigé, en utilisant la distance définie comme la somme des inverses des poids, et trace un histogramme de la distribution des distances avec une échelle logarithmique sur l’axe des abscisses.
- Parameters:
nb_bins – Nombre de barres dans l’histogramme
titre – Titre du graphique
sauvegarder – Booléen pour indiquer si le graphique doit être sauvegardé
nom_fichier – Nom du fichier pour la sauvegarde du graphique
- calculer_et_tracer_distribution_distances_V2(nb_bins=50, titre='Distribution des distances entre les nœuds', sauvegarder=False, nom_fichier='histogramme_distances.png')[source]#
Calcule les plus courts chemins en excluant les chemins passant par des nœuds intermédiaires spécifiques, puis trace l’histogramme des longueurs des plus courts chemins.
- Parameters:
nb_bins – Nombre de barres dans l’histogramme
titre – Titre du graphique
sauvegarder – Booléen indiquant si le graphique doit être sauvegardé
nom_fichier – Nom du fichier pour la sauvegarde du graphique
- Returns:
Longueur moyenne des chemins
- dijkstra_exclusion(source, weight='weight', exclude_nodes={})[source]#
Algorithme de Dijkstra personnalisé pour calculer les plus courts chemins dans un graphe, en excluant les nœuds intermédiaires appartenant à ‘exclude_nodes’, tout en permettant que les nœuds exclus soient utilisés comme nœud de départ ou nœud final.
- Parameters:
source – Le nœud de départ à partir duquel les chemins doivent être calculés
weight – Nom de l’attribut des arêtes représentant les poids (par défaut ‘weight’)
exclude_nodes – Ensemble des nœuds à exclure en tant que nœuds intermédiaires
- Returns:
distances, paths distances: dictionnaire {nœud: coût du plus court chemin depuis le nœud de départ} paths: dictionnaire {nœud: liste représentant le chemin le plus court depuis le nœud de départ}
- in_centrality()[source]#
Calcule la centralité d’entrée pondérée (somme des poids entrants) pour chaque nœud du graphe. :return: Dictionnaire {nœud: centralité d’entrée pondérée}
- obtenir_n_plus_courts_chemins(n)[source]#
Obtenir les ‘n’ plus courts chemins dans tout le graphe en appliquant l’algorithme dijkstra_exclusion, c’est-à-dire en excluant certains nœuds comme nœuds intermédiaires.
- Parameters:
G – Graphe NetworkX avec un attribut ‘weight’ pour les arêtes
n – Nombre total de chemins à retourner
- Returns:
Liste des ‘n’ plus courts chemins [(source, cible, coût, chemin)]
- class grafs_e.graphes_objet.GraphVisualizer(G)[source]#
Bases:
object
- afficher_chemins_graphiquement(n)[source]#
Affiche graphiquement les chemins trouvés dans le graphe, en ajustant les arêtes pour qu’elles se terminent à la périphérie des nœuds et non au centre. Utilise des labels avec un fond de la même couleur que les nœuds.
- Parameters:
n – Nombre total de plus courts chemins à afficher
- afficher_chemins_graphiquement_sous_graph(n)[source]#
Affiche graphiquement les chemins trouvés dans un graphe, en mettant en évidence uniquement les nœuds et les arêtes impliqués dans les chemins sélectionnés, avec les noms des nœuds affichés plutôt que leurs numéros.
- Parameters:
n – Nombre total de plus courts chemins à afficher
- afficher_chemins_graphiquement_tot(n)[source]#
Affiche graphiquement les chemins trouvés dans le graphe, en mettant en évidence les nœuds et les arêtes impliqués dans les chemins sélectionnés.
- Parameters:
n – Nombre total de plus courts chemins à afficher
- afficher_et_visualiser_10_noeuds_plus_proches(noeud_depart_label)[source]#
Affiche les 10 nœuds les plus proches du nœud de départ, leur flux total, et visualise le sous-graphe correspondant en excluant les nœuds intermédiaires spécifiés. L’épaisseur des liens est proportionnelle au flux (avec échelle logarithmique).
- Parameters:
noeud_depart_label – Label du nœud de départ
- afficher_et_visualiser_10_noeuds_plus_proches_2(noeud_depart_label)[source]#
Affiche les 10 nœuds les plus proches du nœud de départ, leur flux total, et visualise le sous-graphe correspondant en excluant les nœuds intermédiaires spécifiés. L’épaisseur des liens est proportionnelle au flux (avec échelle logarithmique).
- Parameters:
noeud_depart_label – Label du nœud de départ
- draw_custom_networkx_edges(subgraph, pos, edgelist=None, width=1, edge_color='blue', arrows=True, arrowstyle='->', arrowsize=15, node_size=300)[source]#
Dessine des arêtes avec des flèches ajustées pour qu’elles se terminent à la périphérie des nœuds.
- Parameters:
subgraph – Le sous-graphe NetworkX
pos – Positions des nœuds calculées par un layout (ex: nx.spring_layout)
edgelist – Liste des arêtes à dessiner (par défaut, toutes les arêtes du sous-graphe)
width – Largeur des arêtes (peut être une liste correspondant à chaque arête)
edge_color – Couleur des arêtes
arrows – Afficher des flèches ou non
arrowstyle – Style des flèches (‘->’, ‘-|>’, etc.)
arrowsize – Taille des flèches
node_size – Taille des nœuds pour ajuster les points de début et de fin des arêtes
- draw_hexagonal_graph(node_property, year=None, node_labels=None, scale=1.0, filename=None)[source]#
Dessine un graphe avec un layout hexagonal et une échelle logarithmique dynamique, en tenant compte d’un ordre fixe des nœuds spécifié par node_labels.
- Parameters:
node_property – Propriété scalaire des nœuds (dict) à représenter avec une échelle logarithmique pour la taille des nœuds
year – L’année à afficher en haut à gauche de l’image
node_labels – Liste des labels des nœuds pour fixer leur ordre (par défaut, tous les labels)
scale – Échelle du layout hexagonal
filename – Nom du fichier si vous souhaitez sauvegarder l’image
grafs_e.launch module#
- grafs_e.launch.run()[source]#
Script used by the ‘grafs-e’ command to launch the graphical interface.
- This function is executed when the user runs the grafs-e command. It:
Finds the path of the grafs_e package,
Constructs the full path to the app.py script (Streamlit app),
Simulates the execution of the Streamlit CLI command to start the app (streamlit run app.py),
Launches the Streamlit server using streamlit.web.cli.main().
- Returns:
None
- Return type:
None
grafs_e.prospective module#
- class grafs_e.prospective.CultureData_prospect(main, area, data_path, categories_mapping, func_prod)[source]#
Bases:
object
Prepare and structure crop data required for prospective scenarios in the NitrogenFlowModel.
This class constructs a DataFrame (df_cultures) that includes area, fertilization spread ratio, nitrogen content, and yield function parameters (depending on the selected model).
- create_culture_dataframe()[source]#
Construct the df_cultures DataFrame combining area, fertilization spreading ratio, nitrogen content, and yield function parameters for each crop.
The structure and included parameters depend on the selected yield function model.
- Returns:
A pandas DataFrame with all necessary parameters for crop modeling.
- Return type:
pd.DataFrame
- class grafs_e.prospective.ElevageData_prospect(main, technical, data_path)[source]#
Bases:
object
Prepare and structure livestock data required for prospective scenarios in the NitrogenFlowModel.
This class aggregates technical coefficients and main livestock statistics to compute nitrogen flows, production outputs, and excretion routes by species.
- create_elevage_dataframe(main, technical, data_path)[source]#
Construct the df_elevage DataFrame containing: - livestock units (LU) per species - productivity indicators (carcass and dairy) - excretion distributions - volatilisation rates - ingestion and nitrogen partitioning (edible, non-edible, excreted)
- Parameters:
main (pd.DataFrame) – General livestock statistics.
technical (pd.DataFrame) – Technical coefficients for livestock management.
data_path (str) – Path to nitrogen content Excel file.
- Returns:
A pandas DataFrame with livestock nitrogen and productivity balances.
- Return type:
pd.DataFrame
- class grafs_e.prospective.NitrogenFlowModel_prospect(scenar_path)[source]#
Bases:
object
Prospective extension of the NitrogenFlowModel for forward-looking nitrogen flow simulations.
This class initializes and manages all components required for scenario-based nitrogen budgeting. It uses scenario-specific sheets for inputs (land use, livestock, technical parameters), and dynamically computes nitrogen fluxes between labeled system compartments using an adjacency matrix.
- Attributes:
scenar_path (str): Path to the Excel file containing scenario sheets. labels (list): List of nitrogen system compartments used to label the adjacency matrix. df_cultures (pd.DataFrame): Crop-related nitrogen flows and parameters. df_elevage (pd.DataFrame): Livestock-related nitrogen flows and parameters. adjacency_matrix (np.ndarray): Matrix of nitrogen fluxes between compartments (in ktN/year). label_to_index (dict): Mapping from compartment labels to matrix indices. year (int): Scenario year (extracted from metadata). region (str): Scenario region (extracted from metadata).
- LU_density()[source]#
Calculates the livestock unit density over the agricultural area.
- Returns:
Livestock unit per hectare (LU/ha).
- Return type:
float
- N2O_em()[source]#
Returns the total N₂O emissions in the system.
- Returns:
N₂O emissions in kt.
- Return type:
float
- NH3_vol()[source]#
Returns the total NH₃ volatilization in the system.
- Returns:
NH₃ emissions in kt.
- Return type:
float
- NUE()[source]#
Calculates the crop-level nitrogen use efficiency (NUE).
Defined as the ratio of nitrogen produced by crops over total nitrogen inputs.
- Returns:
NUE of crop systems (%).
- Return type:
float
- NUE_system()[source]#
Calculates system-wide nitrogen use efficiency, including crop and livestock production.
Accounts for feed losses and nitrogen consumed via imported feed.
- Returns:
System-wide NUE (%).
- Return type:
float
- NUE_system_2()[source]#
Alternative NUE computation considering livestock conversion factors and feed inputs.
Includes non-edible nitrogen outputs and imported feed consumption in the calculation.
- Returns:
Adjusted system-wide NUE (%).
- Return type:
float
- N_self_sufficient()[source]#
Estimates nitrogen self-sufficiency of the system.
Defined as the share of atmospheric (biological) nitrogen inputs relative to all external nitrogen sources.
- Returns:
Self-sufficiency ratio (%).
- Return type:
float
- Y(culture)[source]#
Computes the nitrogen yield of a given crop.
Yield is calculated as nitrogen production (kgN) per hectare for the specified crop.
- Parameters:
culture (str) – The name of the crop (index of df_cultures).
- Returns:
Nitrogen yield in kgN/ha.
- Return type:
float
- animal_production()[source]#
Returns the total edible nitrogen produced by livestock sectors.
- Returns:
Total nitrogen in edible animal products (in ktN).
- Return type:
float
- cereals_production()[source]#
Returns the nitrogen production from cereal crops.
- Returns:
Total nitrogen from cereals (in ktN).
- Return type:
float
- cereals_production_r()[source]#
Returns the share of nitrogen production from cereals relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from cereals.
- Return type:
float
- compute_fluxes()[source]#
Compute nitrogen flows across all compartments for the given scenario.
- This method:
Retrieves key scenario inputs (year, region, crop and livestock data).
Initializes the flux generator using crop and livestock data.
Updates the adjacency matrix accordingly.
Must be called during initialization to populate model outputs.
- Returns:
None
- emissions()[source]#
Computes the total nitrogen emissions from the system.
Includes N₂O emissions, atmospheric N₂ release, and NH₃ volatilization, with unit conversions.
- Returns:
A pandas Series with nitrogen emission quantities.
- Return type:
pandas.Series
- env_footprint()[source]#
Calculates the land footprint (in ha) of nitrogen flows linked to: - local food and feed production, - imported food and feed, - imported and exported livestock nitrogen, - crop exports for feed and food.
This is expressed as theoretical land areas mobilized by the nitrogen content.
- Returns:
A pandas Series of land footprint values (in ha), positive for imports and local use, negative for exports.
- Return type:
pandas.Series
- extract_input_output_matrixs(clean=True)[source]#
Extracts input and output matrices (C and B blocks) from the full transition matrix.
These matrices represent the nitrogen flows between core and external sectors: - B: Outputs from core to external sectors. - C: Inputs from external to core sectors.
If clean is True, the method removes rows and columns corresponding to inactive sectors.
- Parameters:
clean (bool) – Whether to remove zero-flow sectors from the matrices.
- Returns:
A tuple (B, C) of NumPy arrays.
- Return type:
tuple[numpy.ndarray, numpy.ndarray]
- fruits_and_vegetable_production()[source]#
Returns the nitrogen production from fruits and vegetables crops.
- Returns:
Total nitrogen from fruits and vegetables (in ktN).
- Return type:
float
- fruits_and_vegetable_production_r()[source]#
Returns the share of nitrogen production from fruits and vegetables relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from fruits and vegetables.
- Return type:
float
- get_adjacency_matrix()[source]#
Returns the binary adjacency matrix of nitrogen fluxes.
This matrix has the same dimensions as the core matrix and indicates the presence (1) or absence (0) of nitrogen fluxes between sectors.
- Returns:
A binary adjacency matrix.
- Return type:
numpy.ndarray
- get_core_matrix()[source]#
Extracts and returns the core matrix of nitrogen fluxes between active sectors.
This method filters out rows and columns with no flows and excludes external sectors. The result isolates the central dynamics of the system.
- Returns:
A 2D NumPy array of the filtered core matrix.
- Return type:
numpy.ndarray
- get_df_culture()[source]#
Returns the DataFrame containing crop-related data.
- Returns:
A pandas DataFrame with crop data used in the nitrogen model.
- Return type:
pandas.DataFrame
- get_df_elevage()[source]#
Returns the DataFrame containing livestock-related data.
- Returns:
A pandas DataFrame with livestock data used in the nitrogen model.
- Return type:
pandas.DataFrame
- get_transition_matrix()[source]#
Returns the full nitrogen transition matrix.
This matrix represents all nitrogen fluxes between sectors, including core and external processes.
- Returns:
A 2D NumPy array representing nitrogen fluxes between all sectors.
- Return type:
numpy.ndarray
- grassland_and_forages_production()[source]#
Returns the nitrogen production from grassland and forages crops.
- Returns:
Total nitrogen from grassland and forages (in ktN).
- Return type:
float
- grassland_and_forages_production_r()[source]#
Returns the share of nitrogen production from forages relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from forages.
- Return type:
float
- imported_nitrogen()[source]#
Calculates the total amount of nitrogen imported into the system.
Includes nitrogen in imported food, feed, and excess feed.
- Returns:
Total imported nitrogen (in ktN).
- Return type:
float
- leguminous_production()[source]#
Returns the nitrogen production from leguminous crops.
- Returns:
Total nitrogen from leguminous (in ktN).
- Return type:
float
- leguminous_production_r()[source]#
Returns the share of nitrogen production from leguminous relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from leguminous.
- Return type:
float
- net_footprint()[source]#
Computes the net nitrogen land footprint of the region (in Mha).
Aggregates all imports and exports to yield a net balance of nitrogen-dependent land use.
- Returns:
Net land footprint (in million hectares).
- Return type:
float
- net_imported_animal()[source]#
Returns the net nitrogen export for animal sectors.
- Returns:
Total nitrogen exported via animal products (in ktN).
- Return type:
float
- net_imported_plant()[source]#
Computes the net nitrogen imports for plant sectors.
Calculated as the difference between total nitrogen imports and plant sector availability after local uses (feed and food).
- Returns:
Net nitrogen import for plant-based products (in ktN).
- Return type:
float
- oleaginous_production()[source]#
Returns the nitrogen production from oleaginous crops.
- Returns:
Total nitrogen from oleaginous (in ktN).
- Return type:
float
- oleaginous_production_r()[source]#
Returns the share of nitrogen production from oleaginous relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from oleaginous.
- Return type:
float
- plot_heatmap()[source]#
Plot a static heatmap of the nitrogen flux adjacency matrix.
The heatmap displays nitrogen transfers (in ktN/year) between system compartments, on a log scale. Axes are labeled with numerical indices, and a legend maps these indices to compartment names.
- Features:
Log-normalized color scale (“plasma_r”).
Axis ticks on top (X) and left (Y).
Custom colorbar and visual grid.
Aspect ratio constrained to “equal” for readability.
Compartment label legend placed on the right.
- Returns:
None
- plot_heatmap_interactive()[source]#
Generate an interactive Plotly heatmap of the nitrogen flux adjacency matrix.
This interactive version allows detailed inspection of each flux with tooltip information, uses a log10 transformation for the color scale, and supports hover interactivity and zooming.
- Features:
Simulated log-scale using log10.
Horizontal colorbar with real-world units (ktN/year).
Tooltip shows source, target, and value.
Index-to-label legend annotated on the right.
Matrix layout with reversed Y axis and axis ticks from 1 to N.
- Returns:
Plotly Figure object (can be shown with fig.show()).
- Return type:
plotly.graph_objs.Figure
- primXsec()[source]#
Calculates the percentage of nitrogen from secondary sources (biological or recycled), compared to the total nitrogen inputs.
Secondary sources include: human excretion, animal excretion, atmospheric inputs, seeds, and leguminous fixation.
- Returns:
Share of secondary sources in total nitrogen inputs (%).
- Return type:
float
- rel_fert()[source]#
Computes the relative share (%) of each nitrogen input source.
- Returns:
A pandas Series with nitrogen input sources as percentage of the total.
- Return type:
pandas.Series
- roots_production()[source]#
Returns the nitrogen production from roots crops.
- Returns:
Total nitrogen from roots (in ktN).
- Return type:
float
- roots_production_r()[source]#
Returns the share of nitrogen production from roots relative to total plant production.
- Returns:
Percentage of total plant nitrogen production from roots.
- Return type:
float
- stacked_plant_production()[source]#
Returns the vector of nitrogen production by crop category.
- Returns:
A pandas Series of nitrogen production per crop.
- Return type:
pandas.Series
- surfaces()[source]#
Returns the cultivated area per crop.
- Returns:
A pandas Series with area per crop (in hectares).
- Return type:
pandas.Series
- surfaces_tot()[source]#
Returns the total cultivated area in the model.
- Returns:
Total area (in hectares).
- Return type:
float
- class grafs_e.prospective.Y(dataloader=None)[source]#
Bases:
object
Class for modeling and fitting nitrogen yield response curves based on historical data.
This class extracts yield and fertilization data from NitrogenFlowModel instances, and provides a suite of theoretical models (e.g., Mitscherlich, exponential, linear) to fit production curves.
- Parameters:
dataloader (DataLoader, optional) – Optional instance of DataLoader to use. If None, a default one is initialized.
- Variables:
dataloader (DataLoader) – DataLoader instance used for retrieving regional crop data.
int_yr (list[int]) – List of integer years available in the dataset.
- static Y_th(f, y_max)[source]#
Mitscherlich-type yield response: Y = f * y_max / (f + y_max)
- Parameters:
f (float or np.ndarray) – Fertilization input (kgN/ha).
y_max (float) – Maximum attainable yield (kgN/ha).
- Returns:
Estimated yield.
- Return type:
float or np.ndarray
- static Y_th_exp(f, y_max, k)[source]#
Exponential growth model without cap.
- Computes yield as:
Y(f) = y_max * (1 - exp(-f / k))
- Parameters:
f (float or np.ndarray) – Fertilization input (kgN/ha).
y_max (float) – Maximum yield asymptote (kgN/ha).
k (float) – Growth curvature parameter (kgN/ha).
- Returns:
Yield response Y(f).
- Return type:
float or np.ndarray
- static Y_th_exp_cap(f, y_max, k)[source]#
Exponential response with physical cap at 99% of fertilization.
- Formula:
Y(f) = min(y_max * (1 - exp(-f / k)), 0.99 * f)
- Parameters:
f (float or np.ndarray) – Fertilization input (kgN/ha).
y_max (float) – Maximum yield asymptote (kgN/ha).
k (float) – Growth curvature parameter (kgN/ha).
- Returns:
Capped yield response Y(f).
- Return type:
float or np.ndarray
- static Y_th_lin(f, a, b)[source]#
Simple linear yield response with a saturation cap.
- Formula:
Y(f) = min(a * f, b)
- Parameters:
f (float or np.ndarray) – Fertilization input (kgN/ha).
a (float) – Linear coefficient.
b (float) – Maximum yield threshold.
- Returns:
Capped linear yield.
- Return type:
float or np.ndarray
- static Y_th_lin_2(f, a, xb, c)[source]#
Piecewise linear yield function with break at xb.
- Formula:
If f ≤ xb: Y = a * f
If f > xb: Y = c * (f - xb) + xb * a
- Parameters:
f (float or np.ndarray) – Fertilization input (kgN/ha).
a (float) – Initial slope before breakpoint.
xb (float) – Breakpoint fertilization value.
c (float) – Slope after breakpoint.
- Returns:
Yield response Y(f).
- Return type:
float or np.ndarray
- static Y_th_lin_2_smooth(f, a, xb, c, s)[source]#
Smooth piecewise linear function using logistic blending near the breakpoint.
- Formula:
transition = 1 / (1 + exp(-s * (f - xb))) Y(f) = (1 - transition) * a * f + transition * (c * (f - xb) + xb * a)
- Parameters:
f (float or np.ndarray) – Fertilization input (kgN/ha).
a (float) – Initial slope.
xb (float) – Breakpoint.
c (float) – Post-breakpoint slope.
s (float) – Sharpness of transition (higher = sharper).
- Returns:
Smoothed yield response Y(f).
- Return type:
float or np.ndarray
- static Y_th_poly(f, a, b)[source]#
Second-order polynomial yield response.
- Formula:
Y(f) = a * f² + b * f
- Parameters:
f (float or np.ndarray) – Fertilization input.
a (float) – Quadratic coefficient.
b (float) – Linear coefficient.
- Returns:
Polynomial yield response.
- Return type:
float or np.ndarray
- static Y_th_poly_cap(f, a, b)[source]#
Polynomial yield response capped at 99% of fertilization.
- Formula:
Y(f) = min(a * f² + b * f, 0.99 * f)
- Parameters:
f (float or np.ndarray) – Fertilization input.
a (float) – Quadratic coefficient.
b (float) – Linear coefficient.
- Returns:
Capped polynomial yield response.
- Return type:
float or np.ndarray
- static Y_th_sigmoid(f, Ymax, k, x0)[source]#
Sigmoidal yield response function.
- Formula:
Y(f) = Ymax / (1 + exp(-k * (f - x0)))
- Parameters:
f (float or np.ndarray) – Fertilization input.
Ymax (float) – Maximum yield.
k (float) – Growth steepness.
x0 (float) – Midpoint of the sigmoid.
- Returns:
Sigmoidal yield response.
- Return type:
float or np.ndarray
- static Y_th_sigmoid_cap(f, Ymax, k, x0)[source]#
Sigmoidal yield function with upper cap at 99% of fertilization input.
- Formula:
Y(f) = min(Ymax / (1 + exp(-k * (f - x0))), 0.99 * f)
- Parameters:
f (float or np.ndarray) – Fertilization input.
Ymax (float) – Maximum yield.
k (float) – Growth steepness.
x0 (float) – Inflection point.
- Returns:
Capped sigmoidal yield response.
- Return type:
float or np.ndarray
- compare_r2(region)[source]#
Compare fitted yield model results across crop types for a given region.
Evaluates and visualizes the yield ceiling (Ymax) or R² for multiple curve-fitting models: - Ratio-based (Mitscherlich) - Exponential - Linear (1 slope) - Linear (2 slopes) - Polynomial - Sigmoid
Results are displayed in a heatmap per culture for the selected region.
- Parameters:
region (str) – Region name or code.
- Returns:
Tuple of NumPy array with values and dictionary of model outputs.
- Return type:
Tuple[np.ndarray, dict]
- fit_Y(culture, region)[source]#
Fits a Mitscherlich-type yield curve (Y_th) to historical fertilization/yield data for a given crop and region.
Returns the optimal y_max value and the fitted curve.
- Parameters:
culture (str) – The name of the crop.
region (str) – The name of the region.
- Returns:
Tuple of (y_max, fitted_yield_values).
- Return type:
tuple[float or None, np.ndarray or None]
- fit_Y_exp(culture, region)[source]#
Fit an exponential yield curve (Y = Y_max(1-exp(F/k))) to historical data for a given crop (culture) and region using non-linear least squares.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
Tuple containing optimal parameters Y_max and k, and the fitted curve.
- Return type:
Tuple[float, float, np.ndarray | None]
- fit_Y_exp_2(culture, region)[source]#
Fit an exponential yield curve using a constrained optimization method (SLSQP). Ensures that k > Y_max for interpretability.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
Tuple with Y_max, k, and the fitted yield curve.
- Return type:
Tuple[float, float, np.ndarray | None]
- fit_Y_lin(culture, region)[source]#
Fit a simple linear model (Y = a * F + b) to yield data.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
Fitted slope and intercept with predicted yield.
- Return type:
Tuple[float, float, np.ndarray | None]
- fit_Y_lin_2(culture, region)[source]#
Fit a piecewise linear model with two slopes to capture yield response.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
Parameters a, xb (threshold), c (second slope), and the fitted curve.
- Return type:
Tuple[float, float, float, np.ndarray | None]
- fit_Y_lin_2_scipy(culture, region)[source]#
Fit the same piecewise linear model as fit_Y_lin_2 but using SLSQP optimizer.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
Optimized parameters a, xb, c and the yield prediction.
- Return type:
Tuple[float, float, float, np.ndarray | None]
- fit_Y_lin_2_smooth(culture, region)[source]#
Fit a smoothed two-slope model (sigmoid transition) for yield response.
- Parameters:
culture (str) – Crop name.
region (str) – Region identifier.
- Returns:
Parameters a, xb, c, s (smoothness), and predicted yield.
- Return type:
Tuple[float, float, float, float, np.ndarray | None]
- fit_Y_poly(culture, region)[source]#
Fit a 2nd-degree polynomial (Y = aF^2 + bF + c) to the data without constraints.
- Parameters:
culture (str) – Crop name.
region (str) – Region identifier.
- Returns:
Parameters a, b, c and the fitted values.
- Return type:
Tuple[float, float, float, np.ndarray | None]
- fit_Y_poly_constrained(culture, region)[source]#
Fit a constrained 2nd-degree polynomial to ensure concavity and meaningful shape (P(F)<F).
- Parameters:
culture (str) – Crop name.
region (str) – Region identifier.
- Returns:
Fitted parameters a, b and predicted yield values.
- Return type:
Tuple[float, float, np.ndarray | None]
- fit_Y_sigmoid(culture, region)[source]#
Fit a logistic sigmoid function (Y = Ymax / (1 + exp(-k(x - x0)))) to yield data.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
Parameters Ymax, k, x0 and fitted yield curve.
- Return type:
Tuple[float, float, float, np.ndarray | None]
- get_Y(culture, region, plot=False)[source]#
Extracts historical fertilization and yield data for a given crop and region.
Optionally displays a scatter plot of the data.
- Parameters:
culture (str) – The name of the crop (index in the NitrogenFlowModel).
region (str) – The name of the region.
plot (bool) – Whether to plot the data (default is False).
- Returns:
Tuple of arrays (F, Y), fertilization and yield values.
- Return type:
tuple[np.ndarray, np.ndarray]
- plot_Y(culture, region)[source]#
Plot the fitted Mitscherlich-type yield curve and historical data points for a specific crop and region.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region identifier.
- Returns:
None. The plot is displayed with matplotlib.
- Return type:
None
- plot_Y_exp(culture, region)[source]#
Plot the fitted exponential yield curve (capped) with the data for the specified crop.
- Parameters:
culture (str) – Name of the crop.
region (str) – Target region.
- Returns:
None. Plot appears inline.
- Return type:
None
- plot_Y_lin(culture, region)[source]#
Plot the fitted linear yield curve (Y = aF + b) and historical data for a crop.
- Parameters:
culture (str) – Crop name.
region (str) – Region identifier.
- Returns:
None. Displays the matplotlib plot.
- Return type:
None
- plot_Y_lin_2(culture, region)[source]#
Plot the fitted piecewise linear yield curve with two slopes and the historical data.
- Parameters:
culture (str) – Crop name.
region (str) – Region identifier.
- Returns:
None. The plot is rendered using matplotlib.
- Return type:
None
- plot_Y_lin_2_smooth(culture, region)[source]#
Plot the smooth transition linear-2 slope yield model and observed data points.
- Parameters:
culture (str) – Name of the crop.
region (str) – Region code.
- Returns:
None. Generates a yield vs fertilization curve.
- Return type:
None
- class grafs_e.prospective.scenario(scenario_path, dataloader=None)[source]#
Bases:
object
Loads and prepares scenario input sheets for prospective nitrogen flow modeling.
This class is used to initialize and manage scenario-specific data, which can be integrated into the NitrogenFlowModel to simulate future or alternative configurations of agro-food systems.
It either takes a pre-initialized DataLoader instance or initializes one internally if not provided.
- Parameters:
scenario_path (str) – Path to the scenario configuration file or directory.
dataloader (DataLoader, optional) – Optional pre-loaded DataLoader instance. If None, a default one is initialized.
- Variables:
scenario_path (str) – Absolute path to the scenario data file.
dataloader (DataLoader) – Instance of the DataLoader used to retrieve or modify base data.
data_path (str) – Path to the general data folder used for model input files.
- static LU_excretion(dataloader, region, t=None)[source]#
Computes average nitrogen excretion per livestock unit (LU) by species over time.
- Parameters:
dataloader (DataLoader) – The DataLoader object to use.
region (str) – Region name.
t (str or int, optional) – Optional key to extract values at a specific year.
- Returns:
Dictionary (or list) of excretion values by livestock type.
- Return type:
dict or list
- static LU_prod(dataloader, region, t=None)[source]#
Computes productivity (and dairy productivity) per LU for each livestock species.
- Parameters:
dataloader (DataLoader) – The DataLoader object to use.
region (str) – Region name.
t (str or int, optional) – Optional key to extract values at a specific year.
- Returns:
Dictionary (or list) of productivity values.
- Return type:
dict or list
- extrapolate_recent_trend(data, future_year, alpha=7.0, seuil_bas=0, seuil_haut=None)[source]#
Extrapolates a trend into the future using a weighted slope method.
Recent years are given higher weight. No predefined functional form is assumed.
- Parameters:
data (list or np.array) – List or array of historical values.
future_year (int) – Year until which to extrapolate.
alpha (float) – Slope weighting coefficient for recent years.
seuil_bas (float) – Lower bound of extrapolated values.
seuil_haut (float or None) – Upper bound of extrapolated values.
- Returns:
(extended_years, extended_values, slope)
- Return type:
tuple[np.array, np.array, float]
- generate_base_scenar(prod_func)[source]#
Generates baseline scenario Excel files for all regions, containing only the crop area distribution sheet.
This method is used to create an initial batch of region-specific scenario templates, filled with yield model projections for each crop, but without demand-side or technical assumptions.
- Parameters:
prod_func (str) – Name of the crop production function to apply (e.g., ‘Linear’, ‘Exponential’).
- Returns:
None. Excel files are saved to the default scenario directory.
- Return type:
None
- generate_crop_tab(region, function_name='Linear')[source]#
Generates a crop area table and fits a yield projection model for each crop.
Available models: ‘linear’, ‘linear2’, ‘exp’, ‘ratio’.
- Parameters:
region (str) – Region to generate data for.
function_name (str) – The model type used for yield extrapolation.
- Returns:
DataFrame with crop areas and model fit parameters.
- Return type:
pandas.DataFrame
- generate_scenario_excel(year, region, name, function_name='Linear')[source]#
Generates a full scenario Excel file for a given region and year.
This method populates all scenario sheets (documentation, main variables, area distribution, technical parameters) using historical data, regional projections (e.g., population), livestock structure, and crop productivity fits.
The output file includes default values for “Business as usual” configurations, which serve as a baseline for future simulations in prospective mode.
- Parameters:
year (int) – The future year for which to generate the scenario.
region (str) – The region to generate the scenario for.
name (str) – File name (without extension) of the output Excel scenario.
function_name (str) – Name of the yield model used for projection (e.g., ‘Linear’, ‘Exponential’).
- Returns:
None. The Excel file is saved to the configured scenario path.
- Return type:
None
- get_import_net(region)[source]#
Extracts net nitrogen import value for a given region over all years.
- Parameters:
region (str) – Region name.
- Returns:
List of net import values.
- Return type:
list[float]
- historic_trend(region, excel_line)[source]#
Extracts the historical trend of a value for a given region and Excel row in GRAFS_full.xslx.
- Parameters:
region (str) – The region of interest.
excel_line (int) – The row identifier (Excel line) to track.
- Returns:
List of historical values over available years.
- Return type:
list[float]
- static livestock_LU(dataloader, region, t=None)[source]#
Computes the number of livestock units (LU) per species over time.
- Parameters:
dataloader (DataLoader) – The DataLoader object to use.
region (str) – Region name.
t (str or int, optional) – Optional key to extract values at a specific year.
- Returns:
Dictionary (or list) of LU values by species.
- Return type:
dict or list
grafs_e.sankey module#
- grafs_e.sankey.merge_nodes(adjacency_matrix, labels, merges)[source]#
Merge groups of nodes (labels) in the adjacency matrix by combining their nitrogen fluxes.
This function allows you to combine multiple nodes (e.g., different sectors) into one, by summing their nitrogen fluxes. It takes a dictionary of node groupings (merges), where each key corresponds to a merged label, and the values are the original labels to be merged.
Parameters:#
- adjacency_matrixnp.ndarray
A square matrix of size (n, n) representing nitrogen fluxes, where each entry (i, j) indicates the nitrogen flow from node i to node j (in ktN/year).
- labelslist of str
A list of the original labels for the nodes, with length n.
- mergesdict
A dictionary defining which nodes to merge. The keys are the new labels for merged groups, and the values are lists of the labels to be merged. For example: {
“population”: [“urban”, “rural”], “livestock”: [“bovines”, “ovines”, “equine”, “poultry”, “porcines”, “caprines”], “industry”: [“haber-bosch”, “other sectors”]
}
Returns:#
- new_matrixnp.ndarray
The new adjacency matrix after merging the nodes, where the fluxes between merged nodes are summed.
- new_labelslist of str
The list of the new, merged labels.
- old_to_newdict
A dictionary mapping the original node indices to the new merged indices.
Notes:#
The function combines nitrogen fluxes between all nodes defined in merges, and returns a reduced matrix with fewer nodes, where the original nodes within each merged group are summed together.
- grafs_e.sankey.streamlit_sankey(transition_matrix, main_node, scope=1, index_to_label=None, index_to_color=None)[source]#
Creates an interactive Sankey diagram in Streamlit, displaying the incoming and outgoing flows of a main node with custom tooltips on hover.
The Sankey diagram is generated based on a transition matrix that models nitrogen flows between different sectors of the system. The function visualizes these flows, highlights the main node, and allows zooming into the flows within a defined scope.
Parameters:#
- transition_matrixnp.ndarray
A 2D NumPy array representing the transition matrix (flows between nodes in ktN/year).
- main_nodeint
The index of the node (sector) to be focused on, used as the central node for flow visualization.
- scopeint, optional
The scope of the flow display (i.e., the depth of incoming and outgoing flow visualization from the main node). Default is 1, meaning it shows only direct flows.
- index_to_labeldict, optional
A dictionary that maps indices of the transition matrix to sector labels for display.
- index_to_colordict, optional
A dictionary that maps indices of the transition matrix to colors for the nodes.
Returns:#
- None
The function directly displays the Sankey diagram in the Streamlit interface.
- grafs_e.sankey.streamlit_sankey_app(model, mode_complet)[source]#
Creates an interactive Sankey diagram in Streamlit, showing nitrogen flows in a system based on a given model.
This function allows users to select a main node (sector) and displays its incoming and outgoing nitrogen flows. The function supports two modes: - Full mode (mode_complet=True): Displays all nodes without any merging. - Simplified mode (mode_complet=False): Merges specific nodes (e.g., combining livestock or trade sectors) for a clearer overview.
In the simplified mode, nodes are merged based on a predefined set of groupings (e.g., merging various livestock categories into one).
Parameters:#
- modelNitrogenFlowModel
The nitrogen flow model containing the adjacency matrix (transition_matrix), labels, and other relevant data.
- mode_completbool
If True, no nodes are merged, and all sectors are shown individually. If False, some nodes are merged for simplicity.
Returns:#
- None
The function directly displays the Sankey diagram in the Streamlit interface.
- grafs_e.sankey.streamlit_sankey_fertilization(model, cultures, legumineuses, prairies, merges={'Industry': ['Haber-Bosch', 'other sectors'], 'Livestock': ['bovines', 'ovines', 'equine', 'poultry', 'porcines', 'caprines'], 'Population': ['urban', 'rural']}, THRESHOLD=0.1)[source]#
Creates a Sankey diagram showing the distribution of backward flows for crops, legumes, and grasslands, after merging specific nodes (e.g., “urban” + “rural” -> “population”). It filters out nodes and flows with throughflow/values below a given threshold.
The Sankey diagram visualizes nitrogen flows, helping to understand the system’s nutrient balance. In this diagram:
Nodes are merged based on predefined categories (e.g., merging various livestock types into one).
Only significant flows (above the THRESHOLD) are kept.
Backward flows (inflowing nitrogen) are shown, with nodes having a higher throughflow prioritized.
Parameters:#
- modelNitrogenFlowModel
The nitrogen flow model used to retrieve the adjacency matrix and labels for sectors.
- cultureslist of str
The list of crop labels involved in the Sankey diagram.
- legumineuseslist of str
The list of leguminous crop labels involved in the Sankey diagram.
- prairieslist of str
The list of grassland or prairie crop labels involved in the Sankey diagram.
- mergesdict, optional
A dictionary specifying the node groups to merge. The keys are the new merged labels, and the values are the labels of the nodes to merge. Default merges include:
“Population”: [“urban”, “rural”]
“Livestock”: [“bovines”, “ovines”, “equine”, “poultry”, “porcines”, “caprines”]
“Industry”: [“Haber-Bosch”, “other sectors”]
- THRESHOLDfloat, optional
The minimum value for flows and throughflows to be displayed. Default is 1e-1, meaning only flows above this threshold are kept in the visualization.
Returns:#
- None
This function directly displays the Sankey diagram in the Streamlit interface.
Notes:#
The function first merges nodes based on the merges dictionary, then constructs the Sankey diagram for backward flows. It uses THRESHOLD to filter out insignificant nodes and flows.
The color coding of nodes is customized based on predefined categories (e.g., “Livestock”, “Population”, etc.).
- grafs_e.sankey.streamlit_sankey_food_flows(model, cultures, legumineuses, prairies, trades, merges={'cereals (excluding rice) trade': ['cereals (excluding rice) food trade', 'cereals (excluding rice) feed trade'], 'fruits and vegetables trade': ['fruits and vegetables food trade', 'fruits and vegetables feed trade'], 'leguminous trade': ['leguminous food trade', 'leguminous feed trade'], 'oleaginous trade': ['oleaginous food trade', 'oleaginous feed trade']}, THRESHOLD=0.1)[source]#
Creates a Sankey diagram showing the distribution of food and feed flows (local, imports and exports) for crops, legumes, and grasslands after merging certain nodes (e.g., merging “urban” + “rural” into “population”). The diagram filters out nodes and flows with values below a given threshold (THRESHOLD).
- This function separates trade nodes into two categories:
“(import)” for incoming flows into the region,
“(export)” for outgoing flows from the region.
Parameters:#
- modelNitrogenFlowModel
The nitrogen flow model used to retrieve the adjacency matrix and labels for sectors.
- cultureslist of str
The list of crop labels involved in the Sankey diagram.
- legumineuseslist of str
The list of leguminous crop labels involved in the Sankey diagram.
- prairieslist of str
The list of grassland or prairie crop labels involved in the Sankey diagram.
- tradeslist of str
The list of trade-related labels to be included in the Sankey diagram.
- mergesdict, optional
A dictionary specifying the node groups to merge. The keys are the new merged labels, and the values are the labels of the nodes to merge. For example:
“cereals (excluding rice) trade”: [“cereals (excluding rice) food trade”, “cereals (excluding rice) feed trade”]
- THRESHOLDfloat, optional
The minimum value for flows to be displayed. Default is 1e-1, meaning only flows above this threshold will be shown.
Returns:#
- None
This function directly displays the Sankey diagram in the Streamlit interface.
Notes:#
The function merges specific nodes based on the merges dictionary, then constructs the Sankey diagram for food flows.
The diagram distinguishes between trade flows and non-trade flows, showing imports and exports separately.
Nodes and flows with values below the THRESHOLD are excluded from the final visualization.
- grafs_e.sankey.streamlit_sankey_systemic_flows(model, merges={'Environment': ['NH3 volatilization', 'N2O emission', 'hydro-system', 'other losses', 'atmospheric N2'], 'cereals (excluding rice)': ['Wheat', 'Rye', 'Barley', 'Oat', 'Grain maize', 'Rice', 'Other cereals'], 'forages': ['Forage maize', 'Forage cabbages', 'Straw'], 'fruits and vegetables': ['Dry vegetables', 'Dry fruits', 'Squash and melons', 'Cabbage', 'Leaves vegetables', 'Fruits', 'Olives', 'Citrus'], 'leguminous': ['Horse beans and faba beans', 'Peas', 'Other protein crops', 'Green peas', 'Dry beans', 'Green beans', 'Soybean'], 'monogastrics': ['porcines', 'poultry'], 'natural meadows ': ['Natural meadows '], 'oleaginous': ['Rapeseed', 'Sunflower', 'Other oil crops'], 'population': ['urban', 'rural'], 'roots': ['Sugar beet', 'Potatoes', 'Other roots'], 'ruminants': ['bovines', 'ovines', 'caprines', 'equine'], 'temporary meadows': ['Non-legume temporary meadow', 'Alfalfa and clover'], 'trade': ['animal trade', 'cereals (excluding rice) food trade', 'fruits and vegetables food trade', 'leguminous food trade', 'oleaginous food trade', 'roots food trade', 'rice food trade', 'cereals (excluding rice) feed trade', 'forages feed trade', 'leguminous feed trade', 'oleaginous feed trade', 'grasslands feed trade']})[source]#
DEPRECATED. Might be removed in futur release. Creates a systemic Sankey diagram displaying all flows from the adjacency matrix of the model.
The Sankey diagram includes all nitrogen flows between sectors and merges certain nodes based on the merges dictionary. Any flow with a value lower than the THRESHOLD is removed from the visualization.
Parameters:#
- modelNitrogenFlowModel
The nitrogen flow model containing the adjacency matrix and labels for sectors.
- mergesdict, optional
A dictionary specifying the nodes to merge. The keys are the new merged labels, and the values are lists of labels to merge. For example:
“cereals (excluding rice)”: [“Wheat”, “Rye”, “Barley”, “Oat”, “Grain maize”, “Rice”, “Other cereals”]
- THRESHOLDfloat, optional
The minimum value for flows to be displayed. Flows below this threshold are excluded from the diagram. The default is 1e-1, which removes flows with values smaller than 0.1 ktN/yr.
Returns:#
- None
This function directly displays the Sankey diagram in the Streamlit interface.
Notes:#
The diagram shows the distribution of all nitrogen flows between sectors after merging specific nodes.
The merging of nodes is defined in the merges dictionary, which groups multiple original labels into new merged labels.
The diagram includes both “import” and “export” flows for the trade-related nodes, and internal flows are displayed as well.
Any flow below the THRESHOLD value is filtered out from the visualization to keep only the significant flows.