| Title: | Maximum Entropy Species Distribution Modeling ('C++' Implementation) |
|---|---|
| Description: | 'C++' implementation of Maximum Entropy (Maxent) species distribution modeling with R bindings via 'Rcpp'. Provides a high-performance reimplementation of the Maxent algorithm for modeling species geographic distributions from occurrence data and environmental variables, following Phillips et al. (2006) <doi:10.1016/j.ecolmodel.2005.03.026>. Supports linear, quadratic, product, hinge, and threshold feature transformations, spatial projection in raw, logistic, and cloglog scales, and model diagnostics including Area Under the ROC Curve (AUC), variable importance, response curves, and Multivariate Environmental Similarity Surfaces (MESS) maps. |
| Authors: | Angel Robles [aut, cre] |
| Maintainer: | Angel Robles <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.0 |
| Built: | 2026-05-19 11:20:08 UTC |
| Source: | https://github.com/alrobles/maxentcpp |
Restricts environmental variable values to the training range. Returns clamped grids and a clamping indicator grid.
clamp_grids(grid_ptrs, var_mins, var_maxs)clamp_grids(grid_ptrs, var_mins, var_maxs)
grid_ptrs |
List of external pointers to Grid<float> objects. |
var_mins |
Numeric vector of minimum training values per variable. |
var_maxs |
Numeric vector of maximum training values per variable. |
A named list with:
List of external pointers to clamped Grid<float>
External pointer to Grid<float> with clamping magnitudes
Measures how similar each cell is to the training environment. Negative values indicate novel (non-analog) conditions.
compute_mess(grid_ptrs, reference_values, feature_names)compute_mess(grid_ptrs, reference_values, feature_names)
grid_ptrs |
List of external pointers to Grid<float> objects. |
reference_values |
List of numeric vectors with reference values for each variable (e.g. values at training sites). |
feature_names |
Character vector of variable names. |
A named list with:
External pointer to Grid<float> with MESS values
External pointer to Grid<float> with MoD variable index (1-based)
Simplified MESS using only the min/max of reference data.
compute_mess_range(grid_ptrs, var_mins, var_maxs)compute_mess_range(grid_ptrs, var_mins, var_maxs)
grid_ptrs |
List of external pointers to Grid<float> objects. |
var_mins |
Numeric vector of minimum reference values. |
var_maxs |
Numeric vector of maximum reference values. |
A named list with mess_grid and mod_grid (external pointers).
Computes variable contribution based on sum of absolute lambda values for features derived from each variable.
compute_percent_contribution(fs_ptr, feature_names)compute_percent_contribution(fs_ptr, feature_names)
fs_ptr |
External pointer to a FeaturedSpace object. |
feature_names |
Character vector of base variable names. |
A data.frame with columns: name, contribution.
Measures how much each environmental variable contributes to model prediction quality by permuting each variable and measuring AUC drop.
compute_permutation_importance( fs_ptr, grid_ptrs, feature_names, presence_rows, presence_cols, absence_rows, absence_cols, seed = 42L )compute_permutation_importance( fs_ptr, grid_ptrs, feature_names, presence_rows, presence_cols, absence_rows, absence_cols, seed = 42L )
fs_ptr |
External pointer to a FeaturedSpace object. |
grid_ptrs |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
presence_rows |
Integer vector of presence site row indices. |
presence_cols |
Integer vector of presence site column indices. |
absence_rows |
Integer vector of absence site row indices. |
absence_cols |
Integer vector of absence site column indices. |
seed |
Random seed for reproducibility. |
A data.frame with columns: name, permutation_importance.
Like compute_response_curve() but applies the Java Maxent cloglog: cloglog_java = 1 - exp(-exp(H) * raw_java)
compute_response_curve( fs_ptr, grid_ptrs, feature_names, var_index, n_steps = 100L )compute_response_curve( fs_ptr, grid_ptrs, feature_names, var_index, n_steps = 100L )
fs_ptr |
External pointer to a FeaturedSpace object. |
grid_ptrs |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
var_index |
0-based index of the variable to vary. |
n_steps |
Number of steps across the variable range. |
This matches the response curves produced by Java Maxent and dismo.
A data.frame with columns: value, prediction.
Like compute_response_curve_fixed() but applies the Java Maxent cloglog: cloglog_java = 1 - exp(-exp(H) * raw_java)
compute_response_curve_fixed( fs_ptr, fixed_values, feature_names, var_index, var_min, var_max, n_steps = 100L )compute_response_curve_fixed( fs_ptr, fixed_values, feature_names, var_index, var_min, var_max, n_steps = 100L )
fs_ptr |
External pointer to a FeaturedSpace object. |
fixed_values |
Numeric vector of fixed values for each variable. |
feature_names |
Character vector of environment variable names. |
var_index |
0-based index of the variable to vary. |
var_min |
Minimum value of the target variable. |
var_max |
Maximum value of the target variable. |
n_steps |
Number of steps. |
A data.frame with columns: value, prediction.
Scans all valid cells to determine min/max of each variable.
compute_variable_ranges(grid_ptrs)compute_variable_ranges(grid_ptrs)
grid_ptrs |
List of external pointers to Grid<float> objects. |
A data.frame with columns: min, max.
Convert geographic coordinates to row/col
coords_to_rowcol(dim_ptr, lon, lat)coords_to_rowcol(dim_ptr, lon, lat)
dim_ptr |
External pointer to GridDimension |
lon |
Longitude |
lat |
Latitude |
Integer vector with row and column indices
Creates a grid dimension specifying the spatial extent and resolution
create_grid_dimension(nrows, ncols, xll, yll, cellsize)create_grid_dimension(nrows, ncols, xll, yll, cellsize)
nrows |
Number of rows |
ncols |
Number of columns |
xll |
X coordinate of lower-left corner |
yll |
Y coordinate of lower-left corner |
cellsize |
Cell size (assumed square cells) |
External pointer to GridDimension object
Creates a raster grid for environmental variables
create_grid_float(dim_ptr, name, nodata_value = -9999)create_grid_float(dim_ptr, name, nodata_value = -9999)
dim_ptr |
External pointer to GridDimension |
name |
Grid layer name |
nodata_value |
Value representing missing data |
External pointer to Grid<float> object
Creates a piecewise-linear hinge feature. Forward hinge: eval(i) = (values[i] > min_knot) ? (values[i] - min_knot) / (max_knot - min_knot) : 0. Reverse hinge: eval(i) = (values[i] < max_knot) ? (max_knot - values[i]) / (max_knot - min_knot) : 0.
create_hinge_feature(values, name, min_knot, max_knot, is_reverse = FALSE)create_hinge_feature(values, name, min_knot, max_knot, is_reverse = FALSE)
values |
Numeric vector of environmental variable values |
name |
Feature name/identifier |
min_knot |
Lower knot of the hinge |
max_knot |
Upper knot of the hinge (must be > min_knot) |
is_reverse |
If TRUE, use reverse hinge; if FALSE (default), use forward hinge |
External pointer to HingeFeature object
Create a Layer metadata object
create_layer(name, type_str)create_layer(name, type_str)
name |
Layer name. |
type_str |
Type string: "Continuous", "Categorical", "Bias", "Mask", "Probability", "Cumulative", "DebiasAvg", or "Unknown". |
External pointer to a Layer object.
Creates a linear (normalized) feature: eval(i) = (values[i] - min) / (max - min). Returns 0 when min == max.
create_linear_feature(values, name, min_val, max_val)create_linear_feature(values, name, min_val, max_val)
values |
Numeric vector of environmental variable values |
name |
Feature name/identifier |
min_val |
Minimum value for normalization |
max_val |
Maximum value for normalization |
External pointer to LinearFeature object
Creates a product (interaction) feature between two environmental variables: eval(i) = norm(values1[i]) * norm(values2[i]).
create_product_feature(values1, values2, name, min1, max1, min2, max2)create_product_feature(values1, values2, name, min1, max1, min2, max2)
values1 |
Numeric vector for the first environmental variable |
values2 |
Numeric vector for the second environmental variable |
name |
Feature name/identifier |
min1 |
Minimum of the first variable |
max1 |
Maximum of the first variable |
min2 |
Minimum of the second variable |
max2 |
Maximum of the second variable |
External pointer to ProductFeature object
Creates a quadratic feature: eval(i) = linear_val^2 where linear_val = (values[i] - min) / (max - min).
create_quadratic_feature(values, name, min_val, max_val)create_quadratic_feature(values, name, min_val, max_val)
values |
Numeric vector of environmental variable values |
name |
Feature name/identifier |
min_val |
Minimum value for normalization |
max_val |
Maximum value for normalization |
External pointer to QuadraticFeature object
Creates a species occurrence sample point
create_sample(point, row, col, lat, lon, name)create_sample(point, row, col, lat, lon, name)
point |
Point identifier |
row |
Row index in grid |
col |
Column index in grid |
lat |
Latitude coordinate |
lon |
Longitude coordinate |
name |
Sample name/identifier |
External pointer to Sample object
Creates a binary step feature: eval(i) = 1.0 if values[i] > threshold, else 0.0.
create_threshold_feature(values, name, threshold)create_threshold_feature(values, name, threshold)
values |
Numeric vector of environmental variable values |
name |
Feature name/identifier |
threshold |
The threshold value |
External pointer to ThresholdFeature object
Close a CsvReader
csv_close(reader_ptr)csv_close(reader_ptr)
reader_ptr |
External pointer to a CsvReader object. |
Called for side effects; returns invisibly.
Get CSV column headers
csv_headers(reader_ptr)csv_headers(reader_ptr)
reader_ptr |
External pointer to a CsvReader object. |
Character vector of header names.
Read the next CSV record
csv_next_record(reader_ptr)csv_next_record(reader_ptr)
reader_ptr |
External pointer to a CsvReader object. |
Character vector of field values, or NULL on EOF.
Open a CSV file for reading
csv_open(filename, has_header = TRUE)csv_open(filename, has_header = TRUE)
filename |
Path to the CSV file. |
has_header |
Logical: first line contains column names (default TRUE). |
External pointer to a CsvReader object.
Reads from the current position to EOF.
csv_read_double_column(reader_ptr, field)csv_read_double_column(reader_ptr, field)
reader_ptr |
External pointer to a CsvReader object. |
field |
Column name. |
Numeric vector.
Close a CsvWriter
csv_writer_close(writer_ptr)csv_writer_close(writer_ptr)
writer_ptr |
External pointer to a CsvWriter object. |
Called for side effects; returns invisibly.
Open a CSV file for writing
csv_writer_open(filename, append = FALSE, precision = 4L)csv_writer_open(filename, append = FALSE, precision = 4L)
filename |
Path to the output CSV file. |
append |
Logical: append to existing file (default FALSE). |
precision |
Number of decimal places for doubles (default 4). |
External pointer to a CsvWriter object.
Write a value into the current row of a CSV
csv_writer_print(writer_ptr, column, value)csv_writer_print(writer_ptr, column, value)
writer_ptr |
External pointer to a CsvWriter object. |
column |
Column name. |
value |
Value to write (character). |
Called for side effects; returns invisibly.
Write a numeric value into the current row of a CSV
csv_writer_print_double(writer_ptr, column, value)csv_writer_print_double(writer_ptr, column, value)
writer_ptr |
External pointer to a CsvWriter object. |
column |
Column name. |
value |
Numeric value. |
Called for side effects; returns invisibly.
Flush the current CSV row to disk
csv_writer_println(writer_ptr)csv_writer_println(writer_ptr)
writer_ptr |
External pointer to a CsvWriter object. |
Called for side effects; returns invisibly.
Computes the Wilcoxon-Mann-Whitney AUC statistic from prediction scores at presence and absence sites.
eval_auc(presence, absence)eval_auc(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
A named list with elements: auc, max_kappa, max_kappa_thresh.
Computes Pearson correlation coefficient between two numeric vectors.
eval_correlation(x, y)eval_correlation(x, y)
x |
Numeric vector. |
y |
Numeric vector (same length as x). |
Correlation coefficient in [-1, 1].
Computes average cross-entropy log-loss from predictions at presence and absence sites.
eval_logloss(presence, absence)eval_logloss(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
Average log-loss value.
Fraction of misclassified samples at threshold 0.5.
eval_misclassification(presence, absence)eval_misclassification(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
Misclassification rate in [0, 1].
Computes all evaluation metrics at once: AUC, correlation, log-loss, squared error, misclassification, max kappa, and prevalence.
eval_model(presence, absence)eval_model(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
A named list with: auc, max_kappa, max_kappa_thresh, correlation, square_error, logloss, misclassification, prevalence.
Presence sites contribute (1-pred)^2, absence sites contribute pred^2.
eval_square_error(presence, absence)eval_square_error(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
Mean squared error.
Species occurrence points from Abeillia abeillei presence points after download and clean from GBIF. This is a hummingbird example. A dataset with three variables. Contains scientific name, longitude and latitude.
example_occ_dfexample_occ_df
A data frame with 73 rows and 3 variables:
Species name
Decimal longitude geographical coordinate, in degrees
Decimal latitude geographical coordinate, in degrees
<doi:10.1016/j.ecolmodel.2021.109823>
Gets Java Maxent raw scores (raw_java = exp(lp - lpNorm) / densityNorm) at specific grid cell locations.
extract_predictions_raw(fs_ptr, grid_ptrs, feature_names, rows, cols)extract_predictions_raw(fs_ptr, grid_ptrs, feature_names, rows, cols)
fs_ptr |
External pointer to a FeaturedSpace object. |
grid_ptrs |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
rows |
Integer vector of row indices. |
cols |
Integer vector of column indices. |
Numeric vector of Java raw scores. NaN for NODATA cells.
Evaluate a feature at a given index
feature_eval(feature_ptr, index)feature_eval(feature_ptr, index)
feature_ptr |
External pointer to a Feature object |
index |
0-based index into the data vector |
Feature value at that index (double)
Returns a list with name, type, lambda, min, and max values.
feature_get_info(feature_ptr)feature_get_info(feature_ptr)
feature_ptr |
External pointer to a Feature object |
Named list with feature properties
Generates all configured feature types (linear, quadratic, product, threshold, hinge) from the supplied data vectors.
generate_features( data_list, feature_types = as.character(c("linear", "quadratic", "product", "threshold", "hinge")), n_thresholds = 10L, n_hinges = 10L )generate_features( data_list, feature_types = as.character(c("linear", "quadratic", "product", "threshold", "hinge")), n_thresholds = 10L, n_hinges = 10L )
data_list |
Named list of numeric vectors, one per environmental variable |
feature_types |
Character vector of feature types to generate. Valid values: "linear", "quadratic", "product", "threshold", "hinge". Defaults to all types. |
n_thresholds |
Number of threshold knots per variable (default: 10) |
n_hinges |
Number of hinge knots per variable (default: 10) |
List of external pointers to Feature objects
Get grid dimension properties
get_grid_dimension_info(dim_ptr)get_grid_dimension_info(dim_ptr)
dim_ptr |
External pointer to GridDimension |
List with dimension properties
Get layer metadata
get_layer_info(layer_ptr)get_layer_info(layer_ptr)
layer_ptr |
External pointer to a Layer object. |
Named list with name and type (string).
Get sample properties
get_sample_info(sample_ptr)get_sample_info(sample_ptr)
sample_ptr |
External pointer to Sample |
List with sample properties
Create a GridFloat from an R matrix
grid_float_from_matrix(mat, xll, yll, cellsize, nodata = -9999, name = "")grid_float_from_matrix(mat, xll, yll, cellsize, nodata = -9999, name = "")
mat |
Numeric matrix with grid data (NA becomes NODATA). |
xll |
X coordinate of lower-left corner. |
yll |
Y coordinate of lower-left corner. |
cellsize |
Cell size. |
nodata |
NODATA value (default -9999). |
name |
Grid name (default ""). |
External pointer to a GridFloat object.
Returns metadata and basic statistics for a GridFloat.
grid_float_info(grid_ptr)grid_float_info(grid_ptr)
grid_ptr |
External pointer to a GridFloat object. |
Named list with nrows, ncols, xll, yll, cellsize, nodata, name, count_data.
Extract the data from a GridFloat as an R matrix
grid_float_to_matrix(grid_ptr)grid_float_to_matrix(grid_ptr)
grid_ptr |
External pointer to a GridFloat object. |
Numeric matrix (nrows × ncols). NODATA cells are set to NA.
Set grid from matrix
grid_from_matrix(grid_ptr, mat)grid_from_matrix(grid_ptr, mat)
grid_ptr |
External pointer to Grid |
mat |
Numeric matrix of values |
Called for side effects; returns invisibly.
Get grid value
grid_get_value(grid_ptr, row, col)grid_get_value(grid_ptr, row, col)
grid_ptr |
External pointer to Grid |
row |
Row index |
col |
Column index |
Grid value
Extract multiple values from a Grid at given row/col indices (batch)
grid_get_values_batch(grid_ptr, rows, cols)grid_get_values_batch(grid_ptr, rows, cols)
grid_ptr |
External pointer to a Grid<float>. |
rows |
Integer vector of 0-based row indices. |
cols |
Integer vector of 0-based column indices. |
Numeric vector of extracted values (NA for NODATA cells).
Check if grid cell has data
grid_has_data(grid_ptr, row, col)grid_has_data(grid_ptr, row, col)
grid_ptr |
External pointer to Grid |
row |
Row index |
col |
Column index |
TRUE if cell has valid data
Reads an ASC raster file and returns a float Grid external pointer.
grid_read_asc(filename)grid_read_asc(filename)
filename |
Path to the .asc file. |
External pointer to a GridFloat object.
Currently supports .asc format. Returns a float Grid.
grid_read_file(filename)grid_read_file(filename)
filename |
Path to the grid file. |
External pointer to a GridFloat object.
Set grid value
grid_set_value(grid_ptr, row, col, value)grid_set_value(grid_ptr, row, col, value)
grid_ptr |
External pointer to Grid |
row |
Row index |
col |
Column index |
value |
Value to set |
Called for side effects; returns invisibly.
Get grid as matrix
grid_to_matrix(grid_ptr)grid_to_matrix(grid_ptr)
grid_ptr |
External pointer to Grid |
Numeric matrix of grid values
Write a float Grid to an ESRI ASCII (.asc) file
grid_write_asc(grid_ptr, filename, scientific = TRUE)grid_write_asc(grid_ptr, filename, scientific = TRUE)
grid_ptr |
External pointer to a GridFloat object. |
filename |
Output file path. |
scientific |
Logical: use scientific notation (default TRUE). |
Called for side effects; returns invisibly.
Strips directory and extension, e.g. "/data/bio1.asc" → "bio1".
layer_name_from_path(path)layer_name_from_path(path)
path |
File path. |
Character: layer name.
Appends one row of species-level summary statistics to a
maxentResults.csv file, creating the file (with a header) if it does
not yet exist. Column names match the Java Maxent output for
cross-tool compatibility.
maxent_append_results_csv( results_file, species, n_training, n_test = 0L, training_gain, training_auc, test_gain = NA_real_, test_auc = NA_real_, entropy, contributions_df, perm_imp_df )maxent_append_results_csv( results_file, species, n_training, n_test = 0L, training_gain, training_auc, test_gain = NA_real_, test_auc = NA_real_, entropy, contributions_df, perm_imp_df )
results_file |
Character: path to the results CSV file. |
species |
Character: species name. |
n_training |
Integer: number of training presence points. |
n_test |
Integer: number of test presence points (default 0). |
training_gain |
Numeric: regularized training gain. |
training_auc |
Numeric: training AUC. |
test_gain |
Numeric or |
test_auc |
Numeric or |
entropy |
Numeric: model entropy. |
contributions_df |
A data.frame with columns |
perm_imp_df |
A data.frame with columns |
Invisibly returns results_file.
contrib <- data.frame(name = c("bio1", "bio12"), contribution = c(60, 40)) perm_imp <- data.frame(name = c("bio1", "bio12"), permutation_importance = c(55, 45)) maxent_append_results_csv( file.path(tempdir(), "maxentResults.csv"), species = "Sp1", n_training = 50L, training_gain = 1.23, training_auc = 0.95, entropy = 6.7, contributions_df = contrib, perm_imp_df = perm_imp)contrib <- data.frame(name = c("bio1", "bio12"), contribution = c(60, 40)) perm_imp <- data.frame(name = c("bio1", "bio12"), permutation_importance = c(55, 45)) maxent_append_results_csv( file.path(tempdir(), "maxentResults.csv"), species = "Sp1", n_training = 50L, training_gain = 1.23, training_auc = 0.95, entropy = 6.7, contributions_df = contrib, perm_imp_df = perm_imp)
Computes the Wilcoxon-Mann-Whitney AUC statistic from prediction scores at presence and absence sites. Also returns max-Kappa and its threshold.
maxent_auc(presence, absence)maxent_auc(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
A named list with elements:
AUC value in [0, 1]
Best Cohen's Kappa found
Threshold at best Kappa
result <- maxent_auc(c(0.8, 0.9, 1.0), c(0.1, 0.2, 0.3)) result$auc # 1.0result <- maxent_auc(c(0.8, 0.9, 1.0), c(0.1, 0.2, 0.3)) result$auc # 1.0
Randomly selects valid (non-NODATA) cells from a reference grid for use as background points in MaxEnt modeling.
maxent_background_indices(grid, n = 10000L, seed = NULL)maxent_background_indices(grid, n = 10000L, seed = NULL)
grid |
External pointer to a GridFloat object used as a reference (e.g. an environmental layer). Only cells with valid data are eligible. |
n |
Integer: number of background points to sample
(default |
seed |
Integer or |
A named list with:
Integer vector of row indices (0-based).
Integer vector of column indices (0-based).
Integer vector of 0-based flat indices
(row * ncols + col), suitable for
maxent_featured_space.
g <- maxent_grid_from_matrix(matrix(runif(100), 10, 10), -120, 35, 0.1, name = "env1") bg <- maxent_background_indices(g, n = 50, seed = 42) bg$indices # 0-based flat indices for FeaturedSpaceg <- maxent_grid_from_matrix(matrix(runif(100), 10, 10), -120, 35, 0.1, name = "env1") bg <- maxent_background_indices(g, n = 50, seed = 42) bg$indices # 0-based flat indices for FeaturedSpace
Restricts environmental variable values to the range observed during training. Values below min are set to min, values above max are set to max. A clamping grid records the total absolute clamping at each cell.
maxent_clamp(env_grids, var_mins, var_maxs)maxent_clamp(env_grids, var_mins, var_maxs)
env_grids |
List of external pointers to Grid<float> objects. |
var_mins |
Numeric vector of minimum training values per variable. |
var_maxs |
Numeric vector of maximum training values per variable. |
A named list with:
List of external pointers to clamped grids
External pointer to clamping magnitude grid
g1 <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(runif(50, 50, 200), 5, 10), -120, 35, 1, name = "precip") result <- maxent_clamp(list(g1, g2), c(0, 50), c(30, 200)) clamped <- result$clamped_grids clamp_mat <- maxent_grid_to_matrix(result$clamp_grid)g1 <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(runif(50, 50, 200), 5, 10), -120, 35, 1, name = "precip") result <- maxent_clamp(list(g1, g2), c(0, 50), c(30, 200)) clamped <- result$clamped_grids clamp_mat <- maxent_grid_to_matrix(result$clamp_grid)
Produces a vector of hex color strings matching the color ramp used by the
Java Maxent software (density/Display.java::showColor()). The
default palette cycles Red → Yellow → Green → Cyan → Blue across 1020
steps, with higher values rendered as red and lower values as blue.
maxent_color_ramp(n = 1020L, mode = "plain")maxent_color_ramp(n = 1020L, mode = "plain")
n |
Integer: number of colors to generate (default 1020, matching the Java implementation). |
mode |
Character: one of |
Character vector of n hex color strings of the form
"#RRGGBB".
pal <- maxent_color_ramp(1020) pal[1] # "#FF0000" (max value → red) pal[510] # near "#00FF00" (mid-point → green) pal[1020] # "#0000FF" (min value → blue)pal <- maxent_color_ramp(1020) pal[1] # "#FF0000" (max value → red) pal[510] # near "#00FF00" (mid-point → green) pal[1020] # "#0000FF" (min value → blue)
Computes the Pearson correlation coefficient between two numeric vectors.
maxent_correlation(x, y)maxent_correlation(x, y)
x |
Numeric vector. |
y |
Numeric vector (same length as x). |
Correlation coefficient in [-1, 1].
maxent_correlation(c(1, 2, 3), c(2, 4, 6)) # 1.0maxent_correlation(c(1, 2, 3), c(2, 4, 6)) # 1.0
Close a CSV Reader
maxent_csv_close(reader)maxent_csv_close(reader)
reader |
External pointer to a CsvReader object. |
Invisibly returns NULL.
Get CSV Column Headers
maxent_csv_headers(reader)maxent_csv_headers(reader)
reader |
External pointer to a CsvReader object. |
Character vector of column names.
Read the Next CSV Record
maxent_csv_next(reader)maxent_csv_next(reader)
reader |
External pointer to a CsvReader object. |
Character vector of field values, or NULL on EOF.
Opens a CSV file and reads column headers.
maxent_csv_open(filename, has_header = TRUE)maxent_csv_open(filename, has_header = TRUE)
filename |
Character: path to the CSV file. |
has_header |
Logical: first line is header (default |
External pointer to a CsvReader C++ object.
Reads from the current file position to EOF.
maxent_csv_read_column(reader, field)maxent_csv_read_column(reader, field)
reader |
External pointer to a CsvReader object. |
field |
Character: column name. |
Numeric vector.
Adds a column = value pair (as a character string) to the current
row buffer. Call maxent_csv_write_row to flush the row.
maxent_csv_write(writer, column, value)maxent_csv_write(writer, column, value)
writer |
External pointer to a CsvWriter object. |
column |
Character: column name. |
value |
Character: value to write. |
Invisibly returns the writer object.
Flushes any pending data and closes the CSV file.
maxent_csv_write_close(writer)maxent_csv_write_close(writer)
writer |
External pointer to a CsvWriter object. |
Invisibly returns NULL.
Adds a column = value pair (as a double) to the current row buffer.
Call maxent_csv_write_row to flush the row.
maxent_csv_write_num(writer, column, value)maxent_csv_write_num(writer, column, value)
writer |
External pointer to a CsvWriter object. |
column |
Character: column name. |
value |
Numeric: value to write. |
Invisibly returns the writer object.
Opens a CSV file and returns a writer object. Use maxent_csv_write,
maxent_csv_write_num, maxent_csv_write_row, and
maxent_csv_write_close to write data and close the file.
maxent_csv_write_open(filename, append = FALSE, precision = 4L)maxent_csv_write_open(filename, append = FALSE, precision = 4L)
filename |
Character: output file path. |
append |
Logical: append to an existing file (default |
precision |
Integer: number of decimal places for numeric values
(default |
External pointer to a CsvWriter C++ object.
Writes all buffered column values as a single CSV row and starts a new row buffer.
maxent_csv_write_row(writer)maxent_csv_write_row(writer)
writer |
External pointer to a CsvWriter object. |
Invisibly returns the writer object.
Defines the spatial extent and resolution of a raster grid.
maxent_dimension(nrows, ncols, xll, yll, cellsize)maxent_dimension(nrows, ncols, xll, yll, cellsize)
nrows |
Number of rows |
ncols |
Number of columns |
xll |
X coordinate of lower-left corner |
yll |
Y coordinate of lower-left corner |
cellsize |
Cell size (square cells) |
GridDimension object (external pointer)
dim <- maxent_dimension( nrows = 100, ncols = 100, xll = -120.0, yll = 35.0, cellsize = 0.1 )dim <- maxent_dimension( nrows = 100, ncols = 100, xll = -120.0, yll = 35.0, cellsize = 0.1 )
Computes all evaluation metrics at once: AUC, correlation, log-loss, squared error, misclassification, max Kappa, and prevalence.
maxent_evaluate(presence, absence)maxent_evaluate(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
A named list with:
AUC value
Best Cohen's Kappa
Threshold at best Kappa
Pearson correlation with labels
Mean squared error
Cross-entropy log-loss
Misclassification rate
Fraction of presence sites
res <- maxent_evaluate(c(0.9, 0.85, 0.95), c(0.1, 0.15, 0.2)) res$auc # 1.0 res$correlation # > 0res <- maxent_evaluate(c(0.9, 0.85, 0.95), c(0.1, 0.15, 0.2)) res$auc # 1.0 res$correlation # > 0
Retrieves the trained lambda (weight) coefficients from the output of
maxent_run, returning them as a named numeric vector.
Each element is the lambda value for the corresponding feature, and the
name of each element is the feature name (e.g. "bio1",
"bio1^2", "bio1'1").
maxent_extract_lambdas(run_result)maxent_extract_lambdas(run_result)
run_result |
A named list as returned by |
The function reads lambdas directly from the trained model object, so
it also works correctly after reloading coefficients with
maxent_load_lambdas.
A named numeric vector of lambda values, one per feature. Names are the feature names as stored in the model.
if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") example_rasters <- terra::unwrap(readRDS(stack_path)) grids <- list( bio1 = maxent_grid_from_terra(example_rasters[[1]]), bio12 = maxent_grid_from_terra(example_rasters[[2]]) ) data(example_occ_df) result <- maxent_run( species = "Abeillia_abeillei", env_grids = grids, occ_df = example_occ_df, output_dir = tempdir(), lon_col = "long", lat_col = "lat") lambdas <- maxent_extract_lambdas(result) print(lambdas) }if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") example_rasters <- terra::unwrap(readRDS(stack_path)) grids <- list( bio1 = maxent_grid_from_terra(example_rasters[[1]]), bio12 = maxent_grid_from_terra(example_rasters[[2]]) ) data(example_occ_df) result <- maxent_run( species = "Abeillia_abeillei", env_grids = grids, occ_df = example_occ_df, output_dir = tempdir(), lon_col = "long", lat_col = "lat") lambdas <- maxent_extract_lambdas(result) print(lambdas) }
Streams finite raster rows through the same callback-backed provider path
used by maxent_featured_space_from_rast, then returns values
at occurrence locations.
maxent_extract_occurrence_env_terra( rast, occurrences, lon_col = "longitude", lat_col = "latitude" )maxent_extract_occurrence_env_terra( rast, occurrences, lon_col = "longitude", lat_col = "latitude" )
rast |
A |
occurrences |
Either a two-column matrix/data.frame (x,y) or a vector of 1-based raster cell indices. |
lon_col |
Longitude column name when |
lat_col |
Latitude column name when |
Numeric matrix with one row per retained occurrence and one column per raster layer.
Gets Java Maxent cloglog scores at specific grid cell locations:
maxent_extract_predictions_cloglog(model, env_grids, feature_names, rows, cols)maxent_extract_predictions_cloglog(model, env_grids, feature_names, rows, cols)
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
rows |
Integer vector of row indices. |
cols |
Integer vector of column indices. |
Numeric vector of cloglog scores in [0, 1]. NaN for NODATA cells.
maxent_extract_predictions_raw,
maxent_project_cloglog
Gets Java Maxent logistic scores at specific grid cell locations:
maxent_extract_predictions_logistic( model, env_grids, feature_names, rows, cols )maxent_extract_predictions_logistic( model, env_grids, feature_names, rows, cols )
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
rows |
Integer vector of row indices. |
cols |
Integer vector of column indices. |
Numeric vector of logistic scores in [0, 1]. NaN for NODATA cells.
maxent_extract_predictions_raw,
maxent_project_logistic
Gets Java Maxent raw scores at specific grid cell locations:
maxent_extract_predictions_raw(model, env_grids, feature_names, rows, cols)maxent_extract_predictions_raw(model, env_grids, feature_names, rows, cols)
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
rows |
Integer vector of row indices. |
cols |
Integer vector of column indices. |
This matches the raw output of Java Maxent and dismo.
Numeric vector of Java raw scores. NaN for NODATA cells.
Evaluates the feature function at the specified index (1-based, as is standard in R). Internally converts to 0-based indexing for C++.
maxent_feature_eval(feature, index)maxent_feature_eval(feature, index)
feature |
External pointer to a Feature C++ object. |
index |
1-based integer index into the data vector. |
Numeric scalar: the feature value at that index.
vals <- c(0, 5, 10) f <- maxent_linear_feature(vals, "temp") maxent_feature_eval(f, 2) # 5/10 = 0.5vals <- c(0, 5, 10) f <- maxent_linear_feature(vals, "temp") maxent_feature_eval(f, 2) # 5/10 = 0.5
Returns a list of metadata for a feature object.
maxent_feature_info(feature)maxent_feature_info(feature)
feature |
External pointer to a Feature C++ object. |
Named list with elements: name, type, lambda,
min, max, size.
vals <- c(0, 5, 10) f <- maxent_linear_feature(vals, "temp") maxent_feature_info(f)vals <- c(0, 5, 10) f <- maxent_linear_feature(vals, "temp") maxent_feature_info(f)
Constructs a MaxEnt FeaturedSpace from background point data, occurrence sample indices, and a list of pre-built Feature objects.
maxent_featured_space( num_points, sample_indices, features, bias_weights = NULL )maxent_featured_space( num_points, sample_indices, features, bias_weights = NULL )
num_points |
Integer: total number of background points. |
sample_indices |
Integer vector: 0-based indices (into the background array) of the occurrence sample locations. |
features |
List of external pointers to Feature objects, as
returned by |
bias_weights |
Optional numeric vector of per-point bias weights
(length |
External pointer to a FeaturedSpace C++ object.
n <- 100L idx <- 90:99 # 0-based sample indices env <- seq(0, 1, length.out = n) f <- maxent_linear_feature(env, "env1") fs <- maxent_featured_space(n, idx, list(f))n <- 100L idx <- 90:99 # 0-based sample indices env <- seq(0, 1, length.out = n) f <- maxent_linear_feature(env, "env1") fs <- maxent_featured_space(n, idx, list(f))
Constructs a MaxEnt FeaturedSpace from background point count, occurrence sample indices, and a list of Feature objects.
maxent_featured_space_create( num_points, sample_indices, feature_ptrs, bias_weights = numeric(0) )maxent_featured_space_create( num_points, sample_indices, feature_ptrs, bias_weights = numeric(0) )
num_points |
Integer: number of background points. |
sample_indices |
Integer vector: 0-based indices of occurrence samples in the background array. |
feature_ptrs |
List of external pointers to Feature objects
(from |
bias_weights |
Optional numeric vector of per-point bias weights
(length |
External pointer to a FeaturedSpace object.
Builds a FeaturedSpace by draining a callback-style background
provider (typically backed by a terra::SpatRaster block loop)
one tile at a time, then constructing features from the concatenated
(num_points x num_layers) matrix via generate_features.
maxent_featured_space_from_callback( num_points, num_layers, layer_names, sample_indices, feature_types, n_thresholds, n_hinges, next_tile_fn, reset_fn, use_cache = TRUE )maxent_featured_space_from_callback( num_points, num_layers, layer_names, sample_indices, feature_types, n_thresholds, n_hinges, next_tile_fn, reset_fn, use_cache = TRUE )
num_points |
Integer: total number of finite background points
the provider will emit (sum of |
num_layers |
Integer: number of environmental variables / raster layers per tile row. |
layer_names |
Character vector of length |
sample_indices |
Integer vector: 0-based indices of occurrence samples in the concatenated background stream. |
feature_types |
Character vector of feature types to generate.
See |
n_thresholds |
Number of threshold knots per variable. |
n_hinges |
Number of hinge knots per variable. |
next_tile_fn |
R function returning the next tile as a numeric
matrix (nrow x num_layers), or a 0-row matrix / |
reset_fn |
R function (no arguments) that rewinds the underlying stream to the beginning. |
use_cache |
Logical; wrap the callback stream in
|
This is the C++ entry point used by
maxent_featured_space_from_rast; end users should prefer
that R-level wrapper.
External pointer to a FeaturedSpace object.
Streams a terra::SpatRaster block-by-block into the C++
FeaturedSpace streaming constructor, filtering NA cells on the fly
and handing the concatenated (num_points x nlyr(rast))
matrix to maxent_generate_features so feature objects are
built inside C++ without the R caller having to materialise the full
raster stack first.
maxent_featured_space_from_rast( rast, sample_indices, feature_types = c("linear", "quadratic", "product", "threshold", "hinge"), n_thresholds = 10L, n_hinges = 10L, enable_streaming_eval = TRUE )maxent_featured_space_from_rast( rast, sample_indices, feature_types = c("linear", "quadratic", "product", "threshold", "hinge"), n_thresholds = 10L, n_hinges = 10L, enable_streaming_eval = TRUE )
rast |
A |
sample_indices |
Integer vector: 0-based indices of occurrence
samples in the concatenated stream of finite background cells. See
|
feature_types |
Character vector of feature types to generate.
Any subset of |
n_thresholds |
Integer; number of threshold knots per variable. |
n_hinges |
Integer; number of hinge knots per variable. |
enable_streaming_eval |
Logical; when |
This is the Phase E.2 entry point described in
docs/ARCHITECTURE_terra_raster.md (sections 3.1 and 3.2). The
result is bit-for-bit identical to the dense path
(maxent_generate_features -> maxent_featured_space)
when the same data, sample indices, and feature configuration are used.
External pointer to a FeaturedSpace object.
maxent_featured_space,
maxent_featured_space_from_callback,
maxent_generate_features.
if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") r <- terra::unwrap(readRDS(stack_path)) fs <- maxent_featured_space_from_rast( r, sample_indices = c(0L, 1L, 2L), feature_types = c("linear", "quadratic") ) }if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") r <- terra::unwrap(readRDS(stack_path)) fs <- maxent_featured_space_from_rast( r, sample_indices = c(0L, 1L, 2L), feature_types = c("linear", "quadratic") ) }
Get FeaturedSpace metadata
maxent_featured_space_info(fs_ptr)maxent_featured_space_info(fs_ptr)
fs_ptr |
External pointer to a FeaturedSpace object. |
Named list with num_points, num_samples, num_features, density_normalizer, linear_predictor_normalizer, has_bias.
Runs the sequential coordinate-ascent MaxEnt optimization on a FeaturedSpace.
maxent_fit( featured_space, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001 )maxent_fit( featured_space, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001 )
featured_space |
External pointer to a FeaturedSpace object (from
|
max_iter |
Maximum number of training iterations (default 500). |
convergence |
Convergence threshold: stop when the per-20-iteration loss improvement is below this value (default 1e-5). |
beta_multiplier |
Regularization multiplier (default 1.0). Higher values increase regularization strength. |
min_deviation |
Minimum sample deviation floor used in regularization (default 0.001). |
Named list with:
Final regularized loss (scalar).
Shannon entropy of the trained distribution.
Number of training iterations completed.
Logical: whether the convergence threshold was reached.
Numeric vector of final lambda (weight) values.
n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) result <- maxent_fit(fs, max_iter = 100, convergence = 1e-5) result$lossn <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) result <- maxent_fit(fs, max_iter = 100, convergence = 1e-5) result$loss
Automatically generates all configured feature types from one or more environmental variable vectors.
maxent_generate_features( data, types = c("linear", "quadratic", "product", "threshold", "hinge"), n_thresholds = 10L, n_hinges = 10L )maxent_generate_features( data, types = c("linear", "quadratic", "product", "threshold", "hinge"), n_thresholds = 10L, n_hinges = 10L )
data |
Named list of numeric vectors, one per environmental variable. |
types |
Character vector of feature types to generate. Valid values:
|
n_thresholds |
Integer; number of threshold knots per variable (default: 10). |
n_hinges |
Integer; number of hinge knots per variable (default: 10). |
Named list of external pointers to Feature C++ objects.
env_data <- list( temperature = c(15, 20, 25, 18, 22), precipitation = c(100, 200, 150, 80, 300) ) features <- maxent_generate_features(env_data, types = c("linear", "hinge")) length(features)env_data <- list( temperature = c(15, 20, 25, 18, 22), precipitation = c(100, 200, 150, 80, 300) ) features <- maxent_generate_features(env_data, types = c("linear", "hinge")) length(features)
Get entropy of a FeaturedSpace distribution
maxent_get_entropy(fs_ptr)maxent_get_entropy(fs_ptr)
fs_ptr |
External pointer to a FeaturedSpace object. |
Shannon entropy (non-negative scalar).
Get current loss of a FeaturedSpace
maxent_get_loss(fs_ptr)maxent_get_loss(fs_ptr)
fs_ptr |
External pointer to a FeaturedSpace object. |
Scalar loss value (negative log-likelihood).
Get current distribution weights from a FeaturedSpace
maxent_get_weights(fs_ptr)maxent_get_weights(fs_ptr)
fs_ptr |
External pointer to a FeaturedSpace object. |
Numeric vector of normalized weights (sums to 1).
Creates a raster grid for storing environmental variable data.
maxent_grid(dim, name = "", nodata_value = -9999)maxent_grid(dim, name = "", nodata_value = -9999)
dim |
GridDimension object defining spatial extent |
name |
Grid layer name |
nodata_value |
Value representing missing data (default: -9999) |
Grid object (external pointer)
dim <- maxent_dimension(100, 100, -120, 35, 0.1) grid <- maxent_grid(dim, "temperature")dim <- maxent_dimension(100, 100, -120, 35, 0.1) grid <- maxent_grid(dim, "temperature")
Builds a GridFloat from a numeric matrix and spatial parameters.
NA values in the matrix are stored as the nodata value.
maxent_grid_from_matrix(mat, xll, yll, cellsize, nodata = -9999, name = "")maxent_grid_from_matrix(mat, xll, yll, cellsize, nodata = -9999, name = "")
mat |
Numeric matrix. |
xll |
X coordinate of lower-left corner. |
yll |
Y coordinate of lower-left corner. |
cellsize |
Cell size. |
nodata |
NODATA sentinel value (default |
name |
Grid name (default |
External pointer to a GridFloat C++ object.
Converts a single-layer terra::SpatRaster into a maxentcpp
GridFloat external pointer. The raster must have exactly one layer and
square cells (equal x and y resolution).
maxent_grid_from_terra(r, name = NULL)maxent_grid_from_terra(r, name = NULL)
r |
A single-layer |
name |
Character: grid name (default: layer name from the raster). |
NA values in the raster are stored as NODATA (sentinel -9999).
Requires the terra package (listed in Suggests).
For the raster package, an equivalent workflow is:
library(raster)
r <- raster("bio1.tif")
mat <- as.matrix(r)
e <- extent(r)
g <- maxent_grid_from_matrix(mat, xll = e@xmin, yll = e@ymin,
cellsize = res(r)[1],
name = names(r))
External pointer to a GridFloat C++ object.
if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") r <- terra::unwrap(readRDS(stack_path)) g <- maxent_grid_from_terra(r[[1]]) maxent_grid_info(g) }if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") r <- terra::unwrap(readRDS(stack_path)) g <- maxent_grid_from_terra(r[[1]]) maxent_grid_info(g) }
Returns metadata about a GridFloat object read from a file.
maxent_grid_info(grid)maxent_grid_info(grid)
grid |
External pointer to a GridFloat object. |
Named list with: nrows, ncols, xll,
yll, cellsize, nodata, name,
count_data.
Extracts the data from a GridFloat as an R numeric matrix.
NODATA cells are converted to NA.
maxent_grid_to_matrix(grid)maxent_grid_to_matrix(grid)
grid |
External pointer to a GridFloat object. |
Numeric matrix (nrows ncols).
Creates a terra::SpatRaster from a maxentcpp GridFloat external
pointer.
maxent_grid_to_terra(grid, crs = "EPSG:4326")maxent_grid_to_terra(grid, crs = "EPSG:4326")
grid |
External pointer to a GridFloat C++ object. |
crs |
Character: coordinate reference system string
(default |
Requires the terra package (listed in Suggests).
For the raster package, an equivalent workflow is:
library(raster)
info <- maxent_grid_info(grid)
mat <- maxent_grid_to_matrix(grid)
r <- raster(mat,
xmn = info$xll,
xmx = info$xll + info$ncols * info$cellsize,
ymn = info$yll,
ymx = info$yll + info$nrows * info$cellsize,
crs = "+proj=longlat +datum=WGS84")
A single-layer terra::SpatRaster.
if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") r <- terra::unwrap(readRDS(stack_path)) g <- maxent_grid_from_terra(r[[1]]) r2 <- maxent_grid_to_terra(g) }if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") r <- terra::unwrap(readRDS(stack_path)) g <- maxent_grid_from_terra(r[[1]]) r2 <- maxent_grid_to_terra(g) }
Creates a piecewise-linear hinge feature.
maxent_hinge_feature(values, name, min_knot, max_knot, reverse = FALSE)maxent_hinge_feature(values, name, min_knot, max_knot, reverse = FALSE)
values |
Numeric vector of environmental variable values. |
name |
Character string: feature name/identifier. |
min_knot |
Lower knot of the hinge. |
max_knot |
Upper knot of the hinge (must be strictly greater than
|
reverse |
Logical; if |
Forward hinge (reverse = FALSE):
eval(i) = max(0, (values[i] - min_knot) / (max_knot - min_knot))
Reverse hinge (reverse = TRUE):
eval(i) = max(0, (max_knot - values[i]) / (max_knot - min_knot))
External pointer to a HingeFeature C++ object.
vals <- c(0, 5, 10, 3) f <- maxent_hinge_feature(vals, "temperature_hinge", min_knot = 2, max_knot = 8) maxent_feature_eval(f, 2) # values[2] = 5 -> (5-2)/(8-2) = 0.5vals <- c(0, 5, 10, 3) f <- maxent_hinge_feature(vals, "temperature_hinge", min_knot = 2, max_knot = 8) maxent_feature_eval(f, 2) # values[2] = 5 -> (5-2)/(8-2) = 0.5
Create a Layer Metadata Object
maxent_layer(name, type = "Continuous")maxent_layer(name, type = "Continuous")
name |
Character: layer name. |
type |
Character: layer type. One of |
External pointer to a Layer C++ object.
Get Layer Metadata
maxent_layer_info(layer)maxent_layer_info(layer)
layer |
External pointer to a Layer object. |
Named list with name and type.
Strips directory prefix and extension.
maxent_layer_name(path)maxent_layer_name(path)
path |
Character: file path. |
Character: layer name (e.g., "/data/bio1.asc" → "bio1").
Creates a linear (normalized) feature that evaluates to
(values[i] - min) / (max - min). Returns 0 when min == max.
maxent_linear_feature(values, name, min_val = NULL, max_val = NULL)maxent_linear_feature(values, name, min_val = NULL, max_val = NULL)
values |
Numeric vector of environmental variable values. |
name |
Character string: feature name/identifier. |
min_val |
Minimum value for normalization. If |
max_val |
Maximum value for normalization. If |
External pointer to a LinearFeature C++ object.
vals <- c(0, 5, 10, 3) f <- maxent_linear_feature(vals, "temperature") maxent_feature_eval(f, 1) # index 1 (R) -> 0-based index 0vals <- c(0, 5, 10, 3) f <- maxent_linear_feature(vals, "temperature") maxent_feature_eval(f, 1) # index 1 (R) -> 0-based index 0
Reads model coefficients from a .lambdas file and applies them to a FeaturedSpace that was created with the same features.
maxent_load_lambdas(featured_space, file)maxent_load_lambdas(featured_space, file)
featured_space |
External pointer to a FeaturedSpace object (must have features with the same names as those in the file). |
file |
Character: path to the lambdas file. |
Invisibly returns the FeaturedSpace external pointer (updated in-place).
n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) maxent_fit(fs, max_iter = 100) f <- tempfile(fileext = ".lambdas") maxent_save_lambdas(fs, f) maxent_load_lambdas(fs, f)n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) maxent_fit(fs, max_iter = 100) f <- tempfile(fileext = ".lambdas") maxent_save_lambdas(fs, f) maxent_load_lambdas(fs, f)
Computes the average cross-entropy log-loss from predictions at presence and absence sites.
maxent_logloss(presence, absence)maxent_logloss(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
Average log-loss value (lower is better).
maxent_logloss(c(0.9, 0.8), c(0.1, 0.2))maxent_logloss(c(0.9, 0.8), c(0.1, 0.2))
Measures how similar each cell is to the training environment using the full distribution of reference values. Negative MESS values indicate novel (non-analog) environments.
maxent_mess(env_grids, reference_values, feature_names)maxent_mess(env_grids, reference_values, feature_names)
env_grids |
List of external pointers to Grid<float> objects. |
reference_values |
List of numeric vectors with reference values for each variable (e.g. values at training sites). |
feature_names |
Character vector of variable names. |
A named list with:
External pointer to Grid<float> with MESS values
External pointer to Grid<float> with Most Dissimilar Variable index (1-based)
g1 <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(runif(50, 50, 200), 5, 10), -120, 35, 1, name = "precip") temp_train_vals <- runif(20) precip_train_vals <- runif(20, 50, 200) result <- maxent_mess(list(g1, g2), list(temp_train_vals, precip_train_vals), c("temp", "precip")) mess_mat <- maxent_grid_to_matrix(result$mess_grid) mod_mat <- maxent_grid_to_matrix(result$mod_grid)g1 <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(runif(50, 50, 200), 5, 10), -120, 35, 1, name = "precip") temp_train_vals <- runif(20) precip_train_vals <- runif(20, 50, 200) result <- maxent_mess(list(g1, g2), list(temp_train_vals, precip_train_vals), c("temp", "precip")) mess_mat <- maxent_grid_to_matrix(result$mess_grid) mod_mat <- maxent_grid_to_matrix(result$mod_grid)
Simplified MESS analysis using only the min/max of the reference data rather than the full distribution.
maxent_mess_range(env_grids, var_mins, var_maxs)maxent_mess_range(env_grids, var_mins, var_maxs)
env_grids |
List of external pointers to Grid<float> objects. |
var_mins |
Numeric vector of minimum reference values per variable. |
var_maxs |
Numeric vector of maximum reference values per variable. |
A named list with mess_grid and mod_grid (external pointers).
Fraction of misclassified samples at threshold 0.5.
maxent_misclassification(presence, absence)maxent_misclassification(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
Misclassification rate in [0, 1].
maxent_misclassification(c(0.8, 0.9), c(0.1, 0.2)) # 0.0maxent_misclassification(c(0.8, 0.9), c(0.1, 0.2)) # 0.0
Returns the Shannon entropy of the current MaxEnt distribution.
maxent_model_entropy(featured_space)maxent_model_entropy(featured_space)
featured_space |
External pointer to a FeaturedSpace object. |
Scalar: Shannon entropy (non-negative).
Returns the current (negative log-likelihood) loss of the model.
maxent_model_loss(featured_space)maxent_model_loss(featured_space)
featured_space |
External pointer to a FeaturedSpace object. |
Scalar: current loss value.
Returns the normalized probability weights of the current MaxEnt distribution over the background points.
maxent_model_weights(featured_space)maxent_model_weights(featured_space)
featured_space |
External pointer to a FeaturedSpace object. |
Numeric vector of weights that sum to 1.
Computes variable contribution based on sum of absolute lambda values for features derived from each variable. Results sum to 100
maxent_percent_contribution(model, feature_names)maxent_percent_contribution(model, feature_names)
model |
External pointer to a FeaturedSpace object. |
feature_names |
Character vector of base variable names. |
A data.frame with columns:
Variable name
Percent contribution
n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(temp = runif(n), precip = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100, convergence = 1e-3) contrib <- maxent_percent_contribution(model, c("temp", "precip")) contrib # data.frame with name and contributionn <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(temp = runif(n), precip = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100, convergence = 1e-3) contrib <- maxent_percent_contribution(model, c("temp", "precip")) contrib # data.frame with name and contribution
Measures how much each environmental variable contributes to model prediction quality by permuting each variable and measuring AUC drop. Results are normalised so that all importances sum to 100
maxent_permutation_importance( model, env_grids, feature_names, presence_rows, presence_cols, absence_rows, absence_cols, seed = 42L )maxent_permutation_importance( model, env_grids, feature_names, presence_rows, presence_cols, absence_rows, absence_cols, seed = 42L )
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names, matching the order of env_grids. |
presence_rows |
Integer vector of presence site row indices (0-based). |
presence_cols |
Integer vector of presence site column indices (0-based). |
absence_rows |
Integer vector of absence/background site row indices. |
absence_cols |
Integer vector of absence/background site column indices. |
seed |
Random seed for reproducibility (default 42). |
A data.frame with columns:
Variable name
Normalised importance (%)
set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(temp = runif(n), precip = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$temp, 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(env$precip, 5, 10), -120, 35, 1, name = "precip") pres_rows <- c(0L, 1L, 2L); pres_cols <- c(0L, 1L, 2L) abs_rows <- c(3L, 4L, 0L); abs_cols <- c(5L, 6L, 7L) imp <- maxent_permutation_importance(model, list(g1, g2), c("temp", "precip"), pres_rows, pres_cols, abs_rows, abs_cols) impset.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(temp = runif(n), precip = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$temp, 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(env$precip, 5, 10), -120, 35, 1, name = "precip") pres_rows <- c(0L, 1L, 2L); pres_cols <- c(0L, 1L, 2L) abs_rows <- c(3L, 4L, 0L); abs_cols <- c(5L, 6L, 7L) imp <- maxent_permutation_importance(model, list(g1, g2), c("temp", "precip"), pres_rows, pres_cols, abs_rows, abs_cols) imp
Generates response curve plots for each environmental variable and saves
them as PNG files, replicating density/ResponsePlot.java::makeplot().
A full-size PNG and an optional thumbnail are written for every variable.
maxent_plot_response_curves( model, env_grids, feature_names, output_dir, species, var_indices = NULL, n_steps = 100L, thumbnail = TRUE, write_dat = FALSE )maxent_plot_response_curves( model, env_grids, feature_names, output_dir, species, var_indices = NULL, n_steps = 100L, thumbnail = TRUE, write_dat = FALSE )
model |
External pointer to a trained FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names
(one entry per element of |
output_dir |
Character: directory under which a |
species |
Character: species name (used in file names). |
var_indices |
Integer vector of 0-based variable indices to plot. Defaults to all variables. |
n_steps |
Integer: number of steps in each curve (default 100). |
thumbnail |
Logical: also write a 210 x 140 pixel thumbnail PNG
(default |
write_dat |
Logical: also write a tab-delimited |
Invisibly returns a named list of file paths written.
set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") maxent_plot_response_curves( model, list(g1, g2), c("bio1", "bio12"), output_dir = tempdir(), species = "Sp1")set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") maxent_plot_response_curves( model, list(g1, g2), c("bio1", "bio12"), output_dir = tempdir(), species = "Sp1")
Creates a horizontal bar chart comparing percent contribution and
permutation importance for each environmental variable, replicating
density/Runner.java::makeJackknifePlots().
maxent_plot_variable_importance( contributions_df, perm_imp_df, species, output_dir )maxent_plot_variable_importance( contributions_df, perm_imp_df, species, output_dir )
contributions_df |
A data.frame with columns |
perm_imp_df |
A data.frame with columns |
species |
Character: species name (used in the filename). |
output_dir |
Character: directory under which a |
Invisibly returns the path to the PNG file.
contrib <- data.frame(name = c("bio1", "bio12"), contribution = c(60, 40)) perm_imp <- data.frame(name = c("bio1", "bio12"), permutation_importance = c(55, 45)) maxent_plot_variable_importance(contrib, perm_imp, species = "Sp1", output_dir = tempdir())contrib <- data.frame(name = c("bio1", "bio12"), contribution = c(60, 40)) perm_imp <- data.frame(name = c("bio1", "bio12"), permutation_importance = c(55, 45)) maxent_plot_variable_importance(contrib, perm_imp, species = "Sp1", output_dir = tempdir())
Computes raw Gibbs distribution scores for new environmental data.
maxent_predict(fs_ptr, new_data)maxent_predict(fs_ptr, new_data)
fs_ptr |
External pointer to a trained FeaturedSpace object. |
new_data |
Numeric matrix with one row per new point and one column per feature (values must be pre-evaluated, i.e., the feature transformation already applied). |
Numeric vector of raw scores (unnormalized).
Computes raw Gibbs distribution scores for new environmental data, using the feature lambdas stored in the trained FeaturedSpace.
maxent_predict_model(featured_space, newdata)maxent_predict_model(featured_space, newdata)
featured_space |
External pointer to a trained FeaturedSpace object. |
newdata |
Numeric matrix: one row per new point, one column per
feature. Column values must be the already-evaluated feature
values (e.g., from running |
Numeric vector of raw (unnormalized) prediction scores.
n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) maxent_fit(fs, max_iter = 100) newdata <- matrix(runif(10), nrow = 5, ncol = 2) preds <- maxent_predict_model(fs, newdata)n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) maxent_fit(fs, max_iter = 100) newdata <- matrix(runif(10), nrow = 5, ncol = 2) preds <- maxent_predict_model(fs, newdata)
Prints a summary of Maxent model performance metrics to the console, replicating the style of the dismo package's MaxEnt output. The report includes sample counts, training (and optionally test) evaluation statistics, and a ranked variable-contributions table.
maxent_print_results( species, eval_result, contributions_df, perm_imp_df, n_presence, n_background, test_eval_result = NULL, n_test = 0L, fit_result = NULL )maxent_print_results( species, eval_result, contributions_df, perm_imp_df, n_presence, n_background, test_eval_result = NULL, n_test = 0L, fit_result = NULL )
species |
Character: species name. |
eval_result |
Named list returned by |
contributions_df |
Data.frame with columns |
perm_imp_df |
Data.frame with columns |
n_presence |
Integer: number of training presence records. |
n_background |
Integer: number of background records. |
test_eval_result |
Named list returned by |
n_test |
Integer: number of test presence records
(default |
fit_result |
Named list returned by |
Invisibly returns a named list with all reported metrics.
eval_result <- maxent_evaluate(c(0.9, 0.85, 0.95), c(0.1, 0.15, 0.2)) contrib <- data.frame(name = c("bio1", "bio12"), contribution = c(60, 40)) perm_imp <- data.frame(name = c("bio1", "bio12"), permutation_importance = c(55, 45)) maxent_print_results( species = "Sp1", eval_result = eval_result, contributions_df = contrib, perm_imp_df = perm_imp, n_presence = 3L, n_background = 100L)eval_result <- maxent_evaluate(c(0.9, 0.85, 0.95), c(0.1, 0.15, 0.2)) contrib <- data.frame(name = c("bio1", "bio12"), contribution = c(60, 40)) perm_imp <- data.frame(name = c("bio1", "bio12"), permutation_importance = c(55, 45)) maxent_print_results( species = "Sp1", eval_result = eval_result, contributions_df = contrib, perm_imp_df = perm_imp, n_presence = 3L, n_background = 100L)
Creates an interaction feature between two environmental variables:
eval(i) = norm(values1[i]) * norm(values2[i]).
maxent_product_feature( values1, values2, name, min1 = NULL, max1 = NULL, min2 = NULL, max2 = NULL )maxent_product_feature( values1, values2, name, min1 = NULL, max1 = NULL, min2 = NULL, max2 = NULL )
values1 |
Numeric vector for the first environmental variable. |
values2 |
Numeric vector for the second environmental variable
(must have the same length as |
name |
Character string: feature name/identifier. |
min1 |
Minimum of the first variable. If |
max1 |
Maximum of the first variable. If |
min2 |
Minimum of the second variable. If |
max2 |
Maximum of the second variable. If |
External pointer to a ProductFeature C++ object.
temp <- c(0, 5, 10) prec <- c(100, 200, 150) f <- maxent_product_feature(temp, prec, "temp_x_prec") maxent_feature_eval(f, 2)temp <- c(0, 5, 10) prec <- c(100, 200, 150) f <- maxent_product_feature(temp, prec, "temp_x_prec") maxent_feature_eval(f, 2)
Applies the Java Maxent cloglog transform to grid predictions:
maxent_project_cloglog(model, env_grids, feature_names)maxent_project_cloglog(model, env_grids, feature_names)
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
where is the model entropy and is the
normalised probability. This matches the cloglog output of Java
Maxent and dismo, and is the recommended output for reporting.
External pointer to a Grid<float> with cloglog scores in [0, 1].
maxent_project_raw,
maxent_project_logistic
Applies the Java Maxent logistic transform to grid predictions:
maxent_project_logistic(model, env_grids, feature_names)maxent_project_logistic(model, env_grids, feature_names)
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
where is the model entropy and is the
normalised probability. This matches the logistic output of Java
Maxent and dismo.
External pointer to a Grid<float> with logistic scores in [0, 1].
maxent_project_raw,
maxent_project_cloglog
Produces Java Maxent "raw" scores for every grid cell:
maxent_project_raw(model, env_grids, feature_names)maxent_project_raw(model, env_grids, feature_names)
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
This matches the raw output of the Java Maxent software and the
dismo R package. See vignette("PREDICTION_SCALES") or
docs/PREDICTION_SCALES.md for a full description of prediction
scales.
External pointer to a Grid<float> with Java raw scores.
maxent_project_cloglog,
maxent_project_logistic
Creates a quadratic feature that evaluates to linear_val^2 where
linear_val = (values[i] - min) / (max - min).
maxent_quadratic_feature(values, name, min_val = NULL, max_val = NULL)maxent_quadratic_feature(values, name, min_val = NULL, max_val = NULL)
values |
Numeric vector of environmental variable values. |
name |
Character string: feature name/identifier. |
min_val |
Minimum value for normalization. If |
max_val |
Maximum value for normalization. If |
External pointer to a QuadraticFeature C++ object.
vals <- c(0, 5, 10) f <- maxent_quadratic_feature(vals, "temperature_sq") maxent_feature_eval(f, 2) # evaluates at index 2 (1-based -> 0-based: 1)vals <- c(0, 5, 10) f <- maxent_quadratic_feature(vals, "temperature_sq") maxent_feature_eval(f, 2) # evaluates at index 2 (1-based -> 0-based: 1)
Maps occurrence cell indices (as produced by terra::cellFromXY)
into 0-based indices within the concatenated stream of finite
(non-NA) background cells emitted by
maxent_featured_space_from_rast.
maxent_raster_sample_indices(rast, cells)maxent_raster_sample_indices(rast, cells)
rast |
A |
cells |
Integer vector of 1-based cell indices
(as returned by |
Integer vector of 0-based indices within the finite-cell stream. Occurrence cells that fall on NA raster values (and therefore never appear in the stream) are silently dropped and a warning is emitted.
Reads a .asc raster file into a GridFloat object.
maxent_read_asc(filename)maxent_read_asc(filename)
filename |
Character: path to the |
External pointer to a GridFloat C++ object.
g <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 0.1, name = "bio1") f <- tempfile(fileext = ".asc") maxent_write_asc(g, f) g2 <- maxent_read_asc(f) maxent_grid_info(g2)g <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 0.1, name = "bio1") f <- tempfile(fileext = ".asc") maxent_write_asc(g, f) g2 <- maxent_read_asc(f) maxent_grid_info(g2)
Reads a raster grid file. The format is detected from the file extension.
Currently supports .asc (ESRI ASCII Grid).
maxent_read_grid(filename)maxent_read_grid(filename)
filename |
Character: path to the grid file. |
External pointer to a GridFloat C++ object.
Restores model coefficients from a .lambdas file. The FeaturedSpace must have been created with the same features (same names and order).
maxent_read_lambdas(fs_ptr, filename)maxent_read_lambdas(fs_ptr, filename)
fs_ptr |
External pointer to a FeaturedSpace object. |
filename |
Character: path to the lambdas file. |
Called for side effects; returns invisibly.
Reads species presence records from a CSV file or an R data.frame
and converts them to row/column indices suitable for
maxent_featured_space.
maxent_read_occurrences( file_or_df, dim, lon_col = "longitude", lat_col = "latitude", name_col = NULL )maxent_read_occurrences( file_or_df, dim, lon_col = "longitude", lat_col = "latitude", name_col = NULL )
file_or_df |
Either a character path to a CSV file, or a
|
dim |
A GridDimension object (from |
lon_col |
Character: name of the longitude column
(default |
lat_col |
Character: name of the latitude column
(default |
name_col |
Character or |
A named list with:
List of Sample external pointers.
Integer vector of row indices (0-based).
Integer vector of column indices (0-based).
Integer vector of 0-based flat indices
(row * ncols + col), suitable for
maxent_featured_space.
dim <- maxent_dimension(100, 100, -120, 35, 0.1) occ <- data.frame(longitude = c(-118.5, -119.0), latitude = c(36.5, 37.0)) result <- maxent_read_occurrences(occ, dim) result$indices # 0-based flat indices for FeaturedSpacedim <- maxent_dimension(100, 100, -120, 35, 0.1) occ <- data.frame(longitude = c(-118.5, -119.0), latitude = c(36.5, 37.0)) result <- maxent_read_occurrences(occ, dim) result$indices # 0-based flat indices for FeaturedSpace
Generates a response curve by varying one environmental variable from its minimum to maximum value while holding all other variables at their mean. Applies the Java Maxent cloglog transform, matching the output of Java Maxent and dismo:
maxent_response_curve( model, env_grids, feature_names, var_index, n_steps = 100L )maxent_response_curve( model, env_grids, feature_names, var_index, n_steps = 100L )
model |
External pointer to a FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
var_index |
0-based index of the variable to vary. |
n_steps |
Number of steps across the variable range (default 100). |
A data.frame with columns:
Environmental variable value
Cloglog-transformed prediction
set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(temp = runif(n), precip = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$temp, 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(env$precip, 5, 10), -120, 35, 1, name = "precip") curve <- maxent_response_curve(model, list(g1, g2), c("temp", "precip"), var_index = 0) plot(curve$value, curve$prediction, type = "l")set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(temp = runif(n), precip = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$temp, 5, 10), -120, 35, 1, name = "temp") g2 <- maxent_grid_from_matrix(matrix(env$precip, 5, 10), -120, 35, 1, name = "precip") curve <- maxent_response_curve(model, list(g1, g2), c("temp", "precip"), var_index = 0) plot(curve$value, curve$prediction, type = "l")
Like maxent_response_curve but the user supplies explicit fixed
values for the non-target variables. Applies the Java Maxent cloglog
transform, matching the output of Java Maxent and dismo:
maxent_response_curve_fixed( model, fixed_values, feature_names, var_index, var_min, var_max, n_steps = 100L )maxent_response_curve_fixed( model, fixed_values, feature_names, var_index, var_min, var_max, n_steps = 100L )
model |
External pointer to a FeaturedSpace object. |
fixed_values |
Numeric vector of fixed values for each variable. |
feature_names |
Character vector of environment variable names. |
var_index |
0-based index of the variable to vary. |
var_min |
Minimum value of the target variable. |
var_max |
Maximum value of the target variable. |
n_steps |
Number of steps (default 100). |
A data.frame with columns: value, prediction.
Provides a single high-level entry point that mirrors running the Java Maxent GUI with one click. Starting from raw environmental grids and occurrence records, the function:
Reads and validates occurrence records.
Samples background points.
Extracts environmental values and builds features.
Trains the Maxent model.
Projects the model onto the full landscape (cloglog output).
Evaluates model performance (AUC).
Computes percent contribution and permutation importance.
Writes all standard output files (lambdas, prediction PNG, response
curve PNGs, omission CSV, sample-predictions CSV, and
maxentResults.csv).
Prints a performance summary to the console.
maxent_run( species, env_grids, occ_df, output_dir, lon_col = "long", lat_col = "lat", n_background = 10000L, types = c("linear", "quadratic", "hinge"), n_hinges = 15L, max_iter = 500L, seed = 42L, bias_weights = NULL, response_curves = TRUE, pictures = TRUE )maxent_run( species, env_grids, occ_df, output_dir, lon_col = "long", lat_col = "lat", n_background = 10000L, types = c("linear", "quadratic", "hinge"), n_hinges = 15L, max_iter = 500L, seed = 42L, bias_weights = NULL, response_curves = TRUE, pictures = TRUE )
species |
Character: species name (used in file names and the console report). |
env_grids |
Named list of external pointers to Grid<float> objects. The names of the list are used as the environmental variable names. |
occ_df |
A |
output_dir |
Character: directory where all output files are written (created if it does not exist). |
lon_col |
Character: longitude column name in |
lat_col |
Character: latitude column name in |
n_background |
Integer: number of background points (default 10000). |
types |
Character vector of feature types passed to
|
n_hinges |
Integer: number of hinge knots (default 15). |
max_iter |
Integer: maximum training iterations (default 500). |
seed |
Integer: random seed for background sampling (default 42). |
bias_weights |
Optional numeric vector of per-background-point bias
weights. Must have length equal to |
response_curves |
Logical: write response curve PNGs
(default |
pictures |
Logical: write prediction map PNG (default |
A named list with:
Trained FeaturedSpace external pointer.
List returned by maxent_fit.
List returned by maxent_evaluate.
Data.frame of percent contributions.
Data.frame of permutation importances.
The output directory used.
if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") example_rasters <- terra::unwrap(readRDS(stack_path)) grids <- list( bio1 = maxent_grid_from_terra(example_rasters[[1]]), bio12 = maxent_grid_from_terra(example_rasters[[2]]) ) data(example_occ_df) result <- maxent_run( species = "Abeillia_abeillei", env_grids = grids, occ_df = example_occ_df, output_dir = tempdir(), lon_col = "long", lat_col = "lat") result$evaluation$auc }if (requireNamespace("terra", quietly = TRUE)) { stack_path <- system.file("extdata", "stack_1_12_crop.rds", package = "maxentcpp") example_rasters <- terra::unwrap(readRDS(stack_path)) grids <- list( bio1 = maxent_grid_from_terra(example_rasters[[1]]), bio12 = maxent_grid_from_terra(example_rasters[[2]]) ) data(example_occ_df) result <- maxent_run( species = "Abeillia_abeillei", env_grids = grids, occ_df = example_occ_df, output_dir = tempdir(), lon_col = "long", lat_col = "lat") result$evaluation$auc }
Creates a sample point representing a species occurrence location.
maxent_sample(lon, lat, name = "", dim = NULL)maxent_sample(lon, lat, name = "", dim = NULL)
lon |
Longitude coordinate |
lat |
Latitude coordinate |
name |
Sample identifier/name |
dim |
Optional GridDimension object to calculate row/col indices |
Sample object (external pointer)
sample <- maxent_sample(lon = -118.5, lat = 36.5, name = "site1")sample <- maxent_sample(lon = -118.5, lat = 36.5, name = "site1")
Writes the trained model coefficients (lambdas) to a CSV file in the standard Maxent .lambdas format.
maxent_save_lambdas(featured_space, file)maxent_save_lambdas(featured_space, file)
featured_space |
External pointer to a trained FeaturedSpace object. |
file |
Character: path to the output file. |
Invisibly returns the output file path.
n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) maxent_fit(fs, max_iter = 100) maxent_save_lambdas(fs, tempfile(fileext = ".lambdas"))n <- 50L idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") fs <- maxent_featured_space(n, idx, feats) maxent_fit(fs, max_iter = 100) maxent_save_lambdas(fs, tempfile(fileext = ".lambdas"))
Runs the full density.Sequential optimizer ported from the
original Java Maxent 3.4.4 on a FeaturedSpace. Unlike
maxent_fit(), which uses the historical goodAlpha-only
loop, this trainer reproduces the real Java optimizer: feature
selection via deltaLossBound, Newton step with 1-D line search
(searchAlpha), every-10-iteration doParallelUpdate with
undo on loss-violating batch steps, and per-feature state tracking.
maxent_sequential_fit( featured_space, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001, parallel_update_frequency = 10L, disable_convergence_test = FALSE, trajectory_iterations = integer(0) )maxent_sequential_fit( featured_space, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001, parallel_update_frequency = 10L, disable_convergence_test = FALSE, trajectory_iterations = integer(0) )
featured_space |
External pointer to a FeaturedSpace object (from
|
max_iter |
Maximum number of iterations (default |
convergence |
Convergence threshold on the per-20-iteration loss
improvement (default |
beta_multiplier |
Regularization multiplier (default |
min_deviation |
Minimum sample-deviation floor used in
regularization (default |
parallel_update_frequency |
Iteration frequency at which
|
disable_convergence_test |
Logical: when |
trajectory_iterations |
Integer vector of 1-based iteration
indices at which to capture |
The lambda trajectory produced by this trainer matches the Java
oracle's to on
at every checkpoint, on both the symmetric and asymmetric fixtures in
maxentcppCompTest — see
docs/ARCHITECTURE_xtensor_openmp.md and the Phase C baseline
report for details.
Named list with:
Final regularized loss (scalar).
Shannon entropy of the trained distribution.
Number of training iterations completed.
Logical: whether the convergence threshold was
reached (always FALSE when
disable_convergence_test = TRUE).
Numeric vector of final lambda values.
A data.frame with one row per captured
checkpoint and columns iteration, loss, entropy,
lambda_0, lambda_1, ..., lambda_{J-1}.
maxent_fit, maxent_featured_space.
n <- 100L idx <- 90:99 env <- seq(0, 1, length.out = n) f <- maxent_linear_feature(env, "env1") fs <- maxent_featured_space(n, idx, list(f)) res <- maxent_sequential_fit( fs, max_iter = 500L, disable_convergence_test = TRUE, trajectory_iterations = c(1L, 2L, 5L, 10L, 50L, 100L, 500L)) print(res$trajectory)n <- 100L idx <- 90:99 env <- seq(0, 1, length.out = n) f <- maxent_linear_feature(env, "env1") fs <- maxent_featured_space(n, idx, list(f)) res <- maxent_sequential_fit( fs, max_iter = 500L, disable_convergence_test = TRUE, trajectory_iterations = c(1L, 2L, 5L, 10L, 50L, 100L, 500L)) print(res$trajectory)
Computes sample expectations and regularization deviations for each feature.
Called automatically by maxent_train(), but exposed for advanced use.
maxent_set_sample_expectations( fs_ptr, beta_multiplier = 1, min_deviation = 0.001 )maxent_set_sample_expectations( fs_ptr, beta_multiplier = 1, min_deviation = 0.001 )
fs_ptr |
External pointer to a FeaturedSpace object. |
beta_multiplier |
Regularization multiplier (default 1.0). |
min_deviation |
Minimum sample deviation (default 0.001). |
Called for side effects; returns invisibly.
Returns basic metadata about a FeaturedSpace object.
maxent_space_info(featured_space)maxent_space_info(featured_space)
featured_space |
External pointer to a FeaturedSpace object. |
Named list with: num_points, num_samples,
num_features, density_normalizer,
linear_predictor_normalizer.
Presence sites contribute (1 - pred)^2, absence sites contribute pred^2.
maxent_square_error(presence, absence)maxent_square_error(presence, absence)
presence |
Numeric vector of prediction scores at presence sites. |
absence |
Numeric vector of prediction scores at absence sites. |
Mean squared error.
maxent_square_error(c(1.0, 1.0), c(0.0, 0.0)) # 0.0maxent_square_error(c(1.0, 1.0), c(0.0, 0.0)) # 0.0
Creates a binary step feature: eval(i) = 1 if
values[i] > threshold, else 0.
maxent_threshold_feature(values, name, threshold)maxent_threshold_feature(values, name, threshold)
values |
Numeric vector of environmental variable values. |
name |
Character string: feature name/identifier. |
threshold |
The threshold value. |
External pointer to a ThresholdFeature C++ object.
vals <- c(1, 5, 10, 3) f <- maxent_threshold_feature(vals, "temperature_threshold", threshold = 5) maxent_feature_eval(f, 3) # values[3] = 10 > 5 -> 1vals <- c(1, 5, 10, 3) f <- maxent_threshold_feature(vals, "temperature_threshold", threshold = 5) maxent_feature_eval(f, 3) # values[3] = 10 > 5 -> 1
Runs the sequential coordinate-ascent MaxEnt optimization.
maxent_train( fs_ptr, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001 )maxent_train( fs_ptr, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001 )
fs_ptr |
External pointer to a FeaturedSpace object. |
max_iter |
Maximum number of training iterations (default 500). |
convergence |
Convergence threshold (default 1e-5). |
beta_multiplier |
Regularization multiplier (default 1.0). |
min_deviation |
Minimum sample deviation floor (default 0.001). |
Named list with elements: loss, entropy,
iterations, converged, lambdas.
High-level convenience wrapper that builds a streaming FeaturedSpace from
rast, maps occurrence locations to finite-stream sample indices, and
trains with maxent_fit.
maxent_train_terra( rast, occurrences, lon_col = "longitude", lat_col = "latitude", feature_types = c("linear", "quadratic", "product", "threshold", "hinge"), n_thresholds = 10L, n_hinges = 10L, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001 )maxent_train_terra( rast, occurrences, lon_col = "longitude", lat_col = "latitude", feature_types = c("linear", "quadratic", "product", "threshold", "hinge"), n_thresholds = 10L, n_hinges = 10L, max_iter = 500L, convergence = 1e-05, beta_multiplier = 1, min_deviation = 0.001 )
rast |
A |
occurrences |
Either a two-column matrix/data.frame (x,y) or a vector of 1-based raster cell indices. |
lon_col |
Longitude column name when |
lat_col |
Latitude column name when |
feature_types |
Feature type set passed to feature generation. |
n_thresholds |
Number of threshold knots. |
n_hinges |
Number of hinge knots. |
max_iter |
Maximum training iterations. |
convergence |
Convergence threshold. |
beta_multiplier |
Regularization multiplier. |
min_deviation |
Minimum deviation floor. |
A named list with training results plus model and
sample_indices.
Scans all valid cells in the grids to determine the [min, max] range of each environmental variable.
maxent_variable_ranges(env_grids)maxent_variable_ranges(env_grids)
env_grids |
List of external pointers to Grid<float> objects. |
A data.frame with columns: min, max (one row per variable).
Writes a GridFloat to a .asc file.
maxent_write_asc(grid, filename, scientific = TRUE)maxent_write_asc(grid, filename, scientific = TRUE)
grid |
External pointer to a GridFloat object. |
filename |
Character: output file path. |
scientific |
Logical: use scientific notation for floating-point
values (default |
Invisibly returns the output file path.
g <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 0.1, name = "bio1") maxent_write_asc(g, tempfile(fileext = ".asc"))g <- maxent_grid_from_matrix(matrix(runif(50), 5, 10), -120, 35, 0.1, name = "bio1") maxent_write_asc(g, tempfile(fileext = ".asc"))
Saves the trained model coefficients in CSV format compatible with the original Java Maxent .lambdas file format.
maxent_write_lambdas(fs_ptr, filename)maxent_write_lambdas(fs_ptr, filename)
fs_ptr |
External pointer to a trained FeaturedSpace object. |
filename |
Character: path to the output file. |
Called for side effects; returns invisibly.
Computes cumulative predictions at all background + presence locations and
derives nine standard threshold statistics, writing the result to
<output_dir>/<species>_omission.csv. The output format mirrors
density/Runner.java::writeCumulativeIndex().
maxent_write_omission_csv( model, env_grids, feature_names, presence_rows, presence_cols, output_dir, species, test_rows = NULL, test_cols = NULL )maxent_write_omission_csv( model, env_grids, feature_names, presence_rows, presence_cols, output_dir, species, test_rows = NULL, test_cols = NULL )
model |
External pointer to a trained FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
presence_rows |
Integer vector of presence row indices (0-based). |
presence_cols |
Integer vector of presence column indices (0-based). |
output_dir |
Character: directory for output files. |
species |
Character: species name (used in the filename). |
test_rows |
Integer vector of test row indices (0-based) or
|
test_cols |
Integer vector of test column indices (0-based) or
|
Invisibly returns the path to the written CSV file.
set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") pres_rows <- c(0L, 1L, 2L); pres_cols <- c(0L, 1L, 2L) maxent_write_omission_csv(model, list(g1, g2), c("bio1", "bio12"), pres_rows, pres_cols, output_dir = tempdir(), species = "Sp1")set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") pres_rows <- c(0L, 1L, 2L); pres_cols <- c(0L, 1L, 2L) maxent_write_omission_csv(model, list(g1, g2), c("bio1", "bio12"), pres_rows, pres_cols, output_dir = tempdir(), species = "Sp1")
Converts a GridFloat prediction grid to a colour PNG image using
the canonical Maxent colour ramp (red = high, blue = low). Optionally
overlays presence and test-point locations, and renders a small legend.
maxent_write_prediction_png( grid, filename, presence_rows = NULL, presence_cols = NULL, test_rows = NULL, test_cols = NULL, mode = "plain", legend = TRUE, width = 800L, height = 600L )maxent_write_prediction_png( grid, filename, presence_rows = NULL, presence_cols = NULL, test_rows = NULL, test_cols = NULL, mode = "plain", legend = TRUE, width = 800L, height = 600L )
grid |
External pointer to a GridFloat prediction grid (e.g.
from |
filename |
Character: path for the output PNG file. |
presence_rows |
Integer vector of presence row indices (0-based) or
|
presence_cols |
Integer vector of presence column indices (0-based) or
|
test_rows |
Integer vector of test-set row indices (0-based) or
|
test_cols |
Integer vector of test-set column indices (0-based) or
|
mode |
Colour mode passed to |
legend |
Logical: draw a colour-bar legend (default |
width |
Integer: PNG width in pixels (default 800). |
height |
Integer: PNG height in pixels (default 600). |
Invisibly returns filename.
set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") pred <- maxent_project_cloglog(model, list(g1, g2), c("bio1", "bio12")) maxent_write_prediction_png(pred, tempfile(fileext = ".png"))set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") pred <- maxent_project_cloglog(model, list(g1, g2), c("bio1", "bio12")) maxent_write_prediction_png(pred, tempfile(fileext = ".png"))
Computes model predictions at presence (and optionally test) locations and
writes <output_dir>/<species>_samplePredictions.csv.
maxent_write_sample_predictions( model, env_grids, feature_names, presence_rows, presence_cols, output_dir, species, test_rows = NULL, test_cols = NULL )maxent_write_sample_predictions( model, env_grids, feature_names, presence_rows, presence_cols, output_dir, species, test_rows = NULL, test_cols = NULL )
model |
External pointer to a trained FeaturedSpace object. |
env_grids |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
presence_rows |
Integer vector of presence row indices (0-based). |
presence_cols |
Integer vector of presence column indices (0-based). |
output_dir |
Character: directory for the output file. |
species |
Character: species name (used in the filename). |
test_rows |
Integer vector of test row indices (0-based) or
|
test_cols |
Integer vector of test column indices (0-based) or
|
Invisibly returns the path to the written CSV.
set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") pres_rows <- c(0L, 1L, 2L); pres_cols <- c(0L, 1L, 2L) maxent_write_sample_predictions(model, list(g1, g2), c("bio1", "bio12"), pres_rows, pres_cols, output_dir = tempdir(), species = "Sp1")set.seed(42) n <- 50L; idx <- c(5L, 15L, 25L, 35L, 45L) env <- list(bio1 = runif(n), bio12 = runif(n)) feats <- maxent_generate_features(env, types = "linear") model <- maxent_featured_space(n, idx, feats) maxent_fit(model, max_iter = 100) g1 <- maxent_grid_from_matrix(matrix(env$bio1, 5, 10), -120, 35, 1, name = "bio1") g2 <- maxent_grid_from_matrix(matrix(env$bio12, 5, 10), -120, 35, 1, name = "bio12") pres_rows <- c(0L, 1L, 2L); pres_cols <- c(0L, 1L, 2L) maxent_write_sample_predictions(model, list(g1, g2), c("bio1", "bio12"), pres_rows, pres_cols, output_dir = tempdir(), species = "Sp1")
Print Sample Information
## S3 method for class 'maxent_sample' print(x, ...)## S3 method for class 'maxent_sample' print(x, ...)
x |
Sample object |
... |
Additional arguments (ignored) |
Invisibly returns x.
Applies the Java Maxent cloglog formula: cloglog_java = 1 - exp(-exp(H) * raw_java)
project_cloglog(fs_ptr, grid_ptrs, feature_names)project_cloglog(fs_ptr, grid_ptrs, feature_names)
fs_ptr |
External pointer to a FeaturedSpace object. |
grid_ptrs |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
where H is the model entropy and raw_java is the normalised probability. This matches the cloglog output of Java Maxent and dismo.
External pointer to a Grid<float> with Java cloglog scores in [0, 1].
Applies the Java Maxent logistic formula: logistic_java = (exp(H) * raw_java) / (1 + exp(H) * raw_java)
project_logistic(fs_ptr, grid_ptrs, feature_names)project_logistic(fs_ptr, grid_ptrs, feature_names)
fs_ptr |
External pointer to a FeaturedSpace object. |
grid_ptrs |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
where H is the model entropy and raw_java is the normalised probability. This matches the logistic output of Java Maxent and dismo.
External pointer to a Grid<float> with Java logistic scores in [0, 1].
Applies a trained FeaturedSpace model to produce Java Maxent "raw" scores: raw_java = exp(lp - lpNorm) / densityNorm
project_raw(fs_ptr, grid_ptrs, feature_names)project_raw(fs_ptr, grid_ptrs, feature_names)
fs_ptr |
External pointer to a FeaturedSpace object. |
grid_ptrs |
List of external pointers to Grid<float> objects. |
feature_names |
Character vector of environment variable names. |
This matches the raw output of the Java Maxent software and the dismo R package.
External pointer to a Grid<float> with Java raw scores.
Get feature value from a sample
sample_get_feature(sample_ptr, feature_name, default_val = 0)sample_get_feature(sample_ptr, feature_name, default_val = 0)
sample_ptr |
External pointer to Sample |
feature_name |
Name of the feature |
default_val |
Default value if feature not found |
Feature value
Set feature value on a sample
sample_set_feature(sample_ptr, feature_name, value)sample_set_feature(sample_ptr, feature_name, value)
sample_ptr |
External pointer to Sample |
feature_name |
Name of the feature |
value |
Feature value |
Called for side effects; returns invisibly.