Ejemplo n.º 1
0
def main():
    solver = DifferentialEvolutionSolver(ND, NP)
    solver.SetRandomInitialPoints()
    solver.SetEvaluationLimits(generations=MAX_GENERATIONS)
    solver.SetGenerationMonitor(VerboseMonitor(10))
  
    #strategy = Best1Exp
    #strategy = Best1Bin
    #strategy = Best2Bin
    strategy = Best2Exp

    solver.Solve(ChebyshevCost, termination=VTR(0.0001), strategy=strategy, \
                 CrossProbability=1.0, ScalingFactor=0.6)

    solution = solver.Solution()
  
    print("\nsolved: ")
    print(poly1d(solution))
    print("\ntarget: ")
    print(poly1d(Chebyshev16))
   #print("actual coefficients vs computed:")
   #for actual,computed in zip(Chebyshev16, solution):
   #    print("%f %f" % (actual, computed))

    plot_solution(solution, Chebyshev16)
Ejemplo n.º 2
0
def main():
    solver = DifferentialEvolutionSolver(ND, NP)
    solver.SetRandomInitialPoints()
    solver.SetEvaluationLimits(generations=MAX_GENERATIONS)
    solver.SetGenerationMonitor(VerboseMonitor(10))

    #strategy = Best1Exp
    #strategy = Best1Bin
    #strategy = Best2Bin
    strategy = Best2Exp

    solver.Solve(ChebyshevCost, termination=VTR(0.0001), strategy=strategy, \
                 CrossProbability=1.0, ScalingFactor=0.6)

    solution = solver.Solution()

    print("\nsolved: ")
    print(poly1d(solution))
    print("\ntarget: ")
    print(poly1d(Chebyshev16))
    #print("actual coefficients vs computed:")
    #for actual,computed in zip(Chebyshev16, solution):
    #    print("%f %f" % (actual, computed))

    plot_solution(solution, Chebyshev16)
Ejemplo n.º 3
0
def plot_solution(params):
    import numpy
    x = numpy.arange(-1.2, 1.2001, 0.01)
    f = poly1d(params)
    y = f(x)
    pylab.plot(x, y, 'y-')
    pylab.legend(["Exact", "Fitted"])
    pylab.axis([-1.4, 1.4, -2, 8], 'k-')
    return
Ejemplo n.º 4
0
def plot_solution(params):
    import numpy
    x = numpy.arange(-1.2, 1.2001, 0.01)
    f = poly1d(params)
    y = f(x)
    pylab.plot(x,y,'y-')
    pylab.legend(["Exact","Fitted"])
    pylab.axis([-1.4,1.4,-2,8],'k-')
    return
Ejemplo n.º 5
0
def plot_solution(params, style='y-'):
    import numpy
    x = numpy.arange(-1.2, 1.2001, 0.01)
    f = poly1d(params)
    y = f(x)
    plt.plot(x, y, style)
    plt.legend(["Exact", "Fitted"])
    plt.axis([-1.4, 1.4, -2, 8], 'k-')
    plt.draw()
    plt.pause(0.001)
    return
Ejemplo n.º 6
0
def plot_solution(params, style="y-"):
    import numpy

    x = numpy.arange(-1.2, 1.2001, 0.01)
    f = poly1d(params)
    y = f(x)
    pylab.plot(x, y, style)
    pylab.legend(["Exact", "Fitted"])
    pylab.axis([-1.4, 1.4, -2, 8], "k-")
    pylab.draw()
    return
Ejemplo n.º 7
0
def plot_solution(params,style='y-'):
    import numpy
    x = numpy.arange(-1.2, 1.2001, 0.01)
    f = poly1d(params)
    y = f(x)
    plt.plot(x,y,style)
    plt.legend(["Exact","Fitted"])
    plt.axis([-1.4,1.4,-2,8],'k-')
    plt.draw()
    plt.pause(0.001)
    return
Ejemplo n.º 8
0
def plot_solution(func, benchmark=Chebyshev8):
    try:
        import pylab, numpy
        x = numpy.arange(-1.2, 1.2001, 0.01)
        x2 = numpy.array([-1.0, 1.0])
        p = poly1d(func)
        chebyshev = poly1d(benchmark)
        y = p(x)
        exact = chebyshev(x)
        pylab.plot(x, y, 'b-', linewidth=2)
        pylab.plot(x, exact, 'r-', linewidth=2)
        pylab.plot(x, 0 * x - 1, 'k-')
        pylab.plot(x2, 0 * x2 + 1, 'k-')
        pylab.plot([-1.2, -1.2], [-1, 10], 'k-')
        pylab.plot([1.2, 1.2], [-1, 10], 'k-')
        pylab.plot([-1.0, -1.0], [1, 10], 'k-')
        pylab.plot([1.0, 1.0], [1, 10], 'k-')
        pylab.axis([-1.4, 1.4, -2, 8], 'k-')
        pylab.legend(('Fitted', 'Chebyshev'))
        pylab.show()
    except ImportError:
        print("Install matplotlib for visualization")
        pass
Ejemplo n.º 9
0
def plot_solution(func, benchmark=Chebyshev8):
    try:
        import pylab, numpy
        x = numpy.arange(-1.2, 1.2001, 0.01)
        x2 = numpy.array([-1.0, 1.0])
        p = poly1d(func)
        chebyshev = poly1d(benchmark)
        y = p(x)
        exact = chebyshev(x)
        pylab.plot(x,y,'b-',linewidth=2)
        pylab.plot(x,exact,'r-',linewidth=2)
        pylab.plot(x,0*x-1,'k-')
        pylab.plot(x2, 0*x2+1,'k-')
        pylab.plot([-1.2, -1.2],[-1, 10],'k-')
        pylab.plot([1.2, 1.2],[-1, 10],'k-')
        pylab.plot([-1.0, -1.0],[1, 10],'k-')
        pylab.plot([1.0, 1.0],[1, 10],'k-')
        pylab.axis([-1.4, 1.4, -2, 8],'k-')
        pylab.legend(('Fitted','Chebyshev'))
        pylab.show()
    except ImportError:
        print "Install matplotlib/numpy for visualization"
        pass
Ejemplo n.º 10
0

if __name__ == '__main__':

    print("Differential Evolution")
    print("======================")

    # set range for random initial guess
    ndim = 9
    x0 = [(-100, 100)] * ndim
    random_seed(321)

    # draw frame and exact coefficients
    plot_exact()

    # use DE to solve 8th-order Chebyshev coefficients
    npop = 10 * ndim
    solution = diffev(chebyshev8cost, x0, npop)

    # use pretty print for polynomials
    print(poly1d(solution))

    # compare solution with actual 8th-order Chebyshev coefficients
    print("\nActual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs))

    # plot solution versus exact coefficients
    plot_solution(solution)
    getch()

# end of file
Ejemplo n.º 11
0
    # use DE to solve 8th-order Chebyshev coefficients
    npop = 10 * ndim
    solver = DifferentialEvolutionSolver2(ndim, npop)
    solver.SetRandomInitialPoints(min=[-100] * ndim, max=[100] * ndim)
    solver.SetEvaluationLimits(generations=999)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)
    solver.enable_signal_handler()
    solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \
                 CrossProbability=1.0, ScalingFactor=0.9)
    solution = solver.bestSolution

    # get solved coefficients and Chi-Squared (from solver members)
    iterations = solver.generations
    cost = solver.bestEnergy
    print("Generation %d has best Chi-Squared: %f" % (iterations, cost))
    print("Solved Coefficients:\n %s\n" % poly1d(solver.bestSolution))

    # plot convergence of coefficients per iteration
    plot_frame('iterations')
    plot_params(stepmon)
    getch()

    # plot convergence of coefficients per function call
    plot_frame('function calls')
    plot_params(evalmon)
    getch()

# end of file
Ejemplo n.º 12
0
 def print_solution(func):
     print poly1d(func)
     return
Ejemplo n.º 13
0
    solver = NelderMeadSimplexSolver(ndim)
    solver.SetInitialPoints(x0)
    solver.SetEvaluationLimits(generations=999)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)
    solver.SetStrictRanges(min_bounds,max_bounds)
    solver.enable_signal_handler()
    solver.Solve(chebyshev8cost, termination=CRT(1e-4,1e-4), \
                 sigint_callback=plot_solution)
    solution = solver.bestSolution

    # get solved coefficients and Chi-Squared (from solver members)
    iterations = solver.generations
    cost = solver.bestEnergy
    print("Generation %d has best Chi-Squared: %f" % (iterations, cost))
    print("Solved Coefficients:\n %s\n" % poly1d(solver.bestSolution))

    # compare solution with actual 8th-order Chebyshev coefficients
    print("Actual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs))

    # plot solution versus exact coefficients
    plot_solution(solution)
    getch()

    # plot convergence of coefficients per iteration
    plot_frame('iterations')
    plot_params(stepmon)
    getch()

    # plot convergence of coefficients per function call
    plot_frame('function calls')
Ejemplo n.º 14
0
                                datefmt='%a, %d %b %Y %H:%M:%S')

    def _init(self):
        Script._init(self)
        return

    def help(self):
        doc = """
# this will solve the default "example" problem
%(name)s

        """ % {
            'name': __file__
        }
        paginate(doc)
        return


# main
if __name__ == '__main__':
    app = DerunApp()
    app.run()

    # Chebyshev8 polynomial (used with "dummy.py")
    from mystic.models.poly import chebyshev8coeffs as target_coeffs
    from mystic.math import poly1d
    print "target:\n", poly1d(target_coeffs)
    print "\nDE Solution:\n", poly1d(app.solution)

# End of file
Ejemplo n.º 15
0
from mystic.models.poly import chebyshev8coeffs as target
from mystic.math import polyeval, poly1d


def chebyshev8cost(trial, M=61):
    """The costfunction for order-n Chebyshev fitting.
M evaluation points between [-1, 1], and two end points"""

    result = 0.0
    x = -1.0
    dx = 2.0 / (M - 1)
    for i in range(M):
        px = polyeval(trial, x)
        if px < -1 or px > 1:
            result += (1 - px) * (1 - px)
        x += dx

    px = polyeval(trial, 1.2) - polyeval(target, 1.2)
    if px < 0: result += px * px

    px = polyeval(trial, -1.2) - polyeval(target, -1.2)
    if px < 0: result += px * px

    return result


if __name__ == '__main__':
    print(poly1d(target))
    print("")
    print(chebyshev8cost(target))
Ejemplo n.º 16
0
    # configure monitor
    stepmon = VerboseMonitor(50)

    # use DE to solve 8th-order Chebyshev coefficients
    npop = 10*ndim
    solver = DifferentialEvolutionSolver2(ndim,npop)
    solver.SetRandomInitialPoints(min=[-100]*ndim, max=[100]*ndim)
    solver.SetGenerationMonitor(stepmon)
    solver.enable_signal_handler()
    solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \
                 CrossProbability=1.0, ScalingFactor=0.9, \
                 sigint_callback=plot_solution)
    solution = solver.Solution()

    # use monitor to retrieve results information
    iterations = len(stepmon)
    cost = stepmon.y[-1]
    print("Generation %d has best Chi-Squared: %f" % (iterations, cost))

    # use pretty print for polynomials
    print(poly1d(solution))

    # compare solution with actual 8th-order Chebyshev coefficients
    print("\nActual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs))

    # plot solution versus exact coefficients
    plot_solution(solution)
    getch()

# end of file
Ejemplo n.º 17
0
                                datefmt='%a, %d %b %Y %H:%M:%S')

    def _init(self):
        Script._init(self)
        return

    def help(self):
        doc = """
# this will solve the default "example" problem
%(name)s

        """ % {
            'name': __file__
        }
        paginate(doc)
        return


# main
if __name__ == '__main__':
    app = DerunApp()
    app.run()

    # Chebyshev8 polynomial (used with "dummy.py")
    from mystic.models.poly import chebyshev8coeffs as target_coeffs
    from mystic.math import poly1d
    print("target:\n%s" % poly1d(target_coeffs))
    print("\nDE Solution:\n%s" % poly1d(app.solution))

# End of file
Ejemplo n.º 18
0
"""

from mystic.models.poly import chebyshev8coeffs as target
from mystic.math import polyeval, poly1d

def chebyshev8cost(trial,M=61):
    """The costfunction for order-n Chebyshev fitting.
M evaluation points between [-1, 1], and two end points"""

    result=0.0
    x=-1.0
    dx = 2.0 / (M-1)
    for i in range(M):
        px = polyeval(trial, x)
        if px<-1 or px>1:
            result += (1 - px) * (1 - px)
        x += dx

    px = polyeval(trial, 1.2) - polyeval(target, 1.2)
    if px<0: result += px*px

    px = polyeval(trial, -1.2) - polyeval(target, -1.2)
    if px<0: result += px*px

    return result

if __name__=='__main__':
    print poly1d(target)
    print ""
    print chebyshev8cost(target)
Ejemplo n.º 19
0
    solver = NelderMeadSimplexSolver(ndim)
    solver.SetInitialPoints(x0)
    solver.SetEvaluationLimits(generations=999)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)
    solver.SetStrictRanges(min_bounds, max_bounds)
    solver.enable_signal_handler()
    solver.Solve(chebyshev8cost, termination=CRT(1e-4,1e-4), \
                 sigint_callback=plot_solution)
    solution = solver.bestSolution

    # get solved coefficients and Chi-Squared (from solver members)
    iterations = solver.generations
    cost = solver.bestEnergy
    print "Generation %d has best Chi-Squared: %f" % (iterations, cost)
    print "Solved Coefficients:\n %s\n" % poly1d(solver.bestSolution)

    # compare solution with actual 8th-order Chebyshev coefficients
    print "Actual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs)

    # plot solution versus exact coefficients
    plot_solution(solution)
    getch()

    # plot convergence of coefficients per iteration
    plot_frame('iterations')
    plot_params(stepmon)
    getch()

    # plot convergence of coefficients per function call
    plot_frame('function calls')
Ejemplo n.º 20
0
def chebyshev8cost(trial,M=61):
    """The costfunction for order-n Chebyshev fitting.
M evaluation points between [-1, 1], and two end points"""

    from mystic.models.poly import chebyshev8coeffs as target
    from mystic.math import polyeval

    result=0.0
    x=-1.0
    dx = 2.0 / (M-1)
    for i in range(M):
        px = polyeval(trial, x)
        if px<-1 or px>1:
            result += (1 - px) * (1 - px)
        x += dx

    px = polyeval(trial, 1.2) - polyeval(target, 1.2)
    if px<0: result += px*px

    px = polyeval(trial, -1.2) - polyeval(target, -1.2)
    if px<0: result += px*px

    return result

if __name__=='__main__':
    from mystic.models.poly import chebyshev8coeffs as target
    from mystic.math import poly1d
    print(poly1d(target))
    print("")
    print(chebyshev8cost(target))
Ejemplo n.º 21
0
"""

from mystic.models.poly import chebyshev8coeffs as target
from mystic.math import polyeval, poly1d

def chebyshev8cost(trial,M=61):
    """The costfunction for order-n Chebyshev fitting.
M evaluation points between [-1, 1], and two end points"""

    result=0.0
    x=-1.0
    dx = 2.0 / (M-1)
    for i in range(M):
        px = polyeval(trial, x)
        if px<-1 or px>1:
            result += (1 - px) * (1 - px)
        x += dx

    px = polyeval(trial, 1.2) - polyeval(target, 1.2)
    if px<0: result += px*px

    px = polyeval(trial, -1.2) - polyeval(target, -1.2)
    if px<0: result += px*px

    return result

if __name__=='__main__':
    print poly1d(target)
    print ""
    print chebyshev8cost(target)
Ejemplo n.º 22
0
    def ForwardFactory(self,coeffs):
        """generates a 1-D polynomial instance from a list of coefficients
using numpy.poly1d(coeffs)"""
        self.__forward__ = poly1d(coeffs)
        return self.__forward__
Ejemplo n.º 23
0
    # use DE to solve 8th-order Chebyshev coefficients
    npop = 10*ndim
    solver = DifferentialEvolutionSolver2(ndim,npop)
    solver.SetRandomInitialPoints(min=[-100]*ndim, max=[100]*ndim)
    solver.SetEvaluationLimits(generations=999)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)
    solver.enable_signal_handler()
    solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \
                 CrossProbability=1.0, ScalingFactor=0.9)
    solution = solver.bestSolution

    # get solved coefficients and Chi-Squared (from solver members)
    iterations = solver.generations
    cost = solver.bestEnergy
    print "Generation %d has best Chi-Squared: %f" % (iterations, cost)
    print "Solved Coefficients:\n %s\n" % poly1d(solver.bestSolution)

    # plot convergence of coefficients per iteration
    plot_frame('iterations')
    plot_params(stepmon) 
    getch()

    # plot convergence of coefficients per function call
    plot_frame('function calls')
    plot_params(evalmon) 
    getch()

# end of file
Ejemplo n.º 24
0
Archivo: poly.py Proyecto: vt100/mystic
    def ForwardFactory(self, coeffs):
        """generates a 1-D polynomial instance from a list of coefficients
using numpy.poly1d(coeffs)"""
        self.__forward__ = poly1d(coeffs)
        return self.__forward__
Ejemplo n.º 25
0
                                datefmt='%a, %d %b %Y %H:%M:%S')

    def _init(self):
        Script._init(self)
        return

    def help(self):
        doc =  """
# this will solve the default "example" problem
%(name)s

        """ % {'name' : __file__}
        paginate(doc)
        return



# main
if __name__ == '__main__':
    app = DerunApp()
    app.run()

    # Chebyshev8 polynomial (used with "dummy.py")
    from mystic.models.poly import chebyshev8coeffs as target_coeffs
    from mystic.math import poly1d
    print "target:\n", poly1d(target_coeffs)
    print "\nDE Solution:\n", poly1d(app.solution)


# End of file
Ejemplo n.º 26
0
 def print_solution(func):
     print(poly1d(func))
     return
Ejemplo n.º 27
0
                                datefmt='%a, %d %b %Y %H:%M:%S')

    def _init(self):
        Script._init(self)
        return

    def help(self):
        doc =  """
# this will solve the default "example" problem
%(name)s

        """ % {'name' : __file__}
        paginate(doc)
        return



# main
if __name__ == '__main__':
    app = DerunApp()
    app.run()

    # Chebyshev8 polynomial (used with "dummy.py")
    from mystic.models.poly import chebyshev8coeffs as target_coeffs
    from mystic.math import poly1d
    print("target:\n%s" % poly1d(target_coeffs))
    print("\nDE Solution:\n%s" % poly1d(app.solution))


# End of file