0

I have hydrology model which I built using excel and I want add the parameter optimization using Particle Swarm Optimization algorithm using Python. The idea of the code is to extract the value of parameters (there are 11 parameters) and objective function (here I am using NS where 1 is the optimum value and - inf is the lower bound) put it into the PSO algorithm and the optimize parameters will be send back into the excel again, and the code will check if the objective function is reached, if not then the process will repeat.

The problem is, I am not sure about how the PSO works especially the terms of best score/Gbest. The code is working but the results converge to the minimum objective function instead of the maximum (1). Below is my code.

import xlwings as xw
import numpy as np
import pyswarms as ps

#connect to excel
wb = xw.Book ('model.xlsx')
sheet = wb.sheet ('sheet1')
#define parameter cells and ranges
PARAM_CELLS = ["D33",'D34','D35', 'D36', 'D37','D38','D39','D40','D41','D42','D43']  # 11 parameters

#update excel parameters, runs the model, and return the objective function
def evaluate model (params):
    if params.ndim == 2:
        params = params.flatten()
    
    for i, cell in enumerate(PARAM_CELLS):
        sheet.range(cell).value = params[i]
    # Recalculate Excel
    wb.app.calculate()
    # Read simulated streamflow
    # simulated = np.array(sheet.range(SIM_STREAMFLOW_RANGE).value)
    
    # NSE
    nse = sheet.range('J37').value
    return nse

# Parameter bounds (min/max values)
bounds = (
    [100, 50, 0.1, 0, 0.05, 0.0005, 0, 1, 45, 1, 45],  # Min for 11 parameters
    [400, 100, 5, 1, 0.8, 0.1, 3, 6, 55, 5, 55]   # Max for 11 parameters
)
# Configure PSO
max_iterations = 500  # Total number of iterations
swarm = 1000
optimizer = ps.single.GlobalBestPSO(
    n_particles=swarm,
    dimensions=11,
    bounds=bounds,
    options={"c1": 1.5, "c2": 1.5, "w": 0.9}
)

# Run optimization
best_params, best_score = optimizer.optimize(evaluate_model, iters=max_iterations)

I have read some article mentioned that instead of nse, i have should use 1-nse since PSO will looking into the minimum number (0). But when I tried that, the optimize parameter still converge to the minimum value.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.