0

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.

DGIorio
  • 11
  • 3
  • What means "wrong result"? Have you tried with a simpler C++ function which e.g. just returns x[0]? Or your function with a very simple x? – Michael Butscher Oct 30 '19 at 18:57
  • Are you sure that "self.n" is always the right size for the given "x" parameter in the "fitness" call? – Michael Butscher Oct 30 '19 at 19:00
  • The result is right, but the code behaves different when the dll is reload inside the class. I'm running an optimization problem and when I run it with the dll being reloaded the fitness is executed for about 6000 times, but when I comment the two lines that reload the dll, the function is executed just 16 times (one iteration).I will fix my question – DGIorio Oct 30 '19 at 19:22

0 Answers0