Esempio n. 1
0
## example10_4
from powell import *
from numarray import array
from math import sqrt

def F(x):
    lam = 1.0                  # Penalty multiplier
    c = x[0]*x[1] - 5.0            # Constraint equation
    return  distSq(x) + lam*c**2   # Penalized merit function

def distSq(x): return (x[0] - 5)**2 + (x[1] - 8)**2
    
xStart = array([1.0,5.0])
x,numIter = powell(F,xStart,0.01)
print "Intersection point =",x
print "Minimum distance =", sqrt(distSq(x))
print "xy =", x[0]*x[1]
print "Number of cycles =",numIter
raw_input ("Press return to exit")
Esempio n. 2
0
def powellConstr(F,
                 x0in,
                 constrains=[],
                 deltas=[],
                 thetas=[],
                 cMin=0.01,
                 iterations=100,
                 m2=10,
                 m1=0.25,
                 bracketStep=0.001,
                 goldenSearchWindow=0.001,
                 epsilon=1.0e-6,
                 bracketing=True,
                 epsilonGoldenSearch=1.0e-6):
    x0 = deepcopy(x0in)
    x0list = []
    locThetas = []
    locDeltas = []
    c0 = 1e6
    cOutList = []
    stopValueList = []
    stopNormList = []
    nIterList = []

    for theta in thetas:
        locThetas.append(theta)

    for delta in deltas:
        locDeltas.append(delta)

    def H(sum):
        if sum > 0:
            return 1
        if sum <= 0:
            return 0

    #--------------------------------------------------------------------------------#
    # TUTAJ BEZ OGRANICZEN POLICZY
    if len(constrains) == 0:
        #print("Nie ma ograniczen!")
        x0, nIter, success, stopValue, stopNorm = powell(
            F,
            x0,
            epsilon=epsilon,
            iterations=iterations,
            bracketing=bracketing,
            bracketStep=bracketStep,
            goldenSearchWindow=goldenSearchWindow,
            epsilonGoldenSearch=epsilonGoldenSearch)
        if not success:
            return False, x0list, stopValue, stopNorm, nIter, cOutList
        #print("Pkt minimum:", x0)
        #print("F(x):", F(x0))
        x0list.append(x0)
        cOutList.append(0)
        stopValueList.append(stopValue)
        stopNormList.append(stopNorm)
        nIterList.append(nIter)
        return True, x0list, stopValueList, stopNormList, nIterList, cOutList

    #--------------------------------------------------------------------------------#
    # WPROWADZANIE OGRANICZEN
    c = 0
    sixStep = False

    for k in range(iterations):  # Allow for 100 cycles as default:
        #print("_"*80)
        #print("Step: ", k)
        #print("Deltas:", locDeltas)
        #print("Thetas:", locThetas)
        #print("X0:", x0)
        def sumOfConstr(x):
            value = 0
            for i in range(len(constrains)):
                value += locDeltas[i] * (
                    constrains[i](x) + locThetas[i])**2 * H(constrains[i](x) +
                                                            locThetas[i])
            return value

        def f(x):
            return F(x) + sumOfConstr(x)  # F in direction of v

        # 2 Dokonaj minimalizacji funkcji oraz uzyskany pkt ekstremalny podstaw w miejsce x0, a ponadto c w miejsce c0
        x0, nIter, success, stopValue, stopNorm = powell(
            f,
            x0,
            epsilon=epsilon,
            iterations=iterations,
            bracketing=bracketing,
            bracketStep=bracketStep,
            goldenSearchWindow=goldenSearchWindow,
            epsilonGoldenSearch=epsilonGoldenSearch)
        if not success:
            return False, x0list, stopValueList, stopNormList, nIterList, cOutList
        x0list.append(x0)
        stopValueList.append(stopValue)
        stopNormList.append(stopNorm)
        nIterList.append(nIter)
        # print("x0 w trakcie:", x0)
        c0 = c

        # 3 Oblicz w punkcie ekstremalnym wartoœæ ograniczeñ gi(x) dla i=1,...,m oraz now¹ wartoœæ c w myœl zasady
        constrViolation = []
        for i in range(len(constrains)):
            temp = constrains[i](x0) + locThetas[i]
            if temp > 0:
                #print("Violation of constraint", i)
                constrViolation.append(abs(constrains[i](x0)))
        # Nale¿y siê upewniæ, ¿e jest ograniczenie, ktore nie zostalo spelnione
        if len(constrViolation) > 0:
            c = max(constrViolation)
        cOutList.append(c)
        #print("The largest violation of constraints:", c)

        # 4 zbadaj czy zosta³o spe³nione kryterium na "minimum" tzn. czy c<cMin.
        if c < cMin:
            #print('zostalo spelnione kryterium na "minimum" tzn. czy c<cMi')
            #print(f(x0))
            #print ("Xmin:", x0)
            return True, x0list, stopValueList, stopNormList, nIterList, cOutList
        # Jeœli tak to zakoñcz dzia³anie procedury, natomiast jeœli nie to kolejne kroki.

        # 5 Zbadaj czy po minimalizacji (krok 2) nastapilo zmniejszenie naruszenia ograniczen,
        # tzn. czy c<c0. Jesli tak, to przejdz do wykonania kroku (8),
        if c < c0:
            # Tutaj jest robiony krok 8
            # 8 Jesli k=0 lub w poprzedniej iteracji byl krok 6 to
            if k == 0 or sixStep:
                # To jest krok 8a, zmien wartosci theta w mysl zasady:
                for i in range(len(locThetas)):
                    locThetas[i] = min(constrains[i](x0) + locThetas[i], 0)
                sixStep = False  # nie bylo 6 kroku w tej iteracji
                continue
            else:
                # Krok 8b
                if c <= m1 * c0:
                    # Wykonaj krok 8a, zmien wartosci theta w mysl zasady:
                    for i in range(len(locThetas)):
                        locThetas[i] = min(constrains[i](x0) + locThetas[i], 0)
                else:
                    # Wykonaj krok 6:
                    sixStep = True
                    modifiedIndexes = []
                    for i in range(len(locDeltas)):
                        if (abs((constrains[i](x0)) > m1 * c0)
                                and (constrains[i](x0) + locThetas[i] > 0)):
                            modifiedIndexes.append(i)
                    for i in modifiedIndexes:
                        locDeltas[i] *= m2
                        locThetas[i] /= m2
                    continue
        # Natomiast w przecinwym razie podstaw na miejsce c jego wartosc przed minimalizacja, tzn c=c0
        else:
            c = c0

        # 6 Zmien wartosc parametriw delta i theta wedlug reguly: delta = m2*delta, theta = theta/m2
        modifiedIndexes = []
        for i in range(len(locDeltas)):
            if (abs((constrains[i](x0)) > m1 * c0)
                    and (constrains[i](x0) + locThetas[i] > 0)):
                modifiedIndexes.append(i)

        for i in modifiedIndexes:
            locDeltas[i] *= m2
            locThetas[i] /= m2

    return True, x0list, stopValueList, stopNormList, nIterList, cOutList
def powellConstr(F, x0, constrains=[], deltas=[], thetas=[], cMin=0.01, iterations=100, m2=10, m1=0.25):

    print("Number of constraints:", len(constrains))

    c = 0.01

    locThetas = []
    locDeltas = []

    for theta in thetas:
        locThetas.append(theta)

    for delta in deltas:
        locDeltas.append(delta)

    print("Deltas:", deltas)
    print("Thetas:", thetas)

    def H(sum):
        if sum > 0:
            return 1
        if sum <= 0:
            return 0


    for j in range(iterations):    # Allow for 100 cycles as default:
        print("_"*80)
        print("Step: ", j)
        print("Deltas:", locDeltas)
        def sumOfConstr(x):
            value = 0
            for i in range(len(constrains)):
                value += locDeltas[i]*(constrains[i](x)+locThetas[i])**2*H(constrains[i](x)+locThetas[i])
            return value

        def f(x):
            return F(x) + sumOfConstr(x)    # F in direction of v

        # 2 Dokonaj minimalizacji funkcji oraz uzyskany pkt ekstremalny podstaw w miejsce x0, a ponadto c w miejsce c0
        x0, nIter, success = powell(f, x0)
        print("x0 w trakcie:", x0)
        c0 = c

        # 3 Oblicz w punkcie ekstremalnym wartoœæ ograniczeñ gi(x) dla i=1,...,m oraz now¹ wartoœæ c w myœl zasady
        constrViolation = []
        for i in range(len(constrains)):
            temp = constrains[i](x0) + locThetas[i]
            if temp > 0:
                print("Violation of constraint", i)
                constrViolation.append(abs(constrains[i](x0)))
        # Nale¿y siê upewniæ, ¿e jest ograniczenie, ktore nie zostalo spelnione
        if len(constrViolation) > 0:
            c = max(constrViolation)
        print("The largest violation of constraints:", c)

        # 4 zbadaj czy zosta³o spe³nione kryterium na "minimum" tzn. czy c<cMin.
        if c < cMin:
            print('zostalo spelnione kryterium na "minimum" tzn. czy c<cMi')
            print(f(x0))
            print ("Xmin:", x0)
            return x0
        # Jeœli tak to zakoñcz dzia³anie procedury, natomiast jeœli nie to kolejne kroki.

        modifiedIndexes = []
        for i in range(len(deltas)):
            if (abs((constrains[i](x0)) > m1*c0) and (constrains[i](x0) + locThetas[i] > 0)):
                modifiedIndexes.append(i)

        for i in modifiedIndexes:
            locDeltas[i] *= m2
            locThetas[i] /= m2
## example10_3
from powell import *
import numpy


def F(x):
    return 100.0 * (x[1] - x[0]**2)**2 + (1 - x[0])**2


xStart = numpy.array([-1.0, 1.0])
xMin, nIter = powell(F, xStart)
print "x =", xMin
print "F(x) =", F(xMin)
print "Number of cycles =", nIter
raw_input("Press return to exit")
Esempio n. 5
0
#!/usr/bin/python
## example10_5
from powell import *
from numpy import array
from math import sqrt
from gaussElimin import *


def F(x):
    global v, weight
    lam = 100.0
    c = 2.0*sqrt(2.0)
    A = array([[c*x[1] + x[2], -x[2], x[2]]  [-x[2], x[2], -x[2]],  [ x[2],  -x[2], c*x[0] + x[2]]])/c
    
    b = array([0.0, -1.0, 0.0])
    v = gaussElimin(A,b)
    weight = x[0] + x[1] + sqrt(2.0)*x[2]
    penalty = max(0.0,abs(v[1]) - 1.0)**2 + max(0.0,-x[0])**2 + max(0.0,-x[1])**2 + max(0.0,-x[2])**2
    return weight + penalty*lam


xStart = array([1.0, 1.0, 1.0])
x,numIter = powell(F,xStart)
print("x = ",x)
print("v = ",v)
print("Relative weight F = ",weight)
print("Number of cycles = ",numIter)
input("Press return to exit")
Esempio n. 6
0
## example10_3
from powell import *
from numarray import array

def F(x): return 100.0*(x[1] - x[0]**2)**2 + (1 - x[0])**2 

xStart = array([-1.0, 1.0])
xMin,nIter = powell(F,xStart)
print "x =",xMin
print "F(x) =",F(xMin)
print "Number of cycles =",nIter
raw_input ("Press return to exit")
def powellConstr(F, x0in, constrains=[], deltas=[], thetas=[], cMin=0.01, iterations=100, m2=10, m1=0.25,
                 bracketStep=0.001, goldenSearchWindow=0.001, epsilon=1.0e-6, bracketing=True, epsilonGoldenSearch=1.0e-6):
    x0 = deepcopy(x0in)
    x0list = []
    locThetas = []
    locDeltas = []
    c0 = 1e6
    cOutList = []
    stopValueList = []
    stopNormList = []
    nIterList = []

    for theta in thetas:
        locThetas.append(theta)

    for delta in deltas:
        locDeltas.append(delta)

    def H(sum):
        if sum > 0:
            return 1
        if sum <= 0:
            return 0

    #--------------------------------------------------------------------------------#
    # TUTAJ BEZ OGRANICZEN POLICZY
    if len(constrains) == 0:
        #print("Nie ma ograniczen!")
        x0, nIter, success, stopValue, stopNorm = powell(F, x0, epsilon=epsilon, iterations=iterations, bracketing=bracketing,
                                      bracketStep=bracketStep, goldenSearchWindow=goldenSearchWindow,
                                      epsilonGoldenSearch=epsilonGoldenSearch)
        if not success:
            return False, x0list, stopValue, stopNorm,  nIter, cOutList
        #print("Pkt minimum:", x0)
        #print("F(x):", F(x0))
        x0list.append(x0)
        cOutList.append(0)
        stopValueList.append(stopValue)
        stopNormList.append(stopNorm)
        nIterList.append(nIter)
        return True, x0list, stopValueList, stopNormList,  nIterList, cOutList

    #--------------------------------------------------------------------------------#
    # WPROWADZANIE OGRANICZEN
    c = 0
    sixStep = False

    for k in range(iterations):    # Allow for 100 cycles as default:
        #print("_"*80)
        #print("Step: ", k)
        #print("Deltas:", locDeltas)
        #print("Thetas:", locThetas)
        #print("X0:", x0)
        def sumOfConstr(x):
            value = 0
            for i in range(len(constrains)):
                value += locDeltas[i]*(constrains[i](x)+locThetas[i])**2*H(constrains[i](x)+locThetas[i])
            return value

        def f(x):
            return F(x) + sumOfConstr(x)    # F in direction of v

        # 2 Dokonaj minimalizacji funkcji oraz uzyskany pkt ekstremalny podstaw w miejsce x0, a ponadto c w miejsce c0
        x0, nIter, success, stopValue, stopNorm = powell(f, x0, epsilon=epsilon, iterations=iterations, bracketing=bracketing,
                                      bracketStep=bracketStep, goldenSearchWindow=goldenSearchWindow,
                                      epsilonGoldenSearch=epsilonGoldenSearch)
        if not success:
            return False, x0list, stopValueList, stopNormList,  nIterList, cOutList
        x0list.append(x0)
        stopValueList.append(stopValue)
        stopNormList.append(stopNorm)
        nIterList.append(nIter)
        # print("x0 w trakcie:", x0)
        c0 = c

        # 3 Oblicz w punkcie ekstremalnym wartoœæ ograniczeñ gi(x) dla i=1,...,m oraz now¹ wartoœæ c w myœl zasady
        constrViolation = []
        for i in range(len(constrains)):
            temp = constrains[i](x0) + locThetas[i]
            if temp > 0:
                #print("Violation of constraint", i)
                constrViolation.append(abs(constrains[i](x0)))
        # Nale¿y siê upewniæ, ¿e jest ograniczenie, ktore nie zostalo spelnione
        if len(constrViolation) > 0:
            c = max(constrViolation)
        cOutList.append(c)
        #print("The largest violation of constraints:", c)

        # 4 zbadaj czy zosta³o spe³nione kryterium na "minimum" tzn. czy c<cMin.
        if c < cMin:
            #print('zostalo spelnione kryterium na "minimum" tzn. czy c<cMi')
            #print(f(x0))
            #print ("Xmin:", x0)
            return True, x0list, stopValueList, stopNormList,  nIterList, cOutList
        # Jeœli tak to zakoñcz dzia³anie procedury, natomiast jeœli nie to kolejne kroki.

        # 5 Zbadaj czy po minimalizacji (krok 2) nastapilo zmniejszenie naruszenia ograniczen,
        # tzn. czy c<c0. Jesli tak, to przejdz do wykonania kroku (8),
        if c < c0:
            # Tutaj jest robiony krok 8
            # 8 Jesli k=0 lub w poprzedniej iteracji byl krok 6 to
            if k == 0 or sixStep:
                # To jest krok 8a, zmien wartosci theta w mysl zasady:
                for i in range(len(locThetas)):
                    locThetas[i] = min(constrains[i](x0) + locThetas[i], 0)
                sixStep = False  # nie bylo 6 kroku w tej iteracji
                continue
            else:
                # Krok 8b
                if c <= m1*c0:
                    # Wykonaj krok 8a, zmien wartosci theta w mysl zasady:
                    for i in range(len(locThetas)):
                        locThetas[i] = min(constrains[i](x0) + locThetas[i], 0)
                else:
                    # Wykonaj krok 6:
                    sixStep = True
                    modifiedIndexes = []
                    for i in range(len(locDeltas)):
                        if (abs((constrains[i](x0)) > m1*c0) and (constrains[i](x0) + locThetas[i] > 0)):
                            modifiedIndexes.append(i)
                    for i in modifiedIndexes:
                        locDeltas[i] *= m2
                        locThetas[i] /= m2
                    continue
        # Natomiast w przecinwym razie podstaw na miejsce c jego wartosc przed minimalizacja, tzn c=c0
        else:
            c = c0

        # 6 Zmien wartosc parametriw delta i theta wedlug reguly: delta = m2*delta, theta = theta/m2
        modifiedIndexes = []
        for i in range(len(locDeltas)):
            if (abs((constrains[i](x0)) > m1*c0) and (constrains[i](x0) + locThetas[i] > 0)):
                modifiedIndexes.append(i)

        for i in modifiedIndexes:
            locDeltas[i] *= m2
            locThetas[i] /= m2

    return True, x0list, stopValueList, stopNormList,  nIterList, cOutList