예제 #1
0
    def configure(self):
        common_io_with_ccblade(self, self.varspeed, self.varpitch, self.cdf_type)
        common_configure_with_ccblade(self, self.varspeed, self.varpitch, self.cdf_type)

        # used for normalization of objective
        self.add('AEP0', Float(1.0, iotype='in', desc='used for normalization'))

        if self.optimizer == 'snopt':
            self.replace('driver', pyOptDriver())
            self.driver.optimizer = 'SNOPT'
            self.driver.options = {'Major feasibility tolerance': 1e-6,
                                   'Minor feasibility tolerance': 1e-6,
                                   'Major optimality tolerance': 1e-5,
                                   'Function precision': 1e-8,
                                   'Iterations limit': 100,
                                   'Print file': 'harpopt_snopt.out',
                                   'Summary file': 'harpopt_snopt_summary.out'}

        elif self.optimizer == 'psqp':
            self.replace('driver', pyOptDriver())
            self.driver.optimizer = 'PSQP'
            self.driver.options = {'XMAX': 100.0,
                                   'TOLG': 1e-4,
                                   'MFV': 100,
                                   'IFILE': 'harpopt_psqp.out'}

        elif self.optimizer == 'slsqp':
            self.replace('driver', SLSQPdriver())
            self.driver.accuracy = 1.0e-6
            self.driver.maxiter = 500

        elif self.optimizer == "conmin": 
            self.replace('driver', CONMINdriver())
            self.driver.delfun = 1e-6
            self.driver.itmax = 500

        else:
            print 'invalid optimizer specified'
            exit()

        # objective
        self.driver.add_objective('-aep.AEP/AEP0')  # maximize AEP

        # design variables
        self.driver.add_parameter('r_max_chord', low=0.1, high=0.5)
        self.driver.add_parameter('chord_sub', low=0.4, high=5.3)
        self.driver.add_parameter('theta_sub', low=-10.0, high=30.0)
        if self.varspeed:
            self.driver.add_parameter('control.tsr', low=3.0, high=14.0)
        # if optimize_stations:
            # self.driver.add_parameter('r_af[1:-1]', low=0.01, high=0.99)


        # outfile = open('results.txt', 'w')
        # self.driver.recorders = [DumpCaseRecorder(outfile)]
        self.driver.recorders = [DumpCaseRecorder()]


        if self.optimizer == 'snopt' or self.optimizer == 'psqp':  # pyopt has an oustanding bug for unconstrained problems, so adding inconsequential constraint
            self.driver.add_constraint('spline.r_max_chord > 0.0')
    def configure(self):
        """ Creates a new Assembly containing a MultiFunction and an optimizer"""

        # pylint: disable=E1101

        # Create MultiFunction component instances
        self.add('multifunction', MultiFunction())

        # Create NSGA2 Optimizer instance
        self.add('driver', pyOptDriver())

        # Driver process definition
        self.driver.workflow.add('multifunction')

        self.driver.print_results = False

        # NSGA2 Objective
        self.driver.add_objective('multifunction.f1_x')
        self.driver.add_objective('multifunction.f2_x')

        # NSGA2 Design Variable
        self.driver.add_parameter('multifunction.x1', low=0.1, high=1.0)
        self.driver.add_parameter('multifunction.x2', low=0.0, high=5.0)

        # NSGA2 Constraints
        self.driver.add_constraint('multifunction.g1_x >= 6.0')
        self.driver.add_constraint('multifunction.g2_x >= 1.0')
    def __init__(self):
        """ Creates a new Assembly containing a Paraboloid and an optimizer"""
        
        # pylint: disable-msg=E1101
        
        super(OptimizationConstrainedDerivatives, self).__init__()

        # Create Paraboloid component instances
        self.add('paraboloid', ParaboloidDerivative())

        # Create CONMIN Optimizer instance
        self.add('driver', pyOptDriver())
        
        # Driver process definition
        self.driver.workflow.add('paraboloid')
        
        # CONMIN Objective 
        self.driver.add_objective('paraboloid.f_xy')
        
        # CONMIN Design Variables 
        self.driver.add_parameter('paraboloid.x', low=-50., high=50.)
        self.driver.add_parameter('paraboloid.y', low=-50., high=50.)
        
        # CONMIN Constraints
        self.driver.add_constraint('paraboloid.x-paraboloid.y >= 15.0')
        
        self.driver.print_results = False
        
        self.driver.differentiator = FiniteDifference()
    def configure(self):
        """ Creates a new Assembly containing a Paraboloid and an optimizer"""

        # pylint: disable=E1101

        # Create Paraboloid component instances
        self.add('paraboloid', Paraboloid())

        # Create CONMIN Optimizer instance
        self.add('driver', pyOptDriver())

        # Driver process definition
        self.driver.workflow.add('paraboloid')

        # CONMIN Objective
        self.driver.add_objective('paraboloid.f_xy')

        # CONMIN Design Variables
        self.driver.add_parameter('paraboloid.x', low=-50., high=50.)
        self.driver.add_parameter('paraboloid.y', low=-50., high=50.)

        # CONMIN Constraints
        self.driver.add_constraint('paraboloid.x-paraboloid.y >= 15.0')

        self.driver.print_results = False
    def configure(self):
        # Create Optimizer instance
        self.add('driver', pyOptDriver())

        # Create Paraboloid component instances
        self.add('one', one())

        # Iteration Hierarchy
        self.driver.workflow.add('one')

        # SLSQP Flags
        self.driver.iprint = 2

        # Objective
        self.driver.add_objective('one.f')

        # Design Variables
        self.driver.add_parameter('one.x', low=3.5, high=50.5)
        # self.driver.add_parameter('one.y', low=1.0, high=500.)
        # Constraints
        # self.driver.add_constraint('3.0*one.x**2.0*one.y>=50.0')
        # self.driver.add_constraint('3.0*one.x**2.0*one.y<=50.0')

        # self.driver.gradient_options.fd_form = 'forward'
        # self.driver.xmax = 0.000000000001
        self.driver.optimizer = 'ALPSO'
    def configure(self):
        """ Creates a new Assembly containing a MultiFunction and an optimizer"""

        # pylint: disable=E1101

        # Create MultiFunction component instances
        self.add('multifunction', MultiFunction())

        # Create NSGA2 Optimizer instance
        self.add('driver', pyOptDriver())

        # Driver process definition
        self.driver.workflow.add('multifunction')

        self.driver.print_results = False

        # NSGA2 Objective
        self.driver.add_objective('multifunction.f1_x')
        self.driver.add_objective('multifunction.f2_x')

        # NSGA2 Design Variable
        self.driver.add_parameter('multifunction.x1', low=0.1, high=1.0)
        self.driver.add_parameter('multifunction.x2', low=0.0, high=5.0)

        # NSGA2 Constraints
        self.driver.add_constraint('multifunction.g1_x >= 6.0')
        self.driver.add_constraint('multifunction.g2_x >= 1.0')
    def configure(self):
        """ Creates a new Assembly containing a Paraboloid and an optimizer"""

        # pylint: disable=E1101

        # Create Paraboloid component instances
        self.add('paraboloid', Paraboloid())

        # Create CONMIN Optimizer instance
        self.add('driver', pyOptDriver())

        # Driver process definition
        self.driver.workflow.add('paraboloid')

        # CONMIN Objective
        self.driver.add_objective('paraboloid.f_xy')

        # CONMIN Design Variables
        self.driver.add_parameter('paraboloid.x', low=-50., high=50.)
        self.driver.add_parameter('paraboloid.y', low=-50., high=50.)

        # CONMIN Constraints
        self.driver.add_constraint('paraboloid.x-paraboloid.y >= 15.0')

        self.driver.print_results = False
예제 #8
0
    def configure(self):
        # add an optimizer and an AeroStructural assembly
        if pyopt_driver and 'SNOPT' in pyopt_driver._check_imports():
            self.add("driver", pyopt_driver.pyOptDriver())
            self.driver.optimizer = "SNOPT"
            self.driver.options = {
                # any changes to default SNOPT options?
            }
        else:
            print 'SNOPT not available, using SLSQP'
            self.add('driver', SLSQPdriver())

        self.add('aso', AeroStructuralOpt())

        # objective: minimize total power
        self.driver.add_objective('aso.Ptot')

        # parameter: rotor speed
        self.driver.add_parameter('aso.Omega_opt',
                                  low=0.15 * 2 * pi,
                                  high=0.25 * 2 * pi)
        self.aso.Omega_opt = 0.2 * 2 * pi  # initial value

        # constraint: lift >= weight
        self.driver.add_constraint('aso.Mtot*9.8-aso.Ttot<=0')
예제 #9
0
    def configure(self):
        # Create Optimizer instance
        self.add('driver', pyOptDriver())

        # Create Paraboloid component instances
        self.add('one', one())

        # Iteration Hierarchy
        self.driver.workflow.add('one')

        # SLSQP Flags
        self.driver.iprint = 2

        # Objective
        self.driver.add_objective('one.f')

        # Design Variables
        self.driver.add_parameter('one.x', low=3.5, high=50.5)
        # self.driver.add_parameter('one.y', low=1.0, high=500.)
        # Constraints
        # self.driver.add_constraint('3.0*one.x**2.0*one.y>=50.0')
        # self.driver.add_constraint('3.0*one.x**2.0*one.y<=50.0')

        # self.driver.gradient_options.fd_form = 'forward'
        # self.driver.xmax = 0.000000000001
        self.driver.optimizer = 'ALPSO'
예제 #10
0
 def configure(self):
     self.add('func',Rosenbrock())
     self.connect('func.f','output')
     self.add('driver',pyOptDriver())
     self.driver.optimizer='NSGA2'
     self.driver.options={'maxGen':250,'pMut_real':0.4}
     self.driver.add_objective('func.f')
     self.driver.add_parameter('func.x1')
     self.driver.add_parameter('func.x2')
     self.driver.add_constraint('func.x1+func.x2-2.0<=0.0')
예제 #11
0
 def configure(self):
     self.add('func', Rosenbrock())
     self.connect('func.f', 'output')
     self.add('driver', pyOptDriver())
     self.driver.optimizer = 'NSGA2'
     self.driver.options = {'maxGen': 250, 'pMut_real': 0.4}
     self.driver.add_objective('func.f')
     self.driver.add_parameter('func.x1')
     self.driver.add_parameter('func.x2')
     self.driver.add_constraint('func.x1+func.x2-2.0<=0.0')
    def test_initial_run(self):
        # Test to make sure fix that put run_iteration
        #   at the top of the execute method is in place and working
        class MyComp(Component):

            x = Float(0.0, iotype='in', low=-10, high=10)
            xx = Float(0.0, iotype='in', low=-10, high=10)
            f_x = Float(iotype='out')
            y = Float(iotype='out')

            def execute(self):
                if self.xx != 1.0:
                    self.raise_exception("Lazy", RuntimeError)
                self.f_x = 2.0*self.x
                self.y = self.x

        @add_delegate(HasParameters)
        class SpecialDriver(Driver):

            implements(IHasParameters)

            def execute(self):
                self.set_parameters([1.0])

        top = set_as_top(Assembly())
        top.add('comp', MyComp())

        try:
            from pyopt_driver.pyopt_driver import pyOptDriver
        except ImportError:
            raise SkipTest("this test requires pyOpt to be installed")

        try:
            top.driver.optimizer = 'CONMIN'
        except ValueError:
            raise SkipTest("CONMIN not present on this system")

        top.driver.title = 'Little Test'
        optdict = {}
        top.driver.options = optdict
        top.driver.pyopt_diff = True

        top.add('driver', pyOptDriver())
        top.add('subdriver', SpecialDriver())
        top.driver.workflow.add('subdriver')
        top.subdriver.workflow.add('comp')

        top.subdriver.add_parameter('comp.xx')
        top.driver.add_parameter('comp.x')
        top.driver.add_constraint('comp.y > 1.0')
        top.driver.add_objective('comp.f_x')

        top.run()
    def test_initial_run(self):
        # Test to make sure fix that put run_iteration
        #   at the top of the execute method is in place and working
        class MyComp(Component):

            x = Float(0.0, iotype='in', low=-10, high=10)
            xx = Float(0.0, iotype='in', low=-10, high=10)
            f_x = Float(iotype='out')
            y = Float(iotype='out')

            def execute(self):
                if self.xx != 1.0:
                    self.raise_exception("Lazy", RuntimeError)
                self.f_x = 2.0 * self.x
                self.y = self.x

        @add_delegate(HasParameters)
        class SpecialDriver(Driver):

            implements(IHasParameters)

            def execute(self):
                self.set_parameters([1.0])

        top = set_as_top(Assembly())
        top.add('comp', MyComp())

        try:
            from pyopt_driver.pyopt_driver import pyOptDriver
        except ImportError:
            raise SkipTest("this test requires pyOpt to be installed")

        try:
            top.driver.optimizer = 'CONMIN'
        except ValueError:
            raise SkipTest("CONMIN not present on this system")

        top.driver.title = 'Little Test'
        optdict = {}
        top.driver.options = optdict
        top.driver.pyopt_diff = True

        top.add('driver', pyOptDriver())
        top.add('subdriver', SpecialDriver())
        top.driver.workflow.add('subdriver')
        top.subdriver.workflow.add('comp')

        top.subdriver.add_parameter('comp.xx')
        top.driver.add_parameter('comp.x')
        top.driver.add_constraint('comp.y > 1.0')
        top.driver.add_objective('comp.f_x')

        top.run()
    def configure(self):
        """ Creates a new Assembly containing ArrayParaboloid and an optimizer"""

        # pylint: disable=E1101

        self.add('paraboloid', ArrayParaboloid())
        self.add('driver', pyOptDriver())
        self.driver.pyopt_diff = True
        self.driver.workflow.add('paraboloid')
        self.driver.add_objective('paraboloid.f_xy')
        self.driver.add_parameter('paraboloid.x', low=-50., high=50.)
        self.driver.add_constraint('paraboloid.x[0]-paraboloid.x[1] >= 15.0')
        self.driver.print_results = False
    def configure(self):
        """ Creates a new Assembly containing ArrayParaboloid and an optimizer"""

        # pylint: disable=E1101

        self.add('paraboloid', ArrayParaboloid())
        self.add('driver', pyOptDriver())
        self.driver.pyopt_diff = True
        self.driver.workflow.add('paraboloid')
        self.driver.add_objective('paraboloid.f_xy')
        self.driver.add_parameter('paraboloid.x', low=-50., high=50.)
        self.driver.add_constraint('paraboloid.x[0]-paraboloid.x[1] >= 15.0')
        self.driver.print_results = False
    def __init__(self):
        """Creates a new Assembly containing a MultiFunction and an optimizer"""

        # pylint: disable=E1101

        super(BenchMarkOptimization, self).__init__()

        # Create MultiFunction component instances
        self.add('benchmark', BenchMark())

        # Create ALPSO Optimizer instance
        self.add('driver', pyOptDriver())

        # Driver process definition
        self.driver.workflow.add('benchmark')

        # PyOpt Flags
        self.driver.optimizer = 'ALPSO'
        self.driver.title = 'Bench mark problem 4 - Unconstrained'
        optdict = {}
        optdict['SwarmSize'] = 40
        optdict['maxOuterIter'] = 100
        optdict['maxInnerIter'] = 3
        optdict['minInnerIter'] = 3
        optdict['etol'] = 1e-4
        optdict['itol'] = 1e-4
        optdict['c1'] = 0.8
        optdict['c2'] = 0.8
        optdict['w1'] = 0.9
        optdict['nf'] = 5
        optdict['dt'] = 1.0
        optdict['vcrazy'] = 1e-4
        optdict['Scaling'] = 1
        optdict['seed'] = 1.0

        self.driver.options = optdict

        # ALPSO Objective
        self.driver.add_objective('benchmark.f_x')

        # ALPSO Design Variables
        self.driver.add_parameter('benchmark.x1', low=0, high=42)
        self.driver.add_parameter('benchmark.x2', low=0, high=42)
        self.driver.add_parameter('benchmark.x3', low=0, high=42)

        # ALPSO Constraints
        self.driver.add_constraint('benchmark.g1_x <= 0.0')
        self.driver.add_constraint('benchmark.h1_x <= 0.0')
    def __init__(self):
        """Creates a new Assembly containing a MultiFunction and an optimizer"""

        # pylint: disable=E1101

        super(BenchMarkOptimization, self).__init__()

        # Create MultiFunction component instances
        self.add('benchmark', BenchMark())

        # Create ALPSO Optimizer instance
        self.add('driver', pyOptDriver())

        # Driver process definition
        self.driver.workflow.add('benchmark')

        # PyOpt Flags
        self.driver.optimizer = 'ALPSO'
        self.driver.title = 'Bench mark problem 4 - Unconstrained'
        optdict = {}
        optdict['SwarmSize'] = 40
        optdict['maxOuterIter'] = 100
        optdict['maxInnerIter'] = 3
        optdict['minInnerIter'] = 3
        optdict['etol'] = 1e-4
        optdict['itol'] = 1e-4
        optdict['c1'] = 0.8
        optdict['c2'] = 0.8
        optdict['w1'] = 0.9
        optdict['nf'] = 5
        optdict['dt'] = 1.0
        optdict['vcrazy'] = 1e-4
        optdict['Scaling'] = 1
        optdict['seed'] = 1.0

        self.driver.options = optdict

        # ALPSO Objective
        self.driver.add_objective('benchmark.f_x')

        # ALPSO Design Variables
        self.driver.add_parameter('benchmark.x1', low=0, high=42)
        self.driver.add_parameter('benchmark.x2', low=0, high=42)
        self.driver.add_parameter('benchmark.x3', low=0, high=42)

        # ALPSO Constraints
        self.driver.add_constraint('benchmark.g1_x <= 0.0')
        self.driver.add_constraint('benchmark.h1_x <= 0.0')
예제 #18
0
    def configure(self):
        self.driver = self.add('driver', pyOptDriver())
        self.driver.optimizer = 'NSGA2'
        self.driver.pyopt_diff = True
        self.driver.options["PopSize"] = 4
        self.driver.options["maxGen"] = 100

        self.add('roseSA',rosenSA())
        self.add('dakBak', get_dak_output())

        self.driver.workflow.add('roseSA')
        self.driver.workflow.add('dakBak')
        self.add('x1',Float(0.4, iotype = 'in'))
        self.driver.add_parameter('x1', low = -6, high = 6)
        self.connect('x1', ['roseSA.x1', 'dakBak.x1'])
        self.driver.add_objective('dakBak.mean_f')
예제 #19
0
    def configure(self):
        self.driver = self.add('driver', pyOptDriver())
        self.driver.optimizer = 'NSGA2'
        self.driver.pyopt_diff = True
        self.driver.options["PopSize"] = 4
        self.driver.options["maxGen"] = 100

        self.add('roseSA', rosenSA())
        self.add('dakBak', get_dak_output())

        self.driver.workflow.add('roseSA')
        self.driver.workflow.add('dakBak')
        self.add('x1', Float(0.4, iotype='in'))
        self.driver.add_parameter('x1', low=-6, high=6)
        self.connect('x1', ['roseSA.x1', 'dakBak.x1'])
        self.driver.add_objective('dakBak.mean_f')
예제 #20
0
    def configure(self):
        # add an optimizer and an AeroStructural assembly
        if pyopt_driver and 'SNOPT' in pyopt_driver._check_imports():
            self.add("driver", pyopt_driver.pyOptDriver())
            self.driver.optimizer = "SNOPT"
            self.driver.options = {
                # any changes to default SNOPT options?
            }
        else:
            print 'SNOPT not available, using SLSQP'
            self.add('driver', SLSQPdriver())

        self.add('aso', AeroStructuralOpt())

        # objective: minimize total power
        self.driver.add_objective('aso.Ptot')

        # parameter: rotor speed
        self.driver.add_parameter('aso.Omega_opt',
                                  low=0.15*2*pi, high=0.25*2*pi)
        self.aso.Omega_opt = 0.2*2*pi  # initial value

        # constraint: lift >= weight
        self.driver.add_constraint('aso.Mtot*9.8-aso.Ttot<=0')
예제 #21
0
    def __init__(self, n=1500, m=300, npts=6):
        super(CADRE_Optimization, self).__init__()

        # add SNOPT driver
        self.add("driver", pyopt_driver.pyOptDriver())
        self.driver.optimizer = "SNOPT"
        self.driver.options = {
            'Major optimality tolerance': 1e-3,
            'Iterations limit': 500000000,
            "New basis file": 10
        }
        if os.path.exists("fort.10"):
            self.driver.options["Old basis file"] = 10

        #driver = self.add("driver", CONMINdriver())

        # Raw data to load
        fpath = os.path.dirname(os.path.realpath(__file__))
        fpath = os.path.join(fpath, 'src/CADRE/data')
        solar_raw1 = np.genfromtxt(fpath + '/Solar/Area10.txt')
        solar_raw2 = np.loadtxt(fpath + '/Solar/Area_all.txt')
        comm_rawGdata = np.genfromtxt(fpath + '/Comm/Gain.txt')
        comm_raw = (10**(comm_rawGdata / 10.0)).reshape((361, 361), order='F')
        power_raw = np.genfromtxt(fpath + '/Power/curve.dat')

        # Load launch data
        launch_data = np.loadtxt(fpath + '/Launch/launch1.dat')

        # orbit position and velocity data for each design point
        r_e2b_I0s = launch_data[1::2, 1:]

        # number of days since launch for each design point
        LDs = launch_data[1::2, 0] - 2451545

        # build design points
        names = ['pt%s' % i for i in range(npts)]
        for i, name in enumerate(names):
            comp = self.add(
                name, CADRE(n, m, solar_raw1, solar_raw2, comm_raw, power_raw))
            self.driver.workflow.add(name)
            comp.set("LD", LDs[i])
            comp.set("r_e2b_I0", r_e2b_I0s[i])

            # add parameters to driver
            self.driver.add_parameter("%s.CP_Isetpt" % name, low=0., high=0.4)
            self.driver.add_parameter("%s.CP_gamma" % name,
                                      low=0,
                                      high=np.pi / 2.)
            self.driver.add_parameter("%s.CP_P_comm" % name, low=0., high=25.)
            self.driver.add_parameter("%s.iSOC[0]" % name, low=0.2, high=1.)

            # add constraints
            self.driver.add_constraint("%s.ConCh <= 0" % name)
            self.driver.add_constraint("%s.ConDs <= 0" % name)
            self.driver.add_constraint("%s.ConS0 <= 0" % name)
            self.driver.add_constraint("%s.ConS1 <= 0" % name)
            self.driver.add_constraint("%s.SOC[0][0] = %s.SOC[0][-1]" %
                                       (name, name))

        # add parameter groups
        cell_param = ["%s.cellInstd" % name for name in names]
        self.driver.add_parameter(cell_param, low=0, high=1)

        finangles = ["%s.finAngle" % name for name in names]
        self.driver.add_parameter(finangles, low=0, high=np.pi / 2.)

        antangles = ["%s.antAngle" % name for name in names]
        self.driver.add_parameter(antangles, low=-np.pi / 4, high=np.pi / 4)

        # add objective
        obj = ''.join(["-%s.Data[0][-1]" % name for name in names])
        self.driver.add_objective(obj)
예제 #22
0
    def __init__(self, n=1500, m=300):
        super(CADRE_Optimization, self).__init__()

        npts = 6
        # add SNOPT driver
        self.add("driver", pyopt_driver.pyOptDriver())
        self.driver.optimizer = "SNOPT"
        self.driver.options = {'Major optimality tolerance': 1e-8,
                               'Iterations limit': 500000000}

        #self.add("driver", CONMINdriver())

        # specify ground station
        self.add("lon", Float(-83.7264, iotype="in"))
        self.add("lat", Float(42.2708, iotype="in"))
        self.add("alt", Float(0.256, iotype="in"))

        # Raw data to load
        solar_raw1 = np.genfromtxt('CADRE/data/Solar/Area10.txt')
        solar_raw2 = np.loadtxt("CADRE/data/Solar/Area_all.txt")
        comm_rawGdata = np.genfromtxt('CADRE/data/Comm/Gain.txt')
        comm_raw = (10 ** (comm_rawGdata / 10.0)).reshape(
            (361, 361), order='F')
        power_raw = np.genfromtxt('CADRE/data/Power/curve.dat')

        # Initialize analysis points

        LDs = [5233.5, 5294.5, 5356.5, 5417.5, 5478.5, 5537.5]

        r_e2b_I0s = [np.array([4505.29362, -3402.16069, -3943.74582,
                               4.1923899, -1.56280012,  6.14347427]),
                     np.array(
                         [-1005.46693,  -597.205348, -6772.86532, -0.61047858,
                          -7.54623146,  0.75907455]),
                     np.array(
                         [4401.10539,  2275.95053, -4784.13188, -5.26605537,
                          -1.08194926, -5.37013745]),
                     np.array(
                         [-4969.91222,  4624.84149,  1135.9414,  0.1874654,
                          -1.62801666,  7.4302362]),
                     np.array(
                         [-235.021232,  2195.72976,  6499.79919, -2.55956031,
                          -6.82743519,  2.21628099]),
                     np.array(
                         [-690.314375, -1081.78239, -6762.90367,  7.44316722,
                          1.19745345, -0.96035904])]

        for i in xrange(npts):
            aname = ''.join(["pt", str(i)])
            self.add(aname, CADRE(n, m, solar_raw1, solar_raw2,
                                  comm_raw, power_raw))
            self.connect("alt", "pt%s.alt" % str(i))
            self.connect("lon", "pt%s.lon" % str(i))
            self.connect("lat", "pt%s.lat" % str(i))
            self.get(aname).set("LD", LDs[i])
            self.get(aname).set("r_e2b_I0", r_e2b_I0s[i])

            # add parameters to driver
            print "adding parameter: CP_Isetpt.."
            for k in xrange(12):
                for j in xrange(m):
                    param = ''.join(["pt", str(i), ".CP_Isetpt[", str(k), "][",
                                     str(j), "]"])
                    self.driver.add_parameter(param, low=0.2, high=0.4)
            print "adding parameter: CP_gamma.."
            for k in xrange(m):
                param = ''.join(["pt", str(i), ".CP_gamma[", str(k), "]"])
                self.driver.add_parameter(param, low=np.pi / 4,
                                          high=np.pi / 2.)
            print "adding parameter: CP_comm.."
            for k in xrange(m):
                param = ''.join(["pt", str(i), ".CP_P_comm[", str(k), "]"])
                self.driver.add_parameter(param, low=0.1, high=25.)

            param = ''.join(["pt", str(i), ".iSOC[0]"])
            self.driver.add_parameter(param, low=0.2, high=1.)

            # add battery constraints
            constr = ''.join(["pt", str(i), ".ConCh <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".ConDs <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".ConS0 <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".ConS1 <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".SOC[0][0] = pt",
                              str(i), ".SOC[0][-1]"])
            self.driver.add_constraint(constr)

        # add rest of parameters to driver

        print "adding constraint: Cellinstd..."
        for i in xrange(7):
            for k in xrange(12):
                param = [''.join(["pt", str(j), ".cellInstd[", str(i),
                                  "][", str(k), "]"]) for j in xrange(npts)]
                self.driver.add_parameter(param, low=0, high=1)

        finangles = ["pt" + str(i) + ".finAngle" for i in xrange(npts)]
        antangles = ["pt" + str(i) + ".antAngle" for i in xrange(npts)]
        self.driver.add_parameter(finangles, low=0, high=np.pi / 2.)
        self.driver.add_parameter(antangles, low=-np.pi / 4, high=np.pi / 4)

        # add objective
        obj = ''.join([''.join(["-pt", str(i), ".Data[0][-1]"])
                      for i in xrange(npts)])
        self.driver.add_objective(obj)
예제 #23
0
파일: tower.py 프로젝트: pjstanle/TowerSE
    plt.legend(bbox_to_anchor=(1.05, 1.0), loc=2)
    plt.xlabel('utilization')
    plt.ylabel('height along tower (m)')
    plt.show()
    # ------------


    if optimize:

        # --- optimizer imports ---
        from pyopt_driver.pyopt_driver import pyOptDriver
        from openmdao.lib.casehandlers.api import DumpCaseRecorder
        # ----------------------

        # --- Setup Pptimizer ---
        tower.replace('driver', pyOptDriver())
        tower.driver.optimizer = 'SNOPT'
        tower.driver.options = {'Major feasibility tolerance': 1e-6,
                               'Minor feasibility tolerance': 1e-6,
                               'Major optimality tolerance': 1e-5,
                               'Function precision': 1e-8}
        # ----------------------

        # --- Objective ---
        tower.driver.add_objective('tower1.mass / 300000')
        # ----------------------

        # --- Design Variables ---
        tower.driver.add_parameter('z_param[1]', low=0.0, high=87.0)
        tower.driver.add_parameter('d_param[:-1]', low=3.87, high=20.0)
        tower.driver.add_parameter('t_param', low=0.005, high=0.2)
예제 #24
0
    def __init__(self, n=1500, m=300, npts=6):
        super(CADRE_Optimization, self).__init__()

        # add SNOPT driver
        self.add("driver", pyopt_driver.pyOptDriver())
        self.driver.optimizer = "SNOPT"
        self.driver.options = {'Major optimality tolerance': 1e-3,
                               'Iterations limit': 500000000,
                               "New basis file": 10}
        if os.path.exists("fort.10"):
            self.driver.options["Old basis file"] = 10

        #driver = self.add("driver", CONMINdriver())

        # Raw data to load
        fpath = os.path.dirname(os.path.realpath(__file__))
        fpath = os.path.join(fpath, 'data')
        solar_raw1 = np.genfromtxt(fpath + '/Solar/Area10.txt')
        solar_raw2 = np.loadtxt(fpath + '/Solar/Area_all.txt')
        comm_rawGdata = np.genfromtxt(fpath + '/Comm/Gain.txt')
        comm_raw = (10 ** (comm_rawGdata / 10.0)
                    ).reshape((361, 361), order='F')
        power_raw = np.genfromtxt(fpath + '/Power/curve.dat')

        # Load launch data
        launch_data = np.loadtxt(fpath + '/Launch/launch1.dat')

        # orbit position and velocity data for each design point
        r_e2b_I0s = launch_data[1::2, 1:]

        # number of days since launch for each design point
        LDs = launch_data[1::2, 0] - 2451545

        # build design points
        names = ['pt%s' % i for i in range(npts)]
        for i, name in enumerate(names):
            comp = self.add(name, CADRE(n, m, solar_raw1, solar_raw2,
                                        comm_raw, power_raw))
            comp.set("LD", LDs[i])
            comp.set("r_e2b_I0", r_e2b_I0s[i])

            # add parameters to driver
            self.driver.add_parameter("%s.CP_Isetpt" % name, low=0., high=0.4)
            self.driver.add_parameter("%s.CP_gamma" %
                                      name, low=0, high=np.pi / 2.)
            self.driver.add_parameter("%s.CP_P_comm" % name, low=0., high=25.)
            self.driver.add_parameter("%s.iSOC[0]" % name, low=0.2, high=1.)

            # add constraints
            self.driver.add_constraint("%s.ConCh <= 0" % name)
            self.driver.add_constraint("%s.ConDs <= 0" % name)
            self.driver.add_constraint("%s.ConS0 <= 0" % name)
            self.driver.add_constraint("%s.ConS1 <= 0" % name)
            self.driver.add_constraint(
                "%s.SOC[0][0] = %s.SOC[0][-1]" % (name, name))

        # add parameter groups
        cell_param = ["%s.cellInstd" % name for name in names]
        self.driver.add_parameter(cell_param, low=0, high=1)

        finangles = ["%s.finAngle" % name for name in names]
        self.driver.add_parameter(finangles, low=0, high=np.pi / 2.)

        antangles = ["%s.antAngle" % name for name in names]
        self.driver.add_parameter(antangles, low=-np.pi / 4, high=np.pi / 4)

        # add objective
        obj = ''.join(["-%s.Data[0][-1]" % name for name in names])
        self.driver.add_objective(obj)
예제 #25
0
    plt.xlabel('wind speed (m/s)')
    plt.ylabel('power (MW)')
    plt.show()

    # --------------------------


    if optimize:

        # --- optimizer imports ---
        from pyopt_driver.pyopt_driver import pyOptDriver
        from openmdao.lib.casehandlers.api import DumpCaseRecorder
        # ----------------------

        # --- Setup Pptimizer ---
        rotor.replace('driver', pyOptDriver())
        rotor.driver.optimizer = 'SNOPT'
        rotor.driver.options = {'Major feasibility tolerance': 1e-6,
                               'Minor feasibility tolerance': 1e-6,
                               'Major optimality tolerance': 1e-5,
                               'Function precision': 1e-8}
        # ----------------------

        # --- Objective ---
        rotor.driver.add_objective('-aep.AEP/%f' % AEP0)
        # ----------------------

        # --- Design Variables ---
        rotor.driver.add_parameter('r_max_chord', low=0.1, high=0.5)
        rotor.driver.add_parameter('chord_sub', low=0.4, high=5.3)
        rotor.driver.add_parameter('theta_sub', low=-10.0, high=30.0)
예제 #26
0
    plt.plot(rotor.V, rotor.P / 1e6)
    plt.xlabel('wind speed (m/s)')
    plt.ylabel('power (MW)')
    plt.show()

    # --------------------------

    if optimize:

        # --- optimizer imports ---
        from pyopt_driver.pyopt_driver import pyOptDriver
        from openmdao.lib.casehandlers.api import DumpCaseRecorder
        # ----------------------

        # --- Setup Pptimizer ---
        rotor.replace('driver', pyOptDriver())
        rotor.driver.optimizer = 'SNOPT'
        rotor.driver.options = {
            'Major feasibility tolerance': 1e-6,
            'Minor feasibility tolerance': 1e-6,
            'Major optimality tolerance': 1e-5,
            'Function precision': 1e-8
        }
        # ----------------------

        # --- Objective ---
        rotor.driver.add_objective('-aep.AEP/%f' % AEP0)
        # ----------------------

        # --- Design Variables ---
        rotor.driver.add_parameter('r_max_chord', low=0.1, high=0.5)
예제 #27
0
def opt_tower(
    sea_depth=np.array([]),
    hmax_50yr=None,
    tp_50yr=None,
    deck_height=None,
    d_monopile=None,
    t_monopile=None,
    t_jacket=None,
    d_tower_base=None,
    d_tower_top=None,
    t_tower_base=None,
    t_tower_top=None,
):

    mytwr = main()[0]

    MDAOswitch = "md_pysnopt"

    # optimization
    import pyOpt
    from pyopt_driver.pyopt_driver import pyOptDriver
    from openmdao.lib.casehandlers.api import DumpCaseRecorder
    from openmdao.lib.drivers.api import COBYLAdriver

    if MDAOswitch == "md_cobyla":
        mytwr.replace("driver", COBYLAdriver())

        mytwr.driver.rhobeg = 0.01
        mytwr.driver.rhoend = 1.0e-3
        mytwr.driver.maxfun = 2000
        mytwr.driver.iprint = 1
    else:
        mytwr.replace("driver", pyOptDriver())
        if MDAOswitch == "md_pysnopt":
            mytwr.driver.optimizer = "SNOPT"
            mytwr.driver.pyopt_diff = True
            # mytwr.driver.sens_step = 1e-8
            mytwr.driver.options = {
                "Major feasibility tolerance": 1e-4,
                "Minor feasibility tolerance": 1e-4,
                "Major optimality tolerance": 1e-4,
                "Function precision": 1e-6,
            }
        elif MDAOswitch == "md_pyCobyla":
            mytwr.driver.optimizer = "COBYLA"
            mytwr.driver.options = {"RHOEND": 1.0e-2, "RHOEND": 1.0e-3, "MAXFUN": 2000, "IPRINT": 1}
        else:
            sys.exit(
                "Error: MDAOswitch must be set to "
                "pyCobyla"
                " or "
                "pySNOPT"
                " or "
                "md_cobyla"
                " or "
                "md_pySNOPT"
                " or "
                "md_pyCobyla"
                "!!!"
            )
    # ----------------------

    # --- Objective ---
    mytwr.driver.add_objective("(tower1.mass) / 500.e3")
    # ----------------------

    # diameter and thickness variables
    mytwr.driver.add_parameter("d_monopile", low=3.0, high=15.0)  # this is OD monopile
    mytwr.driver.add_parameter("t_monopile", low=0.01, high=0.1)  # this is t of monopile
    mytwr.driver.add_parameter(
        "t_jacket", low=0.01, high=0.1
    )  # this is t of jacket # d jacket fixed by monopile + t_jacket + t_grout

    mytwr.driver.add_parameter("d_tower_base", low=3.0, high=15.0)  # This is OD at the base
    mytwr.driver.add_parameter("t_tower_base", low=0.01, high=0.3)  # This is t at the base

    mytwr.driver.add_parameter("d_tower_top", low=3.87, high=8.0)  # This is OD at the top # OD at top should be fixed
    mytwr.driver.add_parameter("t_tower_top", low=0.01, high=0.1)  # This is t at top

    # node positioning variables
    # mytwr.driver.add_parameter('jp.z[5]', low= 0.0,  high= 0.99) # this is H2 (can't move this - will have to add extra variable to make that happen)

    # --- Constraints ---#
    # frequency
    mytwr.driver.add_constraint("tower1.f1 >= 0.20")  # from 0.28 to 0.26
    # mytwr.driver.add_constraint('tower1.f1 <= 0.30')

    # utilization
    mytwr.driver.add_constraint("tower1.stress <= 1.0")
    mytwr.driver.add_constraint("tower2.stress <= 1.0")
    mytwr.driver.add_constraint("tower1.buckling <= 1.0")
    mytwr.driver.add_constraint("tower2.buckling <= 1.0")
    mytwr.driver.add_constraint("tower1.shellBuckling <= 1.0")
    mytwr.driver.add_constraint("tower2.shellBuckling <= 1.0")
    mytwr.driver.add_constraint("tower1.damage <= 1.0")
    # mytwr.driver.add_constraint('gc.weldability <= 0.0') # this goes for entire structure which we don't want
    # mytwr.driver.add_constraint('gc.manufacturability <= 0.0') # just going to use explicit constraints below

    # uniformity of diameter and thickness of tower
    mytwr.driver.add_constraint("d_tower_top <= d_tower_base")
    mytwr.driver.add_constraint("d_tower_base <= d_monopile")
    # mytwr.driver.add_constraint('d_monopile - d_tower_base <= 0.4')
    mytwr.driver.add_constraint("t_tower_top <= t_tower_base")

    # manufacturing and installation
    mytwr.driver.add_constraint(
        "d_tower_top/d_tower_base >= 0.40"
    )  # manufacturability - already covered; taper ratio for manufacturing
    mytwr.driver.add_constraint(
        "d_tower_base/t_tower_base >= 120.0"
    )  # weldibility - already covered; tower DTR for rolling operation
    mytwr.driver.add_constraint("d_tower_top/t_tower_top >= 120.0")
    # mytwr.driver.add_constraint('d_monopile/t_monopile <= 100.0') # pile DTR for installation
    # mytwr.driver.add_constraint('d_tower_base/t_tower_base <= 200.0') # tower DTR for welding (not covered)
    # mytwr.driver.add_constraint('d_tower_top/t_tower_top <= 200.0')

    ## mytwr.driver.add_constraint('Lp0rat >= 0.') # was for embedment - not in model
    # ----------------------

    # set optimization variables
    if sea_depth.size:

        for i in range(len(sea_depth)):
            mytwr.sea_depth = sea_depth[i]
            mytwr.deck_height = deck_height[i]
            mytwr.wave1.hs = hmax_50yr[i]
            mytwr.wave1.T = tp_50yr[i]
            mytwr.wave2.hs = hmax_50yr[i]
            mytwr.wave2.T = tp_50yr[i]

            # reset to initial conditions for geometry
            mytwr.d_monopile = d_monopile[i]
            mytwr.t_monopile = t_monopile[i]
            mytwr.t_jacket = t_jacket[i]
            mytwr.d_tower_base = d_tower_base[i]
            mytwr.d_tower_top = d_tower_top[i]
            mytwr.t_tower_base = t_tower_base[i]
            mytwr.t_tower_top = t_tower_top[i]

            # print IC
            print "Initial condition\n"
            print "sea_depth=", mytwr.sea_depth
            print "deck_height=", mytwr.deck_height
            print "significant wave height=", mytwr.wave1.hs
            print "wave period=", mytwr.wave1.T
            print "d_monopile=", mytwr.d_monopile
            print "t_monopile=", mytwr.t_monopile
            print "t_jacket=", mytwr.t_jacket
            print "d_tower_base=", mytwr.d_tower_base
            print "d_tower_top=", mytwr.d_tower_top
            print "t_tower_base=", mytwr.t_tower_base
            print "t_tower_top=", mytwr.t_tower_top

            mytwr.driver.options.update(
                {"Summary file": "Case_" + str(i) + "_summary.out", "Print file": "Case_" + str(i) + "_print.out"}
            )

            if sea_depth[i] > 60.0:  # deepwater case
                mytwr.driver.options["Major optimality tolerance"] = 1e-3
            else:
                mytwr.driver.options["Major optimality tolerance"] = 1e-3

            # RUN
            import time

            tt = time.time()
            mytwr.run()

            print "Final conditions"
            print "Minimum found at Db=%f, Dt=%f, tb=%f, tt=%f; mass= (%f)" % (
                mytwr.tower1.d[0],
                mytwr.tower1.d[-1],
                mytwr.tower1.t[0],
                mytwr.tower1.t[-1],
                mytwr.tower1.mass,
            )
            print "Minimum found at z1=%f, D1=%f, t1=%f" % (mytwr.tower1.z[1], mytwr.tower1.d[1], mytwr.tower1.t[1])
            print "Minimum found at DTRb DTRt(%f, %f)" % (
                mytwr.tower1.d[0] / mytwr.tower1.t[0],
                mytwr.tower1.d[-1] / mytwr.tower1.t[-1],
            )

            print "\n"
            # print FC
            print "d_monopile=", mytwr.d_monopile
            print "t_monopile=", mytwr.t_monopile
            print "t_jacket=", mytwr.t_jacket
            print "d_tower_base=", mytwr.d_tower_base
            print "d_tower_top=", mytwr.d_tower_top
            print "t_tower_base=", mytwr.t_tower_base
            print "t_tower_top=", mytwr.t_tower_top
            print "zs=", mytwr.tower1.z
            print "ds=", mytwr.tower1.d
            print "ts=", mytwr.tower1.t

            print "\n"
            print "Minimum found at Freq %f" % (mytwr.tower1.f1)
            print "Minimum found at GLutil EUutil %f %f" % (
                np.max(np.vstack((mytwr.tower1.buckling, mytwr.tower2.buckling))),
                np.max(np.vstack((mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling))),
            )
            print "Minimum found at GLutil 1 and 2", mytwr.tower1.buckling, mytwr.tower2.buckling
            print "Minimum found at EUutil 1 and 2", mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling

            print "Elapsed time: ", time.time() - tt, "seconds\n"

            # Plot
            PlotTower(mytwr, util=True, savefileroot=str(i))

    else:

        # RUN
        import time

        tt = time.time()
        mytwr.run()

        print "\n"
        print "Minimum found at Db=%f, Dt=%f, tb=%f, tt=%f; mass= (%f)" % (
            mytwr.tower1.d[0],
            mytwr.tower1.d[-1],
            mytwr.tower1.t[0],
            mytwr.tower1.t[-1],
            mytwr.tower1.mass,
        )
        print "Minimum found at z1=%f, D1=%f, t1=%f" % (mytwr.tower1.z[1], mytwr.tower1.d[1], mytwr.tower1.t[1])
        print "Minimum found at DTRb DTRt(%f, %f)" % (
            mytwr.tower1.d[0] / mytwr.tower1.t[0],
            mytwr.tower1.d[-1] / mytwr.tower1.t[-1],
        )

        print "\n"
        print "zs=", mytwr.tower1.z
        print "ds=", mytwr.tower1.d
        print "ts=", mytwr.tower1.t

        print "\n"
        print "Minimum found at Freq %f" % (mytwr.tower1.f1)
        print "Minimum found at GLutil EUutil %f %f" % (
            np.max(np.vstack((mytwr.tower1.buckling, mytwr.tower2.buckling))),
            np.max(np.vstack((mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling))),
        )
        print "Minimum found at GLutil 1 and 2", mytwr.tower1.buckling, mytwr.tower2.buckling
        print "Minimum found at EUutil 1 and 2", mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling

        print "Elapsed time: ", time.time() - tt, "seconds"
        print "Execution count: ", mytwr.exec_count

        # Plot
        PlotTower(mytwr, util=True)

        print mytwr.jp.z
        print mytwr.jp.towerHeight
        print (mytwr.jp.z * mytwr.jp.towerHeight) - (mytwr.d_monopile * 1.5 - mytwr.monopile_extension)
        print mytwr.z_nodes
예제 #28
0
    def configure(self):
        # add an optimizer and a multi-point AeroStructural assembly
        if pyopt_driver and 'SNOPT' in pyopt_driver._check_imports():
            self.add("driver", pyopt_driver.pyOptDriver())
            self.driver.optimizer = "SNOPT"
            self.driver.options = {
                # any changes to default SNOPT options?
            }
        else:
            print 'SNOPT not available, using SLSQP'
            self.add('driver', SLSQPdriver())

        # Nothing has anlytical derivaties, but we have a lot of
        # nested assemblies, so it is less problematic to just
        # finite difference it all in one block.
        #self.driver.gradient_options.force_fd = True
        #self.driver.gradient_options.fd_step_type = 'relative'
        #self.driver.gradient_options.fd_step = 1.0e-7
        #self.driver.pyopt_diff = True

        self.add('mp', Multipoint())

        self.mp.alt_low = 0.5         # low altitude
        self.mp.alt_high = 3.5        # high altitude
        self.mp.alt_ratio = 35./60.   # proportion of time near ground

        self.mp.TWire_high = 900
        self.mp.TWire_wind = 2100
        self.mp.TWire_grav = 110

        self.mp.OmegaRatio  = 2

        self.mp.vw = 0/3.6   # zero

        self.mp.Cl_max = [1.4, 1.35, 1.55]    # max control

        # objective: minimize total power
        self.driver.add_objective('mp.P')

        # parameter: rotor speed
        self.driver.add_parameter('mp.Omega_low',
                                  low=0.15*2*pi, high=0.25*2*pi)
        self.mp.Omega_low = 0.20*2*pi  # initial value

        self.driver.add_parameter('mp.Omega_high',
                                  low=0.15*2*pi, high=0.19*2*pi)
        self.mp.Omega_high = 0.17*2*pi  # initial value

        # parameter: lift distribution at high altitude
        self.driver.add_parameter('mp.Cl0_high',
                                  low=0.8, high=1.4)
        self.mp.Cl0_high = 1.

        self.driver.add_parameter('mp.Cl1_high',
                                  low=0.8, high=1.3)
        self.mp.Cl1_high = 1.

        # constraint: lift >= weight
        self.driver.add_constraint('mp.Mtot_low*9.8-mp.Ttot_low<=0')
        self.driver.add_constraint('mp.Mtot_high*9.8-mp.Ttot_high<=0')

        # TODO: optional constraints
        #    if flags.ConFail:
        #       Structural Failure in Rotor Spar (ConFail)
        #       Buckling failure of spar (ConFailBuck)
        #       Tensile failure in wire (ConFailWire)
        #
        #    if flags.ConDef:
        #       Constraints on Maximum Deformation (ConDelta)
        #
        #    if flags.MultiPoint && flags.ConJigCont:
        #       Consistent jig twist (ConAlphaJig)
        #
        #    if flags.MultiPoint && flags.ConWireCont
        #       Wire stretch consistency (conWire)

        # Optimization Constraints  (not used... yet)
        vrCon = VariableTree()
        vrCon.MaxDelta    = -0.1
        vrCon.MinDelta    = 0.1
        vrCon.FOSmat      = 0.55    # 1.3
        vrCon.FOSbuck     = 0.5     # 1.3
        vrCon.FOSquadbuck = 5.
        vrCon.FOStorbuck  = 0.5     # 1.5
        vrCon.FOSwire     = 0.5     # 2

        self.driver.workflow.add('mp')
예제 #29
0
def opt_tower(sea_depth=np.array([]), hmax_50yr=None, tp_50yr=None, deck_height=None, d_monopile=None, t_monopile=None, t_jacket=None, \
              d_tower_base=None, d_tower_top=None, t_tower_base=None, t_tower_top=None):

    mytwr = main()[0]

    MDAOswitch = 'md_pysnopt'

    # optimization
    import pyOpt
    from pyopt_driver.pyopt_driver import pyOptDriver
    from openmdao.lib.casehandlers.api import DumpCaseRecorder
    from openmdao.lib.drivers.api import COBYLAdriver

    if MDAOswitch == 'md_cobyla':
        mytwr.replace('driver', COBYLAdriver())

        mytwr.driver.rhobeg = 0.01
        mytwr.driver.rhoend = 1.e-3
        mytwr.driver.maxfun = 2000
        mytwr.driver.iprint = 1
    else:
        mytwr.replace('driver', pyOptDriver())
        if MDAOswitch == 'md_pysnopt':
            mytwr.driver.optimizer = 'SNOPT'
            mytwr.driver.pyopt_diff = True
            #mytwr.driver.sens_step = 1e-8
            mytwr.driver.options = {
                'Major feasibility tolerance': 1e-4,
                'Minor feasibility tolerance': 1e-4,
                'Major optimality tolerance': 1e-4,
                'Function precision': 1e-6
            }
        elif MDAOswitch == 'md_pyCobyla':
            mytwr.driver.optimizer = 'COBYLA'
            mytwr.driver.options = {
                'RHOEND': 1.e-2,
                'RHOEND': 1.e-3,
                'MAXFUN': 2000,
                'IPRINT': 1
            }
        else:
            sys.exit('Error: MDAOswitch must be set to '
                     'pyCobyla'
                     ' or '
                     'pySNOPT'
                     ' or '
                     'md_cobyla'
                     ' or '
                     'md_pySNOPT'
                     ' or '
                     'md_pyCobyla'
                     '!!!')
    # ----------------------

    # --- Objective ---
    mytwr.driver.add_objective('(tower1.mass) / 500.e3')
    # ----------------------

    #diameter and thickness variables
    mytwr.driver.add_parameter('d_monopile', low=3.0,
                               high=15.0)  # this is OD monopile
    mytwr.driver.add_parameter('t_monopile', low=0.01,
                               high=0.1)  # this is t of monopile
    mytwr.driver.add_parameter(
        't_jacket', low=0.01, high=0.1
    )  # this is t of jacket # d jacket fixed by monopile + t_jacket + t_grout

    mytwr.driver.add_parameter('d_tower_base', low=3.0,
                               high=15.0)  #This is OD at the base
    mytwr.driver.add_parameter('t_tower_base', low=0.01,
                               high=0.3)  #This is t at the base

    mytwr.driver.add_parameter(
        'd_tower_top', low=3.87,
        high=8.0)  #This is OD at the top # OD at top should be fixed
    mytwr.driver.add_parameter('t_tower_top', low=0.01,
                               high=0.1)  #This is t at top

    # node positioning variables
    #mytwr.driver.add_parameter('jp.z[5]', low= 0.0,  high= 0.99) # this is H2 (can't move this - will have to add extra variable to make that happen)

    #--- Constraints ---#
    # frequency
    mytwr.driver.add_constraint('tower1.f1 >= 0.20')  # from 0.28 to 0.26
    #mytwr.driver.add_constraint('tower1.f1 <= 0.30')

    # utilization
    mytwr.driver.add_constraint('tower1.stress <= 1.0')
    mytwr.driver.add_constraint('tower2.stress <= 1.0')
    mytwr.driver.add_constraint('tower1.buckling <= 1.0')
    mytwr.driver.add_constraint('tower2.buckling <= 1.0')
    mytwr.driver.add_constraint('tower1.shellBuckling <= 1.0')
    mytwr.driver.add_constraint('tower2.shellBuckling <= 1.0')
    mytwr.driver.add_constraint('tower1.damage <= 1.0')
    #mytwr.driver.add_constraint('gc.weldability <= 0.0') # this goes for entire structure which we don't want
    #mytwr.driver.add_constraint('gc.manufacturability <= 0.0') # just going to use explicit constraints below

    # uniformity of diameter and thickness of tower
    mytwr.driver.add_constraint('d_tower_top <= d_tower_base')
    mytwr.driver.add_constraint('d_tower_base <= d_monopile')
    #mytwr.driver.add_constraint('d_monopile - d_tower_base <= 0.4')
    mytwr.driver.add_constraint('t_tower_top <= t_tower_base')

    # manufacturing and installation
    mytwr.driver.add_constraint(
        'd_tower_top/d_tower_base >= 0.40'
    )  # manufacturability - already covered; taper ratio for manufacturing
    mytwr.driver.add_constraint(
        'd_tower_base/t_tower_base >= 120.0'
    )  # weldibility - already covered; tower DTR for rolling operation
    mytwr.driver.add_constraint('d_tower_top/t_tower_top >= 120.0')
    #mytwr.driver.add_constraint('d_monopile/t_monopile <= 100.0') # pile DTR for installation
    #mytwr.driver.add_constraint('d_tower_base/t_tower_base <= 200.0') # tower DTR for welding (not covered)
    #mytwr.driver.add_constraint('d_tower_top/t_tower_top <= 200.0')

    ## mytwr.driver.add_constraint('Lp0rat >= 0.') # was for embedment - not in model
    # ----------------------

    # set optimization variables
    if sea_depth.size:

        for i in range(len(sea_depth)):
            mytwr.sea_depth = sea_depth[i]
            mytwr.deck_height = deck_height[i]
            mytwr.wave1.hs = hmax_50yr[i]
            mytwr.wave1.T = tp_50yr[i]
            mytwr.wave2.hs = hmax_50yr[i]
            mytwr.wave2.T = tp_50yr[i]

            #reset to initial conditions for geometry
            mytwr.d_monopile = d_monopile[i]
            mytwr.t_monopile = t_monopile[i]
            mytwr.t_jacket = t_jacket[i]
            mytwr.d_tower_base = d_tower_base[i]
            mytwr.d_tower_top = d_tower_top[i]
            mytwr.t_tower_base = t_tower_base[i]
            mytwr.t_tower_top = t_tower_top[i]

            # print IC
            print 'Initial condition\n'
            print 'sea_depth=', mytwr.sea_depth
            print 'deck_height=', mytwr.deck_height
            print 'significant wave height=', mytwr.wave1.hs
            print 'wave period=', mytwr.wave1.T
            print 'd_monopile=', mytwr.d_monopile
            print 't_monopile=', mytwr.t_monopile
            print 't_jacket=', mytwr.t_jacket
            print 'd_tower_base=', mytwr.d_tower_base
            print 'd_tower_top=', mytwr.d_tower_top
            print 't_tower_base=', mytwr.t_tower_base
            print 't_tower_top=', mytwr.t_tower_top

            mytwr.driver.options.update({
                'Summary file':
                'Case_' + str(i) + '_summary.out',
                'Print file':
                'Case_' + str(i) + '_print.out'
            })

            if sea_depth[i] > 60.0:  # deepwater case
                mytwr.driver.options['Major optimality tolerance'] = 1e-3
            else:
                mytwr.driver.options['Major optimality tolerance'] = 1e-3

            #RUN
            import time
            tt = time.time()
            mytwr.run()

            print "Final conditions"
            print "Minimum found at Db=%f, Dt=%f, tb=%f, tt=%f; mass= (%f)" % (
                mytwr.tower1.d[0], mytwr.tower1.d[-1], mytwr.tower1.t[0],
                mytwr.tower1.t[-1], mytwr.tower1.mass)
            print "Minimum found at z1=%f, D1=%f, t1=%f" % (
                mytwr.tower1.z[1], mytwr.tower1.d[1], mytwr.tower1.t[1])
            print "Minimum found at DTRb DTRt(%f, %f)" % (
                mytwr.tower1.d[0] / mytwr.tower1.t[0],
                mytwr.tower1.d[-1] / mytwr.tower1.t[-1])

            print "\n"
            # print FC
            print 'd_monopile=', mytwr.d_monopile
            print 't_monopile=', mytwr.t_monopile
            print 't_jacket=', mytwr.t_jacket
            print 'd_tower_base=', mytwr.d_tower_base
            print 'd_tower_top=', mytwr.d_tower_top
            print 't_tower_base=', mytwr.t_tower_base
            print 't_tower_top=', mytwr.t_tower_top
            print 'zs=', mytwr.tower1.z
            print 'ds=', mytwr.tower1.d
            print 'ts=', mytwr.tower1.t

            print "\n"
            print "Minimum found at Freq %f" % (mytwr.tower1.f1)
            print "Minimum found at GLutil EUutil %f %f" % (
                np.max(
                    np.vstack((mytwr.tower1.buckling, mytwr.tower2.buckling))),
                np.max(
                    np.vstack((mytwr.tower1.shellBuckling,
                               mytwr.tower2.shellBuckling))))
            print "Minimum found at GLutil 1 and 2", mytwr.tower1.buckling, mytwr.tower2.buckling
            print "Minimum found at EUutil 1 and 2", mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling

            print "Elapsed time: ", time.time() - tt, "seconds\n"

            #Plot
            PlotTower(mytwr, util=True, savefileroot=str(i))

    else:

        #RUN
        import time
        tt = time.time()
        mytwr.run()

        print "\n"
        print "Minimum found at Db=%f, Dt=%f, tb=%f, tt=%f; mass= (%f)" % (
            mytwr.tower1.d[0], mytwr.tower1.d[-1], mytwr.tower1.t[0],
            mytwr.tower1.t[-1], mytwr.tower1.mass)
        print "Minimum found at z1=%f, D1=%f, t1=%f" % (
            mytwr.tower1.z[1], mytwr.tower1.d[1], mytwr.tower1.t[1])
        print "Minimum found at DTRb DTRt(%f, %f)" % (
            mytwr.tower1.d[0] / mytwr.tower1.t[0],
            mytwr.tower1.d[-1] / mytwr.tower1.t[-1])

        print "\n"
        print 'zs=', mytwr.tower1.z
        print 'ds=', mytwr.tower1.d
        print 'ts=', mytwr.tower1.t

        print "\n"
        print "Minimum found at Freq %f" % (mytwr.tower1.f1)
        print "Minimum found at GLutil EUutil %f %f" % (
            np.max(np.vstack((mytwr.tower1.buckling, mytwr.tower2.buckling))),
            np.max(
                np.vstack(
                    (mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling))))
        print "Minimum found at GLutil 1 and 2", mytwr.tower1.buckling, mytwr.tower2.buckling
        print "Minimum found at EUutil 1 and 2", mytwr.tower1.shellBuckling, mytwr.tower2.shellBuckling

        print "Elapsed time: ", time.time() - tt, "seconds"
        print "Execution count: ", mytwr.exec_count

        #Plot
        PlotTower(mytwr, util=True)

        print mytwr.jp.z
        print mytwr.jp.towerHeight
        print(mytwr.jp.z * mytwr.jp.towerHeight) - (mytwr.d_monopile * 1.5 -
                                                    mytwr.monopile_extension)
        print mytwr.z_nodes
예제 #30
0
    plt.legend(bbox_to_anchor=(1.05, 1.0), loc=2)
    plt.xlabel('utilization')
    plt.ylabel('height along tower (m)')
    plt.show()
    # ------------


    if optimize:

        # --- optimizer imports ---
        from pyopt_driver.pyopt_driver import pyOptDriver
        from openmdao.lib.casehandlers.api import DumpCaseRecorder
        # ----------------------

        # --- Setup Pptimizer ---
        tower.replace('driver', pyOptDriver())
        tower.driver.optimizer = 'SNOPT'
        tower.driver.options = {'Major feasibility tolerance': 1e-6,
                               'Minor feasibility tolerance': 1e-6,
                               'Major optimality tolerance': 1e-5,
                               'Function precision': 1e-8}
        # ----------------------

        # --- Objective ---
        tower.driver.add_objective('tower1.mass / 300000')
        # ----------------------

        # --- Design Variables ---
        tower.driver.add_parameter('z_param[1]', low=0.0, high=87.0)
        tower.driver.add_parameter('d_param[:-1]', low=3.87, high=20.0)
        tower.driver.add_parameter('t_param', low=0.005, high=0.2)
    def configure(self):

        #Components
        self.add("DeformationCavity_meta",FoamMetaModel())
        self.DeformationCavity_meta.includes=['x1','x2','f1','f2']
        
        self.DeformationCavity_meta.model = DeformationCavity()
        self.DeformationCavity_meta.default_surrogate = ResponseSurface()
        
        self.DeformationCavity_meta.surrogates["f1.latestTimeValue"] = FloatKrigingSurrogate()
        self.DeformationCavity_meta.surrogates["f2.latestTimeValue"] = FloatKrigingSurrogate()
        self.DeformationCavity_meta.surrogates["f1.latestTimeValue"].nugget = 0.0
        self.DeformationCavity_meta.surrogates["f2.latestTimeValue"].nugget = 0.0
        
        
        self.DeformationCavity_meta.recorder = DBCaseRecorder()

        #Training the MetaModel
        self.add("DOE_Trainer",DOEdriver())
        self.DOE_Trainer.DOEgenerator = FullFactorial()
        self.DOE_Trainer.DOEgenerator.num_levels = 4
        self.DOE_Trainer.add_parameter('DeformationCavity_meta.x1', low= -0.1, high=0.1)
        self.DOE_Trainer.add_parameter('DeformationCavity_meta.x2', low=  0.9, high=1.1)
        
        self.DOE_Trainer.case_outputs = ["DeformationCavity_meta.f1.latestTimeValue",
                                        "DeformationCavity_meta.f2.latestTimeValue"]
        
        self.DOE_Trainer.record_doe = False                                
        self.DOE_Trainer.add_event("DeformationCavity_meta.train_next")
        self.DOE_Trainer.recorders = [DBCaseRecorder()]

        #MetaModel Validation
        self.add("DeformationCavity", DeformationCavity())
        self.add("DOE_Validate", DOEdriver())
        self.DOE_Validate.DOEgenerator = FullFactorial()
        self.DOE_Validate.DOEgenerator.num_levels = 3
        self.DOE_Validate.add_parameter(("DeformationCavity_meta.x1", "DeformationCavity.x1"), low=-0.1, high=0.1)
        self.DOE_Validate.add_parameter(("DeformationCavity_meta.x2", "DeformationCavity.x2"), low= 0.9, high=1.1)
                                     
        self.DOE_Validate.case_outputs = ["DeformationCavity.f1.latestTimeValue",
                                          "DeformationCavity.f2.latestTimeValue",
                                          "DeformationCavity_meta.f1.latestTimeValue", 
                                          "DeformationCavity_meta.f2.latestTimeValue"]
                                        
        self.DOE_Validate.record_doe = False                                
        self.DOE_Validate.recorders = [DBCaseRecorder()]
        
        # Create NSGA2 Optimizer instance
        self.add('NSGA2', pyOptDriver())
        self.NSGA2.print_results = True

        # NSGA2 Objective
        self.NSGA2.add_objective('DeformationCavity_meta.f1.latestTimeValue')
        self.NSGA2.add_objective('DeformationCavity_meta.f2.latestTimeValue')
        # NSGA2 Design Variable
        self.NSGA2.add_parameter('DeformationCavity_meta.x1', low=-0.1, high=0.1)
        self.NSGA2.add_parameter('DeformationCavity_meta.x2', low= 0.9, high=1.1)
        # NSGA2 Constraints
#        self.NSGA2.add_constraint('DeformationCavity_meta.x2 - DeformationCavity_meta.x1 >= 1.0')

        self.NSGA2.optimizer = 'NSGA2'
        optdict = {}
        optdict['PopSize'] = 100     #   a multiple of 4
        optdict['maxGen'] = 5
        optdict['pCross_real'] = 0.6 #prob of crossover of design variables in range (0.6-1.0)
        optdict['pMut_real'] = 0.5   #prob of mutation of (1/design varaibles)
        optdict['eta_c'] = 10.0      #distribution index for crossover in range (5 - 20)
        optdict['eta_m'] = 50.0      #distribution index for mutation in range (5 - 50)
        optdict['pCross_bin'] = 1.0  #prob of crossover of binary variable in range(0.6 - 1.0)
        optdict['pMut_real'] = 1.0   #prob of mutation of binary variables in (1/nbits)
        optdict['PrintOut'] = 1      #flag to turn on output to files (0-None, 1-Subset,2-All)
        optdict['seed'] = 0.0        #random seed number (0-autoseed based on time clock)

        self.NSGA2.options = optdict
                
        #Iteration Hierarchy
        self.driver.workflow = SequentialWorkflow()
        self.driver.workflow.add(['DOE_Trainer','DOE_Validate','NSGA2'])
        self.DOE_Trainer.workflow.add('DeformationCavity_meta')
        self.DOE_Validate.workflow.add('DeformationCavity_meta')
        self.DOE_Validate.workflow.add('DeformationCavity')
        # Driver process definition
        self.NSGA2.workflow.add('DeformationCavity_meta') 
예제 #32
0
    def configure(self):
        # add an optimizer and a multi-point AeroStructural assembly
        if pyopt_driver and 'SNOPT' in pyopt_driver._check_imports():
            self.add("driver", pyopt_driver.pyOptDriver())
            self.driver.optimizer = "SNOPT"
            self.driver.options = {
                # any changes to default SNOPT options?
            }
        else:
            print 'SNOPT not available, using SLSQP'
            self.add('driver', SLSQPdriver())

        self.add('mp', Multipoint())

        self.mp.alt_low = 0.5  # low altitude
        self.mp.alt_high = 3.5  # high altitude
        self.mp.alt_ratio = 35. / 60.  # proportion of time near ground

        self.mp.TWire_high = 900
        self.mp.TWire_wind = 2100
        self.mp.TWire_grav = 110

        self.mp.OmegaRatio = 2

        self.mp.vw = 0 / 3.6  # zero

        self.mp.Cl_max = [1.4, 1.35, 1.55]  # max control

        # objective: minimize total power
        self.driver.add_objective('mp.P')

        # parameter: rotor speed
        self.driver.add_parameter('mp.Omega_low',
                                  low=0.15 * 2 * pi,
                                  high=0.25 * 2 * pi)
        self.mp.Omega_low = 0.20 * 2 * pi  # initial value

        self.driver.add_parameter('mp.Omega_high',
                                  low=0.15 * 2 * pi,
                                  high=0.19 * 2 * pi)
        self.mp.Omega_high = 0.17 * 2 * pi  # initial value

        # parameter: lift distribution at high altitude
        self.driver.add_parameter('mp.Cl0_high', low=0.8, high=1.4)
        self.mp.Cl0_high = 1.

        self.driver.add_parameter('mp.Cl1_high', low=0.8, high=1.3)
        self.mp.Cl1_high = 1.

        # constraint: lift >= weight
        self.driver.add_constraint('mp.Mtot_low*9.8-mp.Ttot_low<=0')
        self.driver.add_constraint('mp.Mtot_high*9.8-mp.Ttot_high<=0')

        # TODO: optional constraints
        #    if flags.ConFail:
        #       Structural Failure in Rotor Spar (ConFail)
        #       Buckling failure of spar (ConFailBuck)
        #       Tensile failure in wire (ConFailWire)
        #
        #    if flags.ConDef:
        #       Constraints on Maximum Deformation (ConDelta)
        #
        #    if flags.MultiPoint && flags.ConJigCont:
        #       Consistent jig twist (ConAlphaJig)
        #
        #    if flags.MultiPoint && flags.ConWireCont
        #       Wire stretch consistency (conWire)

        # Optimization Constraints  (not used... yet)
        vrCon = VariableTree()
        vrCon.MaxDelta = -0.1
        vrCon.MinDelta = 0.1
        vrCon.FOSmat = 0.55  # 1.3
        vrCon.FOSbuck = 0.5  # 1.3
        vrCon.FOSquadbuck = 5.
        vrCon.FOStorbuck = 0.5  # 1.5
        vrCon.FOSwire = 0.5  # 2
예제 #33
0
    def __init__(self, n=1500, m=300, npts=6):
        super(CADRE_Optimization, self).__init__()

        # add SNOPT driver
        self.add("driver", pyopt_driver.pyOptDriver())
        self.driver.optimizer = "SNOPT"
        self.driver.options = {'Major optimality tolerance': 1e-4,
                               'Iterations limit': 500000000,
                               "New basis file": 10}
        if os.path.exists("fort.10"):
            self.driver.options["Old basis file"] = 10

        #self.add("driver", CONMINdriver())

        # Raw data to load
        fpath = os.path.dirname(os.path.realpath(__file__))
        solar_raw1 = np.genfromtxt(fpath + '/data/Solar/Area10.txt')
        solar_raw2 = np.loadtxt(fpath + "/data/Solar/Area_all.txt")
        comm_rawGdata = np.genfromtxt(fpath + '/data/Comm/Gain.txt')
        comm_raw = (10 ** (comm_rawGdata / 10.0)).reshape(
            (361, 361), order='F')
        power_raw = np.genfromtxt(fpath + '/data/Power/curve.dat')

        # Load launch data
        launch_data = np.loadtxt(fpath + "/data/Launch/launch1.dat")

        # orbit position and velocity data for each design point
        r_e2b_I0s = launch_data[1::2, 1:]

        # number of days since launch for each design point
        LDs = launch_data[1::2, 0] - 2451545

        # LDs = [5233.5, 5294.5, 5356.5, 5417.5, 5478.5, 5537.5]

        # r_e2b_I0s = [np.array([4505.29362, -3402.16069, -3943.74582,
        #                        4.1923899, -1.56280012,  6.14347427]),
        #              np.array(
        #                  [-1005.46693,  -597.205348, -6772.86532, -0.61047858,
        #                   -7.54623146,  0.75907455]),
        #              np.array(
        #                  [4401.10539,  2275.95053, -4784.13188, -5.26605537,
        #                   -1.08194926, -5.37013745]),
        #              np.array(
        #                  [-4969.91222,  4624.84149,  1135.9414,  0.1874654,
        #                   -1.62801666,  7.4302362]),
        #              np.array(
        #                  [-235.021232,  2195.72976,  6499.79919, -2.55956031,
        #                   -6.82743519,  2.21628099]),
        #              np.array(
        #                  [-690.314375, -1081.78239, -6762.90367,  7.44316722,
        #                   1.19745345, -0.96035904])]

        # build design points
        for i in xrange(npts):
            i_ = str(i)
            aname = ''.join(["pt", str(i)])
            self.add(aname, CADRE(n, m, solar_raw1, solar_raw2,
                                  comm_raw, power_raw))
            self.get(aname).set("LD", LDs[i])
            self.get(aname).set("r_e2b_I0", r_e2b_I0s[i])

            # add parameters to driver
            self.driver.add_parameter("pt%s.CP_Isetpt" % i_, low=0., high=0.4)

            self.driver.add_parameter("pt%s.CP_gamma" % i_, low=0,
                                      high=np.pi / 2.)

            self.driver.add_parameter("pt%s.CP_P_comm" % i_, low=0., high=25.)

            param = ''.join(["pt", str(i), ".iSOC[0]"])
            self.driver.add_parameter(param, low=0.2, high=1.)

            # add constraints
            constr = ''.join(["pt", str(i), ".ConCh <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".ConDs <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".ConS0 <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".ConS1 <= 0"])
            self.driver.add_constraint(constr)

            constr = ''.join(["pt", str(i), ".SOC[0][0] = pt",
                              str(i), ".SOC[0][-1]"])
            self.driver.add_constraint(constr)

        cell_param = ["pt%s.cellInstd" % str(i) for i in xrange(npts)]
        self.driver.add_parameter(cell_param, low=0, high=1)

        finangles = ["pt" + str(i) + ".finAngle" for i in xrange(npts)]
        antangles = ["pt" + str(i) + ".antAngle" for i in xrange(npts)]
        self.driver.add_parameter(finangles, low=0, high=np.pi / 2.)
        self.driver.add_parameter(antangles, low=-np.pi / 4, high=np.pi / 4)

        # add objective
        obj = ''.join([''.join(["-pt", str(i), ".Data[0][-1]"])
                      for i in xrange(npts)])
        self.driver.add_objective(obj)