########################### GATEWAY HEADER ############################# # # _| _| _|_|_| _|_|_| _|_| _|_|_| _|_| # _|_| _|_| _| _| _| _| _| _| _| _| # _| _| _| _| _| _| _|_|_|_| _| _| _| # _| _| _| _| _| _| _| _| _| _| # _| _| _|_|_| _|_|_| _| _| _|_|_| _|_| # # Version 7 # ######################################################################## # # See the MIDACO user manual for detailed information # ######################################################################## # # PYTHON GATEWAY to the MIDACO library (midacopy.so / midacopy.dll) # # Call: solution = midaco.run( problem, option, key ) # # Return: solution['f'], ['g'], ['x'], ['iflag'] and, for o > 1, # solution['psize'] (number of pareto points) and # solution['paretofront'] (the pareto front array) # # option['paradigm'] (optional) selects how the points of a block # are evaluated, if option['parallel'] > 1: # # 0 = multiprocessing problem_function(x) on P processes # 1 = mpi4py problem_function(x) on MPI processes, # start with: mpirun -n 4 python example.py # 2 = vectorized F, G = problem_function(X) gets all P # points at once, X is a numpy array P x n # (one row per point), F is P x o, G is P x m # ######################################################################## import ctypes; from ctypes import * import os import os.path import numpy as np ######################################################################## def run( problem, option, key ): problem_function = problem['@'] o =problem['o'] n =problem['n'] ni=problem['ni'] m =problem['m'] me=problem['me'] xl=problem['xl'] xu=problem['xu'] x =problem['x'] # Input check; +-Inf bounds are rescaled to +-1.0E+6 xl, xu, x = _check_problem(o, n, m, xl, xu, x) maxeval=option['maxeval'] maxtime=option['maxtime'] printeval=option['printeval'] save2file=option['save2file'] resumable=option.get('resumable',0) param=[0.0]*15 param[ 0] = option['param1'] param[ 1] = option['param2'] param[ 2] = option['param3'] param[ 3] = option['param4'] param[ 4] = option['param5'] param[ 5] = option['param6'] param[ 6] = option['param7'] param[ 7] = option['param8'] param[ 8] = option['param9'] param[ 9] = option['param10'] param[10] = option['param11'] param[11] = option['param12'] param[12] = option['param13'] param[13] = option.get('param14',0.0) # SURROGATE param[14] = option.get('param15',0.0) # PMISQP PARALLEL = option['parallel'] if PARALLEL <= 1 : p = 1 if PARALLEL > 1 : p = PARALLEL # Parallelization paradigm: 0 = multiprocessing, 1 = mpi4py, 2 = vectorized paradigm = option.get('paradigm',0) if paradigm not in (0,1,2): raise ValueError("option['paradigm'] must be 0 (multiprocessing), " "1 (mpi4py) or 2 (vectorized), not %r" % (paradigm,)) ######################################################################## # paradigm 1 (mpi4py): midaco.run() is called on ALL MPI processes. # Only process 0 runs MIDACO below, all others only evaluate points # here and return the solution that process 0 hands out at the end. ######################################################################## comm = None if paradigm == 1: try: from mpi4py import MPI except ImportError: raise ImportError("paradigm = 1 requires mpi4py (pip install mpi4py)") comm = MPI.COMM_WORLD if comm.Get_rank() != 0: _mpi_worker(comm, problem_function, o, m) return comm.bcast(None, root=0) ######################################################################## ######################################################################## ######################################################################## ####################### IMPORT MIDACO LIBRARY ########################## ######################################################################## ######################################################################## ######################################################################## # Specify name of the MIDACO library depending on OS if (os.name == "posix"): lib_name = "midacopy.so" # Linux//Mac/Cygwin else: lib_name = "midacopy.dll" # Windows # Specify path were the MIDACO library is expected lib_path=os.path.dirname(os.path.abspath(__file__))+os.path.sep+lib_name # Assign CLIB as name for MIDACO library CLIB = ctypes.CDLL(lib_path) ######################################################################## ######################### CALL MIDACO SOLVER ########################### ######################################################################## # The key may be given as str or bytes if isinstance(key, str): key = key.encode('ascii', 'replace') key_ = c_char_p(key) # Create c-types arguments and initialize workspace and flags n_ = pointer(c_int(n)); n__ = c_int(n); xl_ = (c_double * n)() ni_ = pointer(c_int(ni)); ni__ = c_int(ni); xu_ = (c_double * n)() m_ = pointer(c_int(m)); m__ = c_int(m); x_ = (c_double * n)() me_ = pointer(c_int(me)); me___ = c_int(me); param_ = (c_double *15)() o_ = pointer(c_int(o)); o__ = c_int(o); printeval_ = c_int(printeval); iflag_ = pointer(c_int(0)) save2file_ = c_int(save2file); istop_ = pointer(c_int(0)) resumable_ = c_int(resumable) # MIDACO's integers are 4-byte 'int': larger values are clipped maxeval_ = c_int(min(maxeval,2147483647)); p__= c_int(p); maxtime_ = c_int(min(maxtime,2147483647)); p_ = pointer(c_int(p)) maxevalp_ = pointer(c_int(min(maxeval,2147483647))) # Workspace lengths are given by midaco_ws() lrw_ = pointer(c_int(0)) liw_ = pointer(c_int(0)) CLIB.midaco_ws(p_,o_,n_,ni_,m_,lrw_,liw_) if lrw_[0] <= 0 or liw_[0] <= 0: raise ValueError('MIDACO cannot split parallel = %d' % p) rw_ = (c_double * lrw_[0])(0.0) iw_ = (c_int * liw_[0])(0) lrw__ = c_int(lrw_[0]); liw__ = c_int(liw_[0]) if( o == 1 ): lpf_ = pointer(c_int(1)) if( o > 1 ): lpf_ = pointer(c_int(1000*(o+m+n)+1+100)) if( param[9] >= 1.0 ): lpf_ = pointer(c_int( int(param[9]) * (o+m+n) + 1)) if( param[9] <=-1.0 ): lpf_ = pointer(c_int( -int(param[9]) * (o+m+n) + 1)) pf_ = (c_double * lpf_[0])(0.0) for i in range(0,15): param_[i] = c_double(param[i]) for i in range(0, n): xl_[i] = c_double(xl[i]) for i in range(0, n): xu_[i] = c_double(xu[i]) for i in range(0, n): x_[i] = c_double( x[i]) f_ = (c_double * o)() if ( m > 0): g_ = (c_double * m)() if ( m ==0): g_ = (c_double * 1)() # Dummy for unconstrained problems ######################################################################## if p <= 1 and paradigm == 0 : ######################################################################## ######################################################################## ######################################################################## # Print MIDACO Head information CLIB.midaco_print(1,printeval_,save2file_,resumable_,iflag_,istop_,f_,g_,x_,\ xl_,xu_,o__,n__,ni__,m__,me___,rw_,lrw__,iw_,liw__,pf_,maxeval_,maxtime_,\ param_,p__,key_) ######################################################################## while istop_[0] == 0: # Call MIDACO by reverse communication loop [ fx, gx ] = problem_function(x_[:]) # Evaluate F(X) and G(X) f_[:] = _as_vector(fx, o, 'f', 'o') if( m > 0 ): g_[:] = _as_vector(gx, m, 'g', 'm') # m = 0: g_ is a 1-entry dummy # Check and repair NaN for i in range(0,o): if np.isnan(f_[i]) : f_[i] = 1.0e+33 for i in range(0,m): if np.isnan(g_[i]) : g_[i] = -1.0e+33 # Check and repair Inf for i in range(0,o): if np.isinf(f_[i]) : f_[i] = 1.0e+32 for i in range(0,m): if np.isinf(g_[i]) : g_[i] = -1.0e+32 CLIB.midaco(p_,o_,n_,ni_,m_,me_,x_,f_,g_,xl_,xu_, \ iflag_,istop_,param_,rw_,lrw_,iw_,liw_,pf_,lpf_, \ maxevalp_,key_) CLIB.midaco_print(2,printeval_,save2file_,resumable_,iflag_,istop_, \ f_,g_,x_,xl_,xu_,o__,n__,ni__,m__,me___,rw_,lrw__,iw_,liw__,pf_, \ maxeval_,maxtime_,param_,p__,key_) if istop_[0] != 0: break ######################################################################## ######################################################################## ######################################################################## if p > 1 or paradigm != 0 : ######################################################################## ######################################################################## ######################################################################## # Create parallel arrays for f,g and x (P points, one after another) po = p*o; fff_ = (c_double * po)() pm = p*m; ggg_ = (c_double * max(pm,1))() # m = 0: 1-entry dummy pn = p*n; xxx_ = (c_double * pn)() # # Copy starting point X into all P entries of the XXX array. The # MIDACO printer (head call below) spreads the entries 2,...,P. # for c in range(0,p): for i in range(0, n): xxx_[c*n+i] = c_double(x[i]) # Start the parallel pool (paradigm 0 only) pool = None if paradigm == 0: from multiprocessing import Pool pool = Pool(processes=p) try: ###################################################################### # Print MIDACO Head information # The head call gets the P*n array: a resume (resumable mode) loads all P # pending points into it. CLIB.midaco_print(1,printeval_,save2file_,resumable_,iflag_,istop_,fff_,ggg_,\ xxx_,xl_,xu_,o__,n__,ni__,m__,me___,rw_,lrw__,iw_,liw__,pf_,maxeval_,\ maxtime_,param_,p__,key_) ###################################################################### while istop_[0] == 0: # Call MIDACO by reverse communication loop # Evaluate the P points of the block: F is P x o, G is P x m if paradigm == 0: A = [None]*p for c in range(0,p): A[c] = xxx_[c*n:(c+1)*n] B = pool.map( problem_function, A ) F, G = _stack_results(B, p, o, m) if paradigm == 1: A = [None]*p for c in range(0,p): A[c] = xxx_[c*n:(c+1)*n] B = _mpi_evaluate(comm, problem_function, A) F, G = _stack_results(B, p, o, m) if paradigm == 2: X = np.array(xxx_[:], dtype=float).reshape(p,n) F, G = _check_vectorized(problem_function(X), p, o, m) # Check and repair NaN and Inf F[np.isnan(F)] = 1.0e+33 G[np.isnan(G)] = -1.0e+33 F[np.isinf(F)] = 1.0e+32 G[np.isinf(G)] = -1.0e+32 # Store F and G in the parallel arrays fff_[0:po] = F.reshape(po).tolist() if( m > 0 ): ggg_[0:pm] = G.reshape(pm).tolist() CLIB.midaco(p_,o_,n_,ni_,m_,me_,xxx_,fff_,ggg_,xl_,xu_, \ iflag_,istop_,param_,rw_,lrw_,iw_,liw_,pf_,lpf_, \ maxevalp_,key_) CLIB.midaco_print(2,printeval_,save2file_,resumable_,iflag_,istop_, \ fff_,ggg_,xxx_,xl_,xu_,o__,n__,ni__,m__,me___,rw_,lrw__,iw_,liw__,pf_, \ maxeval_,maxtime_,param_,p__,key_) if istop_[0] != 0: break except BaseException: if pool is not None: pool.terminate(); pool.join(); pool = None if comm is not None: _mpi_abort(comm) raise finally: if pool is not None: pool.close(); pool.join() ######################################################################## ######################################################################## ######################################################################## # Get solution x out of xxx for i in range(0,o): f_[i] = fff_[i] for i in range(0,m): g_[i] = ggg_[i] for i in range(0,n): x_[i] = xxx_[i] # paradigm 1: tell the other MPI processes to stop if comm is not None: comm.scatter([None]*comm.Get_size(), root=0) ######################################################################## #################### RETURN ARGUMENTS = SOLUTION ####################### ######################################################################## f = [0.0]*o g = [0.0]*m x = [0.0]*n for i in range(0,o): f[i] = f_[i] for i in range(0,m): g[i] = g_[i] for i in range(0,n): x[i] = x_[i] solution = {} solution['f'] = f solution['g'] = g solution['x'] = x solution['iflag'] = iflag_[0] solution['psize'] = int(pf_[0]) # Number of pareto points in paretofront solution['paretofront'] = pf_[:] # The pareto front array # paradigm 1: all MPI processes return the same solution if comm is not None: comm.bcast(solution, root=0) return solution ######################################################################## ###################### HELPERS FOR THE PARALLEL MODES ################## ######################################################################## def _check_problem( o, n, m, xl, xu, x ): # Sizes first: o, n >= 1 and m >= 0 are needed before MIDACO can even be # called (ni/me and the bounds themselves are checked by MIDACO, IFLAG) for name, v, lo in (('o',o,1), ('n',n,1), ('m',m,0)): if isinstance(v, bool) or not isinstance(v, (int, np.integer)) or v < lo: raise ValueError("problem['%s'] must be an integer >= %d, not %r" % (name, lo, v)) out = [] for name, v in (('xl',xl), ('xu',xu), ('x',x)): try: v = [float(t) for t in np.asarray(v, dtype=float).reshape(-1)] except (TypeError, ValueError): raise ValueError("problem['%s'] must be a list of %d numbers" % (name, n)) if len(v) != n: raise ValueError("problem['%s'] has %d entries, but n = %d" % (name, len(v), n)) out.append(v) xl, xu, x = out # Re-scale Infinity values: MIDACO needs finite bounds marker = 0 for i in range(0,n): if np.isinf(xl[i]): xl[i] = -1.0e+6; marker = 1 if np.isinf(xu[i]): xu[i] = 1.0e+6; marker = 1 if np.isinf(x[i]): x[i] = xl[i]; marker = 1 if marker == 1: print("\n NOTE: Infinity Values have been rescaled to 1.0E+6 \n") return xl, xu, x def _as_vector( v, k, name, kname ): # f / g as returned by the problem function -> k floats (a plain number # is accepted for k = 1) try: a = np.asarray(v, dtype=float).reshape(-1) except (TypeError, ValueError): raise ValueError("problem function: %s must be a list of %d numbers" % (name, k)) if a.size != k: raise ValueError("problem function returned %d value(s) for %s, " "but %s = %d" % (a.size, name, kname, k)) return a.tolist() def _stack_results( B, p, o, m ): # B[c] = (f,g) of point c, as returned by problem_function(x) F = np.empty((p,o)); G = np.empty((p,m)) for c in range(0,p): F[c,:] = _as_vector(B[c][0], o, 'f', 'o') if( m > 0 ): G[c,:] = _as_vector(B[c][1], m, 'g', 'm') return F, G def _check_vectorized( result, p, o, m ): # paradigm 2: F, G = problem_function(X) with X of shape (P,n). # F must have shape (P,o) and G shape (P,m), one row per point. # For o = 1 (m = 1) a 1D array of length P is accepted as well. try: F, G = result except (TypeError, ValueError): raise ValueError("paradigm = 2 (vectorized): problem function must " "return two values F, G") F = np.asarray(F, dtype=float) if F.ndim == 1 and o == 1 and F.size == p: F = F.reshape(p,1) if F.ndim == 1 and p == 1 and F.size == o: F = F.reshape(1,o) if F.shape != (p,o): raise ValueError("paradigm = 2 (vectorized): F must have shape (P,o) = " "(%d,%d), but has shape %s" % (p,o,F.shape)) if m == 0: if G is not None and np.asarray(G).size != 0: raise ValueError("paradigm = 2 (vectorized): m = 0, but G is not empty") return F, np.empty((p,0)) G = np.asarray(G, dtype=float) if G.ndim == 1 and m == 1 and G.size == p: G = G.reshape(p,1) if G.ndim == 1 and p == 1 and G.size == m: G = G.reshape(1,m) if G.shape != (p,m): raise ValueError("paradigm = 2 (vectorized): G must have shape (P,m) = " "(%d,%d), but has shape %s" % (p,m,G.shape)) return F, G def _mpi_abort( comm ): # An error on one MPI process would leave the others waiting forever import sys, traceback traceback.print_exc(); sys.stdout.flush(); sys.stderr.flush() comm.Abort(1) def _mpi_evaluate( comm, problem_function, A ): # MPI process 0: hand out the points by stride (process r gets the # points r, r+size, r+2*size,...), evaluate own points, collect all. size = comm.Get_size(); p = len(A) mine = comm.scatter([A[r::size] for r in range(0,size)], root=0) R = comm.gather([problem_function(x) for x in mine], root=0) B = [None]*p for r in range(0,size): B[r::size] = R[r] return B def _mpi_worker( comm, problem_function, o, m ): # MPI processes 1,2,...: evaluate points until the stop signal (None) while True: mine = comm.scatter(None, root=0) if mine is None: break try: B = [problem_function(x) for x in mine] except BaseException: _mpi_abort(comm) comm.gather(B, root=0) ######################################################################## ############################ END OF FILE ############################### #######################################################################