<jupyter_start><jupyter_text>Contour plot function<jupyter_code>%matplotlib qt5
from biorefineries import lipidcane2g as lc
import biosteam as bst
import numpy as np
import pandas as pd
from biosteam.utils import colors
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
from biosteam.utils import colors
from biosteam.plots import plot_contour_2d, MetricBar, plot_scatter_points, plot_contour_1d
from math import floor, ceil
from biosteam import plots
from biosteam.utils import CABBI_colors
from thermosteam.units_of_measure import format_units
from biosteam.plots.utils import style_axis, style_plot_limits, fill_plot, set_axes_labels
from biosteam import Metric

def tickmarks(data, accuracy=50, N_points=5):
    dmin = data.min()
    dmax = data.max()
    dmin = floor(dmin/accuracy) * accuracy
    dmax = ceil(dmax/accuracy) * accuracy
    step = (dmax - dmin) / (N_points - 1)
    if step == 0:
        return [0, 1]
    else:
        return [dmin + step * i for i in range(N_points)]
    
CABBI_colors = (colors.CABBI_yellow.tint(75).RGBn, 
                colors.CABBI_yellow.RGBn,
                colors.CABBI_green.RGBn,
                colors.CABBI_teal_green.shade(75).RGBn)
colormaps = [
    LinearSegmentedColormap.from_list('CABBI', CABBI_colors, 25),
    plt.cm.get_cmap('magma_r'),
    plt.cm.get_cmap('copper_r'),
    plt.cm.get_cmap('bone_r'),
]

def create_contour_plots(name='1g', load=False, save=True):
    # %% Generate contour data
    x = np.linspace(0.2, 1., 6)
    y = np.linspace(0.02, 0.15, 6)
    Z = np.array([0.50, 0.75, 1.0])
    X, Y = np.meshgrid(x, y)
    dollar_per_mt = format_units(r'\$/MT')
    MPSP = bst.Metric(
        'MPSP',
        lambda: 1000 * lc.lipidcane_tea.solve_price(lc.lipidcane), # $/MT
        dollar_per_mt,
    )
    EP = bst.Metric( 
        'Elec. prod.',
        lambda: - sum([i.cost for i in lc.lipidcane_sys.power_utilities]) / lipidcane_flow_rate,
        dollar_per_mt,
    )
    NG = bst.Metric( 
        'N.G. cons.',
        lambda: 0.218 * lc.natural_gas.F_mass / lipidcane_flow_rate,
        dollar_per_mt,
    )
    BD = bst.Metric( 
        'Biod. prod.',
        lambda: lc.biodiesel.cost / lipidcane_flow_rate,
        dollar_per_mt
    )
    FCI = bst.Metric( 
        'FCI',
        lambda: lc.lipidcane_tea.FCI / 1e6, # 10^6*$
        dollar_per_mt,
    )
    if name == 0 or name == 1:
        metrics = [MPSP, EP, BD, FCI]
    elif name == 2 or name == 3:
        metrics = [MPSP, NG, BD, FCI]
    if load:
        data = np.load(f'lipid_extraction_analysis_{name}.npy')
    else:
        lc.load(name)
        lipidcane_flow_rate = lc.lipidcane.F_mass / 1e3 # MT / hr
        data = lc.lipid_extraction_specification.evaluate_across_lipid_retention(X, Y, metrics, Z)
        save and np.save(f'lipid_extraction_analysis_{name}', data)

    # %% Plot contours
    xlabel = 'Lipid extraction[%]'
    ylabel = "Lipid content [dry wt. %]"
    xticks = [20, 40, 60, 80, 100]
    yticks = [2, 5, 10, 15]
    metric_bars = [
        MetricBar(j.name, j.units, colormaps[i],
                  tickmarks(data[:, :, i, :], 5, 5))
        for i, j in enumerate(metrics)
    ]
    lipid_content = Z
    def column_title(Z):
        title =  f"{Z:.1f} [%]"
        if Z == 100 * lipid_content[0]:
            title = "Bagasse lipid retention: " + title
        return title
    
    fig, axes = plot_contour_2d(100.*X, 100.*Y, 100*Z, data, 
                                xlabel, ylabel, xticks, yticks, metric_bars, 
                                Z_value_format=column_title,
                                fillblack=False,
                               styleaxiskw=dict(xtick0=False))
    plt.show()<jupyter_output><empty_output><jupyter_text>Contour plots<jupyter_code>create_contour_plots(0, load=True)
plt.suptitle('Biodiesel production from expressed oil from pelleted bagasse and 1g ethanol production from juice')
create_contour_plots(1, load=True)
plt.suptitle('Biodiesel production from expressed oil from pelleted bagasse, 1g ethanol production from juice, and 2g ethanol production from bagasse')
create_contour_plots(2, load=True)
plt.suptitle('Biodiesel production from stillage, 1g ethanol production from juice, and 2g ethanol production from bagasse')
create_contour_plots(3, load=True)
plt.suptitle('Biodiesel production from stillage, ethanol production from juice and bagasse (combined)')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10943820224719102, 'fraction_numerical': 0.02247191011235955, 'mean_word_length': 2.8238831615120277, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '305110', 'license': 'MIT', 'n_tokens_mistral': 1744, 'n_tokens_neox': 1587, 'n_words': 364, 'path': 'BioSTEAM 2.x.x/biorefineries/lipidcane2g/lipid_extraction_efficiency_analysis.ipynb', 'repo_name': 'blsymens/Bioindustrial-Park', 'size': '4450'}