Ejemplo n.º 1
0
 def execute(self):
     """ Run the model by invoking run() on the workflow. """
     self.iter_count = 0
     # get initial values of design vars
     dvinit = [eval(translate_expr(a, self)) for a in self.design_vars]
     
     self.xmin = fmin_cobyla(self._driven_func, dvinit, self._consfuncts,
                             consargs=(),
                             rhobeg=self.rhobeg, rhoend=self.rhoend,
                             iprint=self.iprint, maxfun=self.maxiters)
Ejemplo n.º 2
0
    def test_simple(self):

        function = lambda x: x[0]**2 + abs(x[1])**3
        con1 = lambda x: x[0]**2 + x[1]**2 - 25
        con2 = lambda x: -con1(x)

        x = co.fmin_cobyla(function, [4.95,0.66], [con1, con2], rhobeg=1,
                           rhoend=1e-5, iprint=0, maxfun=100)
        x1 = 2.0/3
        x0 = math.sqrt(25-x1*x1)
        assert_almost_equal(x, [x0, x1], decimal=5)
Ejemplo n.º 3
0
    def execute(self):
        """ Run the model by invoking run() on the workflow. """
        self.iter_count = 0
        # get initial values of design vars
        dvinit = [eval(translate_expr(a, self)) for a in self.design_vars]

        self.xmin = fmin_cobyla(self._driven_func,
                                dvinit,
                                self._consfuncts,
                                consargs=(),
                                rhobeg=self.rhobeg,
                                rhoend=self.rhoend,
                                iprint=self.iprint,
                                maxfun=self.maxiters)
Ejemplo n.º 4
0
    def test_simple(self):

        function = lambda x: x[0]**2 + abs(x[1])**3
        con1 = lambda x: x[0]**2 + x[1]**2 - 25
        con2 = lambda x: -con1(x)

        x = co.fmin_cobyla(function, [4.95, 0.66], [con1, con2],
                           rhobeg=1,
                           rhoend=1e-5,
                           iprint=0,
                           maxfun=100)
        x1 = 2.0 / 3
        x0 = math.sqrt(25 - x1 * x1)
        assert_almost_equal(x, [x0, x1], decimal=5)
    f = open('run_history.txt','a')
    f.write('cw = {0}, cw length = {1}, cw beam length = {2}, sling length = {3}, range = {4}\n'.format(cw_dict['mass'],l2,l1,l4,r))
    f.close()
    '''
    Since scipy optimizers can only minimize, multiply by -1
    '''
    return -1.0*r

def positive_cw_mass(x):
    return x[cw_mass_index]
def positive_cw_beam_length(x):
    return x[cw_beam_length_index]
def positive_cw_length(x):
    return x[cw_length_index]
def positive_sling_length(x):
    return x[sling_length_index]

if __name__ == '__main__':
    if os.path.exists('./run_history.txt'):
        os.remove('run_history.txt')
    print co.fmin_cobyla(projectile_range,
                         x_init,
                         [positive_cw_mass,
                          positive_cw_beam_length,
                          positive_cw_length,
                          positive_sling_length],
                         rhobeg=0.1,
                         rhoend=0.001,
                         iprint=3,
                         maxfun=40)
Ejemplo n.º 6
0
def optimize(PS, figureOfMerit="mass_lbm", desVars=None, 
    findmin=1,  MaxLoop=500, printLevel=1):
    '''to find max, set findmin = 0'''
    
    PS.firstEvaluateIfReqd()
    
    global optFSys, _optLoopCount, _findmin, _constraintLoopCount
    optFSys = PS
    _optLoopCount = 0
    _constraintLoopCount = 0
    _findmin = findmin  # use global flag in objective function
        
    PS.figureOfMerit = figureOfMerit
    PS.optDesVars = []
    
    for dvStr in desVars:
        dv = PS.desVarDict[dvStr]
        if PS.hasFeasibleControlVar( dv.name ):
            print 'WARNING... %s is a feasible design variable\n   It can NOT be used as an optimization variable.'%dvStr
            pass
        else:
            PS.optDesVars.append( dvStr )
        
    #PS.summFile.write('\nPRIOR TO OPTIMIZATION\n')
    if _findmin:
        mLabel = 'MINIMIZE'
    else:
        mLabel = 'MAXIMIZE'
    if printLevel:
        saveOptVarSummary(PS, PS.optDesVars,'\nPRIOR TO %s OPTIMIZATION\n'%mLabel)
        
    
    ndv = len( PS.optDesVars )
    ncon = 0
   
    
    if ndv <= 0:
        print "ERROR... there are no legal design variables for optimization"
        return
 
    xlow=[]
    xhigh=[]
    xinit = []
    
    # get limits of design variables
    i = 0
    for dvStr in PS.optDesVars:
        dv = PS.desVarDict[dvStr]
        xlow.append( dv.minVal / dv.scaleFactor )
        xhigh.append( dv.maxVal / dv.scaleFactor )
        xinit.append( PS.getDesignVar( dvStr) / dv.scaleFactor )
        i += 1
        
    # count any result variables that might be constraints
    PS.constraintList[:] = []
    for key,rv in PS.resultVarDict.items():
        # only handle inequality constraints, equality constraints handled by feasibility variables
        if rv.hasLowConstraint() :  
            PS.constraintList.append( ['>',key] )
            ncon += 1
        if rv.hasHighConstraint():  
            PS.constraintList.append( ['<',key] )
            ncon += 1

    #xOut = mdot.findminormax(findmin,ndv,ncon,MaxLoop, xlow,xhigh,xinit,objAndConstraints)
    
    # set up constraint calling functions
    cons = []
    
    # first do bounds on x array
    def makeLo(n):
        return lambda x: x[n] - xlow[n]
    def makeHi(n):
        return lambda x: xhigh[n] - x[n]
    for n in range( len(xlow) ):
        conLo = makeLo(n)
        conHi = makeHi(n)
        cons.append( conLo )
        cons.append( conHi )
    
    # then do any constraints on result variables
    def makeCon(n):
        return lambda x: constraintFunc(x, n)
    for n in range( len(PS.constraintList) ):
        con = makeCon(n)
        cons.append( con )
    
    
    # rhobeg can be 1.0 because x values are scaled.
    
    xOut = fmin_cobyla(objFunction, xinit, cons, rhobeg=1.0, rhoend=1e-6,
            iprint=cast.intDammit(printLevel), maxfun=MaxLoop)

    if printLevel:
        print
        print "   ==> OPTIMIZATION (Loops = %i)"%_optLoopCount, "(Max = %g)"%MaxLoop,
        print " (%i constraint loops)\n"%_constraintLoopCount
    
    for i in range( len(PS.optDesVars) ):
        dvStr = PS.optDesVars[i]
        dv = PS.desVarDict[ dvStr ]
        
        dvVal = xOut[i] * dv.scaleFactor
        if printLevel:
            print 'optimum',dvStr,'=',dvVal
        #PS.summFile.write( '\noptimum %10s = %g'%(dvStr, dvVal) )
    if printLevel:
        print '\nscaled desVars',PS.optDesVars,'=',xOut[:ndv]
        
        print 'gives',figureOfMerit,'=',PS.getResultVar(figureOfMerit),'\n'
    
    #PS.summFile.write('\n\ngives '+ str(figureOfMerit)+\
    #    ' = '+ str(PS.getResultVar(figureOfMerit))+'\n')
    
        
    for i in range(ndv):
        dvStr = PS.optDesVars[i]
        dv = PS.desVarDict[ dvStr ]
        dvVal = xOut[i] * dv.scaleFactor
        PS.setDesignVar( dvStr, dvVal)
    PS.evaluate()
        
    #PS.summFile.write('\nAFTER OPTIMIZATION\n')
    if printLevel:
        saveOptVarSummary(PS, PS.optDesVars,'\nAFTER %s OPTIMIZATION\n'%mLabel)
Ejemplo n.º 7
0
def optimize(PS,
             figureOfMerit="mass_lbm",
             desVars=None,
             findmin=1,
             MaxLoop=500,
             printLevel=1):
    '''to find max, set findmin = 0'''

    PS.firstEvaluateIfReqd()

    global optFSys, _optLoopCount, _findmin, _constraintLoopCount
    optFSys = PS
    _optLoopCount = 0
    _constraintLoopCount = 0
    _findmin = findmin  # use global flag in objective function

    PS.figureOfMerit = figureOfMerit
    PS.optDesVars = []

    for dvStr in desVars:
        dv = PS.desVarDict[dvStr]
        if PS.hasFeasibleControlVar(dv.name):
            print 'WARNING... %s is a feasible design variable\n   It can NOT be used as an optimization variable.' % dvStr
            pass
        else:
            PS.optDesVars.append(dvStr)

    #PS.summFile.write('\nPRIOR TO OPTIMIZATION\n')
    if _findmin:
        mLabel = 'MINIMIZE'
    else:
        mLabel = 'MAXIMIZE'
    if printLevel:
        saveOptVarSummary(PS, PS.optDesVars,
                          '\nPRIOR TO %s OPTIMIZATION\n' % mLabel)

    ndv = len(PS.optDesVars)
    ncon = 0

    if ndv <= 0:
        print "ERROR... there are no legal design variables for optimization"
        return

    xlow = []
    xhigh = []
    xinit = []

    # get limits of design variables
    i = 0
    for dvStr in PS.optDesVars:
        dv = PS.desVarDict[dvStr]
        xlow.append(dv.minVal / dv.scaleFactor)
        xhigh.append(dv.maxVal / dv.scaleFactor)
        xinit.append(PS.getDesignVar(dvStr) / dv.scaleFactor)
        i += 1

    # count any result variables that might be constraints
    PS.constraintList[:] = []
    for key, rv in PS.resultVarDict.items():
        # only handle inequality constraints, equality constraints handled by feasibility variables
        if rv.hasLowConstraint():
            PS.constraintList.append(['>', key])
            ncon += 1
        if rv.hasHighConstraint():
            PS.constraintList.append(['<', key])
            ncon += 1

    #xOut = mdot.findminormax(findmin,ndv,ncon,MaxLoop, xlow,xhigh,xinit,objAndConstraints)

    # set up constraint calling functions
    cons = []

    # first do bounds on x array
    def makeLo(n):
        return lambda x: x[n] - xlow[n]

    def makeHi(n):
        return lambda x: xhigh[n] - x[n]

    for n in range(len(xlow)):
        conLo = makeLo(n)
        conHi = makeHi(n)
        cons.append(conLo)
        cons.append(conHi)

    # then do any constraints on result variables
    def makeCon(n):
        return lambda x: constraintFunc(x, n)

    for n in range(len(PS.constraintList)):
        con = makeCon(n)
        cons.append(con)

    # rhobeg can be 1.0 because x values are scaled.

    xOut = fmin_cobyla(objFunction,
                       xinit,
                       cons,
                       rhobeg=1.0,
                       rhoend=1e-6,
                       iprint=cast.intDammit(printLevel),
                       maxfun=MaxLoop)

    if printLevel:
        print
        print "   ==> OPTIMIZATION (Loops = %i)" % _optLoopCount, "(Max = %g)" % MaxLoop,
        print " (%i constraint loops)\n" % _constraintLoopCount

    for i in range(len(PS.optDesVars)):
        dvStr = PS.optDesVars[i]
        dv = PS.desVarDict[dvStr]

        dvVal = xOut[i] * dv.scaleFactor
        if printLevel:
            print 'optimum', dvStr, '=', dvVal
        #PS.summFile.write( '\noptimum %10s = %g'%(dvStr, dvVal) )
    if printLevel:
        print '\nscaled desVars', PS.optDesVars, '=', xOut[:ndv]

        print 'gives', figureOfMerit, '=', PS.getResultVar(figureOfMerit), '\n'

    #PS.summFile.write('\n\ngives '+ str(figureOfMerit)+\
    #    ' = '+ str(PS.getResultVar(figureOfMerit))+'\n')

    for i in range(ndv):
        dvStr = PS.optDesVars[i]
        dv = PS.desVarDict[dvStr]
        dvVal = xOut[i] * dv.scaleFactor
        PS.setDesignVar(dvStr, dvVal)
    PS.evaluate()

    #PS.summFile.write('\nAFTER OPTIMIZATION\n')
    if printLevel:
        saveOptVarSummary(PS, PS.optDesVars,
                          '\nAFTER %s OPTIMIZATION\n' % mLabel)
Ejemplo n.º 8
0
def optimize_sizes_cobyla(size_bins):
    likelihood_func = likelihood(size_bins)
    initial_guess = array(initial_x(size_bins))
    constraints = get_constraints(size_bins)
    return fmin_cobyla(likelihood_func, initial_guess, constraints, rhobeg=0.1, rhoend=0.01)
Ejemplo n.º 9
0

def positive_cw_mass(x):
    return x[cw_mass_index]


def positive_cw_beam_length(x):
    return x[cw_beam_length_index]


def positive_cw_length(x):
    return x[cw_length_index]


def positive_sling_length(x):
    return x[sling_length_index]


if __name__ == '__main__':
    if os.path.exists('./run_history.txt'):
        os.remove('run_history.txt')
    print co.fmin_cobyla(projectile_range,
                         x_init, [
                             positive_cw_mass, positive_cw_beam_length,
                             positive_cw_length, positive_sling_length
                         ],
                         rhobeg=0.1,
                         rhoend=0.001,
                         iprint=3,
                         maxfun=40)