I'm using python to load a DLL generated in c++ (working correctly) using the cdll.LoadLibrary(). The issue is that I'm needing to reload the DLL inside the class every time the class is called, otherwise it gives a different behavior.
When I reload the dll inside the class the code evaluate the fitness function for about 4192 times (262 iterations), but when I remove the two lines that reloads the dll, the code runs just 16 times (one iteration), stopping before convergence.
This is my code:
import sys
import os
import pygmo as pg
from ctypes import *
pathname = os.path.dirname(sys.argv[0])
dllPath = os.path.join((os.path.abspath(pathname)), 'optmization_functions.dll')
mydll = cdll.LoadLibrary(dllPath)
mydll.rosen.restype = c_double
class RosenbrockDLL():
def __init__(self, n):
"""Pass dimensions to constructor."""
self.n = n
def fitness(self, x):
"""
The Rosenbrock function.
sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
"""
mydll = cdll.LoadLibrary(dllPath)
mydll.rosen.restype = c_double
x2 = (c_double * self.n)(*x)
r = mydll.rosen(c_int(self.n), x2)
return [r]
def get_bounds(self):
return ([-5]*self.n,[10]*self.n)
def pygmo_methods(func=RosenbrockDLL, N_vars=4, N_pop=16, N_gers=1000):
prob = pg.problem(func(n = N_vars))
algo = pg.algorithm(pg.de1220(gen = N_gers))
algo.set_verbosity(0)
archi = pg.archipelago(1, algo=algo, prob=prob, pop_size=N_pop)
archi.evolve(1)
archi.wait()
bestFevals = archi[0].get_population().problem.get_fevals()
print('\tFunction value:', *archi.get_champions_f())
print('\tDesign values:', *archi.get_champions_x())
print('\tFunction evaluations:', bestFevals)
print('\tNumber of generations:', bestFevals//N_pop)
if __name__ == "__main__":
N = 4
pygmo_methods(func=RosenbrockDLL, N_vars=N, N_pop=16, N_gers=1000)
Right now the code is reloading the dll every time the fitness is called, what increases the elapsed time. I would like to load it just once.