Optimize a ModelΒΆ

This example shows how to optimize model parameters to match a chosen statistic from a reference inventory using PYBOBYQA.

import numpy as np
from spatiocoexistence import Model, Inventory
from spatiocoexistence.data import inventory_file, parameter_file

Initialize the model, the initial inventory is used as reference.

reference_inv = Inventory.from_data(inventory_file)
model = Model(
    initial_inventory=reference_inv,
    parameters=parameter_file,
    threads=4,
)

stat_funcs = [
    (Inventory.get_CI_HS_distribution, Inventory.CI_HS),
]
print(type(stat_funcs))
result = model.optimize_parameters(
    start_params=np.array([0.26]),
    lower=np.array([0.25]),
    upper=np.array([0.27]),
    rhobeg=0.01,
    rhoend=0.001,
    param_names=["mean_reproduction"],
    methods_to_evaluate=stat_funcs,
    stat_indices=[slice(0, 20)],
    n_init=100,
    n_iter=15,
    maxfun=100,
)

print(result)
<class 'list'>
****** Py-BOBYQA Results ******
Solution xmin = [0.25828286]
Objective value f(xmin) = 372.5907966
Needed 100 objective evaluations (at 100 points)
Did a total of 23 runs
Approximate gradient = [-226059.57678459]
Approximate Hessian = [[55041555.63219696]]
Exit flag = 1
Warning (max evals): Objective has been called MAXFUN times
******************************

Total running time of the script: (13 minutes 30.182 seconds)