Exemplo n.º 1
0
import numpy as np

from openmdao.api import ExecComp, IndepVarComp, Group, NLGaussSeidel, \
                         Component, ParallelGroup, ScipyGMRES
from openmdao.api import Problem, ScipyOptimizer
from openmdao.test.mpi_util import MPITestCase
from openmdao.test.util import assert_rel_error, ConcurrentTestCaseMixin, \
                               set_pyoptsparse_opt

try:
    from openmdao.solvers.petsc_ksp import PetscKSP
    from openmdao.core.petsc_impl import PetscImpl as impl
except ImportError:
    impl = None

OPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')

if OPTIMIZER:
    from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver


class SellarDis1(Component):
    """Component containing Discipline 1."""

    def __init__(self, problem_id=0):
        super(SellarDis1, self).__init__()

        self.problem_id = problem_id

        # Global Design Variable
        self.add_param('z', val=np.zeros(2))
Exemplo n.º 2
0
import numpy as np

from openmdao.api import ExecComp, IndepVarComp, Group, NLGaussSeidel, \
                         Component, ParallelGroup, ScipyGMRES
from openmdao.api import Problem, ScipyOptimizer
from openmdao.test.mpi_util import MPITestCase
from openmdao.test.util import assert_rel_error, ConcurrentTestCaseMixin, \
                               set_pyoptsparse_opt

try:
    from openmdao.solvers.petsc_ksp import PetscKSP
    from openmdao.core.petsc_impl import PetscImpl as impl
except ImportError:
    impl = None

OPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')

if OPTIMIZER:
    from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver


class SellarDis1(Component):
    """Component containing Discipline 1."""
    def __init__(self, problem_id=0):
        super(SellarDis1, self).__init__()

        self.problem_id = problem_id

        # Global Design Variable
        self.add_param('z', val=np.zeros(2))
Exemplo n.º 3
0
import numpy as np
from numpy.testing import assert_allclose

from openmdao.api import Problem, SqliteRecorder, ScipyOptimizer
from openmdao.core.vec_wrapper import _ByObjWrapper
from openmdao.test.converge_diverge import ConvergeDiverge
from openmdao.test.example_groups import ExampleGroup
from openmdao.test.sellar import SellarDerivativesGrouped
from openmdao.test.util import assert_rel_error, set_pyoptsparse_opt
from openmdao.util.record_util import format_iteration_coordinate

from openmdao.recorders.sqlite_recorder import format_version

# check that pyoptsparse is installed
# if it is, try to use SNOPT but fall back to SLSQP
OPT, OPTIMIZER = set_pyoptsparse_opt("SNOPT")

if OPTIMIZER:
    from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver


def run_problem(problem):
    t0 = time.time()
    problem.run()
    t1 = time.time()

    return t0, t1


def _assertIterationDataRecorded(test, db, expected, tolerance):
    sentinel = object()
Exemplo n.º 4
0
    def test_discs(self):

        OPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')

        if OPTIMIZER is not 'SNOPT':
            raise unittest.SkipTest("pyoptsparse is not providing SNOPT or SLSQP")

        # So we compare the same starting locations.
        np.random.seed(123)

        radius = 1.0
        pin = 15.0
        n_disc = 7

        prob = Problem()
        prob.root = root = Group()

        from openmdao.api import pyOptSparseDriver
        driver = prob.driver = pyOptSparseDriver()
        driver.options['optimizer'] = 'SNOPT'
        driver.options['print_results'] = False

        # Note, active tolerance requires relevance reduction to work.
        root.ln_solver.options['single_voi_relevance_reduction'] = True

        # Also, need to be in adjoint
        root.ln_solver.options['mode'] = 'rev'

        obj_expr = 'obj = '
        sep = ''
        for i in range(n_disc):

            dist = "dist_%d" % i
            x1var = 'x_%d' % i

            # First disc is pinned
            if i == 0:
                root.add('p_%d' % i, IndepVarComp(x1var, pin), promotes=(x1var, ))

            # The rest are design variables for the optimizer.
            else:
                init_val = 5.0*np.random.random() - 5.0 + pin
                root.add('p_%d' % i, IndepVarComp(x1var, init_val), promotes=(x1var, ))
                driver.add_desvar(x1var)

            for j in range(i):

                x2var = 'x_%d' % j
                yvar = 'y_%d_%d' % (i, j)
                name = dist + "_%d" % j
                expr = '%s= (%s - %s)**2' % (yvar, x1var, x2var)
                root.add(name, ExecComp(expr), promotes = (x1var, x2var, yvar))

                # Constraint (you can experiment with turning on/off the active_tol)
                #driver.add_constraint(yvar, lower=radius)
                driver.add_constraint(yvar, lower=radius, active_tol=radius*3.0)

                # This pair's contribution to objective
                obj_expr += sep + yvar
                sep = ' + '

        root.add('sum_dist', ExecComp(obj_expr), promotes=('*', ))
        driver.add_objective('obj')

        prob.setup(check=False)
        prob.run()
Exemplo n.º 5
0
    def test_discs(self):

        OPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')

        if OPTIMIZER is not 'SNOPT':
            raise unittest.SkipTest(
                "pyoptsparse is not providing SNOPT or SLSQP")

        # So we compare the same starting locations.
        np.random.seed(123)

        radius = 1.0
        pin = 15.0
        n_disc = 7

        prob = Problem()
        prob.root = root = Group()

        from openmdao.api import pyOptSparseDriver
        driver = prob.driver = pyOptSparseDriver()
        driver.options['optimizer'] = 'SNOPT'
        driver.options['print_results'] = False

        # Note, active tolerance requires relevance reduction to work.
        root.ln_solver.options['single_voi_relevance_reduction'] = True

        # Also, need to be in adjoint
        root.ln_solver.options['mode'] = 'rev'

        obj_expr = 'obj = '
        sep = ''
        for i in range(n_disc):

            dist = "dist_%d" % i
            x1var = 'x_%d' % i

            # First disc is pinned
            if i == 0:
                root.add('p_%d' % i,
                         IndepVarComp(x1var, pin),
                         promotes=(x1var, ))

            # The rest are design variables for the optimizer.
            else:
                init_val = 5.0 * np.random.random() - 5.0 + pin
                root.add('p_%d' % i,
                         IndepVarComp(x1var, init_val),
                         promotes=(x1var, ))
                driver.add_desvar(x1var)

            for j in range(i):

                x2var = 'x_%d' % j
                yvar = 'y_%d_%d' % (i, j)
                name = dist + "_%d" % j
                expr = '%s= (%s - %s)**2' % (yvar, x1var, x2var)
                root.add(name, ExecComp(expr), promotes=(x1var, x2var, yvar))

                # Constraint (you can experiment with turning on/off the active_tol)
                #driver.add_constraint(yvar, lower=radius)
                driver.add_constraint(yvar,
                                      lower=radius,
                                      active_tol=radius * 3.0)

                # This pair's contribution to objective
                obj_expr += sep + yvar
                sep = ' + '

        root.add('sum_dist', ExecComp(obj_expr), promotes=('*', ))
        driver.add_objective('obj')

        prob.setup(check=False)
        prob.run()
Exemplo n.º 6
0
    def __init__(self, n=1500, m=300, npts=6):
        super(CADRE_Optimization, self).__init__()

        # add SNOPT driver
        OPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')
        self.driver = pyOptSparseDriver()
        self.driver.options['optimizer'] = OPTIMIZER

        #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())
        self.driver = pyOptSparseDriver()
        self.driver.options['optimizer'] = 'SNOPT'

        # Raw data to load
        fpath = os.path.dirname(os.path.realpath(__file__))
        fpath = os.path.join(fpath, '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.add(name, CADRE(n, m, solar_raw1, solar_raw2,comm_raw, power_raw))
            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)