### Basic parameter sweep example Source: https://biosnicar.vercel.app/reference/sweep Demonstrates a basic parameter sweep with 'solzen' and 'rds' parameters and how to create a pivot table from the results. ```python from biosnicar.drivers.sweep import parameter_sweep df = parameter_sweep( params={ "solzen": [30, 40, 50, 60, 70], "rds": [100, 200, 500, 1000], } ) # Pivot table df.pivot_table(values="BBA", index="solzen", columns="rds") ``` -------------------------------- ### Run Basic Forward Model Source: https://biosnicar.vercel.app/examples Execute the basic forward model script. This example demonstrates using `run_model()` with default settings. ```bash python examples/01_basic_forward_model.py ``` -------------------------------- ### Install BioSNICAR Python Package Source: https://biosnicar.vercel.app/quick-start Clone the repository, navigate to the directory, and install dependencies and the package itself. A virtual environment is recommended. ```bash git clone https://github.com/jmcook1186/biosnicar-py.git cd biosnicar-py pip install -r requirements.txt pip install -e . ``` -------------------------------- ### Build a Focused Emulator Source: https://biosnicar.vercel.app/emulator Create a custom emulator with specific parameter ranges and fixed settings for a particular task. This example sets up an emulator for a field campaign with fixed illumination and solid ice layer. ```python from biosnicar.emulator import Emulator # Focused emulator: 4 free parameters, narrow ranges, fixed illumination ému = Emulator.build( params={ "rds": (100, 3000), "rho": (300, 700), "black_carbon": (0, 50000), "glacier_algae": (0, 200000), }, n_samples=5000, layer_type=1, # fixed: solid ice solzen=50, # fixed direct=1, # fixed ) ému.save("my_field_campaign.npz") ``` -------------------------------- ### Parameter sweep with satellite bands Source: https://biosnicar.vercel.app/reference/sweep Example of performing a parameter sweep and then appending satellite bands for analysis. Shows how to select and print specific columns including band data. ```python # With satellite bands df = parameter_sweep( params={"rds": [500, 1000], "solzen": [50, 60]}, ).to_platform("sentinel2") print(df[["rds", "solzen", "BBA", "B3", "NDSI"]]) ``` -------------------------------- ### Run Emulator Prediction with Plotting Source: https://biosnicar.vercel.app/examples Execute the emulator prediction script with plotting enabled. This example shows how to load and predict using a pre-built emulator. ```bash python examples/05_emulator_predict.py --plot ``` -------------------------------- ### Run End-to-End Workflow with Plotting Source: https://biosnicar.vercel.app/examples Execute the end-to-end workflow script with plotting enabled. This example demonstrates the full BioSNICAR pipeline from observation to physical interpretation. ```bash python examples/10_end_to_end_workflow.py --plot ``` -------------------------------- ### Sweep with Spectral Output Source: https://biosnicar.vercel.app/fundamentals/parameter-sweeps Include the full 480-band spectral albedo in the sweep results by setting `return_spectral=True`. This example sweeps over the diffuse-to-direct albedo ratio. ```python df = parameter_sweep( params={"rds": [500, 1000, 2000]}, return_spectral=True, ) ``` -------------------------------- ### Run Emulator with run_emulator function Source: https://biosnicar.vercel.app/reference/emulator-api Use the run_emulator wrapper to get an Outputs object containing spectral albedo and other calculated fields. The function can also convert outputs to a specified platform format. ```python from biosnicar import run_emulator outputs = run_emulator(emu, rds=1000, rho=600, black_carbon=5000, snow_algae=0, dust=1000, glacier_algae=50000, direct=1, solzen=50) print(outputs.BBA) outputs.to_platform("sentinel2") ``` -------------------------------- ### Quick Start: Convolve to Sentinel-2 and CESM2 Bands Source: https://biosnicar.vercel.app/remote-sensing/band-convolution Chain `.to_platform()` directly onto `run_model()` to map albedo to Sentinel-2 and CESM2 bands. Access specific bands like B3 (green) or computed indices like NDSI. ```python from biosnicar import run_model s2 = run_model(solzen=50, rds=1000).to_platform("sentinel2") print(s2.B3) # green-band albedo print(s2.NDSI) # Normalized Difference Snow Index cesm = run_model(solzen=50, rds=1000).to_platform("cesm2band") print(cesm.vis) # VIS broadband albedo print(cesm.nir) # NIR broadband albedo ``` -------------------------------- ### GCM Parameterization for CESM and MAR Source: https://biosnicar.vercel.app/remote-sensing/band-convolution Generate band albedos suitable for climate model radiation schemes using `.to_platform()`. This example shows obtaining VIS/NIR albedo for CESM2 and SW1/SW2 for MAR. ```python cesm = run_model(solzen=60, rds=1000).to_platform("cesm2band") print(f"CESM VIS: {cesm.vis:.4f}, NIR: {cesm.nir:.4f}") mar = run_model(solzen=60, rds=1000).to_platform("mar") print(f"MAR sw1: {mar.sw1:.4f}, sw2: {mar.sw2:.4f}") ``` -------------------------------- ### Run Model with Default Configuration Source: https://biosnicar.vercel.app/reference/run-model Execute the simulation using the default input file and parameters. ```python outputs = run_model() ``` -------------------------------- ### Run Model with Default and Overridden Parameters Source: https://biosnicar.vercel.app/fundamentals/running-the-model Demonstrates running the model with default settings and overriding specific parameters like solar zenith angle, direct beam, and black carbon content. ```python from biosnicar import run_model # Default configuration outputs = run_model() print(outputs.BBA) # Override specific parameters outputs = run_model(solzen=50, rds=1000, black_carbon=500) print(outputs.albedo) # 480-element spectral albedo ``` -------------------------------- ### Build Basic Custom Emulator Source: https://biosnicar.vercel.app/emulator/building Build a custom emulator with specified parameter ranges, number of samples, and fixed layer type, solar zenith angle, and direct sky conditions. The emulator is then saved to a file. ```python from biosnicar.emulator import Emulator emu = Emulator.build( params={ "rds": (100, 5000), "rho": (100, 917), "black_carbon": (0, 100000), "glacier_algae": (0, 500000), }, n_samples=5000, layer_type=1, # fixed: solid ice solzen=50, # fixed: solar zenith angle direct=1, # fixed: clear sky ) ému.save("my_emulator.npz") ``` -------------------------------- ### Run Forward Model with Default Settings Source: https://biosnicar.vercel.app/examples/forward-model Execute the forward model using its default parameters. This is useful for a quick baseline simulation. ```python from biosnicar import run_model import numpy as np outputs = run_model() print(f"Broadband albedo (BBA): {outputs.BBA:.4f}") print(f"Visible BBA: {outputs.BBAVIS:.4f}") print(f"NIR BBA: {outputs.BBANIR:.4f}") print(f"Spectral albedo shape: {np.array(outputs.albedo).shape}") ``` -------------------------------- ### Add Custom Impurity Type in YAML Source: https://biosnicar.vercel.app/fundamentals/inputs Provides an example of how to add a custom impurity type to `inputs.yaml`, including its file path, coating status, unit, and default concentration. ```yaml IMPURITIES: my_new_impurity: FILE: "my_impurity_file.npz" COATED: False UNIT: 0 # 0 = ppb (mass), 1 = cells/mL (count) CONC: [0, 0] # default concentration per layer ``` -------------------------------- ### Create Custom Albedo Difference Plot Source: https://biosnicar.vercel.app/fundamentals/plotting Example of creating a custom plot to visualize the albedo difference between two model runs using Matplotlib. Saves the figure to a PNG file. ```python # Example: plot albedo difference between two runs clean = run_model(rds=1000) dirty = run_model(rds=1000, black_carbon=5000) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), sharex=True) ax1.plot(wav, clean.albedo, label="Clean") ax1.plot(wav, dirty.albedo, label="+ BC") ax1.set_ylabel("Albedo") ax1.legend() ax2.plot(wav, np.array(clean.albedo) - np.array(dirty.albedo), color="red") ax2.set_ylabel("Albedo reduction") ax2.set_xlabel("Wavelength (µm)") ax2.axhline(0, color="k", linewidth=0.5) plt.tight_layout() plt.savefig("custom_difference_plot.png", dpi=150) ``` -------------------------------- ### Loop Through Multiple Custom Input Files Source: https://biosnicar.vercel.app/fundamentals/running-the-model Demonstrates iterating through a list of custom input YAML files to run the model with different configurations and printing the broadband albedo for each. ```python for config in ["config_clean.yaml", "config_dusty.yaml", "config_algal.yaml"]: outputs = run_model(input_file=config) print(f"{config}: BBA = {outputs.BBA:.4f}") ``` -------------------------------- ### Emulator.build() Source: https://biosnicar.vercel.app/reference/emulator-api Trains an emulator on Latin hypercube samples of the forward model. It accepts parameters for training, including the number of samples, solver type, input file configuration, progress bar display, and a random seed. It can also accept fixed parameter overrides. ```APIDOC ## Emulator.build() ### Description Train an emulator on Latin hypercube samples of the forward model. ### Method Signature ```python Emulator.build(params, n_samples=10000, solver="adding-doubling", input_file="default", progress=True, seed=42, **fixed_overrides) -> Emulator ``` ### Parameters #### Parameters - **params** (dict) - Required - `{name: (min, max)}` for each free parameter - **n_samples** (int) - Optional - Number of LHS training samples (default: 10000) - **solver** (str) - Optional - RT solver (default: "adding-doubling") - **input_file** (str) - Optional - YAML config path (default: "default") - **progress** (bool) - Optional - Show progress bar (default: True) - **seed** (int) - Optional - Random seed (default: 42) - **fixed_overrides** (kwargs) - Optional - Fixed parameters for every run ### Requirements Requires `scikit-learn>=1.0`. ``` -------------------------------- ### Multi-parameter Spectral Retrieval Source: https://biosnicar.vercel.app/remote-sensing/inversions Conducts spectral retrieval for multiple parameters including SSA, black carbon, glacier algae, and dust. This example demonstrates how to specify a broader set of parameters to be retrieved. ```python result = retrieve( observed=measured_albedo, parameters=["ssa", "black_carbon", "glacier_algae", "dust"], emulator=emu, fixed_params={"direct": 1, "solzen": 50, "snow_algae": 0}, ) ``` -------------------------------- ### Build a Custom Emulator Source: https://biosnicar.vercel.app/examples/emulator-examples Use Emulator.build to create a custom emulator with specified parameters, sample count, layer type, solar zenith angle, and direct radiation flag. Verify its accuracy and save it for later use. ```python from biosnicar.emulator import Emulator emu = Emulator.build( params={ "rds": (100, 5000), "rho": (100, 917), "black_carbon": (0, 100000), "glacier_algae": (0, 500000), }, n_samples=5000, layer_type=1, solzen=50, direct=1, ) # Check accuracy result = emu.verify(n_points=50) print(result.summary()) # Save ému.save("my_emulator.npz") ``` -------------------------------- ### Running from the Command Line Source: https://biosnicar.vercel.app/fundamentals/running-the-model Instructions for executing the model directly from the command line using the `main.py` script. ```APIDOC ## Running from the Command Line ### Description Execute the model directly from your terminal for quick testing or basic runs using the provided Python script. ### Command ```bash python main.py ``` ### Behavior This command runs the model with all default settings and prints the results to the console. ``` -------------------------------- ### Get Spectral Fluxes at a Specific Depth Source: https://biosnicar.vercel.app/reference/outputs Retrieve spectral upwelling, downwelling, and net fluxes at an arbitrary depth using linear interpolation with the `subsurface_flux` method. The output contains arrays for each flux type. ```python flux = outputs.subsurface_flux(0.03) print(flux["F_dwn"].shape) # (480,) print(flux["F_up"].shape) # (480,) print(flux["F_net"].shape) # (480,) ``` -------------------------------- ### Import Emulator and run_emulator Source: https://biosnicar.vercel.app/reference/emulator-api Import necessary components from the biosnicar library. ```python from biosnicar.emulator import Emulator from biosnicar import run_emulator ``` -------------------------------- ### Map Model Output to Sentinel-2 Bands Source: https://biosnicar.vercel.app/examples/remote-sensing-examples Chain `.to_platform('sentinel2')` onto a model run to get Sentinel-2 specific bands and indices. Useful for comparing model predictions with actual satellite data. ```python from biosnicar import run_model s2 = run_model(solzen=50, rds=1000).to_platform("sentinel2") print(f"Sentinel-2 B3 (green): {s2.B3:.3f}") print(f"Sentinel-2 NDSI: {s2.NDSI:.3f}") ``` -------------------------------- ### Working with Outputs Source: https://biosnicar.vercel.app/fundamentals/running-the-model Demonstrates how to access and utilize the data returned by the `run_model()` function, including spectral albedo and broadband albedo values. ```APIDOC ## Working with Outputs ### Description Access and process the simulation results contained within the `Outputs` object returned by `run_model()`. This includes spectral albedo, broadband albedo, and other calculated metrics. ### Request Example ```python import numpy as np outputs = run_model(solzen=50, rds=500) albedo = np.array(outputs.albedo) wavelengths = np.arange(0.205, 4.999, 0.01) print(f"Albedo at 0.5 µm: {albedo[29]:.4f}") print(f"Albedo at 1.0 µm: {albedo[79]:.4f}") print(f"Albedo at 1.5 µm: {albedo[129]:.4f}") print(f"Broadband albedo: {outputs.BBA:.4f}") print(f"Visible BBA: {outputs.BBAVIS:.4f}") print(f"NIR BBA: {outputs.BBANIR:.4f}") ``` ``` -------------------------------- ### Run Model from Command Line Source: https://biosnicar.vercel.app/fundamentals/running-the-model Provides the command to run the model directly from the command line with default settings, printing results to the console. ```bash python main.py ``` -------------------------------- ### Applying Regularization to Retrieval Source: https://biosnicar.vercel.app/remote-sensing/inversions Use regularization to incorporate prior information when parameters are weakly constrained. This example shows adding a Gaussian penalty term to the cost function, pulling the retrieval towards a specified prior. ```python result = retrieve( ..., regularization={"dust": (500, 200)}, # prior: 500 ± 200 ppb ) ``` -------------------------------- ### Build Full Illumination Sweep Emulator Source: https://biosnicar.vercel.app/emulator/building Configure an emulator to study illumination conditions by varying grain radius, density, solar zenith angle, and direct sky, while fixing all impurity parameters to zero for clean ice. ```python emu = Emulator.build( params={ "rds": (500, 5000), "rho": (300, 900), "solzen": (20, 85), "direct": (0, 1), }, n_samples=8000, # All impurities fixed at zero — clean ice illumination study black_carbon=0, snow_algae=0, glacier_algae=0, dust=0, ) ``` -------------------------------- ### to_platform() (standalone) Source: https://biosnicar.vercel.app/reference/bands-api Standalone function to map spectral albedo and solar flux onto a specified platform's bands. ```APIDOC ## to_platform() (standalone) ``` from biosnicar.bands import to_platform result = to_platform(albedo_array, "sentinel2", flx_slr=flux_array) ``` ### Parameters #### Path Parameters - **albedo** (ndarray (480,)) - Required - Spectral albedo - **platform** (str) - Required - Platform key - **flx_slr** (ndarray (480,)) - Optional - Spectral solar flux ### Returns `BandResult` ``` -------------------------------- ### Save and Load Emulator Roundtrip Source: https://biosnicar.vercel.app/examples/emulator-examples Demonstrates saving an emulator to a file using emu.save and loading it back with Emulator.load. It includes a verification step to ensure predictions from the original and reloaded emulators are identical. ```python emu.save("my_emulator.npz") emu2 = Emulator.load("my_emulator.npz") # Verify identical predictions albedo1 = emu.predict(rds=1000, rho=600, black_carbon=0, snow_algae=0, dust=0, glacier_algae=0, direct=1, solzen=50) albedo2 = emu2.predict(rds=1000, rho=600, black_carbon=0, snow_algae=0, dust=0, glacier_algae=0, direct=1, solzen=50) print(f"Max difference: {np.max(np.abs(albedo1 - albedo2))}") ``` -------------------------------- ### Specify Custom Input File Source: https://biosnicar.vercel.app/fundamentals/inputs Demonstrates how to use a custom YAML file for input parameters by specifying the file path using the `input_file` argument. ```python run_model(input_file="path/to/custom_inputs.yaml") ``` -------------------------------- ### Import run_model Function Source: https://biosnicar.vercel.app/reference/run-model Import the main function for radiative transfer simulations. ```python from biosnicar import run_model ``` -------------------------------- ### Build Emulator Source: https://biosnicar.vercel.app/reference/emulator-api Train an emulator using Latin hypercube samples. Requires scikit-learn>=1.0. ```python Emulator.build(params, n_samples=10000, solver="adding-doubling", input_file="default", progress=True, seed=42, **fixed_overrides) -> Emulator ``` -------------------------------- ### Run Model with Custom Input File Source: https://biosnicar.vercel.app/fundamentals/running-the-model Shows how to specify a custom input YAML file for the `run_model()` function to use non-standard settings. ```python outputs = run_model(input_file="path/to/custom_inputs.yaml") ``` -------------------------------- ### run_emulator() Source: https://biosnicar.vercel.app/reference/emulator-api A wrapper function that runs the emulator with specified physical parameters and returns an `Outputs` object containing various spectral and broadband albedo values, as well as the solar flux spectrum. It also provides a method to convert outputs to a specific platform format. ```APIDOC ## run_emulator() ### Description Wrapper that returns an `Outputs` object with `.albedo`, `.BBA`, `.BBAVIS`, `.BBANIR`, `.flx_slr`, and `.to_platform()`. ### Method Signature ```python from biosnicar import run_emulator outputs = run_emulator(emu, rds=1000, rho=600, black_carbon=5000, snow_algae=0, dust=1000, glacier_algae=50000, direct=1, solzen=50) ``` ### Parameters #### Parameters - **emu** (Emulator) - Required - The trained emulator instance. - **rds** (float) - Optional - Snow grain radius (default: 1000) - **rho** (float) - Optional - Snow density (default: 600) - **black_carbon** (float) - Optional - Black carbon concentration (default: 5000) - **snow_algae** (float) - Optional - Snow algae concentration (default: 0) - **dust** (float) - Optional - Dust concentration (default: 1000) - **glacier_algae** (float) - Optional - Glacier algae concentration (default: 50000) - **direct** (int) - Optional - Direct beam flag (default: 1) - **solzen** (float) - Optional - Solar zenith angle (default: 50) ### Returns #### Outputs Object - **albedo** - Spectral albedo. - **BBA** - Broadband albedo. - **BBAVIS** - Visible broadband albedo. - **BBANIR** - Near-infrared broadband albedo. - **flx_slr** - Solar flux spectrum. - **to_platform(platform_name)** - Method to convert outputs to a specified platform format. ### Usage Example ```python print(outputs.BBA) outputs.to_platform("sentinel2") ``` ### Notes Fields only available from the full RT solver (`heat_rt`, `absorbed_flux_per_layer`) are `None`. ``` -------------------------------- ### Outputs.to_platform() Source: https://biosnicar.vercel.app/reference/bands-api Chains onto `run_model()` or `run_emulator()` to map spectral output to a specified platform's bands. ```APIDOC ## Outputs.to_platform() Chains onto `run_model()` or `run_emulator()`: ``` s2 = run_model(solzen=50).to_platform("sentinel2") ``` ### Parameters #### Query Parameters - **platform** (str) - Required - Platform key ### Returns `BandResult` ``` -------------------------------- ### Run Model for Multi-layer Simulation Source: https://biosnicar.vercel.app/reference/run-model Configure a multi-layer simulation by providing lists for layer thicknesses, effective radii, and glacier algae concentrations. ```python outputs = run_model( dz=[0.02, 0.05, 0.05, 0.05, 0.83], rds=[800, 900, 1000, 1100, 1200], glacier_algae=[40000, 10000, 0, 0, 0], ) ``` -------------------------------- ### Load and Use Default BioSNICAR Emulator Source: https://biosnicar.vercel.app/emulator Load the pre-built general-purpose emulator and use it to predict spectral albedo or obtain a full Outputs object. The emulator is loaded from a specified .npz file. ```python from biosnicar.emulator import Emulator from biosnicar import run_emulator # Load the pre-built emulator ému = Emulator.load("data/emulators/glacier_ice_8_param_default.npz") # Predict spectral albedo (~1 µs) albedo = emu.predict( rds=1000, rho=600, black_carbon=5000, snow_algae=0, dust=1000, glacier_algae=50000, direct=1, solzen=50, ) # Or get a full Outputs object (BBA, BBAVIS, BBANIR, .to_platform()) outputs = run_emulator( emu, rds=1000, rho=600, black_carbon=5000, snow_algae=0, dust=1000, glacier_algae=50000, direct=1, solzen=50, ) print(outputs.BBA) outputs.to_platform("sentinel2") ``` -------------------------------- ### Configure 5-Layer Ice Structure Source: https://biosnicar.vercel.app/fundamentals/inputs Demonstrates how to configure a 5-layer ice structure by providing lists for layer-specific attributes like thickness, radius, and density. The number of layers is determined by the longest list provided. ```python outputs = run_model( dz=[0.02, 0.05, 0.05, 0.05, 0.83], rds=[800, 900, 1000, 1100, 1200], rho=[500, 600, 700, 750, 800], ) ``` -------------------------------- ### run_model() Source: https://biosnicar.vercel.app/reference/run-model The main entry point for forward radiative transfer simulations. It allows for extensive customization through various parameters and overrides. ```APIDOC ## run_model() ### Description The main entry point for forward radiative transfer simulations. ### Signature ```python run_model(input_file="default", **overrides) -> Outputs ``` ### Parameters #### Path Parameters - **input_file** (str) - Optional - Path to YAML config file. "default" uses bundled `inputs.yaml`. #### Overrides (**kwargs) - **solzen** (int) - Optional - Solar zenith angle (1–89 degrees) - **direct** (int) - Optional - Sky condition: 1 = clear, 0 = overcast - **incoming** (int) - Optional - Irradiance profile index (0–6) - **rds** (int or list) - Optional - Grain/bubble effective radius (µm) - **rho** (int or list) - Optional - Bulk ice density (kg/m³) - **dz** (list[float]) - Optional - Layer thicknesses (m) - **lwc** (float or list) - Optional - Liquid water content - **layer_type** (int or list) - Optional - 0 = granular, 1 = solid ice + Fresnel - **shp** (int or list) - Optional - Grain shape (0–4) - **grain_ar** (float or list) - Optional - Grain aspect ratio - **hex_side** (float or list) - Optional - Hexagonal prism side length (µm) - **hex_length** (float or list) - Optional - Hexagonal prism length (µm) - **black_carbon** (float or list) - Optional - Black carbon concentration (ppb) - **snow_algae** (float or list) - Optional - Snow algae concentration (cells/mL) - **glacier_algae** (float or list) - Optional - Glacier algae concentration (cells/mL) - **dust** (float or list) - Optional - Mineral dust concentration (ppb) ### Override Behaviour * Scalar ice parameters are broadcast to all layers * Scalar impurity concentrations are applied to the first layer only * List overrides that change the layer count trigger automatic resizing of all per-layer attributes ### Returns An Outputs object. ### Examples ```python # Default configuration outputs = run_model() # Override parameters outputs = run_model(solzen=50, rds=1000, black_carbon=500) # Multi-layer outputs = run_model( dz=[0.02, 0.05, 0.05, 0.05, 0.83], rds=[800, 900, 1000, 1100, 1200], glacier_algae=[40000, 10000, 0, 0, 0], ) # Chain to satellite bands s2 = run_model(solzen=50, rds=1000).to_platform("sentinel2") # Custom input file outputs = run_model(input_file="path/to/config.yaml") ``` ``` -------------------------------- ### Import to_platform function Source: https://biosnicar.vercel.app/reference/bands-api Import the necessary `to_platform` function from the biosnicar.bands module. ```python from biosnicar.bands import to_platform ``` -------------------------------- ### Custom Input Files Source: https://biosnicar.vercel.app/fundamentals/running-the-model Explains how to use custom input files, such as YAML, to configure the model for batch processing or non-standard settings. ```APIDOC ## Custom Input Files ### Description Configure the model's behavior for batch processing or specific non-default settings by utilizing custom input files, typically in YAML format. ### Usage Specify a custom input file path using the `input_file` argument in the `run_model()` function. ### Request Example ```python # Using a specific custom input file outputs = run_model(input_file="path/to/custom_inputs.yaml") # Looping through multiple configuration files for config in ["config_clean.yaml", "config_dusty.yaml", "config_algal.yaml"]: outputs = run_model(input_file=config) print(f"{config}: BBA = {outputs.BBA:.4f}") ``` ``` -------------------------------- ### run_model() function Source: https://biosnicar.vercel.app/fundamentals/running-the-model The `run_model()` function is the main entry point for all model simulations. It accepts keyword arguments to override default parameters and returns an `Outputs` object containing simulation results. ```APIDOC ## run_model() ### Description This function serves as the primary interface for executing forward model simulations. It allows for customization through keyword overrides of various parameters and returns a comprehensive `Outputs` object. ### Parameters Any of the supported override keys can be passed as keyword arguments. See 'Supported override keys' for a full list. ### Request Example ```python from biosnicar import run_model # Using default configuration outputs = run_model() print(outputs.BBA) # Overriding specific parameters outputs = run_model(solzen=50, rds=1000, black_carbon=500) print(outputs.albedo) ``` ### Response - **Outputs object**: Contains simulation results, including spectral albedo, broadband albedo (BBA), visible BBA (BBAVIS), and NIR BBA (BBANIR). ``` -------------------------------- ### Process Full Emulator Outputs Source: https://biosnicar.vercel.app/examples/emulator-examples Utilize the run_emulator function for a comprehensive output object that includes various spectral albedo components (BBA, BBAVIS, BBANIR). This object can be chained to platform-specific band outputs. ```python outputs = run_emulator( emu, rds=1000, rho=600, black_carbon=5000, snow_algae=0, dust=1000, glacier_algae=50000, direct=1, solzen=50, ) print(f"BBA: {outputs.BBA:.4f}") print(f"BBAVIS: {outputs.BBAVIS:.4f}") print(f"BBANIR: {outputs.BBANIR:.4f}") # Chain to satellite bands s2 = outputs.to_platform("sentinel2") print(f"S2 B3: {s2.B3:.3f}, NDSI: {s2.NDSI:.3f}") ``` -------------------------------- ### Chaining to Satellite Bands Source: https://biosnicar.vercel.app/fundamentals/running-the-model Shows how to convert the model outputs to a format compatible with satellite bands using the `.to_platform()` method. ```APIDOC ## Chaining to Satellite Bands ### Description Convert the `Outputs` object generated by `run_model()` into a format suitable for analysis with satellite data platforms using the `.to_platform()` method. ### Request Example ```python s2 = run_model(solzen=50, rds=1000).to_platform("sentinel2") print(s2.B3, s2.NDSI) ``` ### Note Refer to the 'Remote Sensing' section for more detailed information. ``` -------------------------------- ### Build Snow-Only Emulator with 3 Parameters Source: https://biosnicar.vercel.app/emulator/building Construct an emulator specifically for snow (layer_type=0) with defined ranges for grain radius, black carbon, and dust, along with fixed solar zenith angle and direct sky conditions. ```python emu = Emulator.build( params={ "rds": (50, 2000), # snow grain radius "black_carbon": (0, 5000), "dust": (0, 10000), }, n_samples=3000, layer_type=0, # snow solzen=50, direct=1, ) ``` -------------------------------- ### Process Model Outputs and Print Spectral Albedo Source: https://biosnicar.vercel.app/fundamentals/running-the-model Shows how to process the model's output, specifically spectral albedo, and print values at different wavelengths, along with broadband, visible, and NIR broadband albedo. ```python import numpy as np outputs = run_model(solzen=50, rds=500) albedo = np.array(outputs.albedo) wavelengths = np.arange(0.205, 4.999, 0.01) print(f"Albedo at 0.5 µm: {albedo[29]:.4f}") print(f"Albedo at 1.0 µm: {albedo[79]:.4f}") print(f"Albedo at 1.5 µm: {albedo[129]:.4f}") print(f"Broadband albedo: {outputs.BBA:.4f}") print(f"Visible BBA: {outputs.BBAVIS:.4f}") print(f"NIR BBA: {outputs.BBANIR:.4f}") ``` -------------------------------- ### Standalone to_platform conversion Source: https://biosnicar.vercel.app/reference/bands-api Use `to_platform` as a standalone function to convert spectral albedo and solar flux arrays to a specified platform's bands. ```python from biosnicar.bands import to_platform result = to_platform(albedo_array, "sentinel2", flx_slr=flux_array) ``` -------------------------------- ### Emulator.predict() Source: https://biosnicar.vercel.app/reference/emulator-api Predicts the 480-band spectral albedo using the trained emulator. This method is highly efficient, operating in microseconds. All emulator parameters must be provided as keyword arguments. ```APIDOC ## Emulator.predict() ### Description Predict 480-band spectral albedo. Pure numpy, ~microseconds. ### Method Signature ```python emu.predict(**params) -> np.ndarray # shape (480,) ``` ### Parameters #### Parameters - **params** (kwargs) - Required - All emulator parameters must be provided as keyword arguments. ``` -------------------------------- ### Predict with a Loaded Emulator Source: https://biosnicar.vercel.app/examples/emulator-examples Load a pre-built emulator using Emulator.load and perform a single prediction by providing all necessary input parameters. The prediction returns an albedo value. ```python from biosnicar.emulator import Emulator from biosnicar import run_emulator # Load pre-built default emulator emu = Emulator.load("data/emulators/glacier_ice_8_param_default.npz") print(f"Parameters: {emu.param_names}") print(f"Bounds: {emu.bounds}") # Single prediction albedo = emu.predict( rds=1000, rho=600, black_carbon=5000, snow_algae=0, dust=1000, glacier_algae=50000, direct=1, solzen=50, ) print(f"Albedo shape: {albedo.shape}") ``` -------------------------------- ### Run Model and Chain to Satellite Bands Source: https://biosnicar.vercel.app/reference/run-model Execute a simulation with specific parameters and then convert the output to Sentinel-2 satellite bands. ```python s2 = run_model(solzen=50, rds=1000).to_platform("sentinel2") ``` -------------------------------- ### Build High-Impurity Glacier Ice Emulator Source: https://biosnicar.vercel.app/emulator/building Create an emulator for glacier ice with extended parameter ranges for grain radius, density, black carbon, and glacier algae, suitable for studying extreme impurity conditions. ```python emu = Emulator.build( params={ "rds": (500, 5000), "rho": (400, 800), "black_carbon": (0, 100000), # extended range "glacier_algae": (0, 1000000), # extreme blooms }, n_samples=10000, solzen=50, direct=1, ) ``` -------------------------------- ### Run Model and Access Subsurface Fluxes Source: https://biosnicar.vercel.app/subsurface-light Demonstrates how to run the BioSNICAR model and access downwelling spectral flux at a specific depth. The flux is normalized, so multiply by actual irradiance for absolute values. ```python from biosnicar import run_model outputs = run_model(solzen=60, rds=500, dz=[0.05, 0.5, 0.45]) # Downwelling spectral flux at 3 cm depth flux = outputs.subsurface_flux(0.03) print(flux["F_dwn"].shape) # (480,) # PAR (400-700 nm) at the surface print(outputs.par(0.0)) # PAR at several depths print(outputs.par([0.0, 0.05, 0.1, 0.5])) ``` -------------------------------- ### Interpolate Subsurface Flux at Arbitrary Depth Source: https://biosnicar.vercel.app/subsurface-light Demonstrates linear interpolation of spectral fluxes (upwelling, downwelling, net) at an arbitrary depth. For thick layers, consider splitting them into thinner sub-layers for better accuracy. ```python flux = outputs.subsurface_flux(0.05) print(flux["F_dwn"].shape) # (480,) print(flux["F_up"].shape) # (480,) print(flux["F_net"].shape) # (480,) ``` ```python flux = outputs.subsurface_flux([0.01, 0.02, 0.05, 0.1]) print(flux["F_dwn"].shape) # (4, 480) ``` -------------------------------- ### List available optical property stems using NumPy Source: https://biosnicar.vercel.app/fundamentals/impurities Load the `lap.npz` archive and print the `_names` array to see all available optical property dataset stems programmatically. This helps in selecting custom datasets. ```python import numpy as np lap = np.load("data/OP_data/480band/lap.npz", allow_pickle=False) print(lap["_names"]) ``` -------------------------------- ### Comparing Optimization Methods Source: https://biosnicar.vercel.app/examples/inversion-examples This snippet compares the performance of different optimization methods ('L-BFGS-B', 'Nelder-Mead', 'differential_evolution') for retrieval. ```python for method in ["L-BFGS-B", "Nelder-Mead", "differential_evolution"]: result = retrieve( observed=measured_albedo, parameters=["ssa", "glacier_algae"], emulator=emu, method=method, fixed_params={"direct": 1, "solzen": 50, "black_carbon": 0, "dust": 0, "snow_algae": 0}, ) print(f"{method:25s} SSA={result.best_fit['ssa']:.4f} " f"cost={result.cost:.6f} evals={result.n_function_evals}") ``` -------------------------------- ### run_emulator() Source: https://biosnicar.vercel.app/reference Emulator wrapper returning Outputs. This function provides a convenient way to use the neural network surrogate model. ```APIDOC ## run_emulator() ### Description Emulator wrapper returning Outputs. ### Method Not specified (likely a Python function call). ### Endpoint Not applicable (Python function). ### Parameters Not specified in the provided text. ### Request Example ```python import biosnicar # Example usage (parameters not specified in source) # results = biosnicar.run_emulator(...) ``` ### Response Not specified in the provided text. ``` -------------------------------- ### Map Albedo to Satellite Bands Source: https://biosnicar.vercel.app/quick-start Convert the 480-band spectral albedo output to standard satellite or climate model bands using the `.to_platform()` method. ```python s2 = run_model(solzen=50, rds=1000).to_platform("sentinel2") print(f"Sentinel-2 B3 (green): {s2.B3:.3f}") print(f"NDSI: {s2.NDSI:.3f}") cesm = run_model(solzen=50, rds=1000).to_platform("cesm2band") print(f"CESM VIS: {cesm.vis:.4f}, NIR: {cesm.nir:.4f}") ``` -------------------------------- ### Chaining to Satellite Bands (Multi-Platform) Source: https://biosnicar.vercel.app/fundamentals/parameter-sweeps Compare parameter sweep results across multiple satellite platforms (Sentinel-2, Landsat-8, MODIS) by chaining to their respective bands and indices. Prints the diffuse-to-direct albedo ratio and the NDSI index for each platform. ```python df = parameter_sweep( params={"rds": [500, 1000]}, ).to_platform("sentinel2", "landsat8", "modis") print(df[["rds", "sentinel2_NDSI", "landsat8_NDSI", "modis_NDSI"]]) ``` -------------------------------- ### Simulate Forward Model with Impurities Source: https://biosnicar.vercel.app/examples/forward-model Compare the broadband albedo (BBA) of clean ice with ice containing impurities like black carbon and glacier algae. ```python clean = run_model(solzen=50, rds=1000) dirty = run_model(solzen=50, rds=1000, black_carbon=5000, glacier_algae=50000) print(f"Clean ice BBA: {clean.BBA:.4f}") print(f"With impurities: {dirty.BBA:.4f}") print(f"Albedo reduction: {clean.BBA - dirty.BBA:.4f}") ``` -------------------------------- ### Load BioSNICAR Emulator Source: https://biosnicar.vercel.app/examples/end-to-end Loads a pre-trained BioSNICAR emulator from a specified file path. This is the first step in any BioSNICAR workflow. ```python from biosnicar.emulator import Emulator emu = Emulator.load("data/emulators/glacier_ice_8_param_default.npz") ``` -------------------------------- ### Load Emulator and Retrieve Ice Properties Source: https://biosnicar.vercel.app/ Load a pre-trained emulator and retrieve ice properties (SSA, black carbon, glacier algae) from observed satellite spectral bands. This snippet showcases the inverse retrieval workflow. ```python from biosnicar.emulator import Emulator from biosnicar.inverse import retrieve import numpy as np # Load emulator and retrieve ice properties from satellite bands ému = Emulator.load("data/emulators/glacier_ice_8_param_default.npz") result = retrieve( observed=np.array([0.82, 0.78, 0.75, 0.45, 0.03]), parameters=["ssa", "black_carbon", "glacier_algae"], emulator=emu, platform="sentinel2", observed_band_names=["B2", "B3", "B4", "B8", "B11"], fixed_params={"direct": 1, "solzen": 50, "dust": 1000, "snow_algae": 0}, ) print(result.summary()) ``` -------------------------------- ### Emulator.save() / Emulator.load() Source: https://biosnicar.vercel.app/reference/emulator-api Saves the trained emulator to a file and loads it back. Loading does not require scikit-learn. ```APIDOC ## Emulator.save() / Emulator.load() ### Description Save and load the trained emulator. ### Method Signatures ```python emu.save("path.npz") emu = Emulator.load("path.npz") ``` ### Notes No sklearn required for loading. ``` -------------------------------- ### Pivot Table for Analysis Source: https://biosnicar.vercel.app/fundamentals/parameter-sweeps Generate a pivot table from parameter sweep results to analyze broadband albedo (BBA) values indexed by solar zenith angle and columns of diffuse-to-direct albedo ratio. The resulting pivot table is then plotted. ```python df = parameter_sweep( params={ "solzen": [30, 40, 50, 60, 70], "rds": [100, 200, 500, 1000], } ) df.pivot_table(values="BBA", index="solzen", columns="rds").plot() ``` -------------------------------- ### Compare Model Outputs Across Multiple Satellite Platforms Source: https://biosnicar.vercel.app/examples/remote-sensing-examples Iterate through a list of platform names and use `.to_platform()` to retrieve band and index information for each. This helps in understanding how model outputs translate across different satellite sensors. ```python outputs = run_model(solzen=50, rds=1000) for plat in ["sentinel2", "landsat8", "modis", "cesm2band"]: r = outputs.to_platform(plat) print(f"{plat:12s} bands: {len(r.band_names):2d} indices: {r.index_names}") ``` -------------------------------- ### .to_platform(platform) Source: https://biosnicar.vercel.app/reference/outputs Convolves spectral albedo to satellite or climate model bands. Returns a BandResult object. ```APIDOC ## .to_platform(platform) ### Description Convolve spectral albedo to satellite or climate model bands. ### Parameters #### Path Parameters - **platform** (string) - Required - The target platform (e.g., "sentinel2"). ### Request Example ```python s2 = outputs.to_platform("sentinel2") print(s2.B3, s2.NDSI) ``` ### Response Returns a BandResult. ``` -------------------------------- ### Configure Impurity Concentrations Source: https://biosnicar.vercel.app/fundamentals/inputs Shows how to set impurity concentrations. Scalar values are applied to the first layer, while lists specify concentrations for each layer. ```python # Scalar: applied to first layer only run_model(black_carbon=5000, glacier_algae=50000) # Per-layer list run_model(glacier_algae=[40000, 10000, 0]) ``` -------------------------------- ### Basic Parameter Sweep Source: https://biosnicar.vercel.app/fundamentals/parameter-sweeps Run a parameter sweep over solar zenith angle and diffuse-to-direct albedo ratio. Prints the solar zenith angle, diffuse-to-direct albedo ratio, and broadband albedo (BBA) from the resulting DataFrame. ```python from biosnicar.drivers.sweep import parameter_sweep df = parameter_sweep( params={ "solzen": [30, 40, 50, 60, 70], "rds": [100, 200, 500, 1000], } ) print(df[["solzen", "rds", "BBA"]]) ``` -------------------------------- ### Downstream Analysis with Retrieved Parameters Source: https://biosnicar.vercel.app/examples/end-to-end Utilizes the retrieved ice properties to generate a full spectrum using the emulator and convolve it to different satellite platforms (Sentinel-2, CESM2). This demonstrates how retrieved parameters can be used for further analysis. ```python from biosnicar import run_emulator # Generate full spectrum from retrieved parameters emu_params = { "rds": result.derived["rds_internal"], "rho": result.derived["rho_ref"], "black_carbon": result.best_fit["black_carbon"], "glacier_algae": result.best_fit["glacier_algae"], } outputs = run_emulator(emu, **emu_params, **fixed) print(f"BBA (retrieved): {outputs.BBA:.4f}") # Convolve to other platforms s2_ret = outputs.to_platform("sentinel2") cesm_ret = outputs.to_platform("cesm2band") print(f"S2 NDSI: {s2_ret.NDSI:.4f}") print(f"CESM VIS: {cesm_ret.vis:.4f}, NIR: {cesm_ret.nir:.4f}") ``` -------------------------------- ### parameter_sweep() Source: https://biosnicar.vercel.app/reference/sweep Runs the model over the Cartesian product of parameter values. It takes a dictionary of parameters and their corresponding values, and optionally accepts a solver type, a flag to return spectral data, and a flag to display a progress bar. ```APIDOC ## parameter_sweep() ### Description Runs the model over the Cartesian product of parameter values. It takes a dictionary of parameters and their corresponding values, and optionally accepts a solver type, a flag to return spectral data, and a flag to display a progress bar. ### Method `parameter_sweep(params, solver="adding-doubling", return_spectral=False, progress=True)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (dict) - Required - `{name: [values]}` for each parameter. Supported parameter keys: `solzen`, `direct`, `incoming`, `rds`, `rho`, `dz`, `layer_type`, and impurity names (`black_carbon`, `snow_algae`, `glacier_algae`, `dust`). - **solver** (str) - Optional - ` ```