# Catalog of Custom Functions

GeoPard offers a comprehensive catalog of custom functions designed to improve the readability and functionality of equation-based analytics. These functions encapsulate complex `python` code, allowing you to implement sophisticated data manipulations and calculations with ease.

### Enter Equation

<figure><img src="https://docs.geopard.tech/~gitbook/image?url=https%3A%2F%2F3272281156-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYICBELdyAXXebKAzfLOR%252Fuploads%252FdHTdBE1CN2gSJbE7Bfo0%252Fimage.png%3Falt%3Dmedia%26token%3Dd8e3544f-feca-43a6-b6a1-f1305068de88&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=508ec9e0&#x26;sv=2" alt=""><figcaption><p>Enter an Equation</p></figcaption></figure>

The list of available pre-built functions for creating more intuitive and maintainable equations in GeoPard is included in the `geopard` package:

### fill\_gaps\_with\_k\_neighbors

```python
# input_data is a Dataset attribute layer (e.g., Yield, NDVI)
filled_layer = geopard.fill_gaps_with_k_neighbors(yield_layer, k=5)
```

This function restores data gaps or zeros in a dataset using the K-Neighbors algorithm. By specifying the `input_data` variable (as Dataset with the selected attribute) and the number of neighbors `k`, you can seamlessly fill in missing values, ensuring data continuity and integrity.

This function works well when data gaps are distributed across the field and not allocated to any particular part of the field boundary.

### determine\_data\_similarity

```python
similarity = geopard.determine_data_similarity(yield_2023, yield_2024)
```

Use this function to calculate the per-pixel similarity between two Datasets. The variables `data_layer_1` and `data_layer_2` should represent the **same measurement** in the **same units** to ensure meaningful comparison. By providing variables `data_layer_1` and `data_layer_2` associated with Datasets, you can generate a similarity map with values ranging from 0 to 1, facilitating comparative studies and pattern recognition.

### determine\_data\_similarity\_from\_normalized

```python
layer_1_norm = geopard.normalize_data(layer_1)
layer_2_norm = geopard.normalize_data(layer_2)

similarity = geopard.determine_data_similarity_from_normalized(layer_1_norm, layer_2_norm)
```

Use this function to calculate the per-pixel similarity between two normalized datasets. Normalization is recommended when the original `data_layer_1` and `data_layer_2` have different scales or units. By providing these datasets as input, the function generates a similarity map with values ranging from 0 to 1, making it suitable for comparative studies, pattern recognition, and spatial consistency analysis.

### determine\_low\_high\_similarity

```python
zones = geopard.determine_low_high_similarity(soil_ph, yield_layer)
```

This function assesses the low-high similarity between two Datasets. By inputting variables `data_layer_1` and `data_layer_2` associated with Datasets, you receive a categorized similarity map indicating combinations such as low-low, low-high, high-low, and high-high, which is useful for nuanced data classification.

### get\_value\_for\_zone

```python
zone_3_values = geopard.get_value_for_zone(yield_layer, zone_map, zone_id=3)
```

Use this function to extract all values from a Dataset attribute within a single zone. Provide `data_layer` (the attribute layer), `zones_layer` (the zones map), and `zone_id` (the zone number) to isolate values for analysis, such as yield, application rate, or seed rate, inside that zone.

### drop\_value

```python
clean_layer = geopard.drop_value(elevation_layer, value_to_drop=0)
```

This function lets you remove specific values from a dataset attribute. By specifying `data_layer` and `value_to_drop`, you can clean the dataset by eliminating those values from the result, technically replacing them with `NaN`.

### normalize\_data

```python
ndvi_normalized = geopard.normalize_data(ndvi_layer)
```

Normalize a dataset attribute with this function. By passing `data_layer`, you can scale the data to a standardized range from 0 to 1, making comparison and integration across different datasets easier.

### calculate\_total\_applied\_fertilizer

```python
applications = [urea_rate, map_rate]
coefficients = [1.0, 1.0]  # use 1.0 to keep units, or adjust for product concentration

total_applied = geopard.calculate_total_applied_fertilizer(applications, coefficients)
```

Calculate the Total Applied Fertilizer in units per area (for example, in kg/ha, l/ha, gal/ac, etc). By providing `application_list` Datasets with AppliedRate attributes and corresponding `active_ingredient_coefficient_list` with fertilizer products to get the actual total applied fertilizer in units (for example, in kg, l, gal, etc).

### calculate\_total\_applied\_nitrogen

```python
applications = [urea_rate, uan_rate]
nitrogen_coefficients = [0.46, 0.32]  # N fraction (active ingredient) in each product

N_total_applied = geopard.calculate_total_applied_nitrogen(applications, nitrogen_coefficients)
```

Calculate the Total Applied Nitrogen in kg/ha using this function. By providing `application_list` Datasets with AppliedRate attributes and corresponding `active_ingredient_coefficient_list` with nitrogen products to convert actual nitrogen to kg/ha, you can accurately compute Total Applied Nitrogen, essential for agricultural planning and sustainability assessments. The output is used as `N_total_applied` in[`geopard.calculate_nitrogen_use_efficiency`](#calculate_nitrogen_use_efficiency).

### calculate\_nitrogen\_uptake

```python
N_uptake = geopard.calculate_nitrogen_uptake(
    yield_wet_tha=yield_layer,
    moisture_pct=moisture_layer,
    protein_pct=protein_layer,
    protein_crop_correction_coefficient=6.25
)
```

Determine Nitrogen Uptake in kg/ha with this function. By supplying `yield_wet_tha`, `moisture_pct`, `protein_pct` from the Yield Dataset and `protein_crop_correction_coefficient` representing the linkage protein to the uptake of nitrogen, you can assess the Nitrogen Use Efficiency in crop production. The output is used as `N_uptake` in[`geopard.calculate_nitrogen_use_efficiency`](#calculate_nitrogen_use_efficiency) .

### calculate\_nitrogen\_use\_efficiency

```python
NUE_pct = geopard.calculate_nitrogen_use_efficiency(N_total_applied, N_uptake)
```

Evaluate Nitrogen Use Efficiency as a percentage using this function. By inputting [`N_total_applied`](#calculate_total_applied_nitrogen) and [`N_uptake`](#calculate_nitrogen_uptake) variables (from previous functions), you can measure the effectiveness of nitrogen application, aiding in optimizing fertilizer usage.

### calculate\_costs

```python
rates = [seed_rate, fertilizer_rate]
prices = [1.2, 0.8]  # price per unit for each rate layer
costs = geopard.calculate_costs(rates, prices)
```

Compute Total Costs based on application rates and prices with this function. By providing a `application_rate_list` of Datasets with the AppliedRate attributes and a corresponding `price_per_unit_list`, you can aggregate expenses related to various agricultural activities, supporting budget management and financial planning. The output is used as `costs` in[`geopard.calculate_profit`](#calculate_profit).

### calculate\_revenue

```python
revenue = geopard.calculate_revenue(yield_as_mass=yield_layer, yield_price_per_unit=0.25)
```

Calculate Revenue from the Yield Dataset using this function. By inputting `yield_as_mass` associated with the Yield Dataset attribute and the `yield_price_per_unit`, you can estimate income generated from crop production, facilitating economic evaluations. The output is used as `costs` in[`geopard.calculate_profit`](#calculate_profit) .

### calculate\_profit

```python
profit = geopard.calculate_profit(revenue, costs)
```

Determine Profit by subtracting Costs from Revenue using this function. By providing the [`revenue`](#calculate_revenue) and [`costs`](#calculate_costs) variables (from previous functions), you can easily compute the financial gain from their agricultural operations, supporting profitability analysis and strategic decision-making.

### fill\_value\_for\_range

```python
# keep only values between 10 and 20, replace the rest with 0
filtered = geopard.fill_value_for_range(layer, min_value=10, max_value=20, value_to_fill=0)
```

This function filters values within a specified range in the `input` array. By providing the `input` array, along with optional `min_value` and optional `max_value` thresholds, you can isolate values that fall within the desired range. The `value_to_fill` parameter allows for replacing out-of-range values with a specified value, enhancing data filtering and normalization processes.

### calculate\_per\_pixel\_mae

```python
mae_layer = geopard.calculate_per_pixel_mae(predicted_yield, observed_yield)
```

Use this function to compute the Mean Absolute Error (MAE) per pixel between two datasets. It provides a spatial map of absolute differences. The "absolute difference" is simply the size of the gap between corresponding pixel values, ignoring whether one is higher or lower.

The function helps to identify areas with larger discrepancies.

### calculate\_per\_pixel\_relative\_deviation

```python
relative_dev = geopard.calculate_per_pixel_relative_deviation(observed_yield, modeled_yield)
```

This function computes the relative deviation for each pixel between two datasets, expressing the difference as a percentage of the value in `dataset_1`. Essentially, it shows how much one pixel's value deviates from the corresponding value in `dataset_1` in proportional terms.

This approach is particularly valuable when analyzing variations in soil properties, crop yield, or remote sensing data, because it helps you quickly spot areas with significant proportional differences.

### calculate\_difference

```python
difference = geopard.calculate_difference(yield_2024, yield_2023)
```

This function subtracts one dataset from another to create a difference map. It highlights areas where the values in one dataset are higher or lower compared to the other, making it easier to spot trends and changes over time.

This tool is especially useful for visualizing variations in soil properties, crop yield, or remote sensing data, helping you quickly identify areas that may require further analysis or intervention.

### calculate\_relative\_difference

```python
relative_diff = geopard.calculate_relative_difference(yield_2024, yield_2023)
```

This function computes the relative difference for each pixel by normalizing the difference between the datasets using the values from `dataset_2`. This means it shows how significant the change is in relation to the magnitude of `dataset_2`.

Such a proportional comparison is especially useful when working with datasets of different scales, helping reveal relative shifts in soil properties, crop yields, or sensor outputs. This approach helps pinpoint areas with notable variation.

### calculate\_normalized\_difference

```python
normalized_diff = geopard.calculate_normalized_difference(layer_1, layer_2)
```

This function computes the normalized difference for each pixel by scaling both datasets against their global maximum value. This process makes the datasets directly comparable even if they originally have different ranges.

The resulting map provides a clear view of variations in soil properties, crop yield, and remote sensing data, allowing you to quickly identify and assess key differences.

### build\_zones\_by\_intervals

```python
# intervals for zoning
intervals = [
    (4, 8),
    (8, 12),
    (12, 16)
]

# usage
zones = geopard.build_zones_by_intervals(
    layer, 
    intervals
)
```

This function creates a management zone map by classifying a continuous raster layer into discrete zones based on user-defined value intervals.

Each interval defines a zone, and every pixel is assigned to the zone whose value range it falls into. Pixels that do not match any interval are marked as -1.

This zoning approach is commonly used to transform yield maps, soil properties, or remote sensing indices into actionable management zones for variable-rate applications.

**Typical use cases**

* Creating management zones from yield, NDVI, or soil layers
* Preparing zone maps for nutrient or seeding rate calculations
* Segmenting fields into homogeneous zones for decision-making

### calculate\_nutrient\_rate\_as\_active\_ingredients\_per\_zone

```python
# target_nutrient options
target_nutrient_option1 = 50 # constant number
# OR
target_nutrient_option2 = {1: 20, 2: 40} # per-zone dict
# OR
target_nutrient_option3 = np.array([[1, 1], [2, 3]], dtype=float) # continuous raster layer

# applied_nutrient_operations options
applied_operations = [
    5,                                      # operation1 as constant number
    {1: 2, 2: 4},                           # operation2 as per-zone dict
    np.array([[1, 1], [2, 3]], dtype=float) # operation3 as continuous raster layer
]

# usage
rates_as_active_ingredients = geopard.calculate_nutrient_rate_as_active_ingredients_per_zone(
    zone_map, 
    target_nutrient, 
    plant_available_soil_nutrient, 
    applied_nutrient_operations = applied_operations # or []
)
```

This function calculates the required nutrient application rate (active ingredient) for each management zone.

The calculation is based on:

* a target nutrient level,
* plant-available nutrient supply from soil,
* nutrients already applied through previous operations (manure, fertilizers, digestate, etc.).

Applied nutrient operations can be provided as constants, per-zone values, raster layers, or any combination of these. All inputs are automatically resolved and aggregated per zone.

By default, the required rate is calculated as the difference between the target nutrient level and the sum of soil supply and applied nutrients. The result is returned as a raster map where each zone contains a uniform nutrient rate.

### convert\_active\_ingredient\_and\_product

```python
# conversion coefficient active_ingredient to product and vice versa
corrected_coefficient = 1.5  # constant coefficient
# OR
corrected_coefficient = np.array([[np.nan, 5], [np.nan, 1]], dtype=float)  # per-pixel coefficients

# usage
rates_as_products = geopard.convert_active_ingredient_and_product(
    layer, 
    corrected_coefficient
)
```

This function converts a raster layer between **active ingredient rates and product rates** using a correction coefficient.

The `corrected_coefficient` can be a single **float** (applied to all pixels) or a coefficient **matrix** (per-pixel conversion). It is typically used to translate calculated nutrient requirements (active ingredient) into actual product application rates, or vice versa, based on fertilizer composition or nutrient concentration.

The conversion is applied pixel-wise, preserving the spatial structure of the original layer.

**Typical use cases**

* Converting nutrient rates to fertilizer product rates
* Adjusting application maps based on nutrient concentration
* Preparing final prescription maps for machinery

### estimate\_texture\_class\_based\_on\_usda

```python
usda_texture = geopard.estimate_texture_class_based_on_usda(
    sand_pct_layer,
    silt_pct_layer,
    clay_pct_layer
)
```

This function estimates USDA soil texture for each pixel using sand, silt, and clay percentages.

Provide three raster layers in percent (0-100) that represent the particle-size fractions. The output is <mark style="background-color:green;">USDA class names such as</mark> *<mark style="background-color:green;">sand, loamy\_sand, sandy\_loam, loam, silt\_loam, sandy\_clay\_loam, clay\_loam, silty\_clay\_loam, silty\_clay, or undefined</mark>* <mark style="background-color:green;">when inputs are invalid.</mark>

### estimate\_texture\_class\_based\_on\_fao\_wrb

```python
fao_wrb_texture = geopard.estimate_texture_class_based_on_fao_wrb(
    sand_pct_layer,
    silt_pct_layer,
    clay_pct_layer
)
```

This function estimates the FAO/WRB (ISO 11277) soil texture class for each pixel based on sand, silt, and clay percentages.

Provide three raster layers in percent (0-100) that represent the particle-size fractions. The output is <mark style="background-color:green;">FAO/WRB class codes such as</mark> *<mark style="background-color:green;">S, LS, SL, L, SiL, Si, SCL, CL, SiCL, SC, SiC, C, HC, or undefined</mark>* <mark style="background-color:green;">when inputs are invalid</mark>.

### calculate\_soil\_bulk\_density

```python
bulk_density = geopard.calculate_soil_bulk_density(texture_class_layer, som_pct_layer)
```

This function calculates <mark style="background-color:green;">soil bulk density (g/cm³) based on texture class and optional soil organic matter (SOM)</mark>.

The `texture_class_layer` should contain class names or codes produced by the [USDA texture function](#estimate_texture_class_based_on_usda) or the [FAO/WRB texture function](#estimate_texture_class_based_on_fao_wrb) mentioned above.

If `som_pct_layer` is provided as a percent value, the function adjusts bulk density using SOM. Otherwise, it returns soil bulk density values in g/cm³ associated with texture classes according to the USDA or FAO/WRB lookup.
