diff --git a/benchmark/benchmark_beam.py b/benchmark/benchmark_beam.py index 272e5f92ee..1eeaff4c11 100644 --- a/benchmark/benchmark_beam.py +++ b/benchmark/benchmark_beam.py @@ -3,7 +3,7 @@ """ import unittest -from openmdao.api import Problem +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_group import MultipointBeamGroup @@ -22,9 +22,9 @@ def benchmark_beam_np1(self): num_cp = 4 num_load_cases = 32 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases)) prob.setup() @@ -46,9 +46,9 @@ def benchmark_beam_np2(self): num_cp = 4 num_load_cases = 32 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases)) prob.setup() @@ -71,9 +71,9 @@ def benchmark_beam_np4(self): num_cp = 4 num_load_cases = 32 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases)) prob.setup() diff --git a/benchmark/benchmark_manycomps.py b/benchmark/benchmark_manycomps.py index 4ad64b1031..e7a49187e7 100644 --- a/benchmark/benchmark_manycomps.py +++ b/benchmark/benchmark_manycomps.py @@ -1,7 +1,7 @@ import unittest -from openmdao.api import Problem, Group +import openmdao.api as om from openmdao.test_suite.build4test import DynComp, create_dyncomps @@ -9,19 +9,19 @@ class BM(unittest.TestCase): """Setup of models with lots of components""" def benchmark_100(self): - p = Problem() + p = om.Problem() create_dyncomps(p.model, 100, 10, 10, 5) - p.setup(check=False) + p.setup() p.final_setup() def benchmark_500(self): - p = Problem() + p = om.Problem() create_dyncomps(p.model, 500, 10, 10, 5) - p.setup(check=False) + p.setup() p.final_setup() def benchmark_1K(self): - p = Problem() + p = om.Problem() create_dyncomps(p.model, 1000, 10, 10, 5) - p.setup(check=False) + p.setup() p.final_setup() diff --git a/benchmark/benchmark_manyvars.py b/benchmark/benchmark_manyvars.py index f27ddbd2b5..217c56300c 100644 --- a/benchmark/benchmark_manyvars.py +++ b/benchmark/benchmark_manyvars.py @@ -1,12 +1,12 @@ import unittest -from openmdao.api import Problem, Group +import openmdao.api as om from openmdao.test_suite.build4test import DynComp, create_dyncomps def _build_comp(np, no, ns=0): - prob = Problem() + prob = om.Problem() prob.model.add_subsystem("C1", DynComp(np, no, ns)) return prob @@ -18,36 +18,36 @@ class BM(unittest.TestCase): def benchmark_1Kparams(self): prob = _build_comp(1000, 1) - prob.setup(check=False) + prob.setup() prob.final_setup() def benchmark_2Kparams(self): prob = _build_comp(2000, 1) - prob.setup(check=False) + prob.setup() prob.final_setup() def benchmark_1Kouts(self): prob = _build_comp(1, 1000) - prob.setup(check=False) + prob.setup() prob.final_setup() def benchmark_2Kouts(self): prob = _build_comp(1, 2000) - prob.setup(check=False) + prob.setup() prob.final_setup() def benchmark_1Kvars(self): prob = _build_comp(500, 500) - prob.setup(check=False) + prob.setup() prob.final_setup() def benchmark_2Kvars(self): prob = _build_comp(1000, 1000) - prob.setup(check=False) + prob.setup() prob.final_setup() if __name__ == '__main__': prob = _build_comp(1, 2000) - prob.setup(check=False) + prob.setup() prob.final_setup() diff --git a/benchmark/benchmark_multipoint.py b/benchmark/benchmark_multipoint.py index 4b078121cb..43b5ccec05 100644 --- a/benchmark/benchmark_multipoint.py +++ b/benchmark/benchmark_multipoint.py @@ -1,13 +1,14 @@ from __future__ import print_function +import time import unittest from six.moves import range + import numpy as np -import time -from openmdao.api import Problem, Group, ExplicitComponent, IndepVarComp, ExecComp +import openmdao.api as om -class Plus(ExplicitComponent): +class Plus(om.ExplicitComponent): def __init__(self, adder): super(Plus, self).__init__() self.adder = float(adder) @@ -19,7 +20,8 @@ def setup(self): def compute(self, inputs, outputs): outputs['f1'] = inputs['x'] + self.adder -class Times(ExplicitComponent): + +class Times(om.ExplicitComponent): def __init__(self, scalar): super(Times, self).__init__() self.scalar = float(scalar) @@ -31,7 +33,8 @@ def setup(self): def compute(self, inputs, outputs): outputs['f2'] = inputs['f1'] + self.scalar -class Point(Group): + +class Point(om.Group): def __init__(self, adder, scalar): super(Point, self).__init__() @@ -42,7 +45,8 @@ def setup(self): self.add_subsystem('plus', Plus(self.adder), promotes=['*']) self.add_subsystem('times', Times(self.scalar), promotes=['*']) -class Summer(ExplicitComponent): + +class Summer(om.ExplicitComponent): def __init__(self, size): super(Summer, self).__init__() @@ -60,7 +64,8 @@ def compute(self, inputs, outputs): tot += inputs['y%d'%i] outputs['total'] = tot -class MultiPoint(Group): + +class MultiPoint(om.Group): def __init__(self, adders, scalars): super(MultiPoint, self).__init__() @@ -78,6 +83,7 @@ def setup(self): self.add_subsystem('aggregate', Summer(size)) + class BM(unittest.TestCase): """A few 'brute force' multipoint cases (1K, 2K, 5K)""" @@ -87,8 +93,8 @@ def _setup_bm(self, npts): adders = np.random.random(size) scalars = np.random.random(size) - prob = Problem(MultiPoint(adders, scalars)) - prob.setup(check=False) + prob = om.Problem(MultiPoint(adders, scalars)) + prob.setup() return prob diff --git a/benchmark/benchmark_parallel_GA.py b/benchmark/benchmark_parallel_GA.py index c94a2b7d72..5be028a370 100644 --- a/benchmark/benchmark_parallel_GA.py +++ b/benchmark/benchmark_parallel_GA.py @@ -4,7 +4,7 @@ from time import time import unittest -from openmdao.api import Problem, SimpleGADriver, IndepVarComp, Group +import openmdao.api as om from openmdao.test_suite.components.exec_comp_for_test import ExecComp4Test @@ -15,13 +15,13 @@ POPSIZE = 40 -class GAGroup(Group): +class GAGroup(om.Group): def setup(self): - self.add_subsystem('p1', IndepVarComp('x', 1.0)) - self.add_subsystem('p2', IndepVarComp('y', 1.0)) - self.add_subsystem('p3', IndepVarComp('z', 1.0)) + self.add_subsystem('p1', om.IndepVarComp('x', 1.0)) + self.add_subsystem('p2', om.IndepVarComp('y', 1.0)) + self.add_subsystem('p3', om.IndepVarComp('z', 1.0)) self.add_subsystem('comp', ExecComp4Test(['f = x + y + z'], nl_delay=DELAY)) @@ -37,10 +37,10 @@ class BenchParGA1(unittest.TestCase): def benchmark_genetic_1(self): - prob = Problem() + prob = om.Problem() prob.model = GAGroup() - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() driver.options['max_gen'] = MAXGEN driver.options['pop_size'] = POPSIZE driver.options['run_parallel'] = True @@ -58,10 +58,10 @@ class BenchParGA2(unittest.TestCase): def benchmark_genetic_2(self): - prob = Problem() + prob = om.Problem() prob.model = GAGroup() - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() driver.options['max_gen'] = MAXGEN driver.options['pop_size'] = POPSIZE driver.options['run_parallel'] = True @@ -79,10 +79,10 @@ class BenchParGA4(unittest.TestCase): def benchmark_genetic_4(self): - prob = Problem() + prob = om.Problem() prob.model = GAGroup() - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() driver.options['max_gen'] = MAXGEN driver.options['pop_size'] = POPSIZE driver.options['run_parallel'] = True diff --git a/benchmark/benchmark_param_cycle.py b/benchmark/benchmark_param_cycle.py index f7acf5580f..d40c2ae64c 100644 --- a/benchmark/benchmark_param_cycle.py +++ b/benchmark/benchmark_param_cycle.py @@ -1,13 +1,12 @@ import unittest -from openmdao.api import Problem, Group, NewtonSolver, ScipyKrylov, NonlinearBlockGS, \ - LinearBlockGS, DirectSolver +import openmdao.api as om from openmdao.test_suite.parametric_suite import ParameterizedInstance from openmdao.utils.assert_utils import assert_rel_error -def _build(solver_class=NewtonSolver, linear_solver_class=ScipyKrylov, +def _build(solver_class=om.NewtonSolver, linear_solver_class=om.ScipyKrylov, solver_options=None, linear_solver_options=None, **options): suite = ParameterizedInstance('cycle', **options) suite.solver_class = solver_class @@ -44,7 +43,7 @@ class BM(unittest.TestCase): def benchmark_comp200_var5_nlbs_lbgs(self): suite = _build( - solver_class=NonlinearBlockGS, linear_solver_class=LinearBlockGS, + solver_class=om.NonlinearBlockGS, linear_solver_class=om.LinearBlockGS, assembled_jac=False, jacobian_type='dense', connection_type='explicit', @@ -58,7 +57,7 @@ def benchmark_comp200_var5_nlbs_lbgs(self): def benchmark_comp200_var5_newton_lings(self): suite = _build( - solver_class=NewtonSolver, linear_solver_class=LinearBlockGS, + solver_class=om.NewtonSolver, linear_solver_class=om.LinearBlockGS, solver_options={'maxiter': 20}, linear_solver_options={'maxiter': 200, 'atol': 1e-10, 'rtol': 1e-10}, assembled_jac=False, @@ -74,7 +73,7 @@ def benchmark_comp200_var5_newton_lings(self): def benchmark_comp200_var5_newton_direct_assembled(self): suite = _build( - solver_class=NewtonSolver, linear_solver_class=DirectSolver, + solver_class=om.NewtonSolver, linear_solver_class=om.DirectSolver, linear_solver_options={}, # defaults not valid for DirectSolver assembled_jac=True, jacobian_type='dense', @@ -89,7 +88,7 @@ def benchmark_comp200_var5_newton_direct_assembled(self): def benchmark_comp50_var5_newton_direct_assembled_fd(self): suite = _build( - solver_class=NewtonSolver, linear_solver_class=DirectSolver, + solver_class=om.NewtonSolver, linear_solver_class=om.DirectSolver, linear_solver_options={}, # defaults not valid for DirectSolver assembled_jac=True, jacobian_type='dense', diff --git a/benchmark/benchmark_trees.py b/benchmark/benchmark_trees.py index 48d76ad4c4..e041106113 100644 --- a/benchmark/benchmark_trees.py +++ b/benchmark/benchmark_trees.py @@ -1,7 +1,7 @@ import unittest -from openmdao.api import Problem, Group +import openmdao.api as om from openmdao.test_suite.build4test import DynComp, create_dyncomps, make_subtree @@ -9,22 +9,22 @@ class BM(unittest.TestCase): """Setup of models with various tree structures""" def benchmark_L4_sub2_c10(self): - p = Problem() + p = om.Problem() make_subtree(p.model, nsubgroups=2, levels=4, ncomps=10, ninputs=10, noutputs=10, nconns=5) - p.setup(check=False) + p.setup() p.final_setup() def benchmark_L6_sub2_c10(self): - p = Problem() + p = om.Problem() make_subtree(p.model, nsubgroups=2, levels=6, ncomps=10, ninputs=10, noutputs=10, nconns=5) - p.setup(check=False) + p.setup() p.final_setup() def benchmark_L7_sub2_c10(self): - p = Problem() + p = om.Problem() make_subtree(p.model, nsubgroups=2, levels=7, ncomps=10, ninputs=10, noutputs=10, nconns=5) - p.setup(check=False) + p.setup() p.final_setup() diff --git a/openmdao/components/add_subtract_comp.py b/openmdao/components/add_subtract_comp.py index c211d4f16b..1f4baecfca 100644 --- a/openmdao/components/add_subtract_comp.py +++ b/openmdao/components/add_subtract_comp.py @@ -1,9 +1,11 @@ -"""Definition of the Add/Subtract Component.""" - +""" +Definition of the Add/Subtract Component. +""" import collections +from six import string_types + import numpy as np from scipy import sparse as sp -from six import string_types from openmdao.core.explicitcomponent import ExplicitComponent diff --git a/openmdao/components/balance_comp.py b/openmdao/components/balance_comp.py index 5d116ca3ca..7056945b7e 100644 --- a/openmdao/components/balance_comp.py +++ b/openmdao/components/balance_comp.py @@ -67,7 +67,7 @@ def __init__(self, name=None, eq_units=None, lhs_name=None, rhs_name=None, rhs_v .. code-block:: python - prob = Problem(model=Group()) + prob = Problem() bal = BalanceComp() bal.add_balance('x', val=1.0) tgt = IndepVarComp(name='y_tgt', val=2) @@ -88,7 +88,7 @@ def __init__(self, name=None, eq_units=None, lhs_name=None, rhs_name=None, rhs_v .. code-block:: python - prob = Problem(model=Group()) + prob = Problem() bal = BalanceComp('x', val=1.0) tgt = IndepVarComp(name='y_tgt', val=2) exec_comp = ExecComp('y=x**2') diff --git a/openmdao/components/exec_comp.py b/openmdao/components/exec_comp.py index ad4e4d7326..71a0d9797c 100644 --- a/openmdao/components/exec_comp.py +++ b/openmdao/components/exec_comp.py @@ -189,8 +189,8 @@ def __init__(self, exprs=[], **kwargs): .. code-block:: python import numpy - from openmdao.api import ExecComp - excomp = ExecComp('y=sum(x)', x=numpy.ones(10,dtype=float)) + import openmdao.api as om + excomp = om.ExecComp('y=sum(x)', x=numpy.ones(10,dtype=float)) In this example, 'y' would be assumed to be the default type of float and would be given the default initial value of 1.0, while 'x' would be diff --git a/openmdao/components/tests/test_add_subtract_comp.py b/openmdao/components/tests/test_add_subtract_comp.py index 30b4c1dd4d..18b7dfe34f 100644 --- a/openmdao/components/tests/test_add_subtract_comp.py +++ b/openmdao/components/tests/test_add_subtract_comp.py @@ -4,16 +4,16 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp -from openmdao.components.add_subtract_comp import AddSubtractComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials + class TestAddSubtractCompScalars(unittest.TestCase): def setUp(self): self.nn = 1 - self.p = Problem(model=Group()) - ivc = IndepVarComp() + self.p = om.Problem() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn,)) ivc.add_output(name='b', shape=(self.nn,)) @@ -22,7 +22,7 @@ def setUp(self): promotes_outputs=['a', 'b']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b']) self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -46,14 +46,15 @@ def test_partials(self): partials = self.p.check_partials(method='fd', out_stream=None) assert_check_partials(partials) + class TestAddSubtractCompNx1(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn,)) ivc.add_output(name='b', shape=(self.nn,)) @@ -62,7 +63,7 @@ def setUp(self): promotes_outputs=['a', 'b']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b'],vec_size=self.nn) self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -92,9 +93,9 @@ class TestAddSubtractCompNx3(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3)) ivc.add_output(name='b', shape=(self.nn, 3)) @@ -103,7 +104,7 @@ def setUp(self): promotes_outputs=['a', 'b']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b'],vec_size=self.nn,length=3) self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -127,14 +128,15 @@ def test_partials(self): partials = self.p.check_partials(method='fd', out_stream=None) assert_check_partials(partials) + class TestAddSubtractMultipleInputs(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3)) ivc.add_output(name='b', shape=(self.nn, 3)) ivc.add_output(name='c', shape=(self.nn, 3)) @@ -144,7 +146,7 @@ def setUp(self): promotes_outputs=['a', 'b','c']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b','input_c'],vec_size=self.nn,length=3) self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -171,14 +173,15 @@ def test_partials(self): partials = self.p.check_partials(method='fd', out_stream=None) assert_check_partials(partials) + class TestAddSubtractScalingFactors(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3)) ivc.add_output(name='b', shape=(self.nn, 3)) ivc.add_output(name='c', shape=(self.nn, 3)) @@ -188,7 +191,7 @@ def setUp(self): promotes_outputs=['a', 'b','c']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b','input_c'],vec_size=self.nn,length=3,scaling_factors=[2.,1.,-1]) self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -215,14 +218,15 @@ def test_partials(self): partials = self.p.check_partials(method='fd', out_stream=None) assert_check_partials(partials) + class TestAddSubtractUnits(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3),units='ft') ivc.add_output(name='b', shape=(self.nn, 3),units='m') ivc.add_output(name='c', shape=(self.nn, 3),units='m') @@ -232,7 +236,7 @@ def setUp(self): promotes_outputs=['a', 'b','c']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b','input_c'],vec_size=self.nn,length=3,units='ft') self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -260,13 +264,14 @@ def test_partials(self): partials = self.p.check_partials(method='fd', out_stream=None) assert_check_partials(partials) + class TestWrongScalingFactorCount(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3)) ivc.add_output(name='b', shape=(self.nn, 3)) ivc.add_output(name='c', shape=(self.nn, 3)) @@ -276,7 +281,7 @@ def setUp(self): promotes_outputs=['a', 'b','c']) adder=self.p.model.add_subsystem(name='add_subtract_comp', - subsys=AddSubtractComp()) + subsys=om.AddSubtractComp()) adder.add_equation('adder_output',['input_a','input_b','input_c'],vec_size=self.nn,length=3,scaling_factors=[1,-1]) self.p.model.connect('a', 'add_subtract_comp.input_a') @@ -287,34 +292,36 @@ def setUp(self): def test_for_exception(self): self.assertRaises(ValueError,self.p.setup) -class TestForDocs(unittest.TestCase): + +class TestFeature(unittest.TestCase): def test(self): """ A simple example to compute the resultant force on an aircraft and demonstrate the AddSubtract component """ import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, AddSubtractComp - from openmdao.utils.assert_utils import assert_rel_error + + import openmdao.api as om n = 3 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() - #the vector represents forces at 3 time points (rows) in 2 dimensional plane (cols) - ivc.add_output(name='thrust', shape=(n,2),units='kN') - ivc.add_output(name='drag', shape=(n,2),units='kN') - ivc.add_output(name='lift', shape=(n,2),units='kN') - ivc.add_output(name='weight', shape=(n,2),units='kN') + ivc = om.IndepVarComp() + # The vector represents forces at 3 time points (rows) in 2 dimensional plane (cols) + ivc.add_output(name='thrust', shape=(n, 2), units='kN') + ivc.add_output(name='drag', shape=(n, 2), units='kN') + ivc.add_output(name='lift', shape=(n, 2), units='kN') + ivc.add_output(name='weight', shape=(n, 2), units='kN') p.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['thrust', 'drag', 'lift', 'weight']) - #construct an adder/subtracter here. create a relationship through the add_equation method - adder = AddSubtractComp() - adder.add_equation('total_force',input_names=['thrust','drag','lift','weight'],vec_size=n,length=2, scaling_factors=[1,-1,1,-1], units='kN') - #note the scaling factors. we assume all forces are positive sign upstream + # Construct an adder/subtracter here. create a relationship through the add_equation method + adder = om.AddSubtractComp() + adder.add_equation('total_force', input_names=['thrust', 'drag', 'lift', 'weight'], + vec_size=n, length=2, scaling_factors=[1, -1, 1, -1], units='kN') + # Note the scaling factors. we assume all forces are positive sign upstream p.model.add_subsystem(name='totalforcecomp', subsys=adder) @@ -325,18 +332,18 @@ def test(self): p.setup() - #set thrust to exceed drag, weight to equal lift for this scenario - p['thrust'][:,0] = [500, 600, 700] - p['drag'][:,0] = [400, 400, 400] - p['weight'][:,1] = [1000, 1001, 1002] - p['lift'][:,1] = [1000, 1000, 1000] + # Set thrust to exceed drag, weight to equal lift for this scenario + p['thrust'][:, 0] = [500, 600, 700] + p['drag'][:, 0] = [400, 400, 400] + p['weight'][:, 1] = [1000, 1001, 1002] + p['lift'][:, 1] = [1000, 1000, 1000] p.run_model() # print(p.get_val('totalforcecomp.total_force', units='kN')) # Verify the results - expected_i = np.array([[100, 200, 300],[0, -1, -2]]).T + expected_i = np.array([[100, 200, 300], [0, -1, -2]]).T assert_rel_error(self, p.get_val('totalforcecomp.total_force', units='kN'), expected_i) diff --git a/openmdao/components/tests/test_akima_comp.py b/openmdao/components/tests/test_akima_comp.py index 9e021b3037..7a23e339b9 100644 --- a/openmdao/components/tests/test_akima_comp.py +++ b/openmdao/components/tests/test_akima_comp.py @@ -6,8 +6,7 @@ import numpy as np from numpy.testing import assert_array_almost_equal -from openmdao.api import Problem, IndepVarComp -from openmdao.components.akima_spline_comp import AkimaSplineComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials @@ -20,10 +19,10 @@ def test_basic(self): n = 50 x = np.linspace(1.0, 12.0, n) - prob = Problem() + prob = om.Problem() - comp = AkimaSplineComp(num_control_points=ncp, num_points=n, - name='chord', input_x=True, input_xcp=True) + comp = om.AkimaSplineComp(num_control_points=ncp, num_points=n, + name='chord', input_x=True, input_xcp=True) prob.model.add_subsystem('akima', comp) @@ -58,10 +57,10 @@ def test_fixed_grid(self): ncp = len(ycp) n = 11 - prob = Problem() + prob = om.Problem() - comp = AkimaSplineComp(num_control_points=ncp, num_points=n, - name='chord', eval_at='end') + comp = om.AkimaSplineComp(num_control_points=ncp, num_points=n, + name='chord', eval_at='end') prob.model.add_subsystem('akima', comp) @@ -92,10 +91,10 @@ def test_vectorized(self): n = 12 x = np.linspace(1.0, 12.0, n) - prob = Problem() + prob = om.Problem() - comp = AkimaSplineComp(num_control_points=ncp, num_points=n, vec_size=2, - name='chord', input_x=True, input_xcp=True) + comp = om.AkimaSplineComp(num_control_points=ncp, num_points=n, vec_size=2, + name='chord', input_x=True, input_xcp=True) prob.model.add_subsystem('akima', comp) @@ -126,8 +125,7 @@ class TestAkimaFeature(unittest.TestCase): def test_input_grid(self): import numpy as np - from openmdao.api import Problem - from openmdao.components.akima_spline_comp import AkimaSplineComp + import openmdao.api as om xcp = np.array([1.0, 2.0, 4.0, 6.0, 10.0, 12.0]) ycp = np.array([5.0, 12.0, 14.0, 16.0, 21.0, 29.0]) @@ -135,10 +133,10 @@ def test_input_grid(self): n = 50 x = np.linspace(1.0, 12.0, n) - prob = Problem() + prob = om.Problem() - comp = AkimaSplineComp(num_control_points=ncp, num_points=n, - name='chord', input_x=True, input_xcp=True) + comp = om.AkimaSplineComp(num_control_points=ncp, num_points=n, + name='chord', input_x=True, input_xcp=True) prob.model.add_subsystem('akima', comp) @@ -167,18 +165,16 @@ def test_input_grid(self): def test_fixed_grid(self): import numpy as np - from openmdao.api import Problem - from openmdao.components.akima_spline_comp import AkimaSplineComp - + import openmdao.api as om ycp = np.array([5.0, 12.0, 14.0, 16.0, 21.0, 29.0]) ncp = len(ycp) n = 11 - prob = Problem() + prob = om.Problem() - comp = AkimaSplineComp(num_control_points=ncp, num_points=n, - name='chord', eval_at='end') + comp = om.AkimaSplineComp(num_control_points=ncp, num_points=n, + name='chord', eval_at='end') prob.model.add_subsystem('akima', comp) diff --git a/openmdao/components/tests/test_balance_comp.py b/openmdao/components/tests/test_balance_comp.py index d1bb41397f..8d9a8bbfc6 100644 --- a/openmdao/components/tests/test_balance_comp.py +++ b/openmdao/components/tests/test_balance_comp.py @@ -1,3 +1,6 @@ +""" +Unit tests for the BalanceComp. +""" from __future__ import print_function, division, absolute_import import os @@ -7,29 +10,24 @@ import numpy as np from numpy.testing import assert_almost_equal -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, \ - NewtonSolver, DirectSolver -from openmdao.api import BalanceComp +import openmdao.api as om class TestBalanceComp(unittest.TestCase): def test_scalar_example(self): - prob = Problem(model=Group()) - - bal = BalanceComp() + prob = om.Problem() + bal = om.BalanceComp() bal.add_balance('x', val=1.0) - tgt = IndepVarComp(name='y_tgt', val=2) + tgt = om.IndepVarComp(name='y_tgt', val=2) - exec_comp = ExecComp('y=x**2') + exec_comp = om.ExecComp('y=x**2') prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) - prob.model.add_subsystem(name='exec', subsys=exec_comp) - prob.model.add_subsystem(name='balance', subsys=bal) prob.model.connect('y_tgt', 'balance.rhs:x') @@ -50,8 +48,8 @@ def test_scalar_example(self): assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5) # set an actual solver, and re-setup. Then check derivatives at a converged point - prob.model.linear_solver = DirectSolver() - prob.model.nonlinear_solver = NewtonSolver() + prob.model.linear_solver = om.DirectSolver() + prob.model.nonlinear_solver = om.NewtonSolver() prob.setup() @@ -66,26 +64,24 @@ def test_scalar_example(self): def test_create_on_init(self): - prob = Problem(model=Group()) + prob = om.Problem() - bal = BalanceComp('x', val=1.0) + bal = om.BalanceComp('x', val=1.0) - tgt = IndepVarComp(name='y_tgt', val=2) + tgt = om.IndepVarComp(name='y_tgt', val=2) - exec_comp = ExecComp('y=x**2') + exec_comp = om.ExecComp('y=x**2') prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) - prob.model.add_subsystem(name='exec', subsys=exec_comp) - prob.model.add_subsystem(name='balance', subsys=bal) prob.model.connect('y_tgt', 'balance.rhs:x') prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver() - prob.model.nonlinear_solver = NewtonSolver() + prob.model.linear_solver = om.DirectSolver() + prob.model.nonlinear_solver = om.NewtonSolver() prob.setup() @@ -103,13 +99,13 @@ def test_create_on_init(self): def test_create_on_init_no_normalization(self): - prob = Problem(model=Group()) + prob = om.Problem() - bal = BalanceComp('x', val=1.0, normalize=False) + bal = om.BalanceComp('x', val=1.0, normalize=False) - tgt = IndepVarComp(name='y_tgt', val=1.5) + tgt = om.IndepVarComp(name='y_tgt', val=1.5) - exec_comp = ExecComp('y=x**2') + exec_comp = om.ExecComp('y=x**2') prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) @@ -121,8 +117,8 @@ def test_create_on_init_no_normalization(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver() - prob.model.nonlinear_solver = NewtonSolver(iprint=0) + prob.model.linear_solver = om.DirectSolver() + prob.model.nonlinear_solver = om.NewtonSolver(iprint=0) prob.setup() @@ -141,15 +137,15 @@ def test_vectorized(self): n = 100 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', val=np.ones(n)) - tgt = IndepVarComp(name='y_tgt', val=4*np.ones(n)) + tgt = om.IndepVarComp(name='y_tgt', val=4*np.ones(n)) - exec_comp = ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) + exec_comp = om.ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) @@ -161,9 +157,9 @@ def test_vectorized(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -182,15 +178,15 @@ def test_vectorized_no_normalization(self): n = 100 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', val=np.ones(n), normalize=False) - tgt = IndepVarComp(name='y_tgt', val=1.7*np.ones(n)) + tgt = om.IndepVarComp(name='y_tgt', val=1.7*np.ones(n)) - exec_comp = ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) + exec_comp = om.ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) @@ -202,9 +198,9 @@ def test_vectorized_no_normalization(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -223,17 +219,17 @@ def test_vectorized_with_mult(self): n = 100 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', val=np.ones(n), use_mult=True) - tgt = IndepVarComp(name='y_tgt', val=4*np.ones(n)) + tgt = om.IndepVarComp(name='y_tgt', val=4*np.ones(n)) - mult_ivc = IndepVarComp(name='mult', val=2.0*np.ones(n)) + mult_ivc = om.IndepVarComp(name='mult', val=2.0*np.ones(n)) - exec_comp = ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) + exec_comp = om.ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='mult_comp', subsys=mult_ivc, promotes_outputs=['mult']) @@ -247,9 +243,9 @@ def test_vectorized_with_mult(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -272,13 +268,13 @@ def test_vectorized_with_default_mult(self): n = 100 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp('x', val=np.ones(n), use_mult=True, mult_val=2.0) + bal = om.BalanceComp('x', val=np.ones(n), use_mult=True, mult_val=2.0) - tgt = IndepVarComp(name='y_tgt', val=4 * np.ones(n)) + tgt = om.IndepVarComp(name='y_tgt', val=4 * np.ones(n)) - exec_comp = ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) + exec_comp = om.ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) @@ -290,9 +286,9 @@ def test_vectorized_with_default_mult(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -310,14 +306,14 @@ def test_vectorized_with_default_mult(self): def test_shape(self): n = 100 - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', shape=(n,)) - tgt = IndepVarComp(name='y_tgt', val=4*np.ones(n)) + tgt = om.IndepVarComp(name='y_tgt', val=4*np.ones(n)) - exe = ExecComp('y=x**2', x=np.zeros(n), y=np.zeros(n)) + exe = om.ExecComp('y=x**2', x=np.zeros(n), y=np.zeros(n)) - model = Group() + model = om.Group() model.add_subsystem('tgt', tgt, promotes_outputs=['y_tgt']) model.add_subsystem('exe', exe) @@ -327,10 +323,10 @@ def test_shape(self): model.connect('bal.x', 'exe.x') model.connect('exe.y', 'bal.lhs:x') - model.linear_solver = DirectSolver(assemble_jac=True) - model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + model.linear_solver = om.DirectSolver(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob['bal.x'] = np.random.rand(n) @@ -343,15 +339,15 @@ def test_complex_step(self): n = 1 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x') - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) @@ -363,9 +359,9 @@ def test_complex_step(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup(force_alloc_complex=True) @@ -384,15 +380,15 @@ def test_scalar(self): n = 1 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x') - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) @@ -404,9 +400,9 @@ def test_scalar(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -425,16 +421,16 @@ def test_scalar_with_guess_func(self): n = 1 - model=Group(assembled_jac_type='dense') + model=om.Group(assembled_jac_type='dense') def guess_function(inputs, outputs, residuals): outputs['x'] = np.sqrt(inputs['rhs:x']) - bal = BalanceComp('x', guess_func=guess_function) # test guess_func as kwarg + bal = om.BalanceComp('x', guess_func=guess_function) # test guess_func as kwarg - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) model.add_subsystem(name='exec', subsys=exec_comp) @@ -444,10 +440,10 @@ def guess_function(inputs, outputs, residuals): model.connect('balance.x', 'exec.x') model.connect('exec.y', 'balance.lhs:x') - model.linear_solver = DirectSolver(assemble_jac=True) - model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + model.linear_solver = om.DirectSolver(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob['balance.x'] = np.random.rand(n) @@ -464,17 +460,17 @@ def guess_function(inputs, outputs, residuals): def test_scalar_with_guess_func_additional_input(self): - model = Group(assembled_jac_type='dense') + model = om.Group(assembled_jac_type='dense') - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x') bal.add_input('guess_x', val=0.0) - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='y_tgt', val=4) ivc.add_output(name='guess_x', val=2.5) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['y_tgt', 'guess_x']) model.add_subsystem(name='exec', subsys=exec_comp) @@ -485,10 +481,10 @@ def test_scalar_with_guess_func_additional_input(self): model.connect('balance.x', 'exec.x') model.connect('exec.y', 'balance.lhs:x') - model.linear_solver = DirectSolver(assemble_jac=True) - model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + model.linear_solver = om.DirectSolver(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) - prob = Problem(model) + prob = om.Problem(model) prob.setup() # run problem without a guess function @@ -517,15 +513,15 @@ def guess_function(inputs, outputs, resids): def test_scalar_guess_func_using_outputs(self): - model = Group() + model = om.Group() - ind = IndepVarComp() + ind = om.IndepVarComp() ind.add_output('a', 1) ind.add_output('b', -4) ind.add_output('c', 3) - lhs = ExecComp('lhs=-(a*x**2+b*x)') - bal = BalanceComp(name='x', rhs_name='c') + lhs = om.ExecComp('lhs=-(a*x**2+b*x)') + bal = om.BalanceComp(name='x', rhs_name='c') model.add_subsystem('ind_comp', ind, promotes_outputs=['a', 'b', 'c']) model.add_subsystem('lhs_comp', lhs, promotes_inputs=['a', 'b', 'x']) @@ -533,12 +529,12 @@ def test_scalar_guess_func_using_outputs(self): model.connect('lhs_comp.lhs', 'bal_comp.lhs:x') - model.linear_solver = DirectSolver() - model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + model.linear_solver = om.DirectSolver() + model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) # first verify behavior of the balance comp without the guess function # at initial conditions x=5, x=0 and x=-1 - prob = Problem(model) + prob = om.Problem(model) prob.setup() # default solution with initial value of 5 is x=3. @@ -584,11 +580,11 @@ def test_rhs_val(self): n = 1 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp('x', rhs_val=4.0) + bal = om.BalanceComp('x', rhs_val=4.0) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='exec', subsys=exec_comp) @@ -597,9 +593,9 @@ def test_rhs_val(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -618,17 +614,17 @@ def test_scalar_with_mult(self): n = 1 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', use_mult=True) - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - mult_ivc = IndepVarComp(name='mult', val=2.0) + mult_ivc = om.IndepVarComp(name='mult', val=2.0) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='mult_comp', subsys=mult_ivc, promotes_outputs=['mult']) @@ -642,9 +638,9 @@ def test_scalar_with_mult(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -663,17 +659,17 @@ def test_renamed_vars(self): n = 1 - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', use_mult=True, mult_name='MUL', lhs_name='XSQ', rhs_name='TARGETXSQ') - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - mult_ivc = IndepVarComp(name='mult', val=2.0) + mult_ivc = om.IndepVarComp(name='mult', val=2.0) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='mult_comp', subsys=mult_ivc, promotes_outputs=['mult']) @@ -687,9 +683,9 @@ def test_renamed_vars(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.XSQ') - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() @@ -706,19 +702,18 @@ def test_renamed_vars(self): def test_feature_scalar(self): from numpy.testing import assert_almost_equal - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NewtonSolver, \ - DirectSolver, BalanceComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', use_mult=True) - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - mult_ivc = IndepVarComp(name='mult', val=2.0) + mult_ivc = om.IndepVarComp(name='mult', val=2.0) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='mult_comp', subsys=mult_ivc, promotes_outputs=['mult']) @@ -730,10 +725,10 @@ def test_feature_scalar(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) - prob.setup(check=False) + prob.setup() # A reasonable initial guess to find the positive root. prob['balance.x'] = 1.0 @@ -744,17 +739,16 @@ def test_feature_scalar(self): def test_feature_scalar_with_default_mult(self): from numpy.testing import assert_almost_equal - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NewtonSolver, \ - DirectSolver, BalanceComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance('x', use_mult=True, mult_val=2.0) - tgt = IndepVarComp(name='y_tgt', val=4) + tgt = om.IndepVarComp(name='y_tgt', val=4) - exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) + exec_comp = om.ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='exec', subsys=exec_comp) @@ -764,10 +758,10 @@ def test_feature_scalar_with_default_mult(self): prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) - prob.setup(check=False) + prob.setup() # A reasonable initial guess to find the positive root. prob['balance.x'] = 1.0 @@ -780,28 +774,28 @@ def test_feature_vector(self): import numpy as np from numpy.testing import assert_almost_equal - from openmdao.api import Problem, Group, ExecComp, NewtonSolver, DirectSolver, BalanceComp + import openmdao.api as om n = 100 - prob = Problem() + prob = om.Problem() - exec_comp = ExecComp('y=b*x+c', - b={'value': np.random.uniform(0.01,100, size=n)}, - c={'value': np.random.rand(n)}, - x={'value': np.zeros(n)}, - y={'value': np.ones(n)}) + exec_comp = om.ExecComp('y=b*x+c', + b={'value': np.random.uniform(0.01, 100, size=n)}, + c={'value': np.random.rand(n)}, + x={'value': np.zeros(n)}, + y={'value': np.ones(n)}) prob.model.add_subsystem(name='exec', subsys=exec_comp) - prob.model.add_subsystem(name='balance', subsys=BalanceComp('x', val=np.ones(n))) + prob.model.add_subsystem(name='balance', subsys=om.BalanceComp('x', val=np.ones(n))) prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') - prob.model.linear_solver = DirectSolver(assemble_jac=True) - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) - prob.setup(check=False) + prob.setup() prob['balance.x'] = np.random.rand(n) diff --git a/openmdao/components/tests/test_bsplines_comp.py b/openmdao/components/tests/test_bsplines_comp.py index 2bdb8205f7..4e54de2d78 100644 --- a/openmdao/components/tests/test_bsplines_comp.py +++ b/openmdao/components/tests/test_bsplines_comp.py @@ -12,15 +12,14 @@ except ImportError: matplotlib = None -from openmdao.api import Problem, IndepVarComp -from openmdao.components.bsplines_comp import BsplinesComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error class TestBsplinesComp(unittest.TestCase): def test_basic(self): - prob = Problem() + prob = om.Problem() model = prob.model n_cp = 80 @@ -29,16 +28,16 @@ def test_basic(self): t = np.linspace(0, 3.0*np.pi, n_cp) x = np.sin(t) - model.add_subsystem('px', IndepVarComp('x', val=x)) - model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp, - num_points=n_point, - in_name='h_cp', - out_name='h', - distribution='uniform')) + model.add_subsystem('px', om.IndepVarComp('x', val=x)) + model.add_subsystem('interp', om.BsplinesComp(num_control_points=n_cp, + num_points=n_point, + in_name='h_cp', + out_name='h', + distribution='uniform')) model.connect('px.x', 'interp.h_cp') - prob.setup(check=False) + prob.setup() prob.run_model() xx = prob['interp.h'].flatten() @@ -56,14 +55,14 @@ def test_units(self): n_cp = 5 n_point = 10 - interp = BsplinesComp(num_control_points=n_cp, - num_points=n_point, - in_name='h_cp', - out_name='h', - units='inch') + interp = om.BsplinesComp(num_control_points=n_cp, + num_points=n_point, + in_name='h_cp', + out_name='h', + units='inch') - prob = Problem(model=interp) - prob.setup(check=False) + prob = om.Problem(model=interp) + prob.setup() prob.run_model() # verify that both input and output of the bsplines comp have proper units @@ -83,11 +82,11 @@ class TestBsplinesCompFeature(unittest.TestCase): def test_basic(self): import numpy as np - from openmdao.api import Problem, IndepVarComp - from openmdao.components.bsplines_comp import BsplinesComp + + import openmdao.api as om from openmdao.utils.general_utils import printoptions - prob = Problem() + prob = om.Problem() model = prob.model n_cp = 5 @@ -96,14 +95,14 @@ def test_basic(self): t = np.linspace(0, 0.5*np.pi, n_cp) x = np.sin(t) - model.add_subsystem('px', IndepVarComp('x', val=x)) - model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp, - num_points=n_point, - in_name='h_cp', - out_name='h')) + model.add_subsystem('px', om.IndepVarComp('x', val=x)) + model.add_subsystem('interp', om.BsplinesComp(num_control_points=n_cp, + num_points=n_point, + in_name='h_cp', + out_name='h')) model.connect('px.x', 'interp.h_cp') - prob.setup(check=False) + prob.setup() prob.run_model() xx = prob['interp.h'].flatten() @@ -122,11 +121,11 @@ def test_basic(self): def test_vectorized(self): import numpy as np - from openmdao.api import Problem, IndepVarComp - from openmdao.components.bsplines_comp import BsplinesComp + + import openmdao.api as om from openmdao.utils.general_utils import printoptions - prob = Problem() + prob = om.Problem() model = prob.model n_cp = 5 @@ -137,15 +136,15 @@ def test_vectorized(self): x[0, :] = np.sin(t) x[1, :] = 2.0*np.sin(t) - model.add_subsystem('px', IndepVarComp('x', val=x)) - model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp, - num_points=n_point, - vec_size=2, - in_name='h_cp', - out_name='h')) + model.add_subsystem('px', om.IndepVarComp('x', val=x)) + model.add_subsystem('interp', om.BsplinesComp(num_control_points=n_cp, + num_points=n_point, + vec_size=2, + in_name='h_cp', + out_name='h')) model.connect('px.x', 'interp.h_cp') - prob.setup(check=False) + prob.setup() prob.run_model() xx = prob['interp.h'] @@ -177,10 +176,9 @@ def setUp(self): matplotlib.use('Agg') def test_distribution_uniform(self): - from openmdao.api import Problem, IndepVarComp - from openmdao.components.bsplines_comp import BsplinesComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model n_cp = 20 @@ -189,15 +187,15 @@ def test_distribution_uniform(self): t = np.linspace(0, 3.0*np.pi, n_cp) x = np.sin(t) - model.add_subsystem('px', IndepVarComp('x', val=x)) - model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp, - num_points=n_point, - in_name='h_cp', - out_name='h', - distribution='uniform')) + model.add_subsystem('px', om.IndepVarComp('x', val=x)) + model.add_subsystem('interp', om.BsplinesComp(num_control_points=n_cp, + num_points=n_point, + in_name='h_cp', + out_name='h', + distribution='uniform')) model.connect('px.x', 'interp.h_cp') - prob.setup(check=False) + prob.setup() prob.run_model() xx = prob['interp.h'].flatten() @@ -215,10 +213,9 @@ def test_distribution_uniform(self): plt.show() def test_distribution_sine(self): - from openmdao.api import Problem, IndepVarComp - from openmdao.components.bsplines_comp import BsplinesComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model n_cp = 20 @@ -228,15 +225,15 @@ def test_distribution_sine(self): t = 3.0 * np.pi * 0.5 * (1.0 + np.sin(-0.5 * np.pi + tvec * np.pi)) x = np.sin(t) - model.add_subsystem('px', IndepVarComp('x', val=x)) - model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp, - num_points=n_point, - in_name='h_cp', - out_name='h', - distribution='sine')) + model.add_subsystem('px', om.IndepVarComp('x', val=x)) + model.add_subsystem('interp', om.BsplinesComp(num_control_points=n_cp, + num_points=n_point, + in_name='h_cp', + out_name='h', + distribution='sine')) model.connect('px.x', 'interp.h_cp') - prob.setup(check=False) + prob.setup() prob.run_model() xx = prob['interp.h'].flatten() @@ -255,5 +252,6 @@ def test_distribution_sine(self): plt.grid(True) plt.show() + if __name__ == "__main__": unittest.main() diff --git a/openmdao/components/tests/test_cross_product_comp.py b/openmdao/components/tests/test_cross_product_comp.py index 8106971814..8f21ff81f3 100644 --- a/openmdao/components/tests/test_cross_product_comp.py +++ b/openmdao/components/tests/test_cross_product_comp.py @@ -4,7 +4,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, CrossProductComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error @@ -13,9 +13,9 @@ class TestCrossProductCompNx3(unittest.TestCase): def setUp(self): self.n = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.n, 3)) ivc.add_output(name='b', shape=(self.n, 3)) @@ -24,7 +24,7 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='cross_prod_comp', - subsys=CrossProductComp(vec_size=self.n)) + subsys=om.CrossProductComp(vec_size=self.n)) self.p.model.connect('a', 'cross_prod_comp.a') self.p.model.connect('b', 'cross_prod_comp.b') @@ -68,9 +68,9 @@ class TestCrossProductCompNx3x1(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3, 1)) ivc.add_output(name='b', shape=(self.nn, 3, 1)) @@ -79,7 +79,7 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='cross_prod_comp', - subsys=CrossProductComp(vec_size=self.nn)) + subsys=om.CrossProductComp(vec_size=self.nn)) self.p.model.connect('a', 'cross_prod_comp.a') self.p.model.connect('b', 'cross_prod_comp.b') @@ -121,9 +121,9 @@ def test_partials(self): class TestCrossProductCompNonVectorized(unittest.TestCase): def setUp(self): - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(3, 1)) ivc.add_output(name='b', shape=(3, 1)) @@ -132,7 +132,7 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='cross_prod_comp', - subsys=CrossProductComp()) + subsys=om.CrossProductComp()) self.p.model.connect('a', 'cross_prod_comp.a') self.p.model.connect('b', 'cross_prod_comp.b') @@ -177,9 +177,9 @@ class TestUnits(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3), units='ft') ivc.add_output(name='b', shape=(self.nn, 3), units='lbf') @@ -188,9 +188,9 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='cross_prod_comp', - subsys=CrossProductComp(vec_size=self.nn, - a_units='m', b_units='N', - c_units='N*m')) + subsys=om.CrossProductComp(vec_size=self.nn, + a_units='m', b_units='N', + c_units='N*m')) self.p.model.connect('a', 'cross_prod_comp.a') self.p.model.connect('b', 'cross_prod_comp.b') @@ -223,18 +223,19 @@ def test_partials(self): decimal=6) -class TestForDocs(unittest.TestCase): +class TestFeature(unittest.TestCase): def test(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, CrossProductComp + + import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error n = 100 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='r', shape=(n, 3)) ivc.add_output(name='F', shape=(n, 3)) @@ -243,9 +244,9 @@ def test(self): promotes_outputs=['r', 'F']) p.model.add_subsystem(name='cross_prod_comp', - subsys=CrossProductComp(vec_size=n, - a_name='r', b_name='F', c_name='torque', - a_units='m', b_units='N', c_units='N*m')) + subsys=om.CrossProductComp(vec_size=n, + a_name='r', b_name='F', c_name='torque', + a_units='m', b_units='N', c_units='N*m')) p.model.connect('r', 'cross_prod_comp.r') p.model.connect('F', 'cross_prod_comp.F') diff --git a/openmdao/components/tests/test_demux_comp.py b/openmdao/components/tests/test_demux_comp.py index 297cb95a3e..f4b9f9280a 100644 --- a/openmdao/components/tests/test_demux_comp.py +++ b/openmdao/components/tests/test_demux_comp.py @@ -4,25 +4,23 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials -from openmdao.api import DemuxComp - class TestDemuxCompOptions(unittest.TestCase): def test_invalid_axis(self): nn = 10 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(nn,)) p.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['a']) - demux_comp = p.model.add_subsystem(name='demux_comp', subsys=DemuxComp(vec_size=nn)) + demux_comp = p.model.add_subsystem(name='demux_comp', subsys=om.DemuxComp(vec_size=nn)) demux_comp.add_var('a', shape=(nn,), axis=1) @@ -32,19 +30,19 @@ def test_invalid_axis(self): p.setup() self.assertEqual(str(ctx.exception), "Invalid axis (1) for variable 'a' of shape (10,)") - + def test_axis_with_wrong_size(self): nn = 10 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(nn, 7)) ivc.add_output(name='b', shape=(3, nn)) p.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['a', 'b']) - demux_comp = p.model.add_subsystem(name='demux_comp', subsys=DemuxComp(vec_size=nn)) + demux_comp = p.model.add_subsystem(name='demux_comp', subsys=om.DemuxComp(vec_size=nn)) demux_comp.add_var('a', shape=(nn, 7), axis=1) demux_comp.add_var('b', shape=(3, nn), axis=1) @@ -64,9 +62,9 @@ class TestDemuxComp1D(unittest.TestCase): def setUp(self): self.nn = 10 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn,)) ivc.add_output(name='b', shape=(self.nn,)) @@ -75,7 +73,7 @@ def setUp(self): promotes_outputs=['a', 'b']) demux_comp = self.p.model.add_subsystem(name='demux_comp', - subsys=DemuxComp(vec_size=self.nn)) + subsys=om.DemuxComp(vec_size=self.nn)) demux_comp.add_var('a', shape=(self.nn,)) demux_comp.add_var('b', shape=(self.nn,)) @@ -111,9 +109,9 @@ class TestDemuxComp2D(unittest.TestCase): def setUp(self): self.nn = 10 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 7)) ivc.add_output(name='b', shape=(3, self.nn)) @@ -122,7 +120,7 @@ def setUp(self): promotes_outputs=['a', 'b']) demux_comp = self.p.model.add_subsystem(name='demux_comp', - subsys=DemuxComp(vec_size=self.nn)) + subsys=om.DemuxComp(vec_size=self.nn)) demux_comp.add_var('a', shape=(self.nn, 7), axis=0) demux_comp.add_var('b', shape=(3, self.nn), axis=1) @@ -154,14 +152,15 @@ def test_partials(self): assert_check_partials(cpd, atol=1.0E-8, rtol=1.0E-8) -class TestForDocs(unittest.TestCase): +class TestFeature(unittest.TestCase): def test(self): """ An example demonstrating a trivial use case of DemuxComp """ import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, DemuxComp, ExecComp + + import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error # The number of elements to be demuxed @@ -170,9 +169,9 @@ def test(self): # The size of each element to be demuxed m = 100 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='pos_ecef', shape=(m, 3), units='km') p.model.add_subsystem(name='ivc', @@ -180,15 +179,15 @@ def test(self): promotes_outputs=['pos_ecef']) mux_comp = p.model.add_subsystem(name='demux', - subsys=DemuxComp(vec_size=n)) + subsys=om.DemuxComp(vec_size=n)) mux_comp.add_var('pos', shape=(m, n), axis=1, units='km') p.model.add_subsystem(name='longitude_comp', - subsys=ExecComp('long = atan(y/x)', - x={'value': np.ones(m), 'units': 'km'}, - y={'value': np.ones(m), 'units': 'km'}, - long={'value': np.ones(m), 'units': 'rad'})) + subsys=om.ExecComp('long = atan(y/x)', + x={'value': np.ones(m), 'units': 'km'}, + y={'value': np.ones(m), 'units': 'km'}, + long={'value': np.ones(m), 'units': 'rad'})) p.model.connect('demux.pos_0', 'longitude_comp.x') p.model.connect('demux.pos_1', 'longitude_comp.y') diff --git a/openmdao/components/tests/test_dot_product_comp.py b/openmdao/components/tests/test_dot_product_comp.py index 8ba5bc7e76..060fc19b49 100644 --- a/openmdao/components/tests/test_dot_product_comp.py +++ b/openmdao/components/tests/test_dot_product_comp.py @@ -1,10 +1,13 @@ +""" +Unit test for DotProductComp. +""" from __future__ import print_function, division, absolute_import import unittest import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, DotProductComp +import openmdao.api as om class TestDotProductCompNx3(unittest.TestCase): @@ -12,9 +15,9 @@ class TestDotProductCompNx3(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3)) ivc.add_output(name='b', shape=(self.nn, 3)) @@ -23,7 +26,7 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='dot_prod_comp', - subsys=DotProductComp(vec_size=self.nn)) + subsys=om.DotProductComp(vec_size=self.nn)) self.p.model.connect('a', 'dot_prod_comp.a') self.p.model.connect('b', 'dot_prod_comp.b') @@ -60,9 +63,9 @@ class TestDotProductCompNx4(unittest.TestCase): def setUp(self): self.nn = 100 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 4)) ivc.add_output(name='b', shape=(self.nn, 4)) @@ -71,7 +74,7 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='dot_prod_comp', - subsys=DotProductComp(vec_size=self.nn, length=4)) + subsys=om.DotProductComp(vec_size=self.nn, length=4)) self.p.model.connect('a', 'dot_prod_comp.a') self.p.model.connect('b', 'dot_prod_comp.b') @@ -108,9 +111,9 @@ class TestUnits(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3), units='lbf') ivc.add_output(name='b', shape=(self.nn, 3), units='ft/s') @@ -119,9 +122,9 @@ def setUp(self): promotes_outputs=['a', 'b']) self.p.model.add_subsystem(name='dot_prod_comp', - subsys=DotProductComp(vec_size=self.nn, - a_units='N', b_units='m/s', - c_units='W')) + subsys=om.DotProductComp(vec_size=self.nn, + a_units='N', b_units='m/s', + c_units='W')) self.p.model.connect('a', 'dot_prod_comp.a') self.p.model.connect('b', 'dot_prod_comp.b') @@ -154,7 +157,7 @@ def test_partials(self): decimal=6) -class TestForDocs(unittest.TestCase): +class TestFeature(unittest.TestCase): def test(self): """ @@ -162,14 +165,15 @@ def test(self): at 100 points simultaneously. """ import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, DotProductComp + + import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error n = 100 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='force', shape=(n, 3)) ivc.add_output(name='vel', shape=(n, 3)) @@ -177,8 +181,8 @@ def test(self): subsys=ivc, promotes_outputs=['force', 'vel']) - dp_comp = DotProductComp(vec_size=n, length=3, a_name='F', b_name='v', c_name='P', - a_units='N', b_units='m/s', c_units='W') + dp_comp = om.DotProductComp(vec_size=n, length=3, a_name='F', b_name='v', c_name='P', + a_units='N', b_units='m/s', c_units='W') p.model.add_subsystem(name='dot_prod_comp', subsys=dp_comp) diff --git a/openmdao/components/tests/test_eq_constraint_comp.py b/openmdao/components/tests/test_eq_constraint_comp.py index 2800fd01ca..c1b769397f 100644 --- a/openmdao/components/tests/test_eq_constraint_comp.py +++ b/openmdao/components/tests/test_eq_constraint_comp.py @@ -4,18 +4,16 @@ import numpy as np from numpy.testing import assert_almost_equal -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, \ - EQConstraintComp, ScipyOptimizeDriver - +import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarIDF - from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials + class TestEQConstraintComp(unittest.TestCase): def test_sellar_idf(self): - prob = Problem(SellarIDF()) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', disp=False) + prob = om.Problem(SellarIDF()) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', disp=False) prob.setup() # check derivatives @@ -49,14 +47,14 @@ def test_sellar_idf(self): assert_almost_equal(prob['equal.y2'], 0.0) def test_create_on_init(self): - prob = Problem() + prob = om.Problem() model = prob.model # find intersection of two non-parallel lines - model.add_subsystem('indep', IndepVarComp('x', val=0.)) - model.add_subsystem('f', ExecComp('y=3*x-3', x=0.)) - model.add_subsystem('g', ExecComp('y=2.3*x+4', x=0.)) - model.add_subsystem('equal', EQConstraintComp('y', val=11.)) + model.add_subsystem('indep', om.IndepVarComp('x', val=0.)) + model.add_subsystem('f', om.ExecComp('y=3*x-3', x=0.)) + model.add_subsystem('g', om.ExecComp('y=2.3*x+4', x=0.)) + model.add_subsystem('equal', om.EQConstraintComp('y', val=11.)) model.connect('indep.x', 'f.x') model.connect('indep.x', 'g.x') @@ -79,7 +77,7 @@ def test_create_on_init(self): model.add_constraint('equal.y', equals=0.) prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() @@ -96,14 +94,14 @@ def test_create_on_init(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_create_on_init_add_constraint(self): - prob = Problem() + prob = om.Problem() model = prob.model # find intersection of two non-parallel lines - model.add_subsystem('indep', IndepVarComp('x', val=0.)) - model.add_subsystem('f', ExecComp('y=3*x-3', x=0.)) - model.add_subsystem('g', ExecComp('y=2.3*x+4', x=0.)) - model.add_subsystem('equal', EQConstraintComp('y', add_constraint=True)) + model.add_subsystem('indep', om.IndepVarComp('x', val=0.)) + model.add_subsystem('f', om.ExecComp('y=3*x-3', x=0.)) + model.add_subsystem('g', om.ExecComp('y=2.3*x+4', x=0.)) + model.add_subsystem('equal', om.EQConstraintComp('y', add_constraint=True)) model.connect('indep.x', 'f.x') model.connect('indep.x', 'g.x') @@ -119,7 +117,7 @@ def test_create_on_init_add_constraint(self): # verify that the constraint has been added as requested self.assertTrue('equal.y' in model.get_constraints()) - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() @@ -136,15 +134,15 @@ def test_create_on_init_add_constraint(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_create_on_init_add_constraint_no_normalization(self): - prob = Problem() + prob = om.Problem() model = prob.model # find intersection of two non-parallel lines - model.add_subsystem('indep', IndepVarComp('x', val=-2.0)) - model.add_subsystem('f', ExecComp('y=3*x-3', x=0.)) - model.add_subsystem('g', ExecComp('y=2.3*x+4', x=0.)) - model.add_subsystem('equal', EQConstraintComp('y', add_constraint=True, normalize=False, - ref0=0, ref=100.0)) + model.add_subsystem('indep', om.IndepVarComp('x', val=-2.0)) + model.add_subsystem('f', om.ExecComp('y=3*x-3', x=0.)) + model.add_subsystem('g', om.ExecComp('y=2.3*x+4', x=0.)) + model.add_subsystem('equal', om.EQConstraintComp('y', add_constraint=True, normalize=False, + ref0=0, ref=100.0)) model.connect('indep.x', 'f.x') model.connect('indep.x', 'g.x') @@ -167,7 +165,7 @@ def test_create_on_init_add_constraint_no_normalization(self): diff = lhs - rhs assert_rel_error(self, prob['equal.y'], diff) - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() @@ -184,17 +182,17 @@ def test_create_on_init_add_constraint_no_normalization(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_vectorized(self): - prob = Problem() + prob = om.Problem() model = prob.model n = 100 # find intersection of two non-parallel lines, vectorized - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(n))) - model.add_subsystem('f', ExecComp('y=3*x-3', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('g', ExecComp('y=2.3*x+4', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('equal', EQConstraintComp('y', val=np.ones(n), add_constraint=True)) - model.add_subsystem('obj_cmp', ExecComp('obj=sum(y)', y=np.zeros(n))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(n))) + model.add_subsystem('f', om.ExecComp('y=3*x-3', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('g', om.ExecComp('y=2.3*x+4', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('equal', om.EQConstraintComp('y', val=np.ones(n), add_constraint=True)) + model.add_subsystem('obj_cmp', om.ExecComp('obj=sum(y)', y=np.zeros(n))) model.connect('indep.x', 'f.x') model.connect('indep.x', 'g.x') @@ -207,7 +205,7 @@ def test_vectorized(self): prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() @@ -224,18 +222,18 @@ def test_vectorized(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_vectorized_no_normalization(self): - prob = Problem() + prob = om.Problem() model = prob.model n = 100 # find intersection of two non-parallel lines, vectorized - model.add_subsystem('indep', IndepVarComp('x', val=-2.0*np.ones(n))) - model.add_subsystem('f', ExecComp('y=3*x-3', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('g', ExecComp('y=2.3*x+4', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('equal', EQConstraintComp('y', val=np.ones(n), add_constraint=True, - normalize=False)) - model.add_subsystem('obj_cmp', ExecComp('obj=sum(y)', y=np.zeros(n))) + model.add_subsystem('indep', om.IndepVarComp('x', val=-2.0*np.ones(n))) + model.add_subsystem('f', om.ExecComp('y=3*x-3', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('g', om.ExecComp('y=2.3*x+4', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('equal', om.EQConstraintComp('y', val=np.ones(n), add_constraint=True, + normalize=False)) + model.add_subsystem('obj_cmp', om.ExecComp('obj=sum(y)', y=np.zeros(n))) model.connect('indep.x', 'f.x') model.connect('indep.x', 'g.x') @@ -248,7 +246,7 @@ def test_vectorized_no_normalization(self): prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) # verify that the output is not being normalized prob.run_model() @@ -272,14 +270,14 @@ def test_vectorized_no_normalization(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_scalar_with_mult(self): - prob = Problem() + prob = om.Problem() model = prob.model # find where 2*x == x^2 - model.add_subsystem('indep', IndepVarComp('x', val=1.)) - model.add_subsystem('multx', IndepVarComp('m', val=2.)) - model.add_subsystem('f', ExecComp('y=x**2', x=1.)) - model.add_subsystem('equal', EQConstraintComp('y', use_mult=True)) + model.add_subsystem('indep', om.IndepVarComp('x', val=1.)) + model.add_subsystem('multx', om.IndepVarComp('m', val=2.)) + model.add_subsystem('f', om.ExecComp('y=x**2', x=1.)) + model.add_subsystem('equal', om.EQConstraintComp('y', use_mult=True)) model.connect('indep.x', 'f.x') @@ -292,7 +290,7 @@ def test_scalar_with_mult(self): model.add_objective('f.y') prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() assert_rel_error(self, prob['equal.y'], 0., 1e-6) @@ -306,14 +304,14 @@ def test_scalar_with_mult(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_complex_step(self): - prob = Problem() + prob = om.Problem() model = prob.model # find where 2*x == x^2 - model.add_subsystem('indep', IndepVarComp('x', val=1.)) - model.add_subsystem('multx', IndepVarComp('m', val=2.)) - model.add_subsystem('f', ExecComp('y=x**2', x=1.)) - model.add_subsystem('equal', EQConstraintComp('y', use_mult=True)) + model.add_subsystem('indep', om.IndepVarComp('x', val=1.)) + model.add_subsystem('multx', om.IndepVarComp('m', val=2.)) + model.add_subsystem('f', om.ExecComp('y=x**2', x=1.)) + model.add_subsystem('equal', om.EQConstraintComp('y', use_mult=True)) model.connect('indep.x', 'f.x') @@ -326,7 +324,7 @@ def test_complex_step(self): model.add_objective('f.y') prob.setup(mode='fwd', force_alloc_complex=True) - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() with warnings.catch_warnings(): @@ -336,18 +334,18 @@ def test_complex_step(self): assert_check_partials(cpd, atol=1e-10, rtol=1e-10) def test_vectorized_with_mult(self): - prob = Problem() + prob = om.Problem() model = prob.model n = 100 # find where 2*x == x^2, vectorized - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(n))) - model.add_subsystem('multx', IndepVarComp('m', val=np.ones(n)*2.)) - model.add_subsystem('f', ExecComp('y=x**2', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('equal', EQConstraintComp('y', val=np.ones(n), + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(n))) + model.add_subsystem('multx', om.IndepVarComp('m', val=np.ones(n)*2.)) + model.add_subsystem('f', om.ExecComp('y=x**2', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('equal', om.EQConstraintComp('y', val=np.ones(n), use_mult=True, add_constraint=True)) - model.add_subsystem('obj_cmp', ExecComp('obj=sum(y)', y=np.zeros(n))) + model.add_subsystem('obj_cmp', om.ExecComp('obj=sum(y)', y=np.zeros(n))) model.connect('indep.x', 'f.x') @@ -360,7 +358,7 @@ def test_vectorized_with_mult(self): model.add_objective('obj_cmp.obj') prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() assert_rel_error(self, prob['equal.y'], np.zeros(n), 1e-6) @@ -374,17 +372,17 @@ def test_vectorized_with_mult(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_vectorized_with_default_mult(self): - prob = Problem() + prob = om.Problem() model = prob.model n = 100 # find where 2*x == x^2, vectorized - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(n))) - model.add_subsystem('f', ExecComp('y=x**2', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('equal', EQConstraintComp('y', val=np.ones(n), + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(n))) + model.add_subsystem('f', om.ExecComp('y=x**2', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('equal', om.EQConstraintComp('y', val=np.ones(n), use_mult=True, mult_val=2., add_constraint=True)) - model.add_subsystem('obj_cmp', ExecComp('obj=sum(y)', y=np.zeros(n))) + model.add_subsystem('obj_cmp', om.ExecComp('obj=sum(y)', y=np.zeros(n))) model.connect('indep.x', 'f.x') @@ -396,7 +394,7 @@ def test_vectorized_with_default_mult(self): model.add_objective('obj_cmp.obj') prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() assert_rel_error(self, prob['equal.y'], np.zeros(n), 1e-6) @@ -410,13 +408,13 @@ def test_vectorized_with_default_mult(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_rhs_val(self): - prob = Problem() + prob = om.Problem() model = prob.model # find where x^2 == 4 - model.add_subsystem('indep', IndepVarComp('x', val=1.)) - model.add_subsystem('f', ExecComp('y=x**2', x=1.)) - model.add_subsystem('equal', EQConstraintComp('y', rhs_val=4.)) + model.add_subsystem('indep', om.IndepVarComp('x', val=1.)) + model.add_subsystem('f', om.ExecComp('y=x**2', x=1.)) + model.add_subsystem('equal', om.EQConstraintComp('y', rhs_val=4.)) model.connect('indep.x', 'f.x') model.connect('f.y', 'equal.lhs:y') @@ -426,7 +424,7 @@ def test_rhs_val(self): model.add_objective('f.y') prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() assert_rel_error(self, prob['equal.y'], 0., 1e-6) @@ -441,17 +439,17 @@ def test_rhs_val(self): assert_check_partials(cpd, atol=1e-5, rtol=1e-5) def test_vectorized_rhs_val(self): - prob = Problem() + prob = om.Problem() model = prob.model n = 100 # find where x^2 == 4, vectorized - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(n))) - model.add_subsystem('f', ExecComp('y=x**2', x=np.ones(n), y=np.ones(n))) - model.add_subsystem('equal', EQConstraintComp('y', val=np.ones(n), + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(n))) + model.add_subsystem('f', om.ExecComp('y=x**2', x=np.ones(n), y=np.ones(n))) + model.add_subsystem('equal', om.EQConstraintComp('y', val=np.ones(n), rhs_val=np.ones(n)*4., use_mult=True, mult_val=2.)) - model.add_subsystem('obj_cmp', ExecComp('obj=sum(y)', y=np.zeros(n))) + model.add_subsystem('obj_cmp', om.ExecComp('obj=sum(y)', y=np.zeros(n))) model.connect('indep.x', 'f.x') @@ -463,7 +461,7 @@ def test_vectorized_rhs_val(self): model.add_objective('obj_cmp.obj') prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() assert_rel_error(self, prob['equal.y'], np.zeros(n), 1e-6) @@ -475,16 +473,16 @@ def test_vectorized_rhs_val(self): assert_almost_equal(cpd['equal'][of, wrt]['abs error'], 0.0, decimal=5) def test_renamed_vars(self): - prob = Problem() + prob = om.Problem() model = prob.model # find intersection of two non-parallel lines, fx_y and gx_y - equal = EQConstraintComp('y', lhs_name='fx_y', rhs_name='gx_y', - add_constraint=True) + equal = om.EQConstraintComp('y', lhs_name='fx_y', rhs_name='gx_y', + add_constraint=True) - model.add_subsystem('indep', IndepVarComp('x', val=0.)) - model.add_subsystem('f', ExecComp('y=3*x-3', x=0.)) - model.add_subsystem('g', ExecComp('y=2.3*x+4', x=0.)) + model.add_subsystem('indep', om.IndepVarComp('x', val=0.)) + model.add_subsystem('f', om.ExecComp('y=3*x-3', x=0.)) + model.add_subsystem('g', om.ExecComp('y=2.3*x+4', x=0.)) model.add_subsystem('equal', equal) model.connect('indep.x', 'f.x') @@ -497,7 +495,7 @@ def test_renamed_vars(self): model.add_objective('f.y') prob.setup(mode='fwd') - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) prob.run_driver() assert_almost_equal(prob['equal.y'], 0.) @@ -516,11 +514,11 @@ def test_renamed_vars(self): class TestFeatureEQConstraintComp(unittest.TestCase): def test_feature_sellar_idf(self): - from openmdao.api import Problem, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarIDF - prob = Problem(model=SellarIDF()) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', disp=True) + prob = om.Problem(model=SellarIDF()) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', disp=True) prob.setup() prob.run_driver() diff --git a/openmdao/components/tests/test_exec_comp.py b/openmdao/components/tests/test_exec_comp.py index be327535ca..f7e69445ef 100644 --- a/openmdao/components/tests/test_exec_comp.py +++ b/openmdao/components/tests/test_exec_comp.py @@ -14,7 +14,7 @@ except ImportError: from openmdao.utils.assert_utils import SkipParameterized as parameterized -from openmdao.api import IndepVarComp, Group, Problem, ExecComp +import openmdao.api as om from openmdao.components.exec_comp import _expr_dict from openmdao.utils.assert_utils import assert_rel_error @@ -260,72 +260,72 @@ class TestExecComp(unittest.TestCase): def test_no_expr(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp()) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp()) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: No valid expressions provided to ExecComp(): [].") def test_colon_vars(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('y=foo:bar+1.')) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('y=foo:bar+1.')) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: failed to compile expression 'y=foo:bar+1.'.") def test_bad_kwargs(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('y=x+1.', xx=2.0)) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', xx=2.0)) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: arg 'xx' in call to ExecComp() does not refer to any variable " "in the expressions ['y=x+1.']") def test_bad_kwargs_meta(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('y=x+1.', - x={'val': 2, 'low': 0, 'high': 10, 'units': 'ft'})) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', + x={'val': 2, 'low': 0, 'high': 10, 'units': 'ft'})) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: the following metadata names were not recognized for " "variable 'x': ['high', 'low', 'val']") def test_name_collision_const(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('e=x+1.')) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('e=x+1.')) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: cannot assign to variable 'e' because it's already defined " "as an internal function or constant.") def test_name_collision_func(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('sin=x+1.')) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('sin=x+1.')) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: cannot assign to variable 'sin' because it's already defined " "as an internal function or constant.") def test_func_as_rhs_var(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('y=sin+1.')) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('y=sin+1.')) with self.assertRaises(Exception) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "C1: cannot use 'sin' as a variable because it's already defined " "as an internal function.") def test_mixed_type(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y=sum(x)', - x=np.arange(10, dtype=float))) - prob.setup(check=False) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=sum(x)', + x=np.arange(10, dtype=float))) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -339,10 +339,10 @@ def test_mixed_type(self): assert_rel_error(self, C1._outputs['y'], 45.0, 0.00001) def test_simple(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y=x+1.', x=2.0)) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', x=2.0)) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -356,10 +356,10 @@ def test_simple(self): assert_rel_error(self, C1._outputs['y'], 3.0, 0.00001) def test_for_spaces(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y = pi * x', x=2.0)) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y = pi * x', x=2.0)) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -374,15 +374,15 @@ def test_for_spaces(self): assert_rel_error(self, C1._outputs['y'], 2 * math.pi, 0.00001) def test_units(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('indep', IndepVarComp('x', 100.0, units='cm')) - C1 = prob.model.add_subsystem('C1', ExecComp('y=x+z+1.', - x={'value': 2.0, 'units': 'm'}, - y={'units': 'm'}, - z=2.0)) + prob = om.Problem() + prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm')) + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.', + x={'value': 2.0, 'units': 'm'}, + y={'units': 'm'}, + z=2.0)) prob.model.connect('indep.x', 'C1.x') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -390,51 +390,51 @@ def test_units(self): assert_rel_error(self, C1._outputs['y'], 4.0, 0.00001) def test_units_varname(self): - prob = Problem(model=Group()) + prob = om.Problem() with self.assertRaises(TypeError) as cm: - prob.model.add_subsystem('C1', ExecComp('y=x+units+1.', - x={'value': 2.0, 'units': 'm'}, - y={'units': 'm'}, - units=2.0)) + prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.', + x={'value': 2.0, 'units': 'm'}, + y={'units': 'm'}, + units=2.0)) self.assertEqual(str(cm.exception), "Value (2.0) of option 'units' has type 'float', " "but type 'str' was expected.") def test_units_varname_str(self): - prob = Problem(model=Group()) + prob = om.Problem() with self.assertRaises(ValueError) as cm: - prob.model.add_subsystem('C1', ExecComp('y=x+units+1.', - x={'value': 2.0, 'units': 'm'}, - y={'units': 'm'}, - units='two')) + prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.', + x={'value': 2.0, 'units': 'm'}, + y={'units': 'm'}, + units='two')) self.assertEqual(str(cm.exception), "The units 'two' are invalid.") def test_units_varname_novalue(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('indep', IndepVarComp('x', 100.0, units='cm')) - C1 = prob.model.add_subsystem('C1', ExecComp('y=x+units+1.', - x={'value': 2.0, 'units': 'm'}, - y={'units': 'm'})) + prob = om.Problem() + prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm')) + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.', + x={'value': 2.0, 'units': 'm'}, + y={'units': 'm'})) prob.model.connect('indep.x', 'C1.x') with self.assertRaises(NameError) as cm: - prob.setup(check=False) + prob.setup() self.assertEqual(str(cm.exception), "C1: cannot use variable name 'units' because it's a reserved keyword.") def test_common_units(self): # all variables in the ExecComp have the same units - prob = Problem(model=Group()) + prob = om.Problem() - prob.model.add_subsystem('indep', IndepVarComp('x', 100.0, units='cm')) - prob.model.add_subsystem('comp', ExecComp('y=x+z+1.', units='m', - x={'value': 2.0}, - z=2.0)) + prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm')) + prob.model.add_subsystem('comp', om.ExecComp('y=x+z+1.', units='m', + x={'value': 2.0}, + z=2.0)) prob.model.connect('indep.x', 'comp.x') prob.setup() @@ -444,10 +444,10 @@ def test_common_units(self): def test_common_units_no_meta(self): # make sure common units are assigned when no metadata is provided - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('indep', IndepVarComp('x', 2.0, units='km')) - prob.model.add_subsystem('comp', ExecComp('y = x+1', units='m')) + prob.model.add_subsystem('indep', om.IndepVarComp('x', 2.0, units='km')) + prob.model.add_subsystem('comp', om.ExecComp('y = x+1', units='m')) prob.model.connect('indep.x', 'comp.x') @@ -457,28 +457,28 @@ def test_common_units_no_meta(self): assert_rel_error(self, prob['comp.y'], 2001., 0.00001) def test_conflicting_units(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('indep', IndepVarComp('x', 100.0, units='cm')) - C1 = prob.model.add_subsystem('C1', ExecComp('y=x+z+1.', units='m', - x={'value': 2.0, 'units': 'km'}, - z=2.0)) + prob = om.Problem() + prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm')) + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.', units='m', + x={'value': 2.0, 'units': 'km'}, + z=2.0)) prob.model.connect('indep.x', 'C1.x') with self.assertRaises(RuntimeError) as cm: - prob.setup(check=False) + prob.setup() self.assertEqual(str(cm.exception), "C1: units of 'km' have been specified for variable 'x', but " "units of 'm' have been specified for the entire component.") def test_shape_and_value(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', - x={'shape': (5,), 'value': np.zeros(5)}, - y={'shape': (5,), 'value': np.zeros(5)})) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', + x={'shape': (5,), 'value': np.zeros(5)}, + y={'shape': (5,), 'value': np.zeros(5)})) model.connect('indep.x', 'comp.x') @@ -490,13 +490,13 @@ def test_shape_and_value(self): assert_almost_equal(J, np.eye(5)*3., decimal=6) def test_conflicting_shape(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', - x={'shape': (5,), 'value': 5}, - y={'shape': (5,)})) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', + x={'shape': (5,), 'value': 5}, + y={'shape': (5,)})) model.connect('indep.x', 'comp.x') @@ -508,11 +508,11 @@ def test_conflicting_shape(self): "but a value of shape (1,) has been provided.") def test_common_shape(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', shape=(5,))) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,))) model.connect('indep.x', 'comp.x') @@ -524,13 +524,13 @@ def test_common_shape(self): assert_almost_equal(J, np.eye(5)*3., decimal=6) def test_common_shape_with_values(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', shape=(5,), - x={'value': np.zeros(5)}, - y={'value': np.zeros(5)})) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,), + x={'value': np.zeros(5)}, + y={'value': np.zeros(5)})) model.connect('indep.x', 'comp.x') @@ -542,12 +542,12 @@ def test_common_shape_with_values(self): assert_almost_equal(J, np.eye(5)*3., decimal=6) def test_common_shape_conflicting_shape(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', shape=(5,), - y={'shape': (10,)})) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,), + y={'shape': (10,)})) model.connect('indep.x', 'comp.x') @@ -559,12 +559,12 @@ def test_common_shape_conflicting_shape(self): "but shape of (5,) has been specified for the entire component.") def test_common_shape_conflicting_value(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', shape=(5,), - x={'value': 5})) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,), + x={'value': 5})) model.connect('indep.x', 'comp.x') @@ -576,10 +576,10 @@ def test_common_shape_conflicting_value(self): "but shape of (5,) has been specified for the entire component.") def test_math(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y=sin(x)', x=2.0)) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=sin(x)', x=2.0)) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -593,12 +593,12 @@ def test_math(self): assert_rel_error(self, C1._outputs['y'], math.sin(2.0), 0.00001) def test_array(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y=x[1]', - x=np.array([1., 2., 3.]), - y=0.0)) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x[1]', + x=np.array([1., 2., 3.]), + y=0.0)) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -612,12 +612,12 @@ def test_array(self): assert_rel_error(self, C1._outputs['y'], 2.0, 0.00001) def test_array_lhs(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp(['y[0]=x[1]', 'y[1]=x[0]'], - x=np.array([1., 2., 3.]), - y=np.array([0., 0.]))) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp(['y[0]=x[1]', 'y[1]=x[0]'], + x=np.array([1., 2., 3.]), + y=np.array([0., 0.]))) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -631,16 +631,15 @@ def test_array_lhs(self): assert_rel_error(self, C1._outputs['y'], np.array([2., 1.]), 0.00001) def test_simple_array_model(self): - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p1', IndepVarComp('x', np.ones([2]))) - prob.model.add_subsystem('comp', ExecComp(['y[0]=2.0*x[0]+7.0*x[1]', - 'y[1]=5.0*x[0]-3.0*x[1]'], - x=np.zeros([2]), y=np.zeros([2]))) + prob = om.Problem() + prob.model.add_subsystem('p1', om.IndepVarComp('x', np.ones([2]))) + prob.model.add_subsystem('comp', om.ExecComp(['y[0]=2.0*x[0]+7.0*x[1]', + 'y[1]=5.0*x[0]-3.0*x[1]'], + x=np.zeros([2]), y=np.zeros([2]))) prob.model.connect('p1.x', 'comp.x') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -654,16 +653,15 @@ def test_simple_array_model(self): assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][2], 0.0, 1e-5) def test_simple_array_model2(self): - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p1', IndepVarComp('x', np.ones([2]))) - prob.model.add_subsystem('comp', ExecComp('y = mat.dot(x)', - x=np.zeros((2,)), y=np.zeros((2,)), - mat=np.array([[2., 7.], [5., -3.]]))) + prob = om.Problem() + prob.model.add_subsystem('p1', om.IndepVarComp('x', np.ones([2]))) + prob.model.add_subsystem('comp', om.ExecComp('y = mat.dot(x)', + x=np.zeros((2,)), y=np.zeros((2,)), + mat=np.array([[2., 7.], [5., -3.]]))) prob.model.connect('p1.x', 'comp.x') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -677,10 +675,10 @@ def test_simple_array_model2(self): assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][2], 0.0, 1e-5) def test_complex_step(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp(['y=2.0*x+1.'], x=2.0)) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0)) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -698,9 +696,9 @@ def test_complex_step(self): assert_rel_error(self, C1._jacobian[('y', 'x')], [[2.0]], 0.00001) def test_complex_step2(self): - prob = Problem(Group()) - prob.model.add_subsystem('p1', IndepVarComp('x', 2.0)) - prob.model.add_subsystem('comp', ExecComp('y=x*x + x*2.0')) + prob = om.Problem(om.Group()) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 2.0)) + prob.model.add_subsystem('comp', om.ExecComp('y=x*x + x*2.0')) prob.model.connect('p1.x', 'comp.x') prob.set_solver_print(level=0) @@ -717,10 +715,10 @@ def test_complex_step2(self): assert_rel_error(self, J['comp.y', 'p1.x'], np.array([[6.0]]), 0.00001) def test_abs_complex_step(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y=2.0*abs(x)', x=-2.0)) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=2.0*abs(x)', x=-2.0)) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -740,11 +738,11 @@ def test_abs_complex_step(self): assert_rel_error(self, C1._jacobian['y', 'x'], [[2.0]], 0.00001) def test_abs_array_complex_step(self): - prob = Problem(model=Group()) - C1 = prob.model.add_subsystem('C1', ExecComp('y=2.0*abs(x)', - x=np.ones(3)*-2.0, y=np.zeros(3))) + prob = om.Problem() + C1 = prob.model.add_subsystem('C1', om.ExecComp('y=2.0*abs(x)', + x=np.ones(3)*-2.0, y=np.zeros(3))) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -773,13 +771,13 @@ def test_abs_array_complex_step(self): assert_rel_error(self, C1._jacobian['y', 'x'], expect, 0.00001) def test_vectorize_error(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(3))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(3))) model.add_design_var('indep.x') mat = np.arange(15).reshape((3,5)) - model.add_subsystem('comp', ExecComp('y=A.dot(x)', vectorize=True, A=mat, x=np.ones(5), y=np.ones(3))) + model.add_subsystem('comp', om.ExecComp('y=A.dot(x)', vectorize=True, A=mat, x=np.ones(5), y=np.ones(3))) model.connect('indep.x', 'comp.x') with self.assertRaises(Exception) as context: @@ -788,12 +786,12 @@ def test_vectorize_error(self): "comp: vectorize is True but partial(y, A) is not square (shape=(3, 15)).") def test_vectorize_shape_only(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', vectorize=True, - x={'shape': (5,)}, y={'shape': (5,)})) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', vectorize=True, + x={'shape': (5,)}, y={'shape': (5,)})) model.connect('indep.x', 'comp.x') p.setup() @@ -805,13 +803,13 @@ def test_vectorize_shape_only(self): def test_feature_vectorize(self): import numpy as np - from openmdao.api import IndepVarComp, Problem, ExecComp + import openmdao.api as om - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5))) - model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', vectorize=True, x=np.ones(5), y=np.ones(5))) + model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', vectorize=True, x=np.ones(5), y=np.ones(5))) model.connect('indep.x', 'comp.x') p.setup() @@ -822,13 +820,13 @@ def test_feature_vectorize(self): assert_almost_equal(J, np.eye(5)*3., decimal=6) def test_feature_simple(self): - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0)) - model.add_subsystem('comp', ExecComp('y=x+1.')) + model.add_subsystem('p', om.IndepVarComp('x', 2.0)) + model.add_subsystem('comp', om.ExecComp('y=x+1.')) model.connect('p.x', 'comp.x') @@ -840,13 +838,13 @@ def test_feature_simple(self): assert_rel_error(self, prob['comp.y'], 3.0, 0.00001) def test_feature_multi_output(self): - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0)) - model.add_subsystem('comp', ExecComp(['y1=x+1.', 'y2=x-1.'])) + model.add_subsystem('p', om.IndepVarComp('x', 2.0)) + model.add_subsystem('comp', om.ExecComp(['y1=x+1.', 'y2=x-1.'])) model.connect('p.x', 'comp.x') @@ -861,15 +859,15 @@ def test_feature_multi_output(self): def test_feature_array(self): import numpy as np - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p', IndepVarComp('x', np.array([1., 2., 3.]))) - model.add_subsystem('comp', ExecComp('y=x[1]', - x=np.array([1., 2., 3.]), - y=0.0)) + model.add_subsystem('p', om.IndepVarComp('x', np.array([1., 2., 3.]))) + model.add_subsystem('comp', om.ExecComp('y=x[1]', + x=np.array([1., 2., 3.]), + y=0.0)) model.connect('p.x', 'comp.x') prob.setup() @@ -882,14 +880,14 @@ def test_feature_array(self): def test_feature_math(self): import numpy as np - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.pi/2.0)) - model.add_subsystem('p2', IndepVarComp('y', np.pi/2.0)) - model.add_subsystem('comp', ExecComp('z = sin(x)**2 + cos(y)**2')) + model.add_subsystem('p1', om.IndepVarComp('x', np.pi/2.0)) + model.add_subsystem('p2', om.IndepVarComp('y', np.pi/2.0)) + model.add_subsystem('comp', om.ExecComp('z = sin(x)**2 + cos(y)**2')) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') @@ -904,13 +902,13 @@ def test_feature_math(self): def test_feature_numpy(self): import numpy as np - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p', IndepVarComp('x', np.array([1., 2., 3.]))) - model.add_subsystem('comp', ExecComp('y=sum(x)', x=np.zeros((3, )))) + model.add_subsystem('p', om.IndepVarComp('x', np.array([1., 2., 3.]))) + model.add_subsystem('comp', om.ExecComp('y=sum(x)', x=np.zeros((3, )))) model.connect('p.x', 'comp.x') prob.setup() @@ -921,17 +919,17 @@ def test_feature_numpy(self): assert_rel_error(self, prob['comp.y'], 6.0, 0.00001) def test_feature_metadata(self): - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 12.0, units='inch')) - model.add_subsystem('p2', IndepVarComp('y', 1.0, units='ft')) - model.add_subsystem('comp', ExecComp('z=x+y', - x={'value': 0.0, 'units': 'inch'}, - y={'value': 0.0, 'units': 'inch'}, - z={'value': 0.0, 'units': 'inch'})) + model.add_subsystem('p1', om.IndepVarComp('x', 12.0, units='inch')) + model.add_subsystem('p2', om.IndepVarComp('y', 1.0, units='ft')) + model.add_subsystem('comp', om.ExecComp('z=x+y', + x={'value': 0.0, 'units': 'inch'}, + y={'value': 0.0, 'units': 'inch'}, + z={'value': 0.0, 'units': 'inch'})) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') @@ -943,18 +941,18 @@ def test_feature_metadata(self): assert_rel_error(self, prob['comp.z'], 24.0, 0.00001) def test_feature_options(self): - from openmdao.api import IndepVarComp, Group, Problem, ExecComp + import openmdao.api as om - model = Group() + model = om.Group() - indep = model.add_subsystem('indep', IndepVarComp('x', shape=(2,), units='cm')) - xcomp = model.add_subsystem('comp', ExecComp('y=2*x', shape=(2,))) + indep = model.add_subsystem('indep', om.IndepVarComp('x', shape=(2,), units='cm')) + xcomp = model.add_subsystem('comp', om.ExecComp('y=2*x', shape=(2,))) xcomp.options['units'] = 'm' model.connect('indep.x', 'comp.x') - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob['indep.x'] = [100., 200.] @@ -972,18 +970,18 @@ class TestExecCompParameterized(unittest.TestCase): def test_exec_comp_value(self, f): test_data = _ufunc_test_data[f] - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model if len(test_data['args']) > 1: - ivc = model.add_subsystem(name='ivc', subsys=IndepVarComp()) + ivc = model.add_subsystem(name='ivc', subsys=om.IndepVarComp()) for arg_name, arg_value in iteritems(test_data['args']): if arg_name == 'f': continue ivc.add_output(name=arg_name, val=arg_value['value']) model.connect('ivc.{0}'.format(arg_name), 'comp.{0}'.format(arg_name)) - model.add_subsystem('comp', ExecComp(test_data['str'], **test_data['args']), + model.add_subsystem('comp', om.ExecComp(test_data['str'], **test_data['args']), promotes_outputs=['f']) prob.setup() prob.run_model() @@ -1017,11 +1015,11 @@ def test_exec_comp_value(self, f): def test_exec_comp_jac(self, f): test_data = _ufunc_test_data[f] - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model if len(test_data['args']) > 1: - ivc = model.add_subsystem(name='ivc', subsys=IndepVarComp()) + ivc = model.add_subsystem(name='ivc', subsys=om.IndepVarComp()) for arg_name, arg_value in iteritems(test_data['args']): if arg_name == 'f': continue @@ -1030,7 +1028,7 @@ def test_exec_comp_jac(self, f): '{0}_comp.{1}'.format(f, arg_name)) model.add_subsystem('{0}_comp'.format(f), - ExecComp(test_data['str'], **test_data['args']), + om.ExecComp(test_data['str'], **test_data['args']), promotes_outputs=['f']) prob.setup() prob.run_model() diff --git a/openmdao/components/tests/test_external_code_comp.py b/openmdao/components/tests/test_external_code_comp.py index e280e8eff2..47fe15be47 100644 --- a/openmdao/components/tests/test_external_code_comp.py +++ b/openmdao/components/tests/test_external_code_comp.py @@ -9,7 +9,7 @@ from scipy.optimize import fsolve -from openmdao.api import Problem, ExternalCodeComp, AnalysisError +import openmdao.api as om from openmdao.components.external_code_comp import STDOUT from openmdao.utils.assert_utils import assert_rel_error, assert_warning @@ -52,9 +52,9 @@ def setUp(self): shutil.copy(os.path.join(DIRECTORY, 'extcode_example.py'), os.path.join(self.tempdir, 'extcode_example.py')) - self.prob = Problem() + self.prob = om.Problem() - self.extcode = self.prob.model.add_subsystem('extcode', ExternalCodeComp()) + self.extcode = self.prob.model.add_subsystem('extcode', om.ExternalCodeComp()) def tearDown(self): os.chdir(self.startdir) @@ -117,7 +117,7 @@ def test_timeout_raise(self): self.prob.setup(check=True) try: self.prob.run_model() - except AnalysisError as exc: + except om.AnalysisError as exc: self.assertEqual(str(exc), 'Timed out after 1.0 sec.') else: self.fail('Expected AnalysisError') @@ -152,7 +152,7 @@ def test_error_code_soft(self): self.prob.setup(check=True) try: self.prob.run_model() - except AnalysisError as err: + except om.AnalysisError as err: self.assertTrue("delay must be >= 0" in str(err), "expected 'delay must be >= 0' to be in '%s'" % str(err)) self.assertTrue('Traceback' in str(err), @@ -192,7 +192,7 @@ def test_badcmd(self): # Set command to nonexistant path. self.extcode.options['command'] = ['no-such-command'] - self.prob.setup(check=False) + self.prob.setup() try: self.prob.run_model() except ValueError as exc: @@ -206,7 +206,7 @@ def test_nullcmd(self): self.extcode.stdout = 'nullcmd.out' self.extcode.stderr = STDOUT - self.prob.setup(check=False) + self.prob.setup() try: self.prob.run_model() except ValueError as exc: @@ -237,12 +237,12 @@ class TestExternalCodeCompArgs(unittest.TestCase): def test_kwargs(self): # check kwargs are passed to options - extcode = ExternalCodeComp(poll_delay=999) + extcode = om.ExternalCodeComp(poll_delay=999) self.assertTrue(extcode.options['poll_delay'] == 999) # check subclass kwargs are also passed to options - class MyComp(ExternalCodeComp): + class MyComp(om.ExternalCodeComp): def initialize(self): self.options.declare('my_arg', 'foo', desc='subclass option') @@ -258,7 +258,7 @@ def initialize(self): self.assertEqual(my_comp_opts.difference(extcode_opts), set(('my_arg',))) -class ParaboloidExternalCodeComp(ExternalCodeComp): +class ParaboloidExternalCodeComp(om.ExternalCodeComp): def setup(self): self.add_input('x', val=0.0) self.add_input('y', val=0.0) @@ -295,7 +295,7 @@ def compute(self, inputs, outputs): outputs['f_xy'] = f_xy -class ParaboloidExternalCodeCompFD(ExternalCodeComp): +class ParaboloidExternalCodeCompFD(om.ExternalCodeComp): def setup(self): self.add_input('x', val=0.0) self.add_input('y', val=0.0) @@ -335,7 +335,7 @@ def compute(self, inputs, outputs): outputs['f_xy'] = f_xy -class ParaboloidExternalCodeCompDerivs(ExternalCodeComp): +class ParaboloidExternalCodeCompDerivs(om.ExternalCodeComp): def setup(self): self.add_input('x', val=0.0) self.add_input('y', val=0.0) @@ -419,15 +419,15 @@ def tearDown(self): pass def test_main(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.components.tests.test_external_code_comp import ParaboloidExternalCodeComp - prob = Problem() + prob = om.Problem() model = prob.model # create and connect inputs - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('p', ParaboloidExternalCodeComp()) model.connect('p1.x', 'p.x') @@ -441,16 +441,15 @@ def test_main(self): self.assertEqual(prob['p.f_xy'], -15.0) def test_optimize_fd(self): - from openmdao.api import Problem, IndepVarComp - from openmdao.api import ScipyOptimizeDriver + import openmdao.api as om from openmdao.components.tests.test_external_code_comp import ParaboloidExternalCodeCompFD - prob = Problem() + prob = om.Problem() model = prob.model # create and connect inputs - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('p', ParaboloidExternalCodeCompFD()) model.connect('p1.x', 'p.x') @@ -458,7 +457,7 @@ def test_optimize_fd(self): # find optimal solution with SciPy optimize # solution (minimum): x = 6.6667; y = -7.3333 - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('p1.x', lower=-50, upper=50) @@ -476,16 +475,15 @@ def test_optimize_fd(self): assert_rel_error(self, prob['p2.y'], -7.3333333, 1e-6) def test_optimize_derivs(self): - from openmdao.api import Problem, IndepVarComp - from openmdao.api import ScipyOptimizeDriver + import openmdao.api as om from openmdao.components.tests.test_external_code_comp import ParaboloidExternalCodeCompDerivs - prob = Problem() + prob = om.Problem() model = prob.model # create and connect inputs - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('p', ParaboloidExternalCodeCompDerivs()) model.connect('p1.x', 'p.x') @@ -493,7 +491,7 @@ def test_optimize_derivs(self): # find optimal solution with SciPy optimize # solution (minimum): x = 6.6667; y = -7.3333 - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('p1.x', lower=-50, upper=50) @@ -537,7 +535,7 @@ def setUp(self): with assert_warning(DeprecationWarning, msg): self.extcode = DeprecatedExternalCodeForTesting() - self.prob = Problem() + self.prob = om.Problem() self.prob.model.add_subsystem('extcode', self.extcode) @@ -591,10 +589,9 @@ def tearDown(self): pass def test_simple_external_code_implicit_comp(self): - from openmdao.api import Group, NewtonSolver, Problem, IndepVarComp, DirectSolver, \ - ExternalCodeImplicitComp + import openmdao.api as om - class MachExternalCodeComp(ExternalCodeImplicitComp): + class MachExternalCodeComp(om.ExternalCodeImplicitComp): def initialize(self): self.options.declare('super_sonic', types=bool) @@ -646,17 +643,17 @@ def solve_nonlinear(self, inputs, outputs): mach = float(output_file.read()) outputs['mach'] = mach - group = Group() - group.add_subsystem('ar', IndepVarComp('area_ratio', 0.5)) + group = om.Group() + group.add_subsystem('ar', om.IndepVarComp('area_ratio', 0.5)) mach_comp = group.add_subsystem('comp', MachExternalCodeComp(), promotes=['*']) - prob = Problem(model=group) - group.nonlinear_solver = NewtonSolver() + prob = om.Problem(model=group) + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['solve_subsystems'] = True group.nonlinear_solver.options['iprint'] = 0 group.nonlinear_solver.options['maxiter'] = 20 - group.linear_solver = DirectSolver() + group.linear_solver = om.DirectSolver() - prob.setup(check=False) + prob.setup() area_ratio = 1.3 super_sonic = False diff --git a/openmdao/components/tests/test_ks_comp.py b/openmdao/components/tests/test_ks_comp.py index 940494abff..eddd103968 100644 --- a/openmdao/components/tests/test_ks_comp.py +++ b/openmdao/components/tests/test_ks_comp.py @@ -5,9 +5,7 @@ import numpy as np -from openmdao.api import Problem, IndepVarComp, Group, ExecComp, ScipyOptimizeDriver, \ - ExplicitComponent -from openmdao.components.ks_comp import KSComp +import openmdao.api as om from openmdao.test_suite.components.simple_comps import DoubleArrayComp from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_stress import MultipointBeamGroup from openmdao.utils.assert_utils import assert_rel_error, assert_warning @@ -16,12 +14,12 @@ class TestKSFunction(unittest.TestCase): def test_basic_ks(self): - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) + model.add_subsystem('px', om.IndepVarComp(name="x", val=np.ones((2, )))) model.add_subsystem('comp', DoubleArrayComp()) - model.add_subsystem('ks', KSComp(width=2)) + model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'comp.x1') model.connect('comp.y2', 'ks.g') @@ -29,28 +27,28 @@ def test_basic_ks(self): model.add_objective('comp.y1') model.add_constraint('ks.KS', upper=0.0) - prob.setup(check=False) + prob.setup() prob.run_driver() assert_rel_error(self, max(prob['comp.y2']), prob['ks.KS'][0]) def test_vectorized(self): - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model x = np.zeros((3, 5)) x[0, :] = np.array([3.0, 5.0, 11.0, 13.0, 17.0]) x[1, :] = np.array([13.0, 11.0, 5.0, 17.0, 3.0])*2 x[2, :] = np.array([11.0, 3.0, 17.0, 5.0, 13.0])*3 - model.add_subsystem('px', IndepVarComp(name="x", val=x)) - model.add_subsystem('ks', KSComp(width=5, vec_size=3)) + model.add_subsystem('px', om.IndepVarComp(name="x", val=x)) + model.add_subsystem('ks', om.KSComp(width=5, vec_size=3)) model.connect('px.x', 'ks.g') model.add_design_var('px.x') model.add_constraint('ks.KS', upper=0.0) - prob.setup(check=False) + prob.setup() prob.run_driver() assert_rel_error(self, prob['ks.KS'][0], 17.0) @@ -63,17 +61,17 @@ def test_vectorized(self): assert_rel_error(self, partials['ks'][of, wrt]['abs error'][0], 0.0, 1e-6) def test_partials_no_compute(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0]))) - ks_comp = model.add_subsystem('ks', KSComp(width=2)) + ks_comp = model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'ks.g') - prob.setup(check=False) + prob.setup() prob.run_driver() # compute partials with the current model inputs @@ -101,11 +99,11 @@ def test_beam_stress(self): num_elements = 25 num_load_cases = 2 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, max_bending = max_bending, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, max_bending = max_bending, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases)) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -127,12 +125,12 @@ def test_beam_stress(self): def test_upper(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) - model.add_subsystem('comp', ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) - model.add_subsystem('ks', KSComp(width=2)) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0]))) + model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) + model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') @@ -145,12 +143,12 @@ def test_upper(self): def test_lower_flag(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) - model.add_subsystem('comp', ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) - model.add_subsystem('ks', KSComp(width=2)) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0]))) + model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) + model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') @@ -167,10 +165,10 @@ def test_deprecated_ks_component(self): # self-contained, to be removed when class name goes away. from openmdao.components.ks_comp import KSComponent # deprecated - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2,)))) + model.add_subsystem('px', om.IndepVarComp(name="x", val=np.ones((2,)))) model.add_subsystem('comp', DoubleArrayComp()) msg = "'KSComponent' has been deprecated. Use 'KSComp' instead." @@ -185,7 +183,7 @@ def test_deprecated_ks_component(self): model.add_objective('comp.y1') model.add_constraint('ks.KS', upper=0.0) - prob.setup(check=False) + prob.setup() prob.run_driver() assert_rel_error(self, max(prob['comp.y2']), prob['ks.KS'][0]) @@ -196,15 +194,15 @@ class TestKSFunctionFeatures(unittest.TestCase): def test_basic(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp - from openmdao.components.ks_comp import KSComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) - model.add_subsystem('comp', ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) - model.add_subsystem('ks', KSComp(width=2)) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0]))) + model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), + y=np.zeros((2, )))) + model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') @@ -217,15 +215,15 @@ def test_basic(self): def test_vectorized(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp - from openmdao.components.ks_comp import KSComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([[5.0, 4.0], [10.0, 8.0]]))) - model.add_subsystem('comp', ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('ks', KSComp(width=2, vec_size=2)) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([[5.0, 4.0], [10.0, 8.0]]))) + model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, 2)), + y=np.zeros((2, 2)))) + model.add_subsystem('ks', om.KSComp(width=2, vec_size=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') @@ -239,15 +237,15 @@ def test_vectorized(self): def test_upper(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp - from openmdao.components.ks_comp import KSComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) - model.add_subsystem('comp', ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) - model.add_subsystem('ks', KSComp(width=2)) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0]))) + model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), + y=np.zeros((2, )))) + model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') @@ -261,15 +259,15 @@ def test_upper(self): def test_lower_flag(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp - from openmdao.components.ks_comp import KSComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) - model.add_subsystem('comp', ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, )))) - model.add_subsystem('ks', KSComp(width=2)) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0]))) + model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), + y=np.zeros((2, )))) + model.add_subsystem('ks', om.KSComp(width=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') diff --git a/openmdao/components/tests/test_linear_system_comp.py b/openmdao/components/tests/test_linear_system_comp.py index 7a3e520a83..15b06d841f 100644 --- a/openmdao/components/tests/test_linear_system_comp.py +++ b/openmdao/components/tests/test_linear_system_comp.py @@ -4,8 +4,7 @@ import numpy as np -from openmdao.api import Group, Problem, IndepVarComp -from openmdao.api import LinearSystemComp, ScipyKrylov, DirectSolver +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error @@ -15,25 +14,25 @@ class TestLinearSystemComp(unittest.TestCase): def test_basic(self): """Check against the scipy solver.""" - model = Group() + model = om.Group() x = np.array([1, 2, -3]) A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = A.dot(x) - model.add_subsystem('p1', IndepVarComp('A', A)) - model.add_subsystem('p2', IndepVarComp('b', b)) + model.add_subsystem('p1', om.IndepVarComp('A', A)) + model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) - lingrp.add_subsystem('lin', LinearSystemComp(size=3)) + lingrp = model.add_subsystem('lingrp', om.Group(), promotes=['*']) + lingrp.add_subsystem('lin', om.LinearSystemComp(size=3)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') - prob = Problem(model) + prob = om.Problem(model) prob.setup() - lingrp.linear_solver = ScipyKrylov() + lingrp.linear_solver = om.ScipyKrylov() prob.set_solver_print(level=0) prob.run_model() @@ -50,25 +49,25 @@ def test_basic(self): def test_vectorized(self): """Check against the scipy solver.""" - model = Group() + model = om.Group() x = np.array([[1, 2, -3], [2, -1, 4]]) A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = np.einsum('jk,ik->ij', A, x) - model.add_subsystem('p1', IndepVarComp('A', A)) - model.add_subsystem('p2', IndepVarComp('b', b)) + model.add_subsystem('p1', om.IndepVarComp('A', A)) + model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) - lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2)) + lingrp = model.add_subsystem('lingrp', om.Group(), promotes=['*']) + lingrp.add_subsystem('lin', om.LinearSystemComp(size=3, vec_size=2)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') - prob = Problem(model) + prob = om.Problem(model) prob.setup() - lingrp.linear_solver = ScipyKrylov() + lingrp.linear_solver = om.ScipyKrylov() prob.set_solver_print(level=0) prob.run_model() @@ -85,26 +84,26 @@ def test_vectorized(self): def test_vectorized_A(self): """Check against the scipy solver.""" - model = Group() + model = om.Group() x = np.array([[1, 2, -3], [2, -1, 4]]) A = np.array([[[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]], [[2.0, 3.0, 4.0], [1.0, -1.0, -2.0], [3.0, 2.0, -2.0]]]) b = np.einsum('ijk,ik->ij', A, x) - model.add_subsystem('p1', IndepVarComp('A', A)) - model.add_subsystem('p2', IndepVarComp('b', b)) + model.add_subsystem('p1', om.IndepVarComp('A', A)) + model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) - lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2, vectorize_A=True)) + lingrp = model.add_subsystem('lingrp', om.Group(), promotes=['*']) + lingrp.add_subsystem('lin', om.LinearSystemComp(size=3, vec_size=2, vectorize_A=True)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') - prob = Problem(model) + prob = om.Problem(model) prob.setup() - lingrp.linear_solver = ScipyKrylov() + lingrp.linear_solver = om.ScipyKrylov() prob.set_solver_print(level=0) prob.run_model() @@ -126,20 +125,20 @@ def test_solve_linear(self): b = A.dot(x) b_T = A.T.dot(x) - lin_sys_comp = LinearSystemComp(size=3) + lin_sys_comp = om.LinearSystemComp(size=3) - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('A', A)) - prob.model.add_subsystem('p2', IndepVarComp('b', b)) + prob.model.add_subsystem('p1', om.IndepVarComp('A', A)) + prob.model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = prob.model.add_subsystem('lingrp', Group(), promotes=['*']) + lingrp = prob.model.add_subsystem('lingrp', om.Group(), promotes=['*']) lingrp.add_subsystem('lin', lin_sys_comp) prob.model.connect('p1.A', 'lin.A') prob.model.connect('p2.b', 'lin.b') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -187,20 +186,20 @@ def test_solve_linear_vectorized(self): b = np.einsum('jk,ik->ij', A, x) b_T = np.einsum('jk,ik->ij', A.T, x) - lin_sys_comp = LinearSystemComp(size=3, vec_size=2) + lin_sys_comp = om.LinearSystemComp(size=3, vec_size=2) - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('A', A)) - prob.model.add_subsystem('p2', IndepVarComp('b', b)) + prob.model.add_subsystem('p1', om.IndepVarComp('A', A)) + prob.model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = prob.model.add_subsystem('lingrp', Group(), promotes=['*']) + lingrp = prob.model.add_subsystem('lingrp', om.Group(), promotes=['*']) lingrp.add_subsystem('lin', lin_sys_comp) prob.model.connect('p1.A', 'lin.A') prob.model.connect('p2.b', 'lin.b') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -249,20 +248,20 @@ def test_solve_linear_vectorized_A(self): b = np.einsum('ijk,ik->ij', A, x) b_T = np.einsum('ijk,ik->ij', A.transpose(0, 2, 1), x) - lin_sys_comp = LinearSystemComp(size=3, vec_size=2, vectorize_A=True) + lin_sys_comp = om.LinearSystemComp(size=3, vec_size=2, vectorize_A=True) - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('A', A)) - prob.model.add_subsystem('p2', IndepVarComp('b', b)) + prob.model.add_subsystem('p1', om.IndepVarComp('A', A)) + prob.model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = prob.model.add_subsystem('lingrp', Group(), promotes=['*']) + lingrp = prob.model.add_subsystem('lingrp', om.Group(), promotes=['*']) lingrp.add_subsystem('lin', lin_sys_comp) prob.model.connect('p1.A', 'lin.A') prob.model.connect('p2.b', 'lin.b') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -315,27 +314,26 @@ def test_solve_linear_vectorized_A(self): def test_feature_basic(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.api import LinearSystemComp, ScipyKrylov + import openmdao.api as om - model = Group() + model = om.Group() A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = np.array([1.0, 2.0, -3.0]) - model.add_subsystem('p1', IndepVarComp('A', A)) - model.add_subsystem('p2', IndepVarComp('b', b)) + model.add_subsystem('p1', om.IndepVarComp('A', A)) + model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) - lingrp.add_subsystem('lin', LinearSystemComp(size=3)) + lingrp = model.add_subsystem('lingrp', om.Group(), promotes=['*']) + lingrp.add_subsystem('lin', om.LinearSystemComp(size=3)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') - prob = Problem(model) + prob = om.Problem(model) prob.setup() - lingrp.linear_solver = ScipyKrylov() + lingrp.linear_solver = om.ScipyKrylov() prob.run_model() @@ -344,27 +342,26 @@ def test_feature_basic(self): def test_feature_vectorized(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.api import LinearSystemComp, ScipyKrylov + import openmdao.api as om - model = Group() + model = om.Group() A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = np.array([[2.0, -3.0, 4.0], [1.0, 0.0, -1.0]]) - model.add_subsystem('p1', IndepVarComp('A', A)) - model.add_subsystem('p2', IndepVarComp('b', b)) + model.add_subsystem('p1', om.IndepVarComp('A', A)) + model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) - lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2)) + lingrp = model.add_subsystem('lingrp', om.Group(), promotes=['*']) + lingrp.add_subsystem('lin', om.LinearSystemComp(size=3, vec_size=2)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') - prob = Problem(model) + prob = om.Problem(model) prob.setup() - lingrp.linear_solver = ScipyKrylov() + lingrp.linear_solver = om.ScipyKrylov() prob.run_model() @@ -375,28 +372,27 @@ def test_feature_vectorized(self): def test_feature_vectorized_A(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.api import LinearSystemComp, ScipyKrylov + import openmdao.api as om - model = Group() + model = om.Group() A = np.array([[[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]], [[2.0, 3.0, 4.0], [1.0, -1.0, -2.0], [3.0, 2.0, -2.0]]]) b = np.array([[-5.0, 2.0, 3.0], [-1.0, 1.0, -3.0]]) - model.add_subsystem('p1', IndepVarComp('A', A)) - model.add_subsystem('p2', IndepVarComp('b', b)) + model.add_subsystem('p1', om.IndepVarComp('A', A)) + model.add_subsystem('p2', om.IndepVarComp('b', b)) - lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) - lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2, vectorize_A=True)) + lingrp = model.add_subsystem('lingrp', om.Group(), promotes=['*']) + lingrp.add_subsystem('lin', om.LinearSystemComp(size=3, vec_size=2, vectorize_A=True)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') - prob = Problem(model) + prob = om.Problem(model) prob.setup() - lingrp.linear_solver = ScipyKrylov() + lingrp.linear_solver = om.ScipyKrylov() prob.run_model() diff --git a/openmdao/components/tests/test_matrix_vector_product_comp.py b/openmdao/components/tests/test_matrix_vector_product_comp.py index 34b8c2cb37..1e90e1bd1d 100644 --- a/openmdao/components/tests/test_matrix_vector_product_comp.py +++ b/openmdao/components/tests/test_matrix_vector_product_comp.py @@ -4,7 +4,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, MatrixVectorProductComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error @@ -13,9 +13,9 @@ class TestMatrixVectorProductComp3x3(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='A', shape=(self.nn, 3, 3)) ivc.add_output(name='x', shape=(self.nn, 3)) @@ -24,7 +24,7 @@ def setUp(self): promotes_outputs=['A', 'x']) self.p.model.add_subsystem(name='mat_vec_product_comp', - subsys=MatrixVectorProductComp(vec_size=self.nn)) + subsys=om.MatrixVectorProductComp(vec_size=self.nn)) self.p.model.connect('A', 'mat_vec_product_comp.A') self.p.model.connect('x', 'mat_vec_product_comp.x') @@ -62,9 +62,9 @@ class TestMatrixVectorProductComp6x4(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='A', shape=(self.nn, 6, 4)) ivc.add_output(name='x', shape=(self.nn, 4)) @@ -73,8 +73,8 @@ def setUp(self): promotes_outputs=['A', 'x']) self.p.model.add_subsystem(name='mat_vec_product_comp', - subsys=MatrixVectorProductComp(vec_size=self.nn, - A_shape=(6, 4))) + subsys=om.MatrixVectorProductComp(vec_size=self.nn, + A_shape=(6, 4))) self.p.model.connect('A', 'mat_vec_product_comp.A') self.p.model.connect('x', 'mat_vec_product_comp.x') @@ -109,9 +109,9 @@ def test_partials(self): class TestMatrixVectorProductCompNonVectorized(unittest.TestCase): def setUp(self): - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='A', shape=(3, 3)) ivc.add_output(name='x', shape=(3, 1)) @@ -120,7 +120,7 @@ def setUp(self): promotes_outputs=['A', 'x']) self.p.model.add_subsystem(name='mat_vec_product_comp', - subsys=MatrixVectorProductComp()) + subsys=om.MatrixVectorProductComp()) self.p.model.connect('A', 'mat_vec_product_comp.A') self.p.model.connect('x', 'mat_vec_product_comp.x') @@ -157,9 +157,9 @@ class TestUnits(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='A', shape=(self.nn, 3, 3), units='ft') ivc.add_output(name='x', shape=(self.nn, 3), units='lbf') @@ -168,9 +168,9 @@ def setUp(self): promotes_outputs=['A', 'x']) self.p.model.add_subsystem(name='mat_vec_product_comp', - subsys=MatrixVectorProductComp(vec_size=self.nn, - A_units='m', x_units='N', - b_units='N*m')) + subsys=om.MatrixVectorProductComp(vec_size=self.nn, + A_units='m', x_units='N', + b_units='N*m')) self.p.model.connect('A', 'mat_vec_product_comp.A') self.p.model.connect('x', 'mat_vec_product_comp.x') @@ -203,18 +203,18 @@ def test_partials(self): decimal=6) -class TestForDocs(unittest.TestCase): +class TestFeature(unittest.TestCase): def test(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, MatrixVectorProductComp + import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error nn = 100 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='A', shape=(nn, 3, 3)) ivc.add_output(name='x', shape=(nn, 3)) @@ -223,8 +223,8 @@ def test(self): promotes_outputs=['A', 'x']) p.model.add_subsystem(name='mat_vec_product_comp', - subsys=MatrixVectorProductComp(A_name='M', vec_size=nn, - b_name='y', b_units='m')) + subsys=om.MatrixVectorProductComp(A_name='M', vec_size=nn, + b_name='y', b_units='m')) p.model.connect('A', 'mat_vec_product_comp.M') p.model.connect('x', 'mat_vec_product_comp.x') diff --git a/openmdao/components/tests/test_meta_model_structured_comp.py b/openmdao/components/tests/test_meta_model_structured_comp.py index e43444beec..62213a9657 100644 --- a/openmdao/components/tests/test_meta_model_structured_comp.py +++ b/openmdao/components/tests/test_meta_model_structured_comp.py @@ -2,18 +2,14 @@ Unit tests for the structured metamodel component. """ from __future__ import division, print_function, absolute_import - -from six import assertRaisesRegex from copy import deepcopy - -from openmdao.core.problem import Problem -from openmdao.core.group import Group -from openmdao.core.indepvarcomp import IndepVarComp -from openmdao.core.analysis_error import AnalysisError -from openmdao.utils.assert_utils import assert_rel_error, assert_warning +import unittest +from six import assertRaisesRegex import numpy as np -import unittest + +import openmdao.api as om +from openmdao.utils.assert_utils import assert_rel_error, assert_warning from numpy.testing import (assert_array_almost_equal, assert_almost_equal, assert_allclose, assert_array_equal, assert_equal) @@ -25,8 +21,7 @@ scipy_gte_019 = False if scipy_gte_019: - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp, \ - _RegularGridInterp, OutOfBoundsError + from openmdao.components.meta_model_structured_comp import _RegularGridInterp, OutOfBoundsError x = np.array([-0.97727788, -0.15135721, -0.10321885, 0.40015721, 0.4105985, 0.95008842, 0.97873798, 1.76405235, 1.86755799, 2.2408932 ]) @@ -779,6 +774,7 @@ def test_error_messages(self): self.assertEqual(set(interp.methods()), set(["quintic", "cubic", "slinear"])) + @unittest.skipIf(not scipy_gte_019, "only run if scipy>=0.19.") class TestRegularGridMap(unittest.TestCase): """ @@ -788,8 +784,8 @@ class TestRegularGridMap(unittest.TestCase): def setUp(self): - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -803,7 +799,7 @@ def setUp(self): model.add_subsystem('des_vars', ivc, promotes=["*"]) - comp = MetaModelStructuredComp(method='slinear', extrapolate=True) + comp = om.MetaModelStructuredComp(method='slinear', extrapolate=True) for param in params: comp.add_input(param['name'], param['default'], param['values']) @@ -812,7 +808,7 @@ def setUp(self): comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) - self.prob = Problem(model) + self.prob = om.Problem(model) self.prob.setup() self.prob['x'] = 1.0 self.prob['y'] = 0.75 @@ -832,8 +828,8 @@ def test_deriv1(self): def test_deriv1_swap(self): # Bugfix test that we can add outputs before inputs. - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -847,7 +843,7 @@ def test_deriv1_swap(self): model.add_subsystem('des_vars', ivc, promotes=["*"]) - comp = MetaModelStructuredComp(method='slinear', extrapolate=True) + comp = om.MetaModelStructuredComp(method='slinear', extrapolate=True) for out in outs: comp.add_output(out['name'], out['default'], out['values']) @@ -856,7 +852,7 @@ def test_deriv1_swap(self): comp.add_input(param['name'], param['default'], param['values']) model.add_subsystem('comp', comp, promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob['x'] = 1.0 prob['y'] = 0.75 @@ -897,8 +893,8 @@ def test_raise_interp_error(self): "but this RegularGridInterp has dimension 0") def test_raise_out_of_bounds_error(self): - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -913,7 +909,7 @@ def test_raise_out_of_bounds_error(self): model.add_subsystem('des_vars', ivc, promotes=["*"]) # Need to make sure extrapolate is False for bounds to be checked - comp = MetaModelStructuredComp(method='slinear', extrapolate=False) + comp = om.MetaModelStructuredComp(method='slinear', extrapolate=False) for param in params: comp.add_input(param['name'], param['default'], param['values']) @@ -922,7 +918,7 @@ def test_raise_out_of_bounds_error(self): comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) - self.prob = Problem(model) + self.prob = om.Problem(model) self.prob.setup() self.prob['x'] = 1.0 @@ -934,12 +930,12 @@ def test_raise_out_of_bounds_error(self): # dict so no guarantee on the order except for Python 3.6 ! msg = "Error interpolating output '[f|g]' in 'comp' because input 'comp.z' was " \ "out of bounds \('.*', '.*'\) with value '9.0'" - with assertRaisesRegex(self, AnalysisError, msg): + with assertRaisesRegex(self, om.AnalysisError, msg): self.run_and_check_derivs(self.prob) def test_training_gradient(self): - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -953,9 +949,9 @@ def test_training_gradient(self): ivc.add_output('f_train', outs[0]['values']) ivc.add_output('g_train', outs[1]['values']) - comp = MetaModelStructuredComp(training_data_gradients=True, - method='cubic', - vec_size=3) + comp = om.MetaModelStructuredComp(training_data_gradients=True, + method='cubic', + vec_size=3) for param in params: comp.add_input(param['name'], param['default'], param['values']) @@ -968,7 +964,7 @@ def test_training_gradient(self): promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob.run_model() @@ -981,8 +977,8 @@ def test_training_gradient(self): self.run_and_check_derivs(prob) def test_training_gradient_setup_called_twice(self): - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -996,9 +992,9 @@ def test_training_gradient_setup_called_twice(self): ivc.add_output('f_train', outs[0]['values']) ivc.add_output('g_train', outs[1]['values']) - comp = MetaModelStructuredComp(training_data_gradients=True, - method='cubic', - vec_size=3) + comp = om.MetaModelStructuredComp(training_data_gradients=True, + method='cubic', + vec_size=3) for param in params: comp.add_input(param['name'], param['default'], param['values']) @@ -1011,7 +1007,7 @@ def test_training_gradient_setup_called_twice(self): promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob.run_model() @@ -1055,7 +1051,7 @@ def test_error_msg_vectorized(self): y_data = np.array([0., 4.]) nn = 5 - class MMComp(MetaModelStructuredComp): + class MMComp(om.MetaModelStructuredComp): def setup(self): nn = self.options['vec_size'] @@ -1063,9 +1059,9 @@ def setup(self): self.add_output(name='y', val=np.zeros(nn), units=None, training_data=y_data) - p = Problem() + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output('x', val=np.linspace(.5, 1.1, nn)) p.model.add_subsystem('ivc', ivc, promotes=['x']) @@ -1073,7 +1069,7 @@ def setup(self): p.setup() - with self.assertRaises(AnalysisError) as cm: + with self.assertRaises(om.AnalysisError) as cm: p.run_model() msg = ("Error interpolating output 'y' in 'MM' because input 'MM.x' was out of bounds ('0.0', '1.0') with value '1.1'") @@ -1086,11 +1082,10 @@ class TestMetaModelStructuredCompMapFeature(unittest.TestCase): @unittest.skipIf(not scipy_gte_019, "only run if scipy>=0.19.") def test_xor(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp + import openmdao.api as om # Create regular grid interpolator instance - xor_interp = MetaModelStructuredComp(method='slinear') + xor_interp = om.MetaModelStructuredComp(method='slinear') # set up inputs and outputs xor_interp.add_input('x', 0.0, training_data=np.array([0.0, 1.0]), units=None) @@ -1099,13 +1094,13 @@ def test_xor(self): xor_interp.add_output('xor', 1.0, training_data=np.array([[0.0, 1.0], [1.0, 0.0]]), units=None) # Set up the OpenMDAO model - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() ivc.add_output('x', 0.0) ivc.add_output('y', 1.0) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', xor_interp, promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() # Now test out a 'fuzzy' XOR @@ -1125,8 +1120,7 @@ def test_xor(self): @unittest.skipIf(not scipy_gte_019, "only run if scipy>=0.19.") def test_shape(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp + import openmdao.api as om # create input param training data, of sizes 25, 5, and 10 points resp. p1 = np.linspace(0, 100, 25) @@ -1141,7 +1135,7 @@ def test_shape(self): print(f.shape) # Create regular grid interpolator instance - interp = MetaModelStructuredComp(method='cubic') + interp = om.MetaModelStructuredComp(method='cubic') interp.add_input('p1', 0.5, training_data=p1) interp.add_input('p2', 0.0, training_data=p2) interp.add_input('p3', 3.14, training_data=p3) @@ -1149,9 +1143,9 @@ def test_shape(self): interp.add_output('f', 0.0, training_data=f) # Set up the OpenMDAO model - model = Group() + model = om.Group() model.add_subsystem('comp', interp, promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() # set inputs @@ -1172,8 +1166,7 @@ def test_shape(self): @unittest.skipIf(not scipy_gte_019, "only run if scipy>=0.19.") def test_vectorized(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp + import openmdao.api as om # create input param training data, of sizes 25, 5, and 10 points resp. p1 = np.linspace(0, 100, 25) @@ -1185,7 +1178,7 @@ def test_vectorized(self): f = np.sqrt(P1) + P2 * P3 # Create regular grid interpolator instance - interp = MetaModelStructuredComp(method='cubic', vec_size=2) + interp = om.MetaModelStructuredComp(method='cubic', vec_size=2) interp.add_input('p1', 0.5, training_data=p1) interp.add_input('p2', 0.0, training_data=p2) interp.add_input('p3', 3.14, training_data=p3) @@ -1193,9 +1186,9 @@ def test_vectorized(self): interp.add_output('f', 0.0, training_data=f) # Set up the OpenMDAO model - model = Group() + model = om.Group() model.add_subsystem('comp', interp, promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() # set inputs @@ -1213,8 +1206,7 @@ def test_vectorized(self): @unittest.skipIf(not scipy_gte_019, "only run if scipy>=0.19.") def test_training_derivatives(self): import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp + import openmdao.api as om # create input param training data, of sizes 25, 5, and 10 points resp. p1 = np.linspace(0, 100, 25) @@ -1229,7 +1221,7 @@ def test_training_derivatives(self): print(f.shape) # Create regular grid interpolator instance - interp = MetaModelStructuredComp(method='cubic', training_data_gradients=True) + interp = om.MetaModelStructuredComp(method='cubic', training_data_gradients=True) interp.add_input('p1', 0.5, p1) interp.add_input('p2', 0.0, p2) interp.add_input('p3', 3.14, p3) @@ -1237,9 +1229,9 @@ def test_training_derivatives(self): interp.add_output('f', 0.0, f) # Set up the OpenMDAO model - model = Group() + model = om.Group() model.add_subsystem('comp', interp, promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() # set inputs @@ -1262,14 +1254,11 @@ def test_meta_model_structured_deprecated(self): # run same test as above, only with the deprecated component, # to ensure we get the warning and the correct answer. # self-contained, to be removed when class name goes away. - import numpy as np - from openmdao.api import Group, Problem, IndepVarComp - from openmdao.components.meta_model_structured_comp import MetaModelStructured # deprecated msg = "'MetaModelStructured' has been deprecated. Use 'MetaModelStructuredComp' instead." with assert_warning(DeprecationWarning, msg): - xor_interp = MetaModelStructured(method='slinear') + xor_interp = om.MetaModelStructured(method='slinear') # set up inputs and outputs xor_interp.add_input('x', 0.0, training_data=np.array([0.0, 1.0]), units=None) @@ -1278,13 +1267,13 @@ def test_meta_model_structured_deprecated(self): xor_interp.add_output('xor', 1.0, training_data=np.array([[0.0, 1.0], [1.0, 0.0]]), units=None) # Set up the OpenMDAO model - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() ivc.add_output('x', 0.0) ivc.add_output('y', 1.0) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', xor_interp, promotes=["*"]) - prob = Problem(model) + prob = om.Problem(model) prob.setup() # Now test out a 'fuzzy' XOR diff --git a/openmdao/components/tests/test_meta_model_unstructured_comp.py b/openmdao/components/tests/test_meta_model_unstructured_comp.py index 868ea80660..2dc8b523cc 100644 --- a/openmdao/components/tests/test_meta_model_unstructured_comp.py +++ b/openmdao/components/tests/test_meta_model_unstructured_comp.py @@ -8,9 +8,7 @@ import numpy as np -from openmdao.api import Group, Problem, MetaModelUnStructuredComp, IndepVarComp, ResponseSurface, \ - FloatKrigingSurrogate, KrigingSurrogate, ScipyOptimizeDriver, SurrogateModel, NearestNeighbor - +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_warning from openmdao.utils.logger_utils import TestLogger @@ -18,12 +16,12 @@ class MetaModelTestCase(unittest.TestCase): def test_sin_metamodel(self): - # create a MetaModelUnStructuredComp for sine and add it to a Problem - sin_mm = MetaModelUnStructuredComp() + # create a MetaModelUnStructuredComp for sine and add it to a om.Problem + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) sin_mm.add_output('f_x', 0.) - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('sin_mm', sin_mm) # check that missing surrogate is detected in check_config @@ -42,10 +40,10 @@ def test_sin_metamodel(self): self.assertTrue(msg in testlogger.get('error')[0]) # check that output with no specified surrogate gets the default - sin_mm.options['default_surrogate'] = KrigingSurrogate() - prob.setup(check=False) + sin_mm.options['default_surrogate'] = om.KrigingSurrogate() + prob.setup() surrogate = sin_mm._metadata('f_x').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate), + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate), 'sin_mm.f_x should get the default surrogate') # check error message when no training data is provided @@ -69,14 +67,14 @@ def test_sin_metamodel(self): def test_error_no_surrogate(self): # Seems like the error message from above should also be present and readable even if the # user chooses to skip checking the model. - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) sin_mm.add_output('f_x', 0.) - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('sin_mm', sin_mm) - prob.setup(check=False) + prob.setup() sin_mm.options['train:x'] = np.linspace(0,10,20) sin_mm.options['train:f_x'] = .5*np.sin(sin_mm.options['train:x']) @@ -93,11 +91,11 @@ def test_sin_metamodel_preset_data(self): f_x = .5*np.sin(x) # create a MetaModelUnStructuredComp for Sin and add it to a Problem - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0., training_data=x) sin_mm.add_output('f_x', 0., training_data=f_x) - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('sin_mm', sin_mm) # check that missing surrogate is detected in check_setup @@ -116,11 +114,11 @@ def test_sin_metamodel_preset_data(self): self.assertTrue(msg in testlogger.get('error')[0]) # check that output with no specified surrogate gets the default - sin_mm.options['default_surrogate'] = KrigingSurrogate() - prob.setup(check=False) + sin_mm.options['default_surrogate'] = om.KrigingSurrogate() + prob.setup() surrogate = sin_mm._metadata('f_x').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate), + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate), 'sin_mm.f_x should get the default surrogate') prob['sin_mm.x'] = 2.22 @@ -131,16 +129,16 @@ def test_sin_metamodel_preset_data(self): def test_sin_metamodel_rmse(self): # create MetaModelUnStructuredComp with Kriging, using the rmse option - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) sin_mm.add_output('f_x', 0.) - sin_mm.options['default_surrogate'] = KrigingSurrogate(eval_rmse=True) + sin_mm.options['default_surrogate'] = om.KrigingSurrogate(eval_rmse=True) # add it to a Problem - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('sin_mm', sin_mm) - prob.setup(check=False) + prob.setup() # train the surrogate and check predicted value sin_mm.options['train:x'] = np.linspace(0,10,20) @@ -155,27 +153,27 @@ def test_sin_metamodel_rmse(self): def test_basics(self): # create a metamodel component - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x1', 0.) mm.add_input('x2', 0.) mm.add_output('y1', 0.) - mm.add_output('y2', 0., surrogate=KrigingSurrogate()) + mm.add_output('y2', 0., surrogate=om.KrigingSurrogate()) - mm.options['default_surrogate'] = ResponseSurface() + mm.options['default_surrogate'] = om.ResponseSurface() # add metamodel to a problem - prob = Problem(model=Group()) + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() # check that surrogates were properly assigned surrogate = mm._metadata('y1').get('surrogate') - self.assertTrue(isinstance(surrogate, ResponseSurface)) + self.assertTrue(isinstance(surrogate, om.ResponseSurface)) surrogate = mm._metadata('y2').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate)) + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate)) # populate training data mm.options['train:x1'] = [1.0, 2.0, 3.0] @@ -203,25 +201,25 @@ def test_basics(self): assert_rel_error(self, prob['mm.y1'], 1.5934, .001) # change default surrogate, re-setup and check that metamodel re-trains - mm.options['default_surrogate'] = KrigingSurrogate() - prob.setup(check=False) + mm.options['default_surrogate'] = om.KrigingSurrogate() + prob.setup() surrogate = mm._metadata('y1').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate)) + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate)) self.assertTrue(mm.train) # training will occur after re-setup def test_vector_inputs(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', np.zeros(4)) mm.add_output('y1', 0.) mm.add_output('y2', 0.) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [ [1.0, 1.0, 1.0, 1.0], @@ -240,16 +238,16 @@ def test_vector_inputs(self): assert_rel_error(self, prob['mm.y2'], 7.0, .00001) def test_array_inputs(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', np.zeros((2,2))) mm.add_output('y1', 0.) mm.add_output('y2', 0.) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [ [[1.0, 1.0], [1.0, 1.0]], @@ -268,15 +266,15 @@ def test_array_inputs(self): assert_rel_error(self, prob['mm.y2'], 7.0, .00001) def test_array_outputs(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', np.zeros((2, 2))) mm.add_output('y', np.zeros(2,)) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [ [[1.0, 1.0], [1.0, 1.0]], @@ -300,15 +298,15 @@ def test_array_outputs(self): assert_rel_error(self, prob['mm.y'], np.array([1.0, 7.0]), .00001) def test_2darray_outputs(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', np.zeros((2, 2))) mm.add_output('y', np.zeros((2, 2))) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [ [[1.0, 1.0], [1.0, 1.0]], @@ -332,16 +330,16 @@ def test_2darray_outputs(self): assert_rel_error(self, prob['mm.y'], np.array([[1.0, 7.0], [1.0, 7.0]]), .00001) def test_unequal_training_inputs(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', 0.) mm.add_input('y', 0.) mm.add_output('f', 0.) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [1.0, 1.0, 1.0, 1.0] mm.options['train:y'] = [1.0, 2.0] @@ -360,16 +358,16 @@ def test_unequal_training_inputs(self): self.assertEqual(str(cm.exception), expected) def test_unequal_training_outputs(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', 0.) mm.add_input('y', 0.) mm.add_output('f', 0.) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [1.0, 1.0, 1.0, 1.0] mm.options['train:y'] = [1.0, 2.0, 3.0, 4.0] @@ -387,14 +385,14 @@ def test_unequal_training_outputs(self): self.assertEqual(str(cm.exception), expected) def test_derivatives(self): - mm = MetaModelUnStructuredComp() + mm = om.MetaModelUnStructuredComp() mm.add_input('x', 0.) mm.add_output('f', 0.) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 0.), + prob = om.Problem() + prob.model.add_subsystem('p', om.IndepVarComp('x', 0.), promotes_outputs=['x']) prob.model.add_subsystem('mm', mm, promotes_inputs=['x']) @@ -435,9 +433,9 @@ def test_metamodel_feature(self): # create a MetaModelUnStructuredComp, specifying surrogates for the outputs import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, KrigingSurrogate + import openmdao.api as om - trig = MetaModelUnStructuredComp() + trig = om.MetaModelUnStructuredComp() x_train = np.linspace(0,10,20) @@ -445,16 +443,16 @@ def test_metamodel_feature(self): trig.add_output('sin_x', 0., training_data=.5*np.sin(x_train), - surrogate=KrigingSurrogate()) + surrogate=om.KrigingSurrogate()) trig.add_output('cos_x', 0., training_data=.5*np.cos(x_train)) - trig.options['default_surrogate'] = KrigingSurrogate() + trig.options['default_surrogate'] = om.KrigingSurrogate() # add it to a Problem, run and check the predicted values - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('trig', trig) - prob.setup(check=False) + prob.setup() prob['trig.x'] = 2.1 prob.run_model() @@ -466,17 +464,17 @@ def test_metamodel_feature2d(self): # similar to previous example, but output is 2d import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, KrigingSurrogate + import openmdao.api as om # create a MetaModelUnStructuredComp that predicts sine and cosine as an array - trig = MetaModelUnStructuredComp(default_surrogate=KrigingSurrogate()) + trig = om.MetaModelUnStructuredComp(default_surrogate=om.KrigingSurrogate()) trig.add_input('x', 0) trig.add_output('y', np.zeros(2)) # add it to a Problem - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('trig', trig) - prob.setup(check=False) + prob.setup() # provide training data trig.options['train:x'] = np.linspace(0, 10, 20) @@ -499,14 +497,14 @@ def test_vectorized(self): size = 3 # create a vectorized MetaModelUnStructuredComp for sine - trig = MetaModelUnStructuredComp(vec_size=size, default_surrogate=KrigingSurrogate()) + trig = om.MetaModelUnStructuredComp(vec_size=size, default_surrogate=om.KrigingSurrogate()) trig.add_input('x', np.zeros(size)) trig.add_output('y', np.zeros(size)) # add it to a Problem - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('trig', trig) - prob.setup(check=False) + prob.setup() # provide training data trig.options['train:x'] = np.linspace(0, 10, 20) @@ -532,15 +530,15 @@ def test_vectorized_kriging(self): size = 3 # create a vectorized MetaModelUnStructuredComp for sine - trig = MetaModelUnStructuredComp(vec_size=size, - default_surrogate=KrigingSurrogate(eval_rmse=True)) + trig = om.MetaModelUnStructuredComp(vec_size=size, + default_surrogate=om.KrigingSurrogate(eval_rmse=True)) trig.add_input('x', np.zeros(size)) trig.add_output('y', np.zeros(size)) # add it to a Problem - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('trig', trig) - prob.setup(check=False) + prob.setup() # provide training data trig.options['train:x'] = np.linspace(0, 10, 20) @@ -557,16 +555,16 @@ def test_vectorized_kriging(self): def test_derivatives_vectorized_multiD(self): vec_size = 5 - mm = MetaModelUnStructuredComp(vec_size=vec_size) + mm = om.MetaModelUnStructuredComp(vec_size=vec_size) mm.add_input('x', np.zeros((vec_size, 2, 3))) mm.add_input('xx', np.zeros((vec_size, 1))) mm.add_output('y', np.zeros((vec_size, 4, 2))) - mm.options['default_surrogate'] = KrigingSurrogate() + mm.options['default_surrogate'] = om.KrigingSurrogate() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [ [[1.0, 2.0, 1.0], [1.0, 2.0, 1.0]], @@ -637,19 +635,19 @@ def test_metamodel_feature_vector(self): # array but you skip all the n-copies thing and do it all as an array import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, KrigingSurrogate + import openmdao.api as om size = 3 # create a vectorized MetaModelUnStructuredComp for sine - trig = MetaModelUnStructuredComp(vec_size=size, default_surrogate=KrigingSurrogate()) + trig = om.MetaModelUnStructuredComp(vec_size=size, default_surrogate=om.KrigingSurrogate()) trig.add_input('x', np.zeros(size)) trig.add_output('y', np.zeros(size)) # add it to a Problem - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('trig', trig) - prob.setup(check=False) + prob.setup() # provide training data trig.options['train:x'] = np.linspace(0, 10, 20) @@ -666,19 +664,19 @@ def test_metamodel_feature_vector2d(self): # similar to previous example, but processes 3 inputs/outputs at a time import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, KrigingSurrogate + import openmdao.api as om size = 3 # create a vectorized MetaModelUnStructuredComp for sine and cosine - trig = MetaModelUnStructuredComp(vec_size=size, default_surrogate=KrigingSurrogate()) + trig = om.MetaModelUnStructuredComp(vec_size=size, default_surrogate=om.KrigingSurrogate()) trig.add_input('x', np.zeros(size)) trig.add_output('y', np.zeros((size, 2))) # add it to a Problem - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('trig', trig) - prob.setup(check=False) + prob.setup() # provide training data trig.options['train:x'] = np.linspace(0, 10, 20) @@ -699,7 +697,7 @@ def test_metamodel_feature_vector2d(self): def test_metamodel_vector_errors(self): # first dimension of all inputs/outputs must be 3 - mm = MetaModelUnStructuredComp(vec_size=3) + mm = om.MetaModelUnStructuredComp(vec_size=3) with self.assertRaises(RuntimeError) as cm: mm.add_input('x', np.zeros(2)) @@ -712,19 +710,19 @@ def test_metamodel_vector_errors(self): "Metamodel: First dimension of output 'y' must be 3") def test_metamodel_subclass_optimize(self): - class Trig(MetaModelUnStructuredComp): + class Trig(om.MetaModelUnStructuredComp): def setup(self): self.add_input('x', 0., training_data=np.linspace(0,10,20)) self.add_output('sin_x', 0., - surrogate=KrigingSurrogate(), + surrogate=om.KrigingSurrogate(), training_data=.5*np.sin(np.linspace(0,10,20))) self.declare_partials(of='sin_x', wrt='x', method='fd') - prob = Problem() + prob = om.Problem() - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('x', 5.) prob.model.add_subsystem('indep', indep) @@ -732,7 +730,7 @@ def setup(self): prob.model.connect('indep.x', 'trig.x') - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.model.add_design_var('indep.x', lower=4, upper=7) @@ -758,26 +756,26 @@ def test_meta_model_unstructured_deprecated(self): mm.add_input('x2', 0.) mm.add_output('y1', 0.) - mm.add_output('y2', 0., surrogate=KrigingSurrogate()) + mm.add_output('y2', 0., surrogate=om.KrigingSurrogate()) msg = "The 'default_surrogate' attribute provides backwards compatibility " \ "with earlier version of OpenMDAO; use options['default_surrogate'] " \ "instead." with assert_warning(DeprecationWarning, msg): - mm.default_surrogate = ResponseSurface() + mm.default_surrogate = om.ResponseSurface() # add metamodel to a problem - prob = Problem(model=Group()) + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() # check that surrogates were properly assigned surrogate = mm._metadata('y1').get('surrogate') - self.assertTrue(isinstance(surrogate, ResponseSurface)) + self.assertTrue(isinstance(surrogate, om.ResponseSurface)) surrogate = mm._metadata('y2').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate)) + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate)) # populate training data msg = "The 'metadata' attribute provides backwards compatibility " \ @@ -813,12 +811,12 @@ def test_meta_model_unstructured_deprecated(self): "earlier version of OpenMDAO; use options['default_surrogate'] instead." with assert_warning(DeprecationWarning, msg): - mm.default_surrogate = KrigingSurrogate() + mm.default_surrogate = om.KrigingSurrogate() - prob.setup(check=False) + prob.setup() surrogate = mm._metadata('y1').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate)) + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate)) self.assertTrue(mm.train) # training will occur after re-setup @@ -843,25 +841,25 @@ def test_metamodel_deprecated(self): mm.add_input('x2', 0.) mm.add_output('y1', 0.) - mm.add_output('y2', 0., surrogate=KrigingSurrogate()) + mm.add_output('y2', 0., surrogate=om.KrigingSurrogate()) msg = "The 'default_surrogate' attribute provides backwards compatibility with " \ "earlier version of OpenMDAO; use options['default_surrogate'] instead." with assert_warning(DeprecationWarning, msg): - mm.default_surrogate = ResponseSurface() + mm.default_surrogate = om.ResponseSurface() # add metamodel to a problem - prob = Problem(model=Group()) + prob = om.Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() # check that surrogates were properly assigned surrogate = mm._metadata('y1').get('surrogate') - self.assertTrue(isinstance(surrogate, ResponseSurface)) + self.assertTrue(isinstance(surrogate, om.ResponseSurface)) surrogate = mm._metadata('y2').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate)) + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate)) # populate training data msg = "The 'metadata' attribute provides backwards compatibility " \ @@ -897,12 +895,12 @@ def test_metamodel_deprecated(self): "earlier version of OpenMDAO; use options['default_surrogate'] instead." with assert_warning(DeprecationWarning, msg): - mm.default_surrogate = KrigingSurrogate() + mm.default_surrogate = om.KrigingSurrogate() - prob.setup(check=False) + prob.setup() surrogate = mm._metadata('y1').get('surrogate') - self.assertTrue(isinstance(surrogate, KrigingSurrogate)) + self.assertTrue(isinstance(surrogate, om.KrigingSurrogate)) self.assertTrue(mm.train) # training will occur after re-setup @@ -913,27 +911,27 @@ def test_metamodel_deprecated(self): assert_rel_error(self, prob['mm.y1'], 1.5, 1e-2) def test_metamodel_use_fd_if_no_surrogate_linearize(self): - class SinSurrogate(SurrogateModel): + class SinSurrogate(om.SurrogateModel): def train(self, x, y): pass def predict(self, x): return sin(x) - class SinTwoInputsSurrogate(SurrogateModel): + class SinTwoInputsSurrogate(om.SurrogateModel): def train(self, x, y): pass def predict(self, x): return sin(x[0] + x[1]) - class Trig(MetaModelUnStructuredComp): + class Trig(om.MetaModelUnStructuredComp): def setup(self): surrogate = SinSurrogate() self.add_input('x', 0.) self.add_output('sin_x', 0., surrogate=surrogate) - class TrigWithFdInSetup(MetaModelUnStructuredComp): + class TrigWithFdInSetup(om.MetaModelUnStructuredComp): def setup(self): surrogate = SinSurrogate() self.add_input('x', 0.) @@ -941,26 +939,26 @@ def setup(self): self.declare_partials('sin_x', 'x', method='fd', form='backward', step=1e-7, step_calc='rel') - class TrigWithCsInSetup(MetaModelUnStructuredComp): + class TrigWithCsInSetup(om.MetaModelUnStructuredComp): def setup(self): surrogate = SinSurrogate() self.add_input('x', 0.) self.add_output('sin_x', 0., surrogate=surrogate) self.declare_partials('sin_x', 'x', method='cs') - class TrigGroup(Group): + class TrigGroup(om.Group): def configure(self): trig = self._get_subsystem('trig') trig.declare_partials('sin_x', 'x', method='fd', form='backward', step=1e-7, step_calc='rel') - class TrigWithFdInConfigure(MetaModelUnStructuredComp): + class TrigWithFdInConfigure(om.MetaModelUnStructuredComp): def setup(self): surrogate = SinSurrogate() self.add_input('x', 0.) self.add_output('sin_x', 0., surrogate=surrogate) - class TrigTwoInputsWithFdInSetup(MetaModelUnStructuredComp): + class TrigTwoInputsWithFdInSetup(om.MetaModelUnStructuredComp): def setup(self): surrogate = SinTwoInputsSurrogate() self.add_input('x1', 0.) @@ -970,15 +968,15 @@ def setup(self): form='backward', step=1e-7, step_calc='rel') def no_surrogate_test_setup(trig, group=None): - prob = Problem() + prob = om.Problem() if group: prob.model = group - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('x', 5.) prob.model.add_subsystem('indep', indep) prob.model.add_subsystem('trig', trig) prob.model.connect('indep.x', 'trig.x') - prob.setup(check=False) + prob.setup() prob['indep.x'] = 5.0 trig.train = False prob.run_model() @@ -1031,23 +1029,23 @@ def no_surrogate_test_setup(trig, group=None): assert_rel_error(self, deriv_using_fd[0], np.cos(prob['indep.x']), 1e-4) # Test with user explicitly setting cs inside of setup. Should throw an error - prob = Problem() - indep = IndepVarComp() + prob = om.Problem() + indep = om.IndepVarComp() indep.add_output('x', 5.) prob.model.add_subsystem('indep', indep) trig = TrigWithCsInSetup() prob.model.add_subsystem('trig', trig) prob.model.connect('indep.x', 'trig.x') with self.assertRaises(ValueError) as context: - prob.setup(check=False) + prob.setup() expected_msg = 'Complex step has not been tested for MetaModelUnStructuredComp' self.assertEqual(expected_msg, str(context.exception)) # Test with user explicitly setting fd on one of the inputs for a meta model # with two inputs. Check to make sure all inputs are fd and with the correct # options - prob = Problem() - indep = IndepVarComp() + prob = om.Problem() + indep = om.IndepVarComp() indep.add_output('x1', 5.) indep.add_output('x2', 5.) prob.model.add_subsystem('indep', indep) @@ -1055,7 +1053,7 @@ def no_surrogate_test_setup(trig, group=None): prob.model.add_subsystem('trig', trig) prob.model.connect('indep.x1', 'trig.x1') prob.model.connect('indep.x2', 'trig.x2') - prob.setup(check=False) + prob.setup() prob['indep.x1'] = 5.0 prob['indep.x2'] = 5.0 trig.train = False @@ -1081,15 +1079,16 @@ def no_surrogate_test_setup(trig, group=None): def test_feature_metamodel_use_fd_if_no_surrogate_linearize(self): from math import sin - from openmdao.api import SurrogateModel, MetaModelUnStructuredComp, Problem, IndepVarComp - class SinSurrogate(SurrogateModel): + import openmdao.api as om + + class SinSurrogate(om.SurrogateModel): def train(self, x, y): pass def predict(self, x): return sin(x) - class TrigWithFdInSetup(MetaModelUnStructuredComp): + class TrigWithFdInSetup(om.MetaModelUnStructuredComp): def setup(self): surrogate = SinSurrogate() self.add_input('x', 0.) @@ -1098,8 +1097,8 @@ def setup(self): form='backward', step=1e-7, step_calc='rel') # Testing explicitly setting fd inside of setup - prob = Problem() - indep = IndepVarComp() + prob = om.Problem() + indep = om.IndepVarComp() indep.add_output('x', 5.) prob.model.add_subsystem('indep', indep) trig = TrigWithFdInSetup() @@ -1114,9 +1113,9 @@ def setup(self): assert_rel_error(self, deriv_using_fd[0], np.cos(prob['indep.x']), 1e-4) def test_metamodel_setup_called_twice_bug(self): - class Trig(MetaModelUnStructuredComp): + class Trig(om.MetaModelUnStructuredComp): def setup(self): - surrogate = NearestNeighbor() + surrogate = om.NearestNeighbor() self.add_input('x', 0., training_data=np.linspace(0, 10, 20)) self.add_output('sin_x', 0., @@ -1124,9 +1123,9 @@ def setup(self): training_data=.5 * np.sin(np.linspace(0, 10, 20))) # Check to make sure bug reported in story 160200719 is fixed - prob = Problem() + prob = om.Problem() - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('x', 5.) prob.model.add_subsystem('indep', indep) @@ -1137,7 +1136,7 @@ def setup(self): prob.model.add_design_var('indep.x', lower=4, upper=7) prob.model.add_objective('trig.sin_x') - prob.setup(check=False) + prob.setup() prob['indep.x'] = 5.0 prob.run_model() J = prob.compute_totals() @@ -1145,7 +1144,7 @@ def setup(self): deriv_first_time = J[('trig.sin_x', 'indep.x')] # Setup and run a second time - prob.setup(check=False) + prob.setup() prob['indep.x'] = 5.0 prob.run_model() J = prob.compute_totals() @@ -1155,21 +1154,21 @@ def setup(self): assert_rel_error(self, deriv_first_time, deriv_second_time, 1e-4) def test_metamodel_setup_called_twice_bug_called_outside_setup(self): - class Trig(MetaModelUnStructuredComp): + class Trig(om.MetaModelUnStructuredComp): def __init__(self): super(Trig, self).__init__() self.add_input('x', 0., training_data=np.linspace(0, 10, 20)) def setup(self): - surrogate = NearestNeighbor() + surrogate = om.NearestNeighbor() self.add_output('sin_x', 0., surrogate=surrogate, training_data=.5 * np.sin(np.linspace(0, 10, 20))) - prob = Problem() + prob = om.Problem() - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('x', 5.) prob.model.add_subsystem('indep', indep) @@ -1182,7 +1181,7 @@ def setup(self): prob.model.add_objective('trig.sin_x') # Check to make sure bug reported in story 160200719 is fixed - prob.setup(check=False) + prob.setup() prob['indep.x'] = 5.0 prob.run_model() J = prob.compute_totals() @@ -1190,7 +1189,7 @@ def setup(self): deriv_first_time = J[('trig.sin_x', 'indep.x')] # Setup and run a second time - prob.setup(check=False) + prob.setup() prob['indep.x'] = 5.0 prob.run_model() J = prob.compute_totals() @@ -1206,16 +1205,16 @@ def test_warning_bug(self): y_train = np.arange(10., 20.) z_train = x_train**2 + y_train**2 - p = Problem() - p.model = m = Group() + p = om.Problem() + p.model = m = om.Group() - params = IndepVarComp() + params = om.IndepVarComp() params.add_output('x', val=0.) params.add_output('y', val=0.) m.add_subsystem('params', params, promotes=['*']) - sm = MetaModelUnStructuredComp(default_surrogate=ResponseSurface()) + sm = om.MetaModelUnStructuredComp(default_surrogate=om.ResponseSurface()) sm.add_input('x', val=0.) sm.add_input('y', val=0.) sm.add_output('z', val=0.) @@ -1253,16 +1252,15 @@ class MetaModelUnstructuredSurrogatesFeatureTestCase(unittest.TestCase): def test_kriging(self): import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, IndepVarComp - from openmdao.api import KrigingSurrogate + import openmdao.api as om - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 2.1)) + prob.model.add_subsystem('p', om.IndepVarComp('x', 2.1)) - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) - sin_mm.add_output('f_x', 0., surrogate=KrigingSurrogate()) + sin_mm.add_output('f_x', 0., surrogate=om.KrigingSurrogate()) prob.model.add_subsystem('sin_mm', sin_mm) @@ -1283,16 +1281,15 @@ def test_kriging(self): def test_nearest_neighbor(self): import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, IndepVarComp - from openmdao.api import NearestNeighbor + import openmdao.api as om - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 2.1)) + prob.model.add_subsystem('p', om.IndepVarComp('x', 2.1)) - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) - sin_mm.add_output('f_x', 0., surrogate=NearestNeighbor(interpolant_type='linear')) + sin_mm.add_output('f_x', 0., surrogate=om.NearestNeighbor(interpolant_type='linear')) prob.model.add_subsystem('sin_mm', sin_mm) @@ -1313,16 +1310,15 @@ def test_nearest_neighbor(self): def test_response_surface(self): import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, IndepVarComp - from openmdao.api import ResponseSurface + import openmdao.api as om - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 2.1)) + prob.model.add_subsystem('p', om.IndepVarComp('x', 2.1)) - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) - sin_mm.add_output('f_x', 0., surrogate=ResponseSurface()) + sin_mm.add_output('f_x', 0., surrogate=om.ResponseSurface()) prob.model.add_subsystem('sin_mm', sin_mm) @@ -1343,16 +1339,15 @@ def test_response_surface(self): def test_kriging_options_eval_rmse(self): import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, IndepVarComp - from openmdao.api import KrigingSurrogate + import openmdao.api as om - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 2.1)) + prob.model.add_subsystem('p', om.IndepVarComp('x', 2.1)) - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) - sin_mm.add_output('f_x', 0., surrogate=KrigingSurrogate(eval_rmse=True)) + sin_mm.add_output('f_x', 0., surrogate=om.KrigingSurrogate(eval_rmse=True)) prob.model.add_subsystem('sin_mm', sin_mm) @@ -1376,16 +1371,15 @@ def test_kriging_options_eval_rmse(self): def test_nearest_neighbor_rbf_options(self): import numpy as np - from openmdao.api import Problem, MetaModelUnStructuredComp, IndepVarComp - from openmdao.api import NearestNeighbor + import openmdao.api as om - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 2.1)) + prob.model.add_subsystem('p', om.IndepVarComp('x', 2.1)) - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) - sin_mm.add_output('f_x', 0., surrogate=NearestNeighbor(interpolant_type='rbf', num_neighbors=3)) + sin_mm.add_output('f_x', 0., surrogate=om.NearestNeighbor(interpolant_type='rbf', num_neighbors=3)) prob.model.add_subsystem('sin_mm', sin_mm) @@ -1408,17 +1402,17 @@ class MetaModelUnstructuredFloatKrigingDeprecation(unittest.TestCase): def test_deprecated(self): - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('p', IndepVarComp('x', 2.1)) + prob.model.add_subsystem('p', om.IndepVarComp('x', 2.1)) - sin_mm = MetaModelUnStructuredComp() + sin_mm = om.MetaModelUnStructuredComp() sin_mm.add_input('x', 0.) msg = "'FloatKrigingSurrogate' has been deprecated. Use 'KrigingSurrogate' instead." with assert_warning(DeprecationWarning, msg): - sin_mm.add_output('f_x', 0., surrogate=FloatKrigingSurrogate()) + sin_mm.add_output('f_x', 0., surrogate=om.FloatKrigingSurrogate()) if __name__ == "__main__": diff --git a/openmdao/components/tests/test_multifi_meta_model_unstructured_comp.py b/openmdao/components/tests/test_multifi_meta_model_unstructured_comp.py index 68cb9040ce..0fb33f5b9a 100644 --- a/openmdao/components/tests/test_multifi_meta_model_unstructured_comp.py +++ b/openmdao/components/tests/test_multifi_meta_model_unstructured_comp.py @@ -32,7 +32,7 @@ def test_error_messages(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [0.0, 0.4, 1.0] mm.options['train:y'] = [3.02720998, 0.11477697, 15.82973195] @@ -57,7 +57,7 @@ def test_error_messages(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [0.0, 0.4, 1.0] mm.options['train:x2'] = [0.0, 0.4, 1.0, 999.0] @@ -85,7 +85,7 @@ def test_error_messages(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [0.0, 0.4, 1.0] mm.options['train:y'] = [3.02720998, 0.11477697, 15.82973195] @@ -111,7 +111,7 @@ def test_inputs_wrt_nfidelity(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() self.assertEqual(mm.options['train:x'], None) self.assertEqual(mm.options['train:x_fi2'], None) @@ -129,7 +129,7 @@ def test_one_dim_one_fidelity_training(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [0.0, 0.4, 1.0] mm.options['train:y'] = [3.02720998, 0.11477697, 15.82973195] @@ -156,7 +156,7 @@ def test_one_dim_one_fidelity_training_run_setup_twice(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = [0.0, 0.4, 1.0] mm.options['train:y'] = [3.02720998, 0.11477697, 15.82973195] @@ -175,7 +175,7 @@ def test_one_dim_one_fidelity_training_run_setup_twice(self): np.testing.assert_array_equal(surr.xpredict, expected_xpredict) # Setup and run second time - prob.setup(check=False) + prob.setup() expected_xpredict=0.5 prob['mm.x'] = expected_xpredict prob.run_model() @@ -191,7 +191,7 @@ def test_one_dim_bi_fidelity_training(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x']= [0.0, 0.4, 1.0] mm.options['train:x_fi2'] = [0.1, 0.2, 0.3, 0.5, 0.6, @@ -226,7 +226,7 @@ def test_two_dim_bi_fidelity_training(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x1'] = [1.0, 2.0, 3.0] mm.options['train:x1_fi2'] = [1.1, 2.1, 3.1, 1.0, 2.0, 3.0] @@ -273,7 +273,7 @@ def branin_low_fidelity(x): prob = Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() x = [[[ 0.13073587, 0.24909577], # expensive (hifi) doe [ 0.91915571, 0.4735261 ], @@ -334,7 +334,7 @@ def branin_low_fidelity(x): prob = Problem() prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() mm.options['train:x'] = x[0] mm.options['train:y'] = y[0] @@ -362,7 +362,7 @@ def test_multifi_meta_model_unstructured_deprecated(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() self.assertEqual(mm.options['train:x'], None) self.assertEqual(mm.options['train:x_fi2'], None) @@ -387,7 +387,7 @@ def test_multifi_meta_model_deprecated(self): prob = Problem(Group()) prob.model.add_subsystem('mm', mm) - prob.setup(check=False) + prob.setup() self.assertEqual(mm.options['train:x'], None) self.assertEqual(mm.options['train:x_fi2'], None) diff --git a/openmdao/components/tests/test_mux_comp.py b/openmdao/components/tests/test_mux_comp.py index 48050dae99..41c1de64f0 100644 --- a/openmdao/components/tests/test_mux_comp.py +++ b/openmdao/components/tests/test_mux_comp.py @@ -4,26 +4,24 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials -from openmdao.api import MuxComp - class TestMuxCompOptions(unittest.TestCase): def test_invalid_axis_scalar(self): nn = 10 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() for i in range(nn): ivc.add_output(name='a_{0}'.format(i), val=1.0) p.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['*']) - mux_comp = p.model.add_subsystem(name='mux_comp', subsys=MuxComp(vec_size=nn)) + mux_comp = p.model.add_subsystem(name='mux_comp', subsys=om.MuxComp(vec_size=nn)) mux_comp.add_var('a', shape=(1,), axis=2) @@ -41,9 +39,9 @@ def test_invalid_axis_1D(self): a_size = 7 b_size = 3 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() for i in range(nn): ivc.add_output(name='a_{0}'.format(i), shape=(a_size,)) ivc.add_output(name='b_{0}'.format(i), shape=(b_size,)) @@ -52,7 +50,7 @@ def test_invalid_axis_1D(self): subsys=ivc, promotes_outputs=['*']) - mux_comp = p.model.add_subsystem(name='mux_comp', subsys=MuxComp(vec_size=nn)) + mux_comp = p.model.add_subsystem(name='mux_comp', subsys=om.MuxComp(vec_size=nn)) mux_comp.add_var('a', shape=(a_size,), axis=0) mux_comp.add_var('b', shape=(b_size,), axis=2) @@ -72,9 +70,9 @@ class TestMuxCompScalar(unittest.TestCase): def setUp(self): self.nn = 10 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() for i in range(self.nn): ivc.add_output(name='a_{0}'.format(i), val=1.0) ivc.add_output(name='b_{0}'.format(i), val=1.0) @@ -83,7 +81,7 @@ def setUp(self): subsys=ivc, promotes_outputs=['*']) - mux_comp = self.p.model.add_subsystem(name='mux_comp', subsys=MuxComp(vec_size=self.nn)) + mux_comp = self.p.model.add_subsystem(name='mux_comp', subsys=om.MuxComp(vec_size=self.nn)) mux_comp.add_var('a', shape=(1,), axis=0) mux_comp.add_var('b', shape=(1,), axis=1) @@ -125,9 +123,9 @@ def setUp(self): a_size = 7 b_size = 3 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() for i in range(self.nn): ivc.add_output(name='a_{0}'.format(i), shape=(a_size,)) ivc.add_output(name='b_{0}'.format(i), shape=(b_size,)) @@ -136,7 +134,7 @@ def setUp(self): subsys=ivc, promotes_outputs=['*']) - mux_comp = self.p.model.add_subsystem(name='mux_comp', subsys=MuxComp(vec_size=self.nn)) + mux_comp = self.p.model.add_subsystem(name='mux_comp', subsys=om.MuxComp(vec_size=self.nn)) mux_comp.add_var('a', shape=(a_size,), axis=0) mux_comp.add_var('b', shape=(b_size,), axis=1) @@ -178,9 +176,9 @@ def setUp(self): a_shape = (3, 3) b_shape = (2, 4) - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() for i in range(self.nn): ivc.add_output(name='a_{0}'.format(i), shape=a_shape) ivc.add_output(name='b_{0}'.format(i), shape=b_shape) @@ -190,7 +188,7 @@ def setUp(self): subsys=ivc, promotes_outputs=['*']) - mux_comp = self.p.model.add_subsystem(name='mux_comp', subsys=MuxComp(vec_size=self.nn)) + mux_comp = self.p.model.add_subsystem(name='mux_comp', subsys=om.MuxComp(vec_size=self.nn)) mux_comp.add_var('a', shape=a_shape, axis=0) mux_comp.add_var('b', shape=b_shape, axis=1) @@ -230,14 +228,15 @@ def test_partials(self): assert_check_partials(cpd, atol=1.0E-8, rtol=1.0E-8) -class TestForDocs(unittest.TestCase): +class TestFeature(unittest.TestCase): def test(self): """ An example demonstrating a trivial use case of MuxComp """ import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, MuxComp, VectorMagnitudeComp + + import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error # The number of elements to be muxed @@ -246,9 +245,9 @@ def test(self): # The size of each element to be muxed m = 100 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='x', shape=(m,), units='m') ivc.add_output(name='y', shape=(m,), units='m') ivc.add_output(name='z', shape=(m,), units='m') @@ -257,13 +256,13 @@ def test(self): subsys=ivc, promotes_outputs=['x', 'y', 'z']) - mux_comp = p.model.add_subsystem(name='mux', subsys=MuxComp(vec_size=n)) + mux_comp = p.model.add_subsystem(name='mux', subsys=om.MuxComp(vec_size=n)) mux_comp.add_var('r', shape=(m,), axis=1, units='m') p.model.add_subsystem(name='vec_mag_comp', - subsys=VectorMagnitudeComp(vec_size=m, length=n, in_name='r', - mag_name='r_mag', units='m')) + subsys=om.VectorMagnitudeComp(vec_size=m, length=n, in_name='r', + mag_name='r_mag', units='m')) p.model.connect('x', 'mux.r_0') p.model.connect('y', 'mux.r_1') diff --git a/openmdao/components/tests/test_vector_magnitude_comp.py b/openmdao/components/tests/test_vector_magnitude_comp.py index c2cbb0a3b1..039b5ff713 100644 --- a/openmdao/components/tests/test_vector_magnitude_comp.py +++ b/openmdao/components/tests/test_vector_magnitude_comp.py @@ -4,7 +4,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, VectorMagnitudeComp +import openmdao.api as om class TestVectorMagnitudeCompNx3(unittest.TestCase): @@ -12,9 +12,9 @@ class TestVectorMagnitudeCompNx3(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3)) self.p.model.add_subsystem(name='ivc', @@ -22,7 +22,7 @@ def setUp(self): promotes_outputs=['a']) self.p.model.add_subsystem(name='vec_mag_comp', - subsys=VectorMagnitudeComp(vec_size=self.nn)) + subsys=om.VectorMagnitudeComp(vec_size=self.nn)) self.p.model.connect('a', 'vec_mag_comp.a') @@ -56,9 +56,9 @@ class TestVectorMagnitudeCompNx4(unittest.TestCase): def setUp(self): self.nn = 100 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 4)) self.p.model.add_subsystem(name='ivc', @@ -66,7 +66,7 @@ def setUp(self): promotes_outputs=['a']) self.p.model.add_subsystem(name='vec_mag_comp', - subsys=VectorMagnitudeComp(vec_size=self.nn, length=4)) + subsys=om.VectorMagnitudeComp(vec_size=self.nn, length=4)) self.p.model.connect('a', 'vec_mag_comp.a') @@ -101,9 +101,9 @@ class TestUnits(unittest.TestCase): def setUp(self): self.nn = 5 - self.p = Problem(model=Group()) + self.p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='a', shape=(self.nn, 3), units='m') self.p.model.add_subsystem(name='ivc', @@ -111,7 +111,7 @@ def setUp(self): promotes_outputs=['a']) self.p.model.add_subsystem(name='vec_mag_comp', - subsys=VectorMagnitudeComp(vec_size=self.nn, units='m')) + subsys=om.VectorMagnitudeComp(vec_size=self.nn, units='m')) self.p.model.connect('a', 'vec_mag_comp.a') @@ -141,29 +141,29 @@ def test_partials(self): decimal=6) -class TestForDocs(unittest.TestCase): +class TestFeature(unittest.TestCase): def test(self): """ A simple example to compute the magnitude of 3-vectors at at 100 points simultaneously. """ import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, VectorMagnitudeComp + import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error n = 100 - p = Problem(model=Group()) + p = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='pos', shape=(n, 3), units='m') p.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['pos']) - dp_comp = VectorMagnitudeComp(vec_size=n, length=3, in_name='r', mag_name='r_mag', - units='km') + dp_comp = om.VectorMagnitudeComp(vec_size=n, length=3, in_name='r', mag_name='r_mag', + units='km') p.model.add_subsystem(name='vec_mag_comp', subsys=dp_comp) diff --git a/openmdao/core/tests/test_add_var.py b/openmdao/core/tests/test_add_var.py index e6222c953b..2e043b28c6 100644 --- a/openmdao/core/tests/test_add_var.py +++ b/openmdao/core/tests/test_add_var.py @@ -1,14 +1,14 @@ """Acceptance and developer tests for add_input and add_output.""" from __future__ import division +import unittest import numpy as np -import unittest -from openmdao.api import Problem, ExplicitComponent +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -class CompAddWithDefault(ExplicitComponent): +class CompAddWithDefault(om.ExplicitComponent): """Component for tests for declaring only default value.""" def setup(self): @@ -24,7 +24,7 @@ def setup(self): self.add_output('y_e', val=6. * np.ones((3, 2))) -class CompAddWithShape(ExplicitComponent): +class CompAddWithShape(om.ExplicitComponent): """Component for tests for declaring only shape.""" def setup(self): @@ -36,7 +36,7 @@ def setup(self): self.add_output('y_c', shape=[3, 3]) -class CompAddWithIndices(ExplicitComponent): +class CompAddWithIndices(om.ExplicitComponent): """Component for tests for declaring only indices.""" def setup(self): @@ -49,7 +49,7 @@ def setup(self): -class CompAddWithShapeAndIndices(ExplicitComponent): +class CompAddWithShapeAndIndices(om.ExplicitComponent): """Component for tests for declaring shape and array indices.""" def setup(self): @@ -59,7 +59,7 @@ def setup(self): self.add_input('x_d', shape=[2, 2], src_indices=np.arange(4).reshape((2, 2))) -class CompAddArrayWithScalar(ExplicitComponent): +class CompAddArrayWithScalar(om.ExplicitComponent): """Component for tests for declaring a scalar val with an array variable.""" def setup(self): @@ -71,7 +71,7 @@ def setup(self): self.add_output('y_b', val=3.0, shape=(3, 2)) -class CompAddWithArrayIndices(ExplicitComponent): +class CompAddWithArrayIndices(om.ExplicitComponent): """Component for tests for declaring with array val and array indices.""" def setup(self): @@ -80,7 +80,7 @@ def setup(self): self.add_output('y') -class CompAddWithBounds(ExplicitComponent): +class CompAddWithBounds(om.ExplicitComponent): """Component for tests for declaring bounds.""" def setup(self): @@ -96,10 +96,10 @@ class TestAddVar(unittest.TestCase): def test_val(self): """Test declaring only default value.""" - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_add_var import CompAddWithDefault - p = Problem(model=CompAddWithDefault()) + p = om.Problem(model=CompAddWithDefault()) p.setup() assert_rel_error(self, p['x_a'], 1.) @@ -115,10 +115,10 @@ def test_val(self): def test_shape(self): """Test declaring only shape.""" - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_add_var import CompAddWithShape - p = Problem(model=CompAddWithShape()) + p = om.Problem(model=CompAddWithShape()) p.setup() assert_rel_error(self, p['x_a'], np.ones(2)) @@ -130,10 +130,10 @@ def test_shape(self): def test_indices(self): """Test declaring only indices.""" - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_add_var import CompAddWithIndices - p = Problem(model=CompAddWithIndices()) + p = om.Problem(model=CompAddWithIndices()) p.setup() assert_rel_error(self, p['x_a'], 1.) @@ -144,7 +144,7 @@ def test_indices(self): def test_shape_and_indices(self): """Test declaring shape and indices.""" - p = Problem(model=CompAddWithShapeAndIndices()) + p = om.Problem(model=CompAddWithShapeAndIndices()) p.setup() assert_rel_error(self, p['x_a'], np.ones(2)) @@ -154,10 +154,10 @@ def test_shape_and_indices(self): def test_scalar_array(self): """Test declaring a scalar val with an array variable.""" - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_add_var import CompAddArrayWithScalar - p = Problem(model=CompAddArrayWithScalar()) + p = om.Problem(model=CompAddArrayWithScalar()) p.setup() assert_rel_error(self, p['x_a'], 2. * np.ones(6)) @@ -169,10 +169,10 @@ def test_scalar_array(self): def test_array_indices(self): """Test declaring with array val and array indices.""" - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_add_var import CompAddWithArrayIndices - p = Problem(model=CompAddWithArrayIndices()) + p = om.Problem(model=CompAddWithArrayIndices()) p.setup() assert_rel_error(self, p['x_a'], 2. * np.ones(6)) @@ -180,10 +180,10 @@ def test_array_indices(self): def test_bounds(self): """Test declaring bounds.""" - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_add_var import CompAddWithBounds - p = Problem(model=CompAddWithBounds()) + p = om.Problem(model=CompAddWithBounds()) p.setup() assert_rel_error(self, p['y_a'], 2.) diff --git a/openmdao/core/tests/test_approx_derivs.py b/openmdao/core/tests/test_approx_derivs.py index 46ffd2f634..cbcb6153b7 100644 --- a/openmdao/core/tests/test_approx_derivs.py +++ b/openmdao/core/tests/test_approx_derivs.py @@ -1,9 +1,8 @@ """ Testing for group finite differencing.""" -from six.moves import range -import unittest -import os import itertools +import unittest from six import iterkeys +from six.moves import range try: from parameterized import parameterized @@ -12,13 +11,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, ExecComp, NewtonSolver, \ - ExplicitComponent, DefaultVector, NonlinearBlockGS, LinearRunOnce, DirectSolver, LinearBlockGS, \ - ScipyOptimizeDriver -from openmdao.core.tests.test_coloring import CounterGroup -from openmdao.utils.assert_utils import assert_rel_error -from openmdao.utils.general_utils import set_pyoptsparse_opt -from openmdao.utils.mpi import MPI +import openmdao.api as om from openmdao.test_suite.components.impl_comp_array import TestImplCompArray, TestImplCompArrayDense from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ @@ -27,12 +20,15 @@ from openmdao.test_suite.components.unit_conv import SrcComp, TgtCompC, TgtCompF, TgtCompK from openmdao.test_suite.groups.parallel_groups import FanInSubbedIDVC from openmdao.test_suite.parametric_suite import parametric_suite +from openmdao.utils.assert_utils import assert_rel_error +from openmdao.utils.general_utils import set_pyoptsparse_opt +from openmdao.utils.mpi import MPI try: from openmdao.parallel_api import PETScVector vector_class = PETScVector except ImportError: - vector_class = DefaultVector + vector_class = om.DefaultVector PETScVector = None # check that pyoptsparse is installed @@ -46,13 +42,13 @@ class TestGroupFiniteDifference(unittest.TestCase): def test_paraboloid(self): - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals() prob.setup(check=False, mode='fwd') @@ -72,7 +68,7 @@ def test_paraboloid(self): def test_fd_count(self): # Make sure we aren't doing extra FD steps. - class ParaboloidA(ExplicitComponent): + class ParaboloidA(om.ExplicitComponent): def setup(self): self.add_input('x', val=0.0) self.add_input('y', val=0.0) @@ -95,10 +91,10 @@ def compute(self, inputs, outputs): self.count += 1 - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=3.0)) - model.add_subsystem('py', IndepVarComp('y', val=5.0)) + model.add_subsystem('px', om.IndepVarComp('x', val=3.0)) + model.add_subsystem('py', om.IndepVarComp('y', val=5.0)) model.add_subsystem('parab', ParaboloidA()) model.connect('px.x', 'parab.x') @@ -108,7 +104,7 @@ def compute(self, inputs, outputs): model.add_design_var('py.y', lower=-50, upper=50) model.add_objective('parab.f_xy') - prob.setup(check=False) + prob.setup() prob.run_model() J = prob.compute_totals(of=['parab.f_xy'], wrt=['px.x', 'py.y']) # print(J) @@ -119,7 +115,7 @@ def compute(self, inputs, outputs): def test_fd_count_driver(self): # Make sure we aren't doing FD wrt any var that isn't in the driver desvar set. - class ParaboloidA(ExplicitComponent): + class ParaboloidA(om.ExplicitComponent): def setup(self): self.add_input('x', val=0.0) self.add_input('y', val=0.0) @@ -139,10 +135,10 @@ def compute(self, inputs, outputs): self.count += 1 - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=3.0)) - model.add_subsystem('py', IndepVarComp('y', val=5.0)) + model.add_subsystem('px', om.IndepVarComp('x', val=3.0)) + model.add_subsystem('py', om.IndepVarComp('y', val=5.0)) model.add_subsystem('parab', ParaboloidA()) model.connect('px.x', 'parab.x') @@ -153,7 +149,7 @@ def compute(self, inputs, outputs): model.approx_totals(method='fd') - prob.setup(check=False) + prob.setup() prob.run_model() prob.driver._compute_totals(of=['parab.f_xy'], wrt=['px.x'], global_names=True) @@ -162,14 +158,14 @@ def compute(self, inputs, outputs): self.assertEqual(model.parab.count, 2) def test_paraboloid_subbed(self): - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) - sub = model.add_subsystem('sub', Group(), promotes=['x', 'y', 'f_xy']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) + sub = model.add_subsystem('sub', om.Group(), promotes=['x', 'y', 'f_xy']) sub.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() sub.approx_totals() prob.setup(check=False, mode='fwd') @@ -191,20 +187,20 @@ def test_paraboloid_subbed(self): self.assertEqual(len(sub._approx_schemes['fd']._exec_dict), 2) def test_paraboloid_subbed_in_setup(self): - class MyModel(Group): + class MyModel(om.Group): def setup(self): self.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) self.approx_totals() - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) sub = model.add_subsystem('sub', MyModel(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() prob.setup(check=False, mode='fwd') prob.set_solver_print(level=0) @@ -225,13 +221,13 @@ def setup(self): self.assertEqual(len(sub._approx_schemes['fd']._exec_dict), 2) def test_paraboloid_subbed_with_connections(self): - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0)) - model.add_subsystem('p2', IndepVarComp('y', 0.0)) - sub = model.add_subsystem('sub', Group()) - sub.add_subsystem('bx', ExecComp('xout = xin')) - sub.add_subsystem('by', ExecComp('yout = yin')) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0)) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0)) + sub = model.add_subsystem('sub', om.Group()) + sub.add_subsystem('bx', om.ExecComp('xout = xin')) + sub.add_subsystem('by', om.ExecComp('yout = yin')) sub.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'sub.bx.xin') @@ -239,7 +235,7 @@ def test_paraboloid_subbed_with_connections(self): model.connect('p2.y', 'sub.by.yin') model.connect('sub.by.yout', 'sub.comp.y') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() sub.approx_totals() prob.setup(check=False, mode='fwd') @@ -273,19 +269,19 @@ def compute_partials(self, inputs, partials): """ pass - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x1', val=np.ones(2))) - model.add_subsystem('p2', IndepVarComp('x2', val=np.ones(2))) + model.add_subsystem('p1', om.IndepVarComp('x1', val=np.ones(2))) + model.add_subsystem('p2', om.IndepVarComp('x2', val=np.ones(2))) comp = model.add_subsystem('comp', DoubleArrayFD()) model.connect('p1.x1', 'comp.x1') model.connect('p2.x2', 'comp.x2') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals() - prob.setup(check=False) + prob.setup() prob.run_model() model.run_linearize() @@ -304,17 +300,17 @@ def setup(self): super(TestImplCompArrayDense, self).setup() self.declare_partials('*', '*', method='fd') - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p_rhs', IndepVarComp('rhs', val=np.ones(2))) - sub = model.add_subsystem('sub', Group()) + model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.ones(2))) + sub = model.add_subsystem('sub', om.Group()) comp = sub.add_subsystem('comp', TestImplCompArrayDense()) model.connect('p_rhs.rhs', 'sub.comp.rhs') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - prob.setup(check=False) + prob.setup() prob.run_model() model.run_linearize() @@ -331,18 +327,18 @@ def solve_nonlinear(self, inputs, outputs): """ Disable local solve.""" pass - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p_rhs', IndepVarComp('rhs', val=np.array([2, 4]))) + model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.array([2, 4]))) model.add_subsystem('comp', TestImplCompArrayDenseNoSolve()) model.connect('p_rhs.rhs', 'comp.rhs') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.approx_totals() - prob.setup(check=False) + prob.setup() prob.run_model() model.approx_totals() assert_rel_error(self, prob['comp.x'], [1.97959184, 4.02040816], 1e-5) @@ -358,13 +354,13 @@ def solve_nonlinear(self, inputs, outputs): def test_step_size(self): # Test makes sure option metadata propagates to the fd function - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() # Worse step so that our answer will be off a wee bit. model.approx_totals(step=1e-2) @@ -382,11 +378,10 @@ def test_step_size(self): def test_unit_conv_group(self): - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1']) - sub1 = prob.model.add_subsystem('sub1', Group()) - sub2 = prob.model.add_subsystem('sub2', Group()) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) + sub1 = prob.model.add_subsystem('sub1', om.Group()) + sub2 = prob.model.add_subsystem('sub2', om.Group()) sub1.add_subsystem('src', SrcComp()) sub2.add_subsystem('tgtF', TgtCompF()) @@ -400,7 +395,7 @@ def test_unit_conv_group(self): sub2.approx_totals(method='fd') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['sub1.src.x2'], 100.0, 1e-6) @@ -428,27 +423,27 @@ def test_unit_conv_group(self): def test_sellar(self): # Basic sellar test. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() model.approx_totals(method='fd', step=1e-5) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -465,7 +460,7 @@ def test_sellar(self): def test_desvar_with_indices(self): # Just desvars on this one to cover code missed by desvar+response test. - class ArrayComp2D(ExplicitComponent): + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component. """ @@ -498,9 +493,9 @@ def compute_partials(self, inputs, partials): """ partials[('y1', 'x1')] = self.JJ - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) @@ -525,7 +520,7 @@ def compute_partials(self, inputs, partials): def test_desvar_and_response_with_indices(self): - class ArrayComp2D(ExplicitComponent): + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component. """ @@ -557,9 +552,9 @@ def compute_partials(self, inputs, partials): """ partials[('y1', 'x1')] = self.JJ - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) @@ -584,11 +579,11 @@ def compute_partials(self, inputs, partials): def test_full_model_fd(self): - class DontCall(LinearRunOnce): + class DontCall(om.LinearRunOnce): def solve(self, vec_names, mode, rel_systems=None): raise RuntimeError("This solver should be ignored!") - class Simple(ExplicitComponent): + class Simple(om.ExplicitComponent): def setup(self): self.add_input('x', val=0.0) self.add_output('y', val=0.0) @@ -599,9 +594,9 @@ def compute(self, inputs, outputs): x = inputs['x'] outputs['y'] = 4.0*x - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) model.add_subsystem('comp', Simple(), promotes=['x', 'y']) model.linear_solver = DontCall() @@ -623,29 +618,29 @@ def compute(self, inputs, outputs): def test_newton_with_densejac_under_full_model_fd(self): # Basic sellar test. - prob = Problem() - model = prob.model = Group(assembled_jac_type='dense') - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model = om.Group(assembled_jac_type='dense') + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = ScipyKrylov(assemble_jac=True) + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.ScipyKrylov(assemble_jac=True) model.approx_totals(method='fd', step=1e-5) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -662,29 +657,29 @@ def test_newton_with_densejac_under_full_model_fd(self): def test_newton_with_cscjac_under_full_model_fd(self): # Basic sellar test. - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = ScipyKrylov(assemble_jac=True) + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.ScipyKrylov(assemble_jac=True) model.approx_totals(method='fd', step=1e-5) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -699,9 +694,9 @@ def test_newton_with_cscjac_under_full_model_fd(self): assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001) def test_approx_totals_multi_input_constrained_desvar(self): - p = Problem(model=Group()) + p = om.Problem() - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['*']) + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*']) indeps.add_output('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717, 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886])) @@ -709,15 +704,15 @@ def test_approx_totals_multi_input_constrained_desvar(self): -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582])) indeps.add_output('r', .7) - arctan_yox = ExecComp('g=arctan(y/x)', vectorize=True, - g=np.ones(10), x=np.ones(10), y=np.ones(10)) + arctan_yox = om.ExecComp('g=arctan(y/x)', vectorize=True, + g=np.ones(10), x=np.ones(10), y=np.ones(10)) p.model.add_subsystem('arctan_yox', arctan_yox) - p.model.add_subsystem('circle', ExecComp('area=pi*r**2')) + p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2')) - p.model.add_subsystem('r_con', ExecComp('g=x**2 + y**2 - r', vectorize=True, - g=np.ones(10), x=np.ones(10), y=np.ones(10))) + p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=True, + g=np.ones(10), x=np.ones(10), y=np.ones(10))) p.model.connect('r', ('circle.r', 'r_con.r')) p.model.connect('x', ['r_con.x', 'arctan_yox.x']) @@ -751,9 +746,9 @@ def test_opt_with_linear_constraint(self): if OPTIMIZER is None: raise unittest.SkipTest("pyoptsparse is not providing SNOPT or SLSQP") - p = Problem() + p = om.Problem() - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['*']) + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*']) indeps.add_output('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717, 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886])) @@ -761,25 +756,25 @@ def test_opt_with_linear_constraint(self): -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582])) indeps.add_output('r', .7) - arctan_yox = ExecComp('g=arctan(y/x)', vectorize=True, - g=np.ones(10), x=np.ones(10), y=np.ones(10)) + arctan_yox = om.ExecComp('g=arctan(y/x)', vectorize=True, + g=np.ones(10), x=np.ones(10), y=np.ones(10)) p.model.add_subsystem('arctan_yox', arctan_yox) - p.model.add_subsystem('circle', ExecComp('area=pi*r**2')) + p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2')) - p.model.add_subsystem('r_con', ExecComp('g=x**2 + y**2 - r', vectorize=True, - g=np.ones(10), x=np.ones(10), y=np.ones(10))) + p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=True, + g=np.ones(10), x=np.ones(10), y=np.ones(10))) thetas = np.linspace(0, np.pi/4, 10) - p.model.add_subsystem('theta_con', ExecComp('g = x - theta', vectorize=True, - g=np.ones(10), x=np.ones(10), - theta=thetas)) - p.model.add_subsystem('delta_theta_con', ExecComp('g = even - odd', vectorize=True, - g=np.ones(10//2), even=np.ones(10//2), - odd=np.ones(10//2))) + p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', vectorize=True, + g=np.ones(10), x=np.ones(10), + theta=thetas)) + p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', vectorize=True, + g=np.ones(10//2), even=np.ones(10//2), + odd=np.ones(10//2))) - p.model.add_subsystem('l_conx', ExecComp('g=x-1', vectorize=True, g=np.ones(10), x=np.ones(10))) + p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', vectorize=True, g=np.ones(10), x=np.ones(10))) IND = np.arange(10, dtype=int) ODD_IND = IND[1::2] # all odd indices @@ -823,7 +818,7 @@ class TestGroupFiniteDifferenceMPI(unittest.TestCase): N_PROCS = 2 def test_indepvarcomp_under_par_sys(self): - prob = Problem() + prob = om.Problem() prob.model = FanInSubbedIDVC() prob.setup(local_vector_class=vector_class, check=False, mode='rev') @@ -842,7 +837,7 @@ class TestGroupCSMPI(unittest.TestCase): N_PROCS = 2 def test_indepvarcomp_under_par_sys_par_cs(self): - prob = Problem() + prob = om.Problem() prob.model = FanInSubbedIDVC(num_par_fd=2) prob.model.approx_totals(method='cs') @@ -861,7 +856,7 @@ class TestGroupFDMPI(unittest.TestCase): N_PROCS = 2 def test_indepvarcomp_under_par_sys_par_fd(self): - prob = Problem() + prob = om.Problem() prob.model = FanInSubbedIDVC(num_par_fd=2) prob.model.approx_totals(method='fd') @@ -883,7 +878,7 @@ class TestGroupComplexStep(unittest.TestCase): def setUp(self): - self.prob = Problem() + self.prob = om.Problem() def tearDown(self): # Global stuff seems to not get cleaned up if test fails. @@ -892,7 +887,7 @@ def tearDown(self): except Exception: pass - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_paraboloid_'+'_'.join(title(a) for a in p.args)) def test_paraboloid(self, vec_class): @@ -901,12 +896,12 @@ def test_paraboloid(self, vec_class): raise unittest.SkipTest("PETSc is not installed") prob = self.prob - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals(method='cs') prob.setup(check=False, mode='fwd', local_vector_class=vec_class) @@ -923,7 +918,7 @@ def test_paraboloid(self, vec_class): # 1 output x 2 inputs self.assertEqual(len(model._approx_schemes['cs']._exec_dict), 2) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_paraboloid_subbed_'+'_'.join(title(a) for a in p.args)) def test_paraboloid_subbed(self, vec_class): @@ -932,13 +927,13 @@ def test_paraboloid_subbed(self, vec_class): raise unittest.SkipTest("PETSc is not installed") prob = self.prob - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) - sub = model.add_subsystem('sub', Group(), promotes=['x', 'y', 'f_xy']) + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) + sub = model.add_subsystem('sub', om.Group(), promotes=['x', 'y', 'f_xy']) sub.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() sub.approx_totals(method='cs') prob.setup(check=False, mode='fwd', local_vector_class=vec_class) @@ -959,7 +954,7 @@ def test_paraboloid_subbed(self, vec_class): # 1 output x 2 inputs self.assertEqual(len(sub._approx_schemes['cs']._exec_dict), 2) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_parab_subbed_with_connections_'+'_'.join(title(a) for a in p.args)) def test_paraboloid_subbed_with_connections(self, vec_class): @@ -968,12 +963,12 @@ def test_paraboloid_subbed_with_connections(self, vec_class): raise unittest.SkipTest("PETSc is not installed") prob = self.prob - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0)) - model.add_subsystem('p2', IndepVarComp('y', 0.0)) - sub = model.add_subsystem('sub', Group()) - sub.add_subsystem('bx', ExecComp('xout = xin')) - sub.add_subsystem('by', ExecComp('yout = yin')) + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0)) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0)) + sub = model.add_subsystem('sub', om.Group()) + sub.add_subsystem('bx', om.ExecComp('xout = xin')) + sub.add_subsystem('by', om.ExecComp('yout = yin')) sub.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'sub.bx.xin') @@ -981,7 +976,7 @@ def test_paraboloid_subbed_with_connections(self, vec_class): model.connect('p2.y', 'sub.by.yin') model.connect('sub.by.yout', 'sub.comp.y') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() sub.approx_totals(method='cs') prob.setup(check=False, mode='fwd', local_vector_class=vec_class) @@ -1005,7 +1000,7 @@ def test_paraboloid_subbed_with_connections(self, vec_class): n_entries += len(v) self.assertEqual(n_entries, 6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_array_comp_'+'_'.join(title(a) for a in p.args)) def test_array_comp(self, vec_class): @@ -1022,15 +1017,15 @@ def compute_partials(self, inputs, partials): pass prob = self.prob - model = prob.model = Group() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x1', val=np.ones(2))) - model.add_subsystem('p2', IndepVarComp('x2', val=np.ones(2))) + model.add_subsystem('p1', om.IndepVarComp('x1', val=np.ones(2))) + model.add_subsystem('p2', om.IndepVarComp('x2', val=np.ones(2))) comp = model.add_subsystem('comp', DoubleArrayFD()) model.connect('p1.x1', 'comp.x1') model.connect('p2.x2', 'comp.x2') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals(method='cs') prob.setup(check=False, local_vector_class=vec_class) @@ -1043,7 +1038,7 @@ def compute_partials(self, inputs, partials): assert_rel_error(self, Jfd['comp.y2', 'p1.x1'], comp.JJ[2:4, 0:2], 1e-6) assert_rel_error(self, Jfd['comp.y2', 'p2.x2'], comp.JJ[2:4, 2:4], 1e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_unit_conv_group_'+'_'.join(title(a) for a in p.args)) def test_unit_conv_group(self, vec_class): @@ -1052,10 +1047,9 @@ def test_unit_conv_group(self, vec_class): raise unittest.SkipTest("PETSc is not installed") prob = self.prob - prob.model = Group() - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1']) - sub1 = prob.model.add_subsystem('sub1', Group()) - sub2 = prob.model.add_subsystem('sub2', Group()) + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) + sub1 = prob.model.add_subsystem('sub1', om.Group()) + sub2 = prob.model.add_subsystem('sub2', om.Group()) sub1.add_subsystem('src', SrcComp()) sub2.add_subsystem('tgtF', TgtCompF()) @@ -1094,7 +1088,7 @@ def test_unit_conv_group(self, vec_class): assert_rel_error(self, J['sub2.tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['sub2.tgtK.x3']['x1'][0][0], 1.0, 1e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_sellar_'+'_'.join(title(a) for a in p.args)) def test_sellar(self, vec_class): @@ -1104,22 +1098,22 @@ def test_sellar(self, vec_class): raise unittest.SkipTest("PETSc is not installed") prob = self.prob - model = prob.model = Group() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.nonlinear_solver.options['atol'] = 1e-50 prob.model.nonlinear_solver.options['rtol'] = 1e-50 @@ -1144,7 +1138,7 @@ def test_sellar(self, vec_class): def test_desvar_and_response_with_indices(self): - class ArrayComp2D(ExplicitComponent): + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component. """ @@ -1176,9 +1170,9 @@ def compute_partials(self, inputs, partials): """ partials[('y1', 'x1')] = self.JJ - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) @@ -1204,7 +1198,7 @@ def compute_partials(self, inputs, partials): def test_desvar_with_indices(self): # Just desvars on this one to cover code missed by desvar+response test. - class ArrayComp2D(ExplicitComponent): + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component. """ @@ -1236,9 +1230,9 @@ def compute_partials(self, inputs, partials): """ partials[('y1', 'x1')] = self.JJ - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) @@ -1261,7 +1255,7 @@ def compute_partials(self, inputs, partials): assert_rel_error(self, J['y1', 'x1'][2][0], Jbase[2, 1], 1e-8) assert_rel_error(self, J['y1', 'x1'][2][1], Jbase[2, 3], 1e-8) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_newton_with_direct_solver_'+'_'.join(title(a) for a in p.args)) def test_newton_with_direct_solver(self, vec_class): @@ -1270,25 +1264,25 @@ def test_newton_with_direct_solver(self, vec_class): if not vec_class: raise unittest.SkipTest("PETSc is not installed") - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = DirectSolver(assemble_jac=False) + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.DirectSolver(assemble_jac=False) sub.nonlinear_solver.options['atol'] = 1e-10 sub.nonlinear_solver.options['rtol'] = 1e-10 @@ -1312,7 +1306,7 @@ def test_newton_with_direct_solver(self, vec_class): assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6) assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_newton_with_direct_solver_dense_'+'_'.join(title(a) for a in p.args)) def test_newton_with_direct_solver_dense(self, vec_class): @@ -1321,25 +1315,25 @@ def test_newton_with_direct_solver_dense(self, vec_class): if not vec_class: raise unittest.SkipTest("PETSc is not installed") - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = DirectSolver() + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.DirectSolver() sub.options['assembled_jac_type'] = 'dense' sub.nonlinear_solver.options['atol'] = 1e-10 @@ -1365,7 +1359,7 @@ def test_newton_with_direct_solver_dense(self, vec_class): assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6) assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_newton_with_direct_solver_csc_'+'_'.join(title(a) for a in p.args)) def test_newton_with_direct_solver_csc(self, vec_class): @@ -1374,25 +1368,25 @@ def test_newton_with_direct_solver_csc(self, vec_class): if not vec_class: raise unittest.SkipTest("PETSc is not installed") - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = DirectSolver() + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.DirectSolver() sub.options['assembled_jac_type'] = 'csc' sub.nonlinear_solver.options['atol'] = 1e-10 @@ -1418,7 +1412,7 @@ def test_newton_with_direct_solver_csc(self, vec_class): assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6) assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_subbed_newton_gs_'+'_'.join(title(a) for a in p.args)) def test_subbed_newton_gs(self, vec_class): @@ -1427,37 +1421,37 @@ def test_subbed_newton_gs(self, vec_class): raise unittest.SkipTest("PETSc is not installed") from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - class SellarDerivatives(Group): + class SellarDerivatives(om.Group): def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - sub = self.add_subsystem('sub', Group(), promotes=['*']) + sub = self.add_subsystem('sub', om.Group(), promotes=['*']) - sub.linear_solver = DirectSolver(assemble_jac=True) + sub.linear_solver = om.DirectSolver(assemble_jac=True) sub.options['assembled_jac_type'] = 'csc' - sub.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, - x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), + sub.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, + x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - sub.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), + sub.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), promotes=['con1', 'y1']) - sub.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), + sub.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), promotes=['con2', 'y2']) - self.nonlinear_solver = NewtonSolver() - self.linear_solver = LinearBlockGS() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.LinearBlockGS() self.linear_solver.options['maxiter'] = 25 self.linear_solver.options['atol'] = 1e-16 - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.setup(check=False) + prob.setup() prob.model.approx_totals(method='cs') @@ -1474,7 +1468,7 @@ def setup(self): assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6) assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_subbed_newton_gs_csc_external_mtx_'+'_'.join(title(a) for a in p.args)) def test_subbed_newton_gs_csc_external_mtx(self, vec_class): @@ -1483,37 +1477,37 @@ def test_subbed_newton_gs_csc_external_mtx(self, vec_class): raise unittest.SkipTest("PETSc is not installed") from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - class SellarDerivatives(Group): + class SellarDerivatives(om.Group): def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - sub = self.add_subsystem('sub', Group(), promotes=['*']) + sub = self.add_subsystem('sub', om.Group(), promotes=['*']) - sub.linear_solver = DirectSolver(assemble_jac=True) + sub.linear_solver = om.DirectSolver(assemble_jac=True) sub.options['assembled_jac_type'] = 'csc' - sub.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, - x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), + sub.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, + x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - sub.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), + sub.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), promotes=['con1', 'y1']) - sub.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), + sub.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), promotes=['con2', 'y2']) - self.nonlinear_solver = NewtonSolver() - self.linear_solver = LinearBlockGS() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.LinearBlockGS() self.linear_solver.options['maxiter'] = 25 self.linear_solver.options['atol'] = 1e-16 - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.setup(check=False) + prob.setup() prob.model.approx_totals(method='cs') @@ -1530,7 +1524,7 @@ def setup(self): assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6) assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_subbed_newton_gs_dense_external_mtx_'+'_'.join(title(a) for a in p.args)) def test_subbed_newton_gs_dense_external_mtx(self, vec_class): @@ -1539,37 +1533,37 @@ def test_subbed_newton_gs_dense_external_mtx(self, vec_class): raise unittest.SkipTest("PETSc is not installed") from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - class SellarDerivatives(Group): + class SellarDerivatives(om.Group): def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - sub = self.add_subsystem('sub', Group(), promotes=['*']) + sub = self.add_subsystem('sub', om.Group(), promotes=['*']) - sub.linear_solver = DirectSolver(assemble_jac=True) + sub.linear_solver = om.DirectSolver(assemble_jac=True) sub.options['assembled_jac_type'] = 'dense' - sub.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, - x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), + sub.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, + x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - sub.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), + sub.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), promotes=['con1', 'y1']) - sub.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), + sub.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), promotes=['con2', 'y2']) - self.nonlinear_solver = NewtonSolver() - self.linear_solver = LinearBlockGS() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.LinearBlockGS() self.linear_solver.options['maxiter'] = 25 self.linear_solver.options['atol'] = 1e-16 - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.setup(check=False) + prob.setup() prob.model.approx_totals(method='cs') @@ -1586,7 +1580,7 @@ def setup(self): assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6) assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6) - @parameterized.expand(itertools.product([DefaultVector, PETScVector]), + @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]), name_func=lambda f, n, p: 'test_newton_with_krylov_solver_'+'_'.join(title(a) for a in p.args)) def test_newton_with_krylov_solver(self, vec_class): @@ -1595,25 +1589,25 @@ def test_newton_with_krylov_solver(self, vec_class): if not vec_class: raise unittest.SkipTest("PETSc is not installed") - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = ScipyKrylov() + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.ScipyKrylov() sub.nonlinear_solver.options['atol'] = 1e-10 sub.nonlinear_solver.options['rtol'] = 1e-10 sub.linear_solver.options['atol'] = 1e-15 @@ -1641,31 +1635,31 @@ def test_newton_with_krylov_solver(self, vec_class): def test_newton_with_cscjac_under_cs(self): # Basic sellar test. - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = ScipyKrylov(assemble_jac=True) + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.ScipyKrylov(assemble_jac=True) sub.nonlinear_solver.options['atol'] = 1e-20 sub.nonlinear_solver.options['rtol'] = 1e-20 model.approx_totals(method='cs', step=1e-12) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -1686,37 +1680,37 @@ def test_newton_with_cscjac_under_cs(self): def test_newton_with_fd_group(self): # Basic sellar test. - prob = Problem() - model = prob.model = Group() - sub = model.add_subsystem('sub', Group(), promotes=['*']) - subfd = sub.add_subsystem('subfd', Group(), promotes=['*']) + prob = om.Problem() + model = prob.model + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) + subfd = sub.add_subsystem('subfd', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) subfd.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) subfd.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) # Finite difference for the Newton linear solve only subfd.approx_totals(method='fd') - sub.nonlinear_solver = NewtonSolver() + sub.nonlinear_solver = om.NewtonSolver() sub.nonlinear_solver.options['maxiter'] = 12 - sub.linear_solver = DirectSolver(assemble_jac=False) + sub.linear_solver = om.DirectSolver(assemble_jac=False) sub.nonlinear_solver.options['atol'] = 1e-20 sub.nonlinear_solver.options['rtol'] = 1e-20 # Complex Step for top derivatives model.approx_totals(method='cs', step=1e-14) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -1737,27 +1731,27 @@ def test_newton_with_fd_group(self): def test_nested_complex_step_unsupported(self): # Basic sellar test. - prob = self.prob = Problem() - model = prob.model = Group() + prob = self.prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1CS(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2CS(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - prob.model.nonlinear_solver = NewtonSolver() - prob.model.linear_solver = DirectSolver(assemble_jac=False) + prob.model.nonlinear_solver = om.NewtonSolver() + prob.model.linear_solver = om.DirectSolver(assemble_jac=False) prob.model.approx_totals(method='cs') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -1788,17 +1782,17 @@ def setup(self): super(TestImplCompArrayDense, self).setup() self.declare_partials('*', '*', method='cs') - prob = self.prob = Problem() - model = prob.model = Group() + prob = self.prob = om.Problem() + model = prob.model - model.add_subsystem('p_rhs', IndepVarComp('rhs', val=np.ones(2))) - sub = model.add_subsystem('sub', Group()) + model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.ones(2))) + sub = model.add_subsystem('sub', om.Group()) comp = sub.add_subsystem('comp', TestImplCompArrayDense()) model.connect('p_rhs.rhs', 'sub.comp.rhs') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - prob.setup(check=False) + prob.setup() prob.run_model() model.run_linearize() @@ -1826,17 +1820,17 @@ def setup(self): self.declare_partials('*', '*', method='fd') self.count += 1 - prob = self.prob = Problem() - model = prob.model = Group() + prob = self.prob = om.Problem() + model = prob.model - model.add_subsystem('p_rhs', IndepVarComp('rhs', val=np.ones(2))) - sub = model.add_subsystem('sub', Group()) + model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.ones(2))) + sub = model.add_subsystem('sub', om.Group()) comp = sub.add_subsystem('comp', TestImplCompArrayDense()) model.connect('p_rhs.rhs', 'sub.comp.rhs') - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - prob.setup(check=False) + prob.setup() prob.run_model() with self.assertRaises(RuntimeError) as context: @@ -1860,7 +1854,7 @@ def setup(self): def test_vector_methods(self): - class KenComp(ExplicitComponent): + class KenComp(om.ExplicitComponent): def setup(self): @@ -1882,14 +1876,14 @@ def compute(self, inputs, outputs): outputs['y1'] *= 1.0 - prob = self.prob = Problem() - model = prob.model = Group() + prob = self.prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=np.array([[7.0, 3.0], [2.4, 3.33]]))) + model.add_subsystem('px', om.IndepVarComp('x', val=np.array([[7.0, 3.0], [2.4, 3.33]]))) model.add_subsystem('comp', KenComp()) model.connect('px.x', 'comp.x1') - prob.setup(check=False) + prob.setup() prob.run_model() of = ['comp.y1'] @@ -1904,26 +1898,26 @@ def compute(self, inputs, outputs): def test_sellar_comp_cs(self): # Basic sellar test. - prob = self.prob = Problem() - model = prob.model = Group() + prob = self.prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1CS(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2CS(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - prob.model.nonlinear_solver = NonlinearBlockGS() - prob.model.linear_solver = DirectSolver(assemble_jac=False) + prob.model.nonlinear_solver = om.NonlinearBlockGS() + prob.model.linear_solver = om.DirectSolver(assemble_jac=False) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -1943,9 +1937,9 @@ def test_sellar_comp_cs(self): self.assertLess(val, 1e-8, msg="Check if CS cleans up after itself.") def test_stepsizes_under_complex_step(self): - from openmdao.api import Problem, ExplicitComponent + import openmdao.api as om - class SimpleComp(ExplicitComponent): + class SimpleComp(om.ExplicitComponent): def setup(self): self.add_input('x', val=1.0) @@ -1999,9 +1993,8 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['y', 'x'] = 3. - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('px', IndepVarComp('x', val=1.0)) + prob = om.Problem() + prob.model.add_subsystem('px', om.IndepVarComp('x', val=1.0)) prob.model.add_subsystem('comp', SimpleComp()) prob.model.connect('px.x', 'comp.x') @@ -2021,9 +2014,9 @@ def compute_partials(self, inputs, partials): prob.check_partials(method='cs', step=1e-14, out_stream=None) def test_feature_under_complex_step(self): - from openmdao.api import Problem, ExplicitComponent, Group, IndepVarComp + import openmdao.api as om - class SimpleComp(ExplicitComponent): + class SimpleComp(om.ExplicitComponent): def setup(self): self.add_input('x', val=1.0) @@ -2039,9 +2032,8 @@ def compute(self, inputs, outputs): print("x", inputs['x']) print("y", outputs['y']) - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('px', IndepVarComp('x', val=1.0)) + prob = om.Problem() + prob.model.add_subsystem('px', om.IndepVarComp('x', val=1.0)) prob.model.add_subsystem('comp', SimpleComp()) prob.model.connect('px.x', 'comp.x') @@ -2060,39 +2052,39 @@ class ApproxTotalsFeature(unittest.TestCase): def test_basic(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, ExplicitComponent + import openmdao.api as om - class CompOne(ExplicitComponent): + class CompOne(om.ExplicitComponent): - def setup(self): - self.add_input('x', val=0.0) - self.add_output('y', val=np.zeros(25)) - self._exec_count = 0 + def setup(self): + self.add_input('x', val=0.0) + self.add_output('y', val=np.zeros(25)) + self._exec_count = 0 - def compute(self, inputs, outputs): - x = inputs['x'] - outputs['y'] = np.arange(25) * x - self._exec_count += 1 + def compute(self, inputs, outputs): + x = inputs['x'] + outputs['y'] = np.arange(25) * x + self._exec_count += 1 - class CompTwo(ExplicitComponent): + class CompTwo(om.ExplicitComponent): - def setup(self): - self.add_input('y', val=np.zeros(25)) - self.add_output('z', val=0.0) - self._exec_count = 0 + def setup(self): + self.add_input('y', val=np.zeros(25)) + self.add_output('z', val=0.0) + self._exec_count = 0 - def compute(self, inputs, outputs): - y = inputs['y'] - outputs['z'] = np.sum(y) - self._exec_count += 1 + def compute(self, inputs, outputs): + y = inputs['y'] + outputs['z'] = np.sum(y) + self._exec_count += 1 - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) model.add_subsystem('comp1', CompOne(), promotes=['x', 'y']) comp2 = model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals() prob.setup() @@ -2108,39 +2100,39 @@ def compute(self, inputs, outputs): def test_basic_cs(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, ExplicitComponent + import openmdao.api as om - class CompOne(ExplicitComponent): + class CompOne(om.ExplicitComponent): - def setup(self): - self.add_input('x', val=0.0) - self.add_output('y', val=np.zeros(25)) - self._exec_count = 0 + def setup(self): + self.add_input('x', val=0.0) + self.add_output('y', val=np.zeros(25)) + self._exec_count = 0 - def compute(self, inputs, outputs): - x = inputs['x'] - outputs['y'] = np.arange(25) * x - self._exec_count += 1 + def compute(self, inputs, outputs): + x = inputs['x'] + outputs['y'] = np.arange(25) * x + self._exec_count += 1 - class CompTwo(ExplicitComponent): + class CompTwo(om.ExplicitComponent): - def setup(self): - self.add_input('y', val=np.zeros(25)) - self.add_output('z', val=0.0) - self._exec_count = 0 + def setup(self): + self.add_input('y', val=np.zeros(25)) + self.add_output('z', val=0.0) + self._exec_count = 0 - def compute(self, inputs, outputs): - y = inputs['y'] - outputs['z'] = np.sum(y) - self._exec_count += 1 + def compute(self, inputs, outputs): + y = inputs['y'] + outputs['z'] = np.sum(y) + self._exec_count += 1 - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) model.add_subsystem('comp1', CompOne(), promotes=['x', 'y']) model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals(method='cs') prob.setup() @@ -2155,39 +2147,39 @@ def compute(self, inputs, outputs): def test_arguments(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, ExplicitComponent + import openmdao.api as om - class CompOne(ExplicitComponent): + class CompOne(om.ExplicitComponent): - def setup(self): - self.add_input('x', val=0.0) - self.add_output('y', val=np.zeros(25)) - self._exec_count = 0 + def setup(self): + self.add_input('x', val=0.0) + self.add_output('y', val=np.zeros(25)) + self._exec_count = 0 - def compute(self, inputs, outputs): - x = inputs['x'] - outputs['y'] = np.arange(25) * x - self._exec_count += 1 + def compute(self, inputs, outputs): + x = inputs['x'] + outputs['y'] = np.arange(25) * x + self._exec_count += 1 - class CompTwo(ExplicitComponent): + class CompTwo(om.ExplicitComponent): - def setup(self): - self.add_input('y', val=np.zeros(25)) - self.add_output('z', val=0.0) - self._exec_count = 0 + def setup(self): + self.add_input('y', val=np.zeros(25)) + self.add_output('z', val=0.0) + self._exec_count = 0 - def compute(self, inputs, outputs): - y = inputs['y'] - outputs['z'] = np.sum(y) - self._exec_count += 1 + def compute(self, inputs, outputs): + y = inputs['y'] + outputs['z'] = np.sum(y) + self._exec_count += 1 - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 1.0), promotes=['x']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 1.0), promotes=['x']) model.add_subsystem('comp1', CompOne(), promotes=['x', 'y']) model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.approx_totals(method='fd', step=1e-7, form='central', step_calc='rel') prob.setup() @@ -2201,13 +2193,13 @@ def compute(self, inputs, outputs): def test_sellarCS(self): # Just tests Newton on Sellar with FD derivs. - from openmdao.api import Problem + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarNoDerivativesCS - prob = Problem() + prob = om.Problem() prob.model = SellarNoDerivativesCS() - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -2230,7 +2222,7 @@ class ParallelFDParametricTestCase(unittest.TestCase): run_by_default=True, ) def test_subset(self, param_instance): - param_instance.linear_solver_class = DirectSolver + param_instance.linear_solver_class = om.DirectSolver param_instance.linear_solver_options = {} # defaults not valid for DirectSolver param_instance.setup() diff --git a/openmdao/core/tests/test_check_derivs.py b/openmdao/core/tests/test_check_derivs.py index cd894af805..4f6fae990e 100644 --- a/openmdao/core/tests/test_check_derivs.py +++ b/openmdao/core/tests/test_check_derivs.py @@ -7,9 +7,7 @@ import numpy as np -from openmdao.api import Problem, Group, ExplicitComponent, ImplicitComponent, \ - IndepVarComp, ExecComp, NonlinearRunOnce, NonlinearBlockGS, ScipyKrylov, NewtonSolver, \ - DirectSolver, LinearBlockGS, BroydenSolver +import openmdao.api as om from openmdao.core.tests.test_impl_comp import QuadraticLinearize, QuadraticJacVec from openmdao.core.tests.test_matmat import MultiJacVec from openmdao.test_suite.components.impl_comp_array import TestImplCompArrayMatVec @@ -29,7 +27,7 @@ PETScVector = None -class ParaboloidTricky(ExplicitComponent): +class ParaboloidTricky(om.ExplicitComponent): """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3. """ @@ -68,7 +66,7 @@ def compute_partials(self, inputs, partials): partials['f_xy', 'y'] = 2.0*y*sc*sc + 8.0*sc + x*sc*sc -class MyCompGoodPartials(ExplicitComponent): +class MyCompGoodPartials(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -85,7 +83,7 @@ def compute_partials(self, inputs, partials): J['y', 'x2'] = np.array([4.0]) -class MyCompBadPartials(ExplicitComponent): +class MyCompBadPartials(om.ExplicitComponent): def setup(self): self.add_input('y1', 3.0) self.add_input('y2', 5.0) @@ -102,7 +100,7 @@ def compute_partials(self, inputs, partials): J['z', 'y2'] = np.array([40.0]) -class MyComp(ExplicitComponent): +class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -125,11 +123,10 @@ class TestProblemCheckPartials(unittest.TestCase): def test_incorrect_jacobian(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('x2', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('comp', MyComp()) prob.model.connect('p1.x1', 'comp.x1') @@ -137,7 +134,7 @@ def test_incorrect_jacobian(self): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() @@ -158,12 +155,12 @@ def test_incorrect_jacobian(self): def test_component_only(self): - prob = Problem() + prob = om.Problem() prob.model = MyComp() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() @@ -178,12 +175,12 @@ def test_component_only(self): def test_component_only_suppress(self): - prob = Problem() + prob = om.Problem() prob.model = MyComp() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() @@ -199,13 +196,13 @@ def test_component_only_suppress(self): self.assertEqual(len(lines), 0) def test_component_has_no_outputs(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem("indep", IndepVarComp('x', 5.)) - model.add_subsystem("comp1", ExecComp("y=2*x")) + model.add_subsystem("indep", om.IndepVarComp('x', 5.)) + model.add_subsystem("comp1", om.ExecComp("y=2*x")) - comp2 = model.add_subsystem("comp2", ExplicitComponent()) + comp2 = model.add_subsystem("comp2", om.ExplicitComponent()) comp2.add_input('x', val=0.) model.connect('indep.x', ['comp1.x', 'comp2.x']) @@ -230,7 +227,7 @@ def test_component_has_no_outputs(self): assert_rel_error(self, data['comp1'][('y', 'x')]['J_rev'][0][0], 2., 1e-15) def test_missing_entry(self): - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -250,10 +247,9 @@ def compute_partials(self, inputs, partials): J['y', 'x1'] = np.array([3.0]) self.lin_count += 1 - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p1', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('x2', 5.0)) + prob = om.Problem() + prob.model.add_subsystem('p1', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('comp', MyComp()) prob.model.connect('p1.x1', 'comp.x1') @@ -261,7 +257,7 @@ def compute_partials(self, inputs, partials): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -287,7 +283,7 @@ def compute_partials(self, inputs, partials): delta=1e-6) def test_nested_fd_units(self): - class UnitCompBase(ExplicitComponent): + class UnitCompBase(om.ExplicitComponent): def setup(self): self.add_input('T', val=284., units="degR", desc="Temperature") self.add_input('P', val=1., units='lbf/inch**2', desc="Pressure") @@ -302,9 +298,9 @@ def compute(self, inputs, outputs): outputs['flow:T'] = inputs['T'] outputs['flow:P'] = inputs['P'] - p = Problem() - model = p.model = Group() - indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*']) + p = om.Problem() + model = p.model + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes=['*']) indep.add_output('T', val=100., units='degK') indep.add_output('P', val=1., units='bar') @@ -323,7 +319,7 @@ def compute(self, inputs, outputs): self.assertAlmostEqual(np.linalg.norm(forward - fd), 0., delta=1e-6) def test_units(self): - class UnitCompBase(ExplicitComponent): + class UnitCompBase(om.ExplicitComponent): def setup(self): self.add_input('T', val=284., units="degR", desc="Temperature") self.add_input('P', val=1., units='lbf/inch**2', desc="Pressure") @@ -345,16 +341,16 @@ def compute(self, inputs, outputs): self.run_count += 1 - p = Problem() - model = p.model = Group() - indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*']) + p = om.Problem() + model = p.model + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes=['*']) indep.add_output('T', val=100., units='degK') indep.add_output('P', val=1., units='bar') units = model.add_subsystem('units', UnitCompBase(), promotes=['*']) - model.nonlinear_solver = NonlinearRunOnce() + model.nonlinear_solver = om.NonlinearRunOnce() p.setup() data = p.check_partials(out_stream=None) @@ -373,7 +369,7 @@ def compute(self, inputs, outputs): self.assertEqual(units.run_count, 5) def test_scalar_val(self): - class PassThrough(ExplicitComponent): + class PassThrough(om.ExplicitComponent): """ Helper component that is needed when variables must be passed directly from input to output @@ -411,9 +407,9 @@ def compute(self, inputs, outputs): def linearize(self, inputs, outputs, J): pass - p = Problem() + p = om.Problem() - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('foo', val=np.ones(4)) indeps.add_output('foo2', val=np.ones(4)) @@ -436,11 +432,10 @@ def linearize(self, inputs, outputs, J): assert_rel_error(self, data['pt2'][('bar2', 'foo2')]['J_fd'], identity, 1e-9) def test_matrix_free_explicit(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidMatVec()) prob.model.connect('p1.x', 'comp.x') @@ -448,7 +443,7 @@ def test_matrix_free_explicit(self): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -470,17 +465,16 @@ def test_matrix_free_explicit(self): assert_rel_error(self, data['comp'][('f_xy', 'y')]['J_rev'][0][0], 21.0, 1e-6) def test_matrix_free_implicit(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('rhs', np.ones((2, )))) + prob.model.add_subsystem('p1', om.IndepVarComp('rhs', np.ones((2, )))) prob.model.add_subsystem('comp', TestImplCompArrayMatVec()) prob.model.connect('p1.rhs', 'comp.rhs') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -500,7 +494,7 @@ def test_implicit_undeclared(self): # Test to see that check_partials works when state_wrt_input and state_wrt_state # partials are missing. - class ImplComp4Test(ImplicitComponent): + class ImplComp4Test(om.ImplicitComponent): def setup(self): self.add_input('x', np.ones(2)) @@ -521,11 +515,10 @@ def linearize(self, inputs, outputs, partials): partials['y', 'x'] = -np.eye(2) partials['y', 'y'] = self.mtx - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', np.ones((2, )))) - prob.model.add_subsystem('p2', IndepVarComp('dummy', np.ones((2, )))) + prob.model.add_subsystem('p1', om.IndepVarComp('x', np.ones((2, )))) + prob.model.add_subsystem('p2', om.IndepVarComp('dummy', np.ones((2, )))) prob.model.add_subsystem('comp', ImplComp4Test()) prob.model.connect('p1.x', 'comp.x') @@ -533,7 +526,7 @@ def linearize(self, inputs, outputs, partials): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -546,7 +539,7 @@ def linearize(self, inputs, outputs, partials): def test_dependent_false_hide(self): # Test that we omit derivs declared with dependent=False - class SimpleComp1(ExplicitComponent): + class SimpleComp1(om.ExplicitComponent): def setup(self): self.add_input('z', shape=(2, 2)) self.add_input('x', shape=(2, 2)) @@ -561,16 +554,15 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['g', 'x'] = 3. - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('z', np.ones((2, 2)))) - prob.model.add_subsystem('p2', IndepVarComp('x', np.ones((2, 2)))) + prob.model.add_subsystem('p1', om.IndepVarComp('z', np.ones((2, 2)))) + prob.model.add_subsystem('p2', om.IndepVarComp('x', np.ones((2, 2)))) prob.model.add_subsystem('comp', SimpleComp1()) prob.model.connect('p1.z', 'comp.z') prob.model.connect('p2.x', 'comp.x') - prob.setup(check=False) + prob.setup() stream = cStringIO() data = prob.check_partials(out_stream=stream) @@ -585,7 +577,7 @@ def test_dependent_false_compact_print_never_hide(self): # API Change: we no longer omit derivatives for compact_print, even when declared as not # dependent. - class SimpleComp1(ExplicitComponent): + class SimpleComp1(om.ExplicitComponent): def setup(self): self.add_input('z', shape=(2, 2)) self.add_input('x', shape=(2, 2)) @@ -600,16 +592,15 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['g', 'x'] = 3. - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('z', np.ones((2, 2)))) - prob.model.add_subsystem('p2', IndepVarComp('x', np.ones((2, 2)))) + prob.model.add_subsystem('p1', om.IndepVarComp('z', np.ones((2, 2)))) + prob.model.add_subsystem('p2', om.IndepVarComp('x', np.ones((2, 2)))) prob.model.add_subsystem('comp', SimpleComp1()) prob.model.connect('p1.z', 'comp.z') prob.model.connect('p2.x', 'comp.x') - prob.setup(check=False) + prob.setup() stream = cStringIO() data = prob.check_partials(out_stream=stream, compact_print=True) @@ -624,7 +615,7 @@ def test_dependent_false_show(self): # Test that we show derivs declared with dependent=False if the fd is not # ~zero. - class SimpleComp2(ExplicitComponent): + class SimpleComp2(om.ExplicitComponent): def setup(self): self.add_input('z', shape=(2, 2)) self.add_input('x', shape=(2, 2)) @@ -639,16 +630,15 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['g', 'x'] = 3. - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('z', np.ones((2, 2)))) - prob.model.add_subsystem('p2', IndepVarComp('x', np.ones((2, 2)))) + prob.model.add_subsystem('p1', om.IndepVarComp('z', np.ones((2, 2)))) + prob.model.add_subsystem('p2', om.IndepVarComp('x', np.ones((2, 2)))) prob.model.add_subsystem('comp', SimpleComp2()) prob.model.connect('p1.z', 'comp.z') prob.model.connect('p2.x', 'comp.x') - prob.setup(check=False) + prob.setup() stream = cStringIO() data = prob.check_partials(out_stream=stream) @@ -660,11 +650,10 @@ def compute_partials(self, inputs, partials): self.assertTrue(('g', 'x') in data['comp']) def test_set_step_on_comp(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -674,7 +663,7 @@ def test_set_step_on_comp(self): comp.set_check_partial_options(wrt='*', step=1e-2) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, compact_print=True) @@ -685,11 +674,10 @@ def test_set_step_on_comp(self): self.assertLess(x_error.reverse, 1e-5) def test_set_step_global(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -697,7 +685,7 @@ def test_set_step_global(self): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, step=1e-2) @@ -708,11 +696,10 @@ def test_set_step_global(self): self.assertLess(x_error.reverse, 1e-5) def test_complex_step_not_allocated(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidMatVec()) prob.model.connect('p1.x', 'comp.x') @@ -722,7 +709,7 @@ def test_complex_step_not_allocated(self): comp.set_check_partial_options(wrt='*', method='cs') - prob.setup(check=False) + prob.setup() prob.run_model() msg = "The following components requested complex step, but force_alloc_complex " + \ @@ -739,11 +726,10 @@ def test_complex_step_not_allocated(self): self.assertLess(x_error.reverse, 1e-5) def test_set_method_on_comp(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -763,11 +749,10 @@ def test_set_method_on_comp(self): self.assertLess(x_error.reverse, 1e-5) def test_set_method_global(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -785,11 +770,10 @@ def test_set_method_global(self): self.assertLess(x_error.reverse, 1e-5) def test_set_form_on_comp(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -799,7 +783,7 @@ def test_set_form_on_comp(self): comp.set_check_partial_options(wrt='*', form='central') - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, compact_print=True) @@ -810,11 +794,10 @@ def test_set_form_on_comp(self): self.assertLess(x_error.reverse, 1e-3) def test_set_form_global(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -822,7 +805,7 @@ def test_set_form_global(self): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, form='central') @@ -833,11 +816,10 @@ def test_set_form_global(self): self.assertLess(x_error.reverse, 1e-3) def test_set_step_calc_on_comp(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -847,7 +829,7 @@ def test_set_step_calc_on_comp(self): comp.set_check_partial_options(wrt='*', step_calc='rel') - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, compact_print=True) @@ -858,11 +840,10 @@ def test_set_step_calc_on_comp(self): self.assertLess(x_error.reverse, 3e-3) def test_set_step_calc_global(self): - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -870,7 +851,7 @@ def test_set_step_calc_global(self): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, step_calc='rel') @@ -883,7 +864,7 @@ def test_set_step_calc_global(self): def test_set_check_option_precedence(self): # Test that we omit derivs declared with dependent=False - class SimpleComp1(ExplicitComponent): + class SimpleComp1(om.ExplicitComponent): def setup(self): self.add_input('ab', 13.0) self.add_input('aba', 13.0) @@ -908,19 +889,18 @@ def compute_partials(self, inputs, partials): partials['y', 'aba'] = 3.0*aba**2 partials['y', 'ba'] = 3.0*ba**2 - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('ab', 13.0)) - prob.model.add_subsystem('p2', IndepVarComp('aba', 13.0)) - prob.model.add_subsystem('p3', IndepVarComp('ba', 13.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('ab', 13.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('aba', 13.0)) + prob.model.add_subsystem('p3', om.IndepVarComp('ba', 13.0)) comp = prob.model.add_subsystem('comp', SimpleComp1()) prob.model.connect('p1.ab', 'comp.ab') prob.model.connect('p2.aba', 'comp.aba') prob.model.connect('p3.ba', 'comp.ba') - prob.setup(check=False) + prob.setup() comp.set_check_partial_options(wrt='a*', step=1e-2) comp.set_check_partial_options(wrt='*a', step=1e-4) @@ -936,11 +916,10 @@ def compute_partials(self, inputs, partials): def test_option_printing(self): # Make sure we print the approximation type for each variable. - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -964,15 +943,14 @@ def test_option_printing(self): msg='Did you change the format for printing check derivs?') def test_set_check_partial_options_invalid(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky from openmdao.test_suite.components.paraboloid_mat_vec import ParaboloidMatVec - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.add_subsystem('comp2', ParaboloidMatVec()) @@ -1051,7 +1029,7 @@ def test_set_check_partial_options_invalid(self): "for check_partial options on Component 'comp': ['a', 'b', 'c'].") def test_compact_print_formatting(self): - class MyCompShortVarNames(ExplicitComponent): + class MyCompShortVarNames(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -1067,7 +1045,7 @@ def compute_partials(self, inputs, partials): J['y', 'x1'] = np.array([4.0]) J['y', 'x2'] = np.array([40]) - class MyCompLongVarNames(ExplicitComponent): + class MyCompLongVarNames(om.ExplicitComponent): def setup(self): self.add_input('really_long_variable_name_x1', 3.0) self.add_input('x2', 5.0) @@ -1085,15 +1063,14 @@ def compute_partials(self, inputs, partials): J['really_long_variable_name_y', 'x2'] = np.array([40]) # First short var names - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p1', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('x2', 5.0)) + prob = om.Problem() + prob.model.add_subsystem('p1', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('comp', MyCompShortVarNames()) prob.model.connect('p1.x1', 'comp.x1') prob.model.connect('p2.x2', 'comp.x2') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1111,15 +1088,14 @@ def compute_partials(self, inputs, partials): header_locations_of_bars = [i for i, ltr in enumerate(line) if ltr == sep] # Then long var names - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p1', IndepVarComp('really_long_variable_name_x1', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('x2', 5.0)) + prob = om.Problem() + prob.model.add_subsystem('p1', om.IndepVarComp('really_long_variable_name_x1', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('comp', MyCompLongVarNames()) prob.model.connect('p1.really_long_variable_name_x1', 'comp.really_long_variable_name_x1') prob.model.connect('p2.x2', 'comp.x2') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1138,20 +1114,20 @@ def compute_partials(self, inputs, partials): def test_compact_print_exceed_tol(self): - prob = Problem() + prob = om.Problem() prob.model = MyCompGoodPartials() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) self.assertEqual(stream.getvalue().count('>ABS_TOL'), 0) self.assertEqual(stream.getvalue().count('>REL_TOL'), 0) - prob = Problem() + prob = om.Problem() prob.model = MyCompBadPartials() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1161,8 +1137,8 @@ def test_compact_print_exceed_tol(self): def test_check_partials_display_rev(self): # 1: Check display of revs for implicit comp for compact and non-compact display - group = Group() - comp1 = group.add_subsystem('comp1', IndepVarComp()) + group = om.Group() + comp1 = group.add_subsystem('comp1', om.IndepVarComp()) comp1.add_output('a', 1.0) comp1.add_output('b', -4.0) comp1.add_output('c', 3.0) @@ -1174,8 +1150,8 @@ def test_check_partials_display_rev(self): group.connect('comp1.a', 'comp3.a') group.connect('comp1.b', 'comp3.b') group.connect('comp1.c', 'comp3.c') - prob = Problem(model=group) - prob.setup(check=False) + prob = om.Problem(model=group) + prob.setup() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1191,7 +1167,7 @@ def test_check_partials_display_rev(self): self.assertEqual(stream.getvalue().count('Jrev'), 20) # 2: Explicit comp, all comps define Jacobians for compact and non-compact display - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -1207,10 +1183,10 @@ def compute_partials(self, inputs, partials): J['z', 'x1'] = np.array([3.0]) J['z', 'x2'] = np.array([-4444.0]) - prob = Problem() + prob = om.Problem() prob.model = MyComp() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1229,15 +1205,14 @@ def compute_partials(self, inputs, partials): # 3: Explicit comp that does not define Jacobian. It defines compute_jacvec_product # For both compact and non-compact display - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob = om.Problem() + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidMatVec()) prob.model.connect('p1.x', 'comp.x') prob.model.connect('p2.y', 'comp.y') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1249,19 +1224,18 @@ def compute_partials(self, inputs, partials): self.assertEqual(stream.getvalue().count('Jrev'), 10) # 4: Mixed comps. Some with jacobians. Some not - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p0', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p1', IndepVarComp('x2', 5.0)) + prob = om.Problem() + prob.model.add_subsystem('p0', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('c0', MyComp()) # in x1,x2, out is z - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidMatVec()) prob.model.connect('p0.x1', 'c0.x1') prob.model.connect('p1.x2', 'c0.x2') prob.model.connect('c0.z', 'comp.x') prob.model.connect('p2.y', 'comp.y') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() @@ -1283,10 +1257,10 @@ def compute_partials(self, inputs, partials): # 5: One comp defines compute_multi_jacvec_product size = 6 - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', val=(np.arange(size, dtype=float) + 1.) * 3.0)) - model.add_subsystem('py', IndepVarComp('y', val=(np.arange(size, dtype=float) + 1.) * 2.0)) + model.add_subsystem('px', om.IndepVarComp('x', val=(np.arange(size, dtype=float) + 1.) * 3.0)) + model.add_subsystem('py', om.IndepVarComp('y', val=(np.arange(size, dtype=float) + 1.) * 2.0)) model.add_subsystem('comp', MultiJacVec(size)) model.connect('px.x', 'comp.x') @@ -1296,7 +1270,7 @@ def compute_partials(self, inputs, partials): model.add_design_var('py.y', vectorize_derivs=False) model.add_constraint('comp.f_xy', vectorize_derivs=False) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() prob.check_partials(out_stream=stream, compact_print=True) @@ -1309,11 +1283,10 @@ def test_check_partials_worst_subjac(self): # repeat the full row for the worst-case subjac (i.e., output-input pair). # This should only occur in the compact_print=True case. - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p0', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p1', IndepVarComp('x2', 5.0)) - prob.model.add_subsystem('p2', IndepVarComp('y2', 6.0)) + prob = om.Problem() + prob.model.add_subsystem('p0', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x2', 5.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y2', 6.0)) prob.model.add_subsystem('good', MyCompGoodPartials()) prob.model.add_subsystem('bad', MyCompBadPartials()) prob.model.connect('p0.x1', 'good.x1') @@ -1321,7 +1294,7 @@ def test_check_partials_worst_subjac(self): prob.model.connect('good.y', 'bad.y1') prob.model.connect('p2.y2', 'bad.y2') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() @@ -1335,11 +1308,10 @@ def test_check_partials_show_only_incorrect(self): # it should print only the subjacs found to be incorrect. This applies # to both compact_print=True and False. - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p0', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p1', IndepVarComp('x2', 5.0)) - prob.model.add_subsystem('p2', IndepVarComp('y2', 6.0)) + prob = om.Problem() + prob.model.add_subsystem('p0', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x2', 5.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y2', 6.0)) prob.model.add_subsystem('good', MyCompGoodPartials()) prob.model.add_subsystem('bad', MyCompBadPartials()) prob.model.connect('p0.x1', 'good.x1') @@ -1347,7 +1319,7 @@ def test_check_partials_show_only_incorrect(self): prob.model.connect('good.y', 'bad.y1') prob.model.connect('p2.y2', 'bad.y2') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() stream = cStringIO() @@ -1365,19 +1337,19 @@ def test_check_partials_show_only_incorrect(self): def test_includes_excludes(self): - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('c1c', Group()) - sub.add_subsystem('d1', ExecComp('y=2*x')) - sub.add_subsystem('e1', ExecComp('y=2*x')) + sub = model.add_subsystem('c1c', om.Group()) + sub.add_subsystem('d1', om.ExecComp('y=2*x')) + sub.add_subsystem('e1', om.ExecComp('y=2*x')) - sub2 = model.add_subsystem('sss', Group()) - sub3 = sub2.add_subsystem('sss2', Group()) - sub2.add_subsystem('d1', ExecComp('y=2*x')) - sub3.add_subsystem('e1', ExecComp('y=2*x')) + sub2 = model.add_subsystem('sss', om.Group()) + sub3 = sub2.add_subsystem('sss2', om.Group()) + sub2.add_subsystem('d1', om.ExecComp('y=2*x')) + sub3.add_subsystem('e1', om.ExecComp('y=2*x')) - model.add_subsystem('abc1cab', ExecComp('y=2*x')) + model.add_subsystem('abc1cab', om.ExecComp('y=2*x')) prob.setup() prob.run_model() @@ -1406,11 +1378,11 @@ def test_includes_excludes(self): def test_directional_derivative_option(self): - prob = Problem() + prob = om.Problem() model = prob.model mycomp = model.add_subsystem('mycomp', ArrayComp(), promotes=['*']) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -1439,7 +1411,7 @@ def setup(self): super(ArrayCompCS, self).setup() self.set_check_partial_options('x*', directional=True, method='cs') - prob = Problem() + prob = om.Problem() model = prob.model mycomp = model.add_subsystem('mycomp', ArrayCompCS(), promotes=['*']) @@ -1462,7 +1434,7 @@ def setup(self): def test_bug_local_method(self): # This fixes a bug setting the check method on a component overrode the requested method for # subsequent components. - prob = Problem() + prob = om.Problem() model = prob.model model.add_subsystem('comp1', Paraboloid()) @@ -1489,7 +1461,7 @@ def test_rel_error_fd_zero(self): # When the fd turns out to be zero, test that we switch the definition of relative # to divide by the forward derivative instead of reporting NaN. - class SimpleComp2(ExplicitComponent): + class SimpleComp2(om.ExplicitComponent): def setup(self): self.add_input('x', val=3.0) self.add_output('y', val=4.0) @@ -1503,14 +1475,13 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['y', 'x'] = 3.0 - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.5)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.5)) prob.model.add_subsystem('comp', SimpleComp2()) prob.model.connect('p1.x', 'comp.x') - prob.setup(check=False) + prob.setup() stream = cStringIO() data = prob.check_partials(out_stream=stream) @@ -1524,9 +1495,9 @@ class TestCheckPartialsFeature(unittest.TestCase): def test_feature_incorrect_jacobian(self): import numpy as np - from openmdao.api import Group, ExplicitComponent, IndepVarComp, Problem + import openmdao.api as om - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -1544,11 +1515,10 @@ def compute_partials(self, inputs, partials): J['y', 'x1'] = np.array([4.0]) J['y', 'x2'] = np.array([40]) - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('x2', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('comp', MyComp()) prob.model.connect('p1.x1', 'comp.x1') @@ -1556,7 +1526,7 @@ def compute_partials(self, inputs, partials): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials() @@ -1574,9 +1544,9 @@ def compute_partials(self, inputs, partials): def test_feature_check_partials_suppress(self): import numpy as np - from openmdao.api import Group, ExplicitComponent, IndepVarComp, Problem + import openmdao.api as om - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -1594,11 +1564,10 @@ def compute_partials(self, inputs, partials): J['y', 'x1'] = np.array([4.0]) J['y', 'x2'] = np.array([40]) - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('x2', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('x2', 5.0)) prob.model.add_subsystem('comp', MyComp()) prob.model.connect('p1.x1', 'comp.x1') @@ -1606,22 +1575,21 @@ def compute_partials(self, inputs, partials): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None, compact_print=True) print(data) def test_set_step_on_comp(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky from openmdao.test_suite.components.paraboloid_mat_vec import ParaboloidMatVec - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.add_subsystem('comp2', ParaboloidMatVec()) @@ -1639,15 +1607,14 @@ def test_set_step_on_comp(self): prob.check_partials(compact_print=True) def test_set_step_global(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky from openmdao.test_suite.components.paraboloid_mat_vec import ParaboloidMatVec - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.add_subsystem('comp2', ParaboloidMatVec()) @@ -1663,15 +1630,14 @@ def test_set_step_global(self): prob.check_partials(step=1e-2, compact_print=True) def test_set_method_on_comp(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky from openmdao.test_suite.components.paraboloid_mat_vec import ParaboloidMatVec - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) comp = prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.add_subsystem('comp2', ParaboloidMatVec()) @@ -1689,15 +1655,14 @@ def test_set_method_on_comp(self): prob.check_partials(compact_print=True) def test_set_method_global(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky from openmdao.test_suite.components.paraboloid_mat_vec import ParaboloidMatVec - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.add_subsystem('comp2', ParaboloidMatVec()) @@ -1713,15 +1678,14 @@ def test_set_method_global(self): prob.check_partials(method='cs', compact_print=True) def test_set_form_global(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky from openmdao.test_suite.components.paraboloid_mat_vec import ParaboloidMatVec - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.add_subsystem('comp2', ParaboloidMatVec()) @@ -1737,14 +1701,13 @@ def test_set_form_global(self): prob.check_partials(form='central', compact_print=True) def test_set_step_calc_global(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_check_derivs import ParaboloidTricky - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('p1', IndepVarComp('x', 3.0)) - prob.model.add_subsystem('p2', IndepVarComp('y', 5.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y', 5.0)) prob.model.add_subsystem('comp', ParaboloidTricky()) prob.model.connect('p1.x', 'comp.x') @@ -1759,9 +1722,9 @@ def test_set_step_calc_global(self): def test_feature_check_partials_show_only_incorrect(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + import openmdao.api as om - class MyCompGoodPartials(ExplicitComponent): + class MyCompGoodPartials(om.ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) @@ -1777,7 +1740,7 @@ def compute_partials(self, inputs, partials): J['y', 'x1'] = np.array([3.0]) J['y', 'x2'] = np.array([4.0]) - class MyCompBadPartials(ExplicitComponent): + class MyCompBadPartials(om.ExplicitComponent): def setup(self): self.add_input('y1', 3.0) self.add_input('y2', 5.0) @@ -1793,11 +1756,10 @@ def compute_partials(self, inputs, partials): J['z', 'y1'] = np.array([33.0]) J['z', 'y2'] = np.array([40.0]) - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('p0', IndepVarComp('x1', 3.0)) - prob.model.add_subsystem('p1', IndepVarComp('x2', 5.0)) - prob.model.add_subsystem('p2', IndepVarComp('y2', 6.0)) + prob = om.Problem() + prob.model.add_subsystem('p0', om.IndepVarComp('x1', 3.0)) + prob.model.add_subsystem('p1', om.IndepVarComp('x2', 5.0)) + prob.model.add_subsystem('p2', om.IndepVarComp('y2', 6.0)) prob.model.add_subsystem('good', MyCompGoodPartials()) prob.model.add_subsystem('bad', MyCompBadPartials()) prob.model.connect('p0.x1', 'good.x1') @@ -1805,28 +1767,28 @@ def compute_partials(self, inputs, partials): prob.model.connect('good.y', 'bad.y1') prob.model.connect('p2.y2', 'bad.y2') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() prob.check_partials(compact_print=True, show_only_incorrect=True) prob.check_partials(compact_print=False, show_only_incorrect=True) def test_includes_excludes(self): - from openmdao.api import Problem, Group, ExecComp + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('c1c', Group()) - sub.add_subsystem('d1', ExecComp('y=2*x')) - sub.add_subsystem('e1', ExecComp('y=2*x')) + sub = model.add_subsystem('c1c', om.Group()) + sub.add_subsystem('d1', om.ExecComp('y=2*x')) + sub.add_subsystem('e1', om.ExecComp('y=2*x')) - sub2 = model.add_subsystem('sss', Group()) - sub3 = sub2.add_subsystem('sss2', Group()) - sub2.add_subsystem('d1', ExecComp('y=2*x')) - sub3.add_subsystem('e1', ExecComp('y=2*x')) + sub2 = model.add_subsystem('sss', om.Group()) + sub3 = sub2.add_subsystem('sss2', om.Group()) + sub2.add_subsystem('d1', om.ExecComp('y=2*x')) + sub3.add_subsystem('e1', om.ExecComp('y=2*x')) - model.add_subsystem('abc1cab', ExecComp('y=2*x')) + model.add_subsystem('abc1cab', om.ExecComp('y=2*x')) prob.setup() prob.run_model() @@ -1840,14 +1802,14 @@ def test_includes_excludes(self): prob.check_partials(compact_print=True, includes='*c*c*', excludes=['*e*']) def test_directional(self): - from openmdao.api import Problem + import openmdao.api as om from openmdao.test_suite.components.array_comp import ArrayComp - prob = Problem() + prob = om.Problem() model = prob.model mycomp = model.add_subsystem('mycomp', ArrayComp(), promotes=['*']) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials() @@ -1856,9 +1818,9 @@ def test_directional(self): class TestProblemCheckTotals(unittest.TestCase): def test_cs(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -1890,9 +1852,9 @@ def test_cs(self): assert_rel_error(self, totals['con_cmp2.con2', 'px.x']['J_fd'], [[0.09692762]], 1e-5) def test_desvar_as_obj(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_objective('x') @@ -1921,7 +1883,7 @@ def test_desvar_as_obj(self): def test_desvar_and_response_with_indices(self): - class ArrayComp2D(ExplicitComponent): + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component. """ @@ -1953,9 +1915,9 @@ def compute_partials(self, inputs, partials): """ partials[('y1', 'x1')] = self.JJ - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) @@ -1986,9 +1948,9 @@ def compute_partials(self, inputs, partials): # Objective instead - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) @@ -2014,9 +1976,9 @@ def compute_partials(self, inputs, partials): assert_rel_error(self, jac[0][1], Jbase[1, 3], 1e-8) def test_cs_suppress(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -2042,9 +2004,9 @@ def test_cs_suppress(self): self.assertTrue('magnitude' in data) def test_two_desvar_as_con(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('z', lower=-100, upper=100) prob.model.add_design_var('x', lower=-100, upper=100) @@ -2053,7 +2015,7 @@ def test_two_desvar_as_con(self): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # We don't call run_driver() here because we don't # actually want the optimizer to run @@ -2071,16 +2033,16 @@ def test_two_desvar_as_con(self): assert_rel_error(self, totals['pz.z', 'px.x']['J_fd'], [[0.0], [0.0]], 1e-5) def test_full_con_with_index_desvar(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('z', lower=-100, upper=100, indices=[1]) prob.model.add_constraint('z', upper=0.0) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # We don't call run_driver() here because we don't # actually want the optimizer to run @@ -2092,16 +2054,16 @@ def test_full_con_with_index_desvar(self): assert_rel_error(self, totals['pz.z', 'pz.z']['J_fd'], [[0.0], [1.0]], 1e-5) def test_full_desvar_with_index_con(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('z', lower=-100, upper=100) prob.model.add_constraint('z', upper=0.0, indices=[1]) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # We don't call run_driver() here because we don't # actually want the optimizer to run @@ -2113,16 +2075,16 @@ def test_full_desvar_with_index_con(self): assert_rel_error(self, totals['pz.z', 'pz.z']['J_fd'], [[0.0, 1.0]], 1e-5) def test_full_desvar_with_index_obj(self): - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('z', lower=-100, upper=100) prob.model.add_objective('z', index=1) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # We don't call run_driver() here because we don't # actually want the optimizer to run @@ -2136,7 +2098,7 @@ def test_full_desvar_with_index_obj(self): def test_bug_fd_with_sparse(self): # This bug was found via the x57 model in pointer. - class TimeComp(ExplicitComponent): + class TimeComp(om.ExplicitComponent): def setup(self): self.node_ptau = node_ptau = np.array([-1., 0., 1.]) @@ -2162,7 +2124,7 @@ def compute_partials(self, inputs, jacobian): jacobian['time', 't_duration'] = 0.5 * (node_ptau + 33) - class CellComp(ExplicitComponent): + class CellComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_nodes', types=int) @@ -2184,12 +2146,12 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['zSOC', 'I_Li'] = -1./(3600.0) - class GaussLobattoPhase(Group): + class GaussLobattoPhase(om.Group): def setup(self): self.connect('t_duration', 'time.t_duration') - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('t_duration', val=1.0) self.add_subsystem('time_extents', indep, promotes_outputs=['*']) self.add_design_var('t_duration', 5.0, 25.0) @@ -2199,18 +2161,18 @@ def setup(self): self.add_subsystem(name='cell', subsys=CellComp(num_nodes=3)) - self.linear_solver = ScipyKrylov() - self.nonlinear_solver = NewtonSolver() + self.linear_solver = om.ScipyKrylov() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['maxiter'] = 1 def initialize(self): self.options.declare('ode_class', desc='System defining the ODE.') - p = Problem(model=GaussLobattoPhase()) + p = om.Problem(model=GaussLobattoPhase()) p.model.add_objective('time', index=-1) - p.model.linear_solver = ScipyKrylov(assemble_jac=True) + p.model.linear_solver = om.ScipyKrylov(assemble_jac=True) p.setup(mode='fwd') p.set_solver_print(level=0) @@ -2224,12 +2186,12 @@ def initialize(self): # Try again with a direct solver and sparse assembled hierarchy. - p = Problem() + p = om.Problem() p.model.add_subsystem('sub', GaussLobattoPhase()) p.model.sub.add_objective('time', index=-1) - p.model.linear_solver = DirectSolver(assemble_jac=True) + p.model.linear_solver = om.DirectSolver(assemble_jac=True) p.setup(mode='fwd') p.set_solver_print(level=0) @@ -2243,10 +2205,10 @@ def initialize(self): def test_vector_scaled_derivs(self): - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) + model.add_subsystem('px', om.IndepVarComp(name="x", val=np.ones((2, )))) comp = model.add_subsystem('comp', DoubleArrayComp()) model.connect('px.x', 'comp.x1') @@ -2255,7 +2217,7 @@ def test_vector_scaled_derivs(self): model.add_constraint('comp.y2', lower=0.0, upper=1.0, ref=np.array([[2.0, 4.0]]), ref0=np.array([1.2, 2.3])) - prob.setup(check=False) + prob.setup() prob.run_driver() # First, test that we get scaled results in compute and check totals. @@ -2295,28 +2257,28 @@ def test_vector_scaled_derivs(self): def test_cs_around_newton(self): # Basic sellar test. - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('sub', Group(), promotes=['*']) + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = NewtonSolver() - sub.linear_solver = DirectSolver(assemble_jac=False) + sub.nonlinear_solver = om.NewtonSolver() + sub.linear_solver = om.DirectSolver(assemble_jac=False) # Need this. - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -2337,28 +2299,28 @@ def test_cs_around_newton(self): def test_cs_around_broyden(self): # Basic sellar test. - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('sub', Group(), promotes=['*']) + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = BroydenSolver() - sub.linear_solver = DirectSolver() + sub.nonlinear_solver = om.BroydenSolver() + sub.linear_solver = om.DirectSolver() # Need this. - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -2377,11 +2339,11 @@ def test_cs_around_broyden(self): assert_rel_error(self, val['rel error'][0], 0.0, 1e-6) def test_cs_error_allocate(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p', IndepVarComp('x', 3.0), promotes=['*']) + model.add_subsystem('p', om.IndepVarComp('x', 3.0), promotes=['*']) model.add_subsystem('comp', ParaboloidTricky(), promotes=['*']) - prob.setup(check=False) + prob.setup() prob.run_model() with self.assertRaises(RuntimeError) as cm: @@ -2399,7 +2361,7 @@ class TestProblemCheckTotalsMPI(unittest.TestCase): def test_indepvarcomp_under_par_sys(self): - prob = Problem() + prob = om.Problem() prob.model = FanInSubbedIDVC() prob.setup(check=False, mode='rev') diff --git a/openmdao/core/tests/test_coloring.py b/openmdao/core/tests/test_coloring.py index 7e24b43465..47a679ff42 100644 --- a/openmdao/core/tests/test_coloring.py +++ b/openmdao/core/tests/test_coloring.py @@ -19,9 +19,7 @@ except ImportError: load_npz = None -from openmdao.api import Problem, IndepVarComp, ExecComp, DirectSolver,\ - ExplicitComponent, LinearRunOnce, ScipyOptimizeDriver, ParallelGroup, Group, \ - SqliteRecorder, CaseReader +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_warning from openmdao.utils.general_utils import set_pyoptsparse_opt from openmdao.utils.coloring import Coloring, _compute_coloring, array_viz @@ -43,7 +41,7 @@ from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver -class CounterGroup(Group): +class CounterGroup(om.Group): def __init__(self, *args, **kwargs): self._solve_count = 0 self._solve_nl_count = 0 @@ -67,7 +65,7 @@ def _apply_nonlinear(self, *args, **kwargs): SIZE = 10 -class DynPartialsComp(ExplicitComponent): +class DynPartialsComp(om.ExplicitComponent): def __init__(self, size): super(DynPartialsComp, self).__init__() self.size = size @@ -92,13 +90,13 @@ def run_opt(driver_class, mode, assemble_type=None, color_info=None, sparsity=No recorder=None, has_lin_constraint=True, vectorize=True, partial_coloring=False, **options): - p = Problem(model=CounterGroup()) + p = om.Problem(model=CounterGroup()) if assemble_type is not None: - p.model.linear_solver = DirectSolver(assemble_jac=True) + p.model.linear_solver = om.DirectSolver(assemble_jac=True) p.model.options['assembled_jac_type'] = assemble_type - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['*']) + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*']) # the following were randomly generated using np.random.random(10)*2-1 to randomly # disperse them within a unit circle centered at the origin. @@ -111,25 +109,25 @@ def run_opt(driver_class, mode, assemble_type=None, color_info=None, sparsity=No if partial_coloring: arctan_yox = DynPartialsComp(SIZE) else: - arctan_yox = ExecComp('g=arctan(y/x)', vectorize=vectorize, - g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE)) + arctan_yox = om.ExecComp('g=arctan(y/x)', vectorize=vectorize, + g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE)) p.model.add_subsystem('arctan_yox', arctan_yox) - p.model.add_subsystem('circle', ExecComp('area=pi*r**2')) + p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2')) - p.model.add_subsystem('r_con', ExecComp('g=x**2 + y**2 - r', vectorize=vectorize, - g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) + p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=vectorize, + g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) thetas = np.linspace(0, np.pi/4, SIZE) - p.model.add_subsystem('theta_con', ExecComp('g = x - theta', vectorize=vectorize, - g=np.ones(SIZE), x=np.ones(SIZE), - theta=thetas)) - p.model.add_subsystem('delta_theta_con', ExecComp('g = even - odd', vectorize=vectorize, - g=np.ones(SIZE//2), even=np.ones(SIZE//2), - odd=np.ones(SIZE//2))) + p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', vectorize=vectorize, + g=np.ones(SIZE), x=np.ones(SIZE), + theta=thetas)) + p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', vectorize=vectorize, + g=np.ones(SIZE//2), even=np.ones(SIZE//2), + odd=np.ones(SIZE//2))) - p.model.add_subsystem('l_conx', ExecComp('g=x-1', vectorize=vectorize, g=np.ones(SIZE), x=np.ones(SIZE))) + p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', vectorize=vectorize, g=np.ones(SIZE), x=np.ones(SIZE))) IND = np.arange(SIZE, dtype=int) ODD_IND = IND[1::2] # all odd indices @@ -351,12 +349,12 @@ class SimulColoringRecordingTestCase(unittest.TestCase): def test_recording(self): # coloring involves an underlying call to run_model (and final_setup), # this verifies that it is handled properly by the recording setup logic - recorder = SqliteRecorder('cases.sql') + recorder = om.SqliteRecorder('cases.sql') p = run_opt(pyOptSparseDriver, 'auto', assemble_type='csc', optimizer='SNOPT', dynamic_total_coloring=True, print_results=False, recorder=recorder) - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') self.assertEqual(cr.list_cases(), ['rank0:pyOptSparse_SNOPT|%d' % i for i in range(p.driver.iter_count)]) @@ -425,19 +423,19 @@ def test_dynamic_rev_simul_coloring_pyoptsparse_slsqp(self): class SimulColoringScipyTestCase(unittest.TestCase): def test_bad_mode(self): - p_color_fwd = run_opt(ScipyOptimizeDriver, 'fwd', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) + p_color_fwd = run_opt(om.ScipyOptimizeDriver, 'fwd', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) coloring = p_color_fwd.driver._coloring_info['coloring'] with self.assertRaises(Exception) as context: - p_color = run_opt(ScipyOptimizeDriver, 'rev', color_info=coloring, optimizer='SLSQP', disp=False) + p_color = run_opt(om.ScipyOptimizeDriver, 'rev', color_info=coloring, optimizer='SLSQP', disp=False) self.assertEqual(str(context.exception), "Simultaneous coloring does forward solves but mode has been set to 'rev'") def test_dynamic_total_coloring_auto(self): # first, run w/o coloring - p = run_opt(ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False) - p_color = run_opt(ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) + p = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False) + p_color = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) assert_almost_equal(p['circle.area'], np.pi, decimal=7) assert_almost_equal(p_color['circle.area'], np.pi, decimal=7) @@ -452,14 +450,14 @@ def test_dynamic_total_coloring_auto(self): def test_simul_coloring_example(self): - from openmdao.api import Problem, IndepVarComp, ExecComp, ScipyOptimizeDriver import numpy as np + import openmdao.api as om SIZE = 10 - p = Problem() + p = om.Problem() - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['*']) + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*']) # the following were randomly generated using np.random.random(10)*2-1 to randomly # disperse them within a unit circle centered at the origin. @@ -469,23 +467,23 @@ def test_simul_coloring_example(self): -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582])) indeps.add_output('r', .7) - p.model.add_subsystem('arctan_yox', ExecComp('g=arctan(y/x)', vectorize=True, - g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) + p.model.add_subsystem('arctan_yox', om.ExecComp('g=arctan(y/x)', vectorize=True, + g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) - p.model.add_subsystem('circle', ExecComp('area=pi*r**2')) + p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2')) - p.model.add_subsystem('r_con', ExecComp('g=x**2 + y**2 - r', vectorize=True, - g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) + p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=True, + g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) thetas = np.linspace(0, np.pi/4, SIZE) - p.model.add_subsystem('theta_con', ExecComp('g = x - theta', vectorize=True, - g=np.ones(SIZE), x=np.ones(SIZE), - theta=thetas)) - p.model.add_subsystem('delta_theta_con', ExecComp('g = even - odd', vectorize=True, - g=np.ones(SIZE//2), even=np.ones(SIZE//2), - odd=np.ones(SIZE//2))) + p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', vectorize=True, + g=np.ones(SIZE), x=np.ones(SIZE), + theta=thetas)) + p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', vectorize=True, + g=np.ones(SIZE//2), even=np.ones(SIZE//2), + odd=np.ones(SIZE//2))) - p.model.add_subsystem('l_conx', ExecComp('g=x-1', vectorize=True, g=np.ones(SIZE), x=np.ones(SIZE))) + p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', vectorize=True, g=np.ones(SIZE), x=np.ones(SIZE))) IND = np.arange(SIZE, dtype=int) ODD_IND = IND[1::2] # all odd indices @@ -498,7 +496,7 @@ def test_simul_coloring_example(self): p.model.connect('arctan_yox.g', 'delta_theta_con.even', src_indices=EVEN_IND) p.model.connect('arctan_yox.g', 'delta_theta_con.odd', src_indices=ODD_IND) - p.driver = ScipyOptimizeDriver() + p.driver = om.ScipyOptimizeDriver() p.driver.options['optimizer'] = 'SLSQP' p.driver.options['disp'] = False @@ -531,10 +529,9 @@ def test_simul_coloring_example(self): def test_total_and_partial_coloring_example(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp, ExplicitComponent, ScipyOptimizeDriver + import openmdao.api as om - - class DynamicPartialsComp(ExplicitComponent): + class DynamicPartialsComp(om.ExplicitComponent): def __init__(self, size): super(DynamicPartialsComp, self).__init__() self.size = size @@ -558,9 +555,9 @@ def compute(self, inputs, outputs): SIZE = 10 - p = Problem() + p = om.Problem() - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['*']) + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*']) # the following were randomly generated using np.random.random(10)*2-1 to randomly # disperse them within a unit circle centered at the origin. @@ -575,20 +572,20 @@ def compute(self, inputs, outputs): arctan_yox = p.model.add_subsystem('arctan_yox', DynamicPartialsComp(SIZE)) ######################################################################## - p.model.add_subsystem('circle', ExecComp('area=pi*r**2')) + p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2')) - p.model.add_subsystem('r_con', ExecComp('g=x**2 + y**2 - r', vectorize=True, - g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) + p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=True, + g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) thetas = np.linspace(0, np.pi/4, SIZE) - p.model.add_subsystem('theta_con', ExecComp('g = x - theta', vectorize=True, - g=np.ones(SIZE), x=np.ones(SIZE), - theta=thetas)) - p.model.add_subsystem('delta_theta_con', ExecComp('g = even - odd', vectorize=True, - g=np.ones(SIZE//2), even=np.ones(SIZE//2), - odd=np.ones(SIZE//2))) + p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', vectorize=True, + g=np.ones(SIZE), x=np.ones(SIZE), + theta=thetas)) + p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', vectorize=True, + g=np.ones(SIZE//2), even=np.ones(SIZE//2), + odd=np.ones(SIZE//2))) - p.model.add_subsystem('l_conx', ExecComp('g=x-1', vectorize=True, g=np.ones(SIZE), x=np.ones(SIZE))) + p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', vectorize=True, g=np.ones(SIZE), x=np.ones(SIZE))) IND = np.arange(SIZE, dtype=int) ODD_IND = IND[1::2] # all odd indices @@ -601,7 +598,7 @@ def compute(self, inputs, outputs): p.model.connect('arctan_yox.g', 'delta_theta_con.even', src_indices=EVEN_IND) p.model.connect('arctan_yox.g', 'delta_theta_con.odd', src_indices=ODD_IND) - p.driver = ScipyOptimizeDriver() + p.driver = om.ScipyOptimizeDriver() p.driver.options['optimizer'] = 'SLSQP' p.driver.options['disp'] = False @@ -650,7 +647,7 @@ class SimulColoringRevScipyTestCase(unittest.TestCase): """Rev mode coloring tests.""" def test_summary(self): - p_color = run_opt(ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) + p_color = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) coloring = p_color.driver._coloring_info['coloring'] save_out = sys.stdout sys.stdout = StringIO() @@ -682,7 +679,7 @@ def test_summary(self): self.assertTrue('Time to compute coloring:' in summary) def test_repr(self): - p_color = run_opt(ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) + p_color = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) coloring = p_color.driver._coloring_info['coloring'] rep = repr(coloring) self.assertEqual(rep.replace('L', ''), 'Coloring (direction: fwd, ncolors: 5, shape: (22, 21)') @@ -693,18 +690,18 @@ def test_repr(self): self.assertEqual(rep.replace('L', ''), 'Coloring (direction: rev, ncolors: 50, shape: (50, 50)') def test_bad_mode(self): - p_color_rev = run_opt(ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) + p_color_rev = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) coloring = p_color_rev.driver._coloring_info['coloring'] with self.assertRaises(Exception) as context: - p_color = run_opt(ScipyOptimizeDriver, 'fwd', color_info=coloring, optimizer='SLSQP', disp=False) + p_color = run_opt(om.ScipyOptimizeDriver, 'fwd', color_info=coloring, optimizer='SLSQP', disp=False) self.assertEqual(str(context.exception), "Simultaneous coloring does reverse solves but mode has been set to 'fwd'") def test_dynamic_total_coloring(self): - p_color = run_opt(ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) - p = run_opt(ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False) + p_color = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True) + p = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False) assert_almost_equal(p['circle.area'], np.pi, decimal=7) assert_almost_equal(p_color['circle.area'], np.pi, decimal=7) @@ -719,7 +716,7 @@ def test_dynamic_total_coloring(self): def test_dynamic_total_coloring_no_derivs(self): with self.assertRaises(Exception) as context: - p_color = run_opt(ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, + p_color = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True, derivs=False) self.assertEqual(str(context.exception), "Derivative support has been turned off but compute_totals was called.") @@ -886,7 +883,7 @@ def test_multipoint_with_coloring(self): np.random.seed(11) - p = Problem() + p = om.Problem() p.driver = pyOptSparseDriver() p.driver.options['optimizer'] = OPTIMIZER p.driver.declare_coloring() @@ -898,26 +895,26 @@ def test_multipoint_with_coloring(self): model = p.model for i in range(num_pts): - model.add_subsystem('indep%d' % i, IndepVarComp('x', val=np.ones(size))) + model.add_subsystem('indep%d' % i, om.IndepVarComp('x', val=np.ones(size))) model.add_design_var('indep%d.x' % i) - par1 = model.add_subsystem('par1', ParallelGroup()) + par1 = model.add_subsystem('par1', om.ParallelGroup()) for i in range(num_pts): mat = _get_mat(5, size) - par1.add_subsystem('comp%d' % i, ExecComp('y=A.dot(x)', A=mat, x=np.ones(size), y=np.ones(5))) + par1.add_subsystem('comp%d' % i, om.ExecComp('y=A.dot(x)', A=mat, x=np.ones(size), y=np.ones(5))) model.connect('indep%d.x' % i, 'par1.comp%d.x' % i) - par2 = model.add_subsystem('par2', ParallelGroup()) + par2 = model.add_subsystem('par2', om.ParallelGroup()) for i in range(num_pts): mat = _get_mat(size, 5) - par2.add_subsystem('comp%d' % i, ExecComp('y=A.dot(x)', A=mat, x=np.ones(5), y=np.ones(size))) + par2.add_subsystem('comp%d' % i, om.ExecComp('y=A.dot(x)', A=mat, x=np.ones(5), y=np.ones(size))) model.connect('par1.comp%d.y' % i, 'par2.comp%d.x' % i) par2.add_constraint('comp%d.y' % i, lower=-1.) - model.add_subsystem('normcomp%d' % i, ExecComp("y=sum(x*x)", x=np.ones(size))) + model.add_subsystem('normcomp%d' % i, om.ExecComp("y=sum(x*x)", x=np.ones(size))) model.connect('par2.comp%d.y' % i, 'normcomp%d.x' % i) - model.add_subsystem('obj', ExecComp("y=" + '+'.join(['x%d' % i for i in range(num_pts)]))) + model.add_subsystem('obj', om.ExecComp("y=" + '+'.join(['x%d' % i for i in range(num_pts)]))) for i in range(num_pts): model.connect('normcomp%d.y' % i, 'obj.x%d' % i) diff --git a/openmdao/core/tests/test_component.py b/openmdao/core/tests/test_component.py index 96d95d17ee..ccf0f2cc77 100644 --- a/openmdao/core/tests/test_component.py +++ b/openmdao/core/tests/test_component.py @@ -21,7 +21,7 @@ class TestExplicitComponent(unittest.TestCase): def test___init___simple(self): """Test a simple explicit component.""" comp = TestExplCompSimple() - prob = Problem(comp).setup(check=False) + prob = Problem(comp).setup() # check optional metadata (desc) self.assertEqual( @@ -42,7 +42,7 @@ def test___init___simple(self): def test___init___array(self): """Test an explicit component with array inputs/outputs.""" comp = TestExplCompArray(thickness=1.) - prob = Problem(comp).setup(check=False) + prob = Problem(comp).setup() prob['lengths'] = 3. prob['widths'] = 2. @@ -205,15 +205,15 @@ def setup(self): self.add_output('y', val=0.0) prob = Problem() - model = prob.model = Group() + model = prob.model comp = model.add_subsystem('comp', MyComp()) - prob.setup(check=False) + prob.setup() self.assertEqual(comp._var_abs_names['input'], ['comp.x']) self.assertEqual(comp._var_abs_names['output'], ['comp.y']) prob.run_model() - prob.setup(check=False) + prob.setup() self.assertEqual(comp._var_abs_names['input'], ['comp.x']) self.assertEqual(comp._var_abs_names['output'], ['comp.y']) @@ -226,7 +226,7 @@ def setup(self): self.add_output('y', val=3.0) prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) @@ -234,7 +234,7 @@ def setup(self): msg = "Variable name 'x' already exists." with assertRaisesRegex(self, ValueError, msg): - prob.setup(check=False) + prob.setup() class Comp(ExplicitComponent): def setup(self): @@ -243,7 +243,7 @@ def setup(self): self.add_output('y', val=3.0) prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) @@ -251,7 +251,7 @@ def setup(self): msg = "Variable name 'y' already exists." with assertRaisesRegex(self, ValueError, msg): - prob.setup(check=False) + prob.setup() class Comp(ExplicitComponent): def setup(self): @@ -260,7 +260,7 @@ def setup(self): self.add_output('y', val=3.0) prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) @@ -268,7 +268,7 @@ def setup(self): msg = "Variable name 'x' already exists." with assertRaisesRegex(self, ValueError, msg): - prob.setup(check=False) + prob.setup() # Make sure we can reconfigure. @@ -278,16 +278,16 @@ def setup(self): self.add_output('y', val=3.0) prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) model.connect('px.x', 'comp.x') - prob.setup(check=False) + prob.setup() # pretend we reconfigured - prob.setup(check=False) + prob.setup() class TestImplicitComponent(unittest.TestCase): @@ -298,7 +298,7 @@ def test___init___simple(self): a = np.abs(np.exp(0.5 * x) / x) comp = TestImplCompSimple() - prob = Problem(comp).setup(check=False) + prob = Problem(comp).setup() prob['a'] = a prob.run_model() @@ -307,7 +307,7 @@ def test___init___simple(self): def test___init___array(self): """Test an implicit component with array inputs/outputs.""" comp = TestImplCompArray() - prob = Problem(comp).setup(check=False) + prob = Problem(comp).setup() prob['rhs'] = np.ones(2) prob.run_model() @@ -356,7 +356,7 @@ def compute(self, inputs, outputs): comp = RangePartialsComp() prob = Problem(model=comp) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['vSum'], np.array([2., 3., 4., 5.]), 0.00001) diff --git a/openmdao/core/tests/test_connections.py b/openmdao/core/tests/test_connections.py index a65a4d9eb5..2c00fc1172 100644 --- a/openmdao/core/tests/test_connections.py +++ b/openmdao/core/tests/test_connections.py @@ -16,7 +16,7 @@ def setUp(self): self.setup_model(None, None) def setup_model(self, c1meta=None, c3meta=None): - self.p = Problem(model=Group()) + self.p = Problem() root = self.p.model if c1meta is None: @@ -36,7 +36,7 @@ def setup_model(self, c1meta=None, c3meta=None): self.C4 = self.G4.add_subsystem("C4", ExecComp('y=x*2.0')) def test_no_conns(self): - self.p.setup(check=False) + self.p.setup() self.p['G1.G2.C1.x'] = 111. self.p['G3.G4.C3.x'] = 222. @@ -52,7 +52,7 @@ def test_inp_inp_explicit_conn_w_src(self): raise unittest.SkipTest("explicit input-input connections not supported yet") self.p.model.connect('G3.G4.C3.x', 'G3.G4.C4.x') # connect inputs self.p.model.connect('G1.G2.C2.x', 'G3.G4.C3.x') # connect src to one of connected inputs - self.p.setup(check=False) + self.p.setup() self.p['G1.G2.C2.x'] = 999. self.assertEqual(self.C3._inputs['x'], 0.) @@ -96,14 +96,13 @@ def solve_nonlinear(self, inputs, outputs, resids): outputs['y2'] = np.sum(x2) p = Problem() - p.model = Group() p.model.add_subsystem('src', Src()) p.model.add_subsystem('tgt', Tgt()) p.model.connect('src.y1', 'tgt.x1') p.model.connect('src.y2', 'tgt.x2') - p.setup(check=False) + p.setup() p.run_model() self.assertEqual(p['tgt.y1'], 12.0) @@ -153,7 +152,6 @@ def solve_nonlinear(self, inputs, outputs, resids): outputs['y3'] = np.sum(x3) top = Problem() - top.model = Group() top.model.add_subsystem('src', Src()) top.model.add_subsystem('tgt', Tgt()) @@ -161,7 +159,7 @@ def solve_nonlinear(self, inputs, outputs, resids): top.model.connect('src.y2', 'tgt.x2', src_indices=(0, 1)) top.model.connect('src.y3', 'tgt.x3') - top.setup(check=False) + top.setup() top.run_model() self.assertEqual(top['tgt.y1'], 6.0) @@ -197,7 +195,7 @@ def test_diff_conn_input_vals(self): self.p.model.connect('G1.G2.C1.x', 'G3.G4.C3.x') try: - self.p.setup(check=False) + self.p.setup() except Exception as err: self.assertTrue( "The following sourceless connected inputs have different initial values: " @@ -216,7 +214,7 @@ def test_diff_conn_input_units(self): self.p.model.connect('G1.G2.C1.x', 'G3.G4.C3.x') try: - self.p.setup(check=False) + self.p.setup() except Exception as err: msg = "The following connected inputs have no source and different units: " \ "[('G1.G2.C1.x', 'ft'), ('G3.G4.C3.x', 'inch')]. " \ @@ -235,7 +233,7 @@ def test_diff_conn_input_units_swap(self): self.p.model.connect('G3.G4.C3.x', 'G1.G2.C1.x') try: - self.p.setup(check=False) + self.p.setup() except Exception as err: msg = "The following connected inputs have no source and different units: " \ "[('G1.G2.C1.x', 'ft'), ('G3.G4.C3.x', 'inch')]. " \ @@ -247,7 +245,7 @@ def test_diff_conn_input_units_swap(self): def test_diff_conn_input_units_w_src(self): raise unittest.SkipTest("no compatability checking of connected inputs yet") - p = Problem(model=Group()) + p = Problem() root = p.model num_comps = 50 @@ -268,7 +266,7 @@ def test_diff_conn_input_units_w_src(self): root.connect("C%d.x" % (i-1), "C%d.x" % i) try: - p.setup(check=False) + p.setup() except Exception as err: self.assertTrue("The following connected inputs have no source and different units" in str(err)) @@ -281,14 +279,14 @@ def test_diff_conn_input_units_w_src(self): root.connect('desvars.dvar1', 'C10.x') - p.setup(check=False) + p.setup() class TestConnectionsPromoted(unittest.TestCase): def test_inp_inp_promoted_no_src(self): - p = Problem(model=Group()) + p = Problem() root = p.model G1 = root.add_subsystem("G1", Group()) @@ -312,7 +310,7 @@ def test_inp_inp_promoted_no_src(self): "[G3.G4.C3.x, G3.G4.C4.x] that are not connected to an output variable.") def test_inp_inp_promoted_w_prom_src(self): - p = Problem(model=Group()) + p = Problem() root = p.model G1 = root.add_subsystem("G1", Group(), promotes=['x']) @@ -325,7 +323,7 @@ def test_inp_inp_promoted_w_prom_src(self): C3 = G4.add_subsystem("C3", ExecComp('y=x*2.0'), promotes=['x']) C4 = G4.add_subsystem("C4", ExecComp('y=x*2.0'), promotes=['x']) - p.setup(check=False) + p.setup() p.set_solver_print(level=0) # setting promoted name will set the value into the outputs, but will @@ -337,7 +335,7 @@ def test_inp_inp_promoted_w_prom_src(self): self.assertEqual(C4._inputs['x'], 999.) def test_inp_inp_promoted_w_explicit_src(self): - p = Problem(model=Group()) + p = Problem() root = p.model G1 = root.add_subsystem("G1", Group()) @@ -351,7 +349,7 @@ def test_inp_inp_promoted_w_explicit_src(self): C4 = G4.add_subsystem("C4", ExecComp('y=x*2.0'), promotes=['x']) p.model.connect('G1.x', 'G3.x') - p.setup(check=False) + p.setup() p.set_solver_print(level=0) # setting promoted name will set the value into the outputs, but will @@ -364,7 +362,7 @@ def test_inp_inp_promoted_w_explicit_src(self): def test_unit_conv_message(self): raise unittest.SkipTest("no units yet") - prob = Problem(model=Group()) + prob = Problem() root = prob.model root.add_subsystem("C1", ExecComp('y=x*2.0', units={'x': 'ft'}), promotes=['x']) @@ -372,7 +370,7 @@ def test_unit_conv_message(self): root.add_subsystem("C3", ExecComp('y=x*2.0', units={'x': 'm'}), promotes=['x']) try: - prob.setup(check=False) + prob.setup() except Exception as err: msg = "The following connected inputs are promoted to 'x', but have different units: " \ "[('C1.x', 'ft'), ('C2.x', 'inch'), ('C3.x', 'm')]. " \ @@ -383,7 +381,7 @@ def test_unit_conv_message(self): # Remedy the problem with an Indepvarcomp - prob = Problem(model=Group()) + prob = Problem() root = prob.model root.add_subsystem("C1", ExecComp('y=x*2.0', units={'x': 'ft'}), promotes=['x']) @@ -391,12 +389,12 @@ def test_unit_conv_message(self): root.add_subsystem("C3", ExecComp('y=x*2.0', units={'x': 'm'}), promotes=['x']) root.add_subsystem('p', IndepVarComp('x', 1.0, units='cm'), promotes=['x']) - prob.setup(check=False) + prob.setup() def test_overlapping_system_names(self): # This ensures that _setup_connections does not think g1 and g1a are the same system prob = Problem() - model = prob.model = Group() + model = prob.model g1 = model.add_subsystem('g1', Group()) g1a = model.add_subsystem('g1a', Group()) @@ -441,7 +439,7 @@ def test_bad_shapes(self): r" Expected \(2.*,\) but got \(1.*,\).") with assertRaisesRegex(self, ValueError, expected): - self.prob.setup(check=False) + self.prob.setup() def test_bad_length(self): # Should not be allowed because the length of src_indices is greater than @@ -453,7 +451,7 @@ def test_bad_length(self): r"The target shape is \(2.*,\) but indices are \(3.*,\).") with assertRaisesRegex(self, ValueError, expected): - self.prob.setup(check=False) + self.prob.setup() def test_bad_value(self): # Should not be allowed because the index value within src_indices is outside @@ -466,7 +464,7 @@ def test_bad_value(self): "size 5.") try: - self.prob.setup(check=False) + self.prob.setup() except ValueError as err: self.assertEqual(str(err), expected) else: diff --git a/openmdao/core/tests/test_des_vars_responses.py b/openmdao/core/tests/test_des_vars_responses.py index acd49f329f..8b1add1f57 100644 --- a/openmdao/core/tests/test_des_vars_responses.py +++ b/openmdao/core/tests/test_des_vars_responses.py @@ -7,13 +7,12 @@ import numpy as np -import openmdao -from openmdao.api import Problem, NonlinearBlockGS, Group, IndepVarComp +from openmdao.api import Problem, NonlinearBlockGS, Group, IndepVarComp, ExecComp, ScipyKrylov from openmdao.utils.assert_utils import assert_rel_error from openmdao.utils.mpi import MPI from openmdao.test_suite.components.sellar import SellarDerivatives, SellarDis1withDerivatives, \ - SellarDis2withDerivatives, ExecComp, ScipyKrylov + SellarDis2withDerivatives try: from openmdao.vectors.petsc_vector import PETScVector @@ -38,7 +37,7 @@ def test_api_backwards_compatible(self): prob.driver.add_constraint('con1') prob.driver.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_des_vars() obj = prob.model.get_objectives() @@ -61,7 +60,7 @@ def test_api_on_model(self): prob.model.add_constraint('con1') prob.model.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() obj = prob.model.get_objectives() @@ -84,7 +83,7 @@ def test_api_response_on_model(self): prob.model.add_response('con1', type_="con") prob.model.add_response('con2', type_="con") - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() responses = prob.model.get_responses() @@ -109,7 +108,7 @@ def test_api_list_on_model(self): prob.model.add_constraint('con1') prob.model.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() obj = prob.model.get_objectives() @@ -134,7 +133,7 @@ def test_api_array_on_model(self): prob.model.add_constraint('con1') prob.model.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() obj = prob.model.get_objectives() @@ -160,7 +159,7 @@ def test_api_iter_on_model(self): prob.model.add_constraint('con1') prob.model.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() obj = prob.model.get_objectives() @@ -173,7 +172,7 @@ def test_api_iter_on_model(self): def test_api_on_subsystems(self): prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp('x', 1.0)) model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) @@ -210,7 +209,7 @@ def test_api_on_subsystems(self): con_comp2 = prob.model.con_cmp2 con_comp2.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() obj = prob.model.get_objectives() @@ -233,7 +232,7 @@ def test_design_var_not_exist(self): prob.model.add_design_var('junk') with self.assertRaises(RuntimeError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "Output not found for design variable 'junk' in system ''.") @@ -290,7 +289,7 @@ def test_desvar_affine_mapping(self): prob.model.add_constraint('con1') prob.model.add_constraint('con2') - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() @@ -316,7 +315,7 @@ def test_desvar_inf_bounds(self): prob.model.add_constraint('con1', scaler=1e6) prob.model.add_constraint('con2', scaler=1e6) - prob.setup(check=False) + prob.setup() des_vars = prob.model.get_design_vars() @@ -376,7 +375,7 @@ def test_constraint_not_exist(self): prob.model.add_constraint('junk') with self.assertRaises(RuntimeError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "Output not found for response 'junk' in system ''.") @@ -433,7 +432,7 @@ def test_constraint_affine_mapping(self): ref=100) prob.model.add_constraint('con2') - prob.setup(check=False) + prob.setup() constraints = prob.model.get_constraints() @@ -595,7 +594,7 @@ def test_obective_not_exist(self): prob.model.add_objective('junk') with self.assertRaises(RuntimeError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "Output not found for response 'junk' in system ''.") @@ -654,7 +653,7 @@ def test_objective_affine_mapping(self): prob.model.add_objective('obj', ref0=1000, ref=1010) prob.model.add_objective('con2') - prob.setup(check=False) + prob.setup() objectives = prob.model.get_objectives() diff --git a/openmdao/core/tests/test_discrete.py b/openmdao/core/tests/test_discrete.py index 09c91b15a0..63f7dc5429 100644 --- a/openmdao/core/tests/test_discrete.py +++ b/openmdao/core/tests/test_discrete.py @@ -8,19 +8,17 @@ import numpy as np +import openmdao.api as om from openmdao.core.group import get_relevant_vars from openmdao.core.driver import Driver -from openmdao.api import Problem, IndepVarComp, NonlinearBlockGS, ScipyOptimizeDriver, \ - ExecComp, Group, NewtonSolver, ImplicitComponent, ScipyKrylov, ExplicitComponent, \ - ImplicitComponent, ParallelGroup, BroydenSolver -from openmdao.utils.assert_utils import assert_rel_error +from openmdao.devtools.problem_viewer.problem_viewer import _get_viewer_data from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.sellar import StateConnection, \ SellarDis1withDerivatives, SellarDis2withDerivatives -from openmdao.devtools.problem_viewer.problem_viewer import _get_viewer_data +from openmdao.utils.assert_utils import assert_rel_error -class ModCompEx(ExplicitComponent): +class ModCompEx(om.ExplicitComponent): def __init__(self, modval, **kwargs): super(ModCompEx, self).__init__(**kwargs) self.modval = modval @@ -36,7 +34,7 @@ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): discrete_outputs['y'] = discrete_inputs['x'] % self.modval -class ModCompIm(ImplicitComponent): +class ModCompIm(om.ImplicitComponent): def __init__(self, modval, **kwargs): super(ModCompIm, self).__init__(**kwargs) self.modval = modval @@ -52,7 +50,7 @@ def solve_nonlinear(self, inputs, outputs, discrete_inputs, discrete_outputs): discrete_outputs['y'] = discrete_inputs['x'] % self.modval -class CompDiscWDerivs(ExplicitComponent): +class CompDiscWDerivs(om.ExplicitComponent): def setup(self): self.add_discrete_input('N', 2) self.add_discrete_output('Nout', 2) @@ -86,7 +84,7 @@ def linearize(self, inputs, outputs, J, discrets_inputs, discrete_outputs): super(CompDiscWDerivsImplicit, self).linearize(inputs, outputs, J) -class MixedCompDiscIn(ExplicitComponent): +class MixedCompDiscIn(om.ExplicitComponent): def __init__(self, mult, **kwargs): super(MixedCompDiscIn, self).__init__(**kwargs) self.mult = mult @@ -99,7 +97,7 @@ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): outputs['y'] = discrete_inputs['x'] * self.mult -class MixedCompDiscOut(ExplicitComponent): +class MixedCompDiscOut(om.ExplicitComponent): def __init__(self, mult, **kwargs): super(MixedCompDiscOut, self).__init__(**kwargs) self.mult = mult @@ -112,7 +110,7 @@ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): discrete_outputs['y'] = inputs['x'] * self.mult -class InternalDiscreteGroup(Group): +class InternalDiscreteGroup(om.Group): # this group has an internal discrete connection with continuous external vars, # so it can be spliced into an existing continuous model to test for discrete # var error checking. @@ -158,7 +156,7 @@ def __imul__(self, val): return self -class PathCompEx(ExplicitComponent): +class PathCompEx(om.ExplicitComponent): def setup(self): self.add_discrete_input('x', val=self.pathname) @@ -168,7 +166,7 @@ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): discrete_outputs['y'] = discrete_inputs['x'] + self.pathname + '/' -class ObjAdderCompEx(ExplicitComponent): +class ObjAdderCompEx(om.ExplicitComponent): def __init__(self, val, **kwargs): super(ObjAdderCompEx, self).__init__(**kwargs) self.val = val @@ -184,10 +182,10 @@ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): class DiscreteTestCase(unittest.TestCase): def test_simple_run_once(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_discrete_output('x', 11) model.add_subsystem('comp', ModCompEx(3)) @@ -199,10 +197,10 @@ def test_simple_run_once(self): assert_rel_error(self, prob['comp.y'], 2) def test_simple_run_once_promoted(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*']) + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes=['*']) indep.add_discrete_output('x', 11) model.add_subsystem('comp', ModCompEx(3), promotes=['*']) @@ -212,10 +210,10 @@ def test_simple_run_once_promoted(self): assert_rel_error(self, prob['y'], 2) def test_simple_run_once_implicit(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_discrete_output('x', 11) model.add_subsystem('comp', ModCompIm(3)) @@ -227,10 +225,10 @@ def test_simple_run_once_implicit(self): assert_rel_error(self, prob['comp.y'], 2) def test_list_inputs_outputs(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_discrete_output('x', 11) model.add_subsystem('expl', ModCompEx(3)) @@ -297,10 +295,10 @@ def test_list_inputs_outputs(self): self.assertEqual(text.count(' y'), 2) # both implicit & explicit def test_float_to_discrete_error(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_output('x', 1.0) model.add_subsystem('comp', ModCompEx(3)) @@ -312,12 +310,12 @@ def test_float_to_discrete_error(self): "Can't connect discrete output 'indep.x' to continuous input 'comp.x'.") def test_discrete_to_float_error(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_discrete_output('x', 1) - model.add_subsystem('comp', ExecComp("y=2.0*x")) + model.add_subsystem('comp', om.ExecComp("y=2.0*x")) model.connect('indep.x', 'comp.x') @@ -327,10 +325,10 @@ def test_discrete_to_float_error(self): "Can't connect discrete output 'indep.x' to continuous input 'comp.x'.") def test_discrete_mismatch_error(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_discrete_output('x', val='foo') model.add_subsystem('comp', ModCompEx(3)) @@ -343,10 +341,10 @@ def test_discrete_mismatch_error(self): def test_driver_discrete_enforce_int(self): # Drivers require discrete vars to be int or ndarrays of int. - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_discrete_output('x', 11) model.add_subsystem('comp', ModCompIm(3)) @@ -389,10 +387,10 @@ def test_driver_discrete_enforce_int(self): prob.run_driver() def test_discrete_deriv_explicit(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_output('x', 1.0) comp = model.add_subsystem('comp', CompDiscWDerivs()) @@ -409,10 +407,10 @@ def test_discrete_deriv_explicit(self): np.testing.assert_almost_equal(J, np.array([[3.]])) def test_discrete_deriv_implicit(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_output('x', 1.0, ref=10.) indep.add_discrete_output('N', 1) @@ -433,23 +431,23 @@ def test_discrete_deriv_implicit(self): np.testing.assert_almost_equal(J, np.array([[-1]])) def test_deriv_err(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp(), promotes_outputs=['x']) + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes_outputs=['x']) indep.add_output('x', 1.0) - G = model.add_subsystem('G', Group(), promotes_inputs=['x']) + G = model.add_subsystem('G', om.Group(), promotes_inputs=['x']) G1 = G.add_subsystem('G1', InternalDiscreteGroup(), promotes_inputs=['x'], promotes_outputs=['y']) - G2 = G.add_subsystem('G2', Group(), promotes_inputs=['x']) - G2.add_subsystem('C2_1', ExecComp('y=3*x'), promotes_inputs=['x']) - G2.add_subsystem('C2_2', ExecComp('y=4*x'), promotes_outputs=['y']) + G2 = G.add_subsystem('G2', om.Group(), promotes_inputs=['x']) + G2.add_subsystem('C2_1', om.ExecComp('y=3*x'), promotes_inputs=['x']) + G2.add_subsystem('C2_2', om.ExecComp('y=4*x'), promotes_outputs=['y']) G2.connect('C2_1.y', 'C2_2.x') - model.add_subsystem('C3', ExecComp('y=3+x')) - model.add_subsystem('C4', ExecComp('y=4+x')) + model.add_subsystem('C3', om.ExecComp('y=3+x')) + model.add_subsystem('C4', om.ExecComp('y=4+x')) model.connect('G.y', 'C3.x') model.connect('G.G2.y', 'C4.x') @@ -472,16 +470,16 @@ def test_deriv_err(self): class SolverDiscreteTestCase(unittest.TestCase): def _setup_model(self, solver_class): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) proms = ['x', 'z', 'y1', 'state_eq.y2_actual', 'state_eq.y2_command', 'd1.y2', 'd2.y2'] - sub = model.add_subsystem('sub', Group(), promotes=proms) + sub = model.add_subsystem('sub', om.Group(), promotes=proms) - subgrp = sub.add_subsystem('state_eq_group', Group(), + subgrp = sub.add_subsystem('state_eq_group', om.Group(), promotes=['state_eq.y2_actual', 'state_eq.y2_command']) subgrp.add_subsystem('state_eq', StateConnection()) @@ -491,13 +489,13 @@ def _setup_model(self, solver_class): model.connect('state_eq.y2_command', 'd1.y2') model.connect('d2.y2', 'state_eq.y2_actual') - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['x', 'z', 'y1', 'obj']) model.connect('d2.y2', 'obj_cmp.y2') - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2']) # splice a group containing discrete vars into the model model.add_subsystem('discrete_g', InternalDiscreteGroup()) @@ -507,12 +505,12 @@ def _setup_model(self, solver_class): model.nonlinear_solver = solver_class() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() return prob def test_discrete_err_newton(self): - prob = self._setup_model(NewtonSolver) + prob = self._setup_model(om.NewtonSolver) with self.assertRaises(Exception) as ctx: prob.run_model() @@ -521,7 +519,7 @@ def test_discrete_err_newton(self): "System '' has a NewtonSolver solver and contains discrete outputs ['discrete_g.C1.y'].") def test_discrete_err_broyden(self): - prob = self._setup_model(BroydenSolver) + prob = self._setup_model(om.BroydenSolver) with self.assertRaises(Exception) as ctx: prob.run_model() @@ -532,20 +530,20 @@ def test_discrete_err_broyden(self): class DiscretePromTestCase(unittest.TestCase): def test_str_pass(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp(), promotes_outputs=['x']) + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes_outputs=['x']) indep.add_discrete_output('x', 'indep/') - G = model.add_subsystem('G', ParallelGroup(), promotes_inputs=['x']) + G = model.add_subsystem('G', om.ParallelGroup(), promotes_inputs=['x']) - G1 = G.add_subsystem('G1', Group(), promotes_inputs=['x'], promotes_outputs=['y']) + G1 = G.add_subsystem('G1', om.Group(), promotes_inputs=['x'], promotes_outputs=['y']) G1.add_subsystem('C1_1', PathCompEx(), promotes_inputs=['x']) G1.add_subsystem('C1_2', PathCompEx(), promotes_outputs=['y']) G1.connect('C1_1.y', 'C1_2.x') - G2 = G.add_subsystem('G2', Group(), promotes_inputs=['x']) + G2 = G.add_subsystem('G2', om.Group(), promotes_inputs=['x']) G2.add_subsystem('C2_1', PathCompEx(), promotes_inputs=['x']) G2.add_subsystem('C2_2', PathCompEx(), promotes_outputs=['y']) G2.connect('C2_1.y', 'C2_2.x') @@ -569,20 +567,20 @@ def test_str_pass(self): self.assertEqual(prob['C4.y'], 'foobar/G.G2.C2_1/G.G2.C2_2/C4/') def test_obj_pass(self): - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp(), promotes_outputs=['x']) + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes_outputs=['x']) indep.add_discrete_output('x', _DiscreteVal(19)) - G = model.add_subsystem('G', ParallelGroup(), promotes_inputs=['x']) + G = model.add_subsystem('G', om.ParallelGroup(), promotes_inputs=['x']) - G1 = G.add_subsystem('G1', Group(), promotes_inputs=['x'], promotes_outputs=['y']) + G1 = G.add_subsystem('G1', om.Group(), promotes_inputs=['x'], promotes_outputs=['y']) G1.add_subsystem('C1_1', ObjAdderCompEx(_DiscreteVal(5)), promotes_inputs=['x']) G1.add_subsystem('C1_2', ObjAdderCompEx(_DiscreteVal(7)), promotes_outputs=['y']) G1.connect('C1_1.y', 'C1_2.x') - G2 = G.add_subsystem('G2', Group(), promotes_inputs=['x']) + G2 = G.add_subsystem('G2', om.Group(), promotes_inputs=['x']) G2.add_subsystem('C2_1', ObjAdderCompEx(_DiscreteVal(1)), promotes_inputs=['x']) G2.add_subsystem('C2_2', ObjAdderCompEx(_DiscreteVal(11)), promotes_outputs=['y']) G2.connect('C2_1.y', 'C2_2.x') @@ -635,9 +633,9 @@ def _var_iter(obj): class DiscreteFeatureTestCase(unittest.TestCase): def test_feature_discrete(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExplicitComponent + import openmdao.api as om - class BladeSolidity(ExplicitComponent): + class BladeSolidity(om.ExplicitComponent): def setup(self): # Continuous Inputs @@ -659,8 +657,8 @@ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): outputs['blade_solidity'] = chord / (2.0 * np.pi * r_m / num_blades) # build the model - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('r_m', 3.2, units="ft") indeps.add_output('chord', .3, units='ft') indeps.add_discrete_output('num_blades', 2) diff --git a/openmdao/core/tests/test_distrib_adder.py b/openmdao/core/tests/test_distrib_adder.py index 1426733554..f4bef0c825 100644 --- a/openmdao/core/tests/test_distrib_adder.py +++ b/openmdao/core/tests/test_distrib_adder.py @@ -85,13 +85,12 @@ def test_distributed_adder(self): size = 100 # how many items in the array prob = Problem() - prob.model = Group() prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size)), promotes=['x']) prob.model.add_subsystem('plus', DistributedAdder(size=size), promotes=['x', 'y']) summer = prob.model.add_subsystem('summer', Summer(size=size), promotes=['y', 'sum']) - prob.setup(check=False) + prob.setup() prob['x'] = np.ones(size) diff --git a/openmdao/core/tests/test_distrib_list_vars.py b/openmdao/core/tests/test_distrib_list_vars.py index fed494e7a2..6416787053 100644 --- a/openmdao/core/tests/test_distrib_list_vars.py +++ b/openmdao/core/tests/test_distrib_list_vars.py @@ -87,13 +87,12 @@ def test_distributed_array_list_vars(self): size = 100 # how many items in the array prob = Problem() - prob.model = Group() prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size)), promotes=['x']) prob.model.add_subsystem('plus', DistributedAdder(size=size), promotes=['x', 'y']) prob.model.add_subsystem('summer', Summer(size=size), promotes=['y', 'sum']) - prob.setup(check=False) + prob.setup() prob['x'] = np.arange(size) diff --git a/openmdao/core/tests/test_distribcomp.py b/openmdao/core/tests/test_distribcomp.py index 2001041192..367e65c7a7 100644 --- a/openmdao/core/tests/test_distribcomp.py +++ b/openmdao/core/tests/test_distribcomp.py @@ -5,7 +5,7 @@ import numpy as np -from openmdao.api import Problem, ExplicitComponent, Group, ExecComp, ParallelGroup +import openmdao.api as om from openmdao.utils.mpi import MPI from openmdao.utils.array_utils import evenly_distrib_idxs, take_nth from openmdao.utils.assert_utils import assert_rel_error, assert_warning @@ -23,7 +23,7 @@ commsize = 1 -class InOutArrayComp(ExplicitComponent): +class InOutArrayComp(om.ExplicitComponent): def initialize(self): self.options.declare('arr_size', types=int, default=10, @@ -43,7 +43,7 @@ def compute(self, inputs, outputs): outputs['outvec'] = inputs['invec'] * 2. -class DistribCompSimple(ExplicitComponent): +class DistribCompSimple(om.ExplicitComponent): """Uses 2 procs but takes full input vars""" def initialize(self): @@ -75,7 +75,7 @@ def compute(self, inputs, outputs): outputs['outvec'] = inputs['invec'] * 0.75 -class DistribInputComp(ExplicitComponent): +class DistribInputComp(om.ExplicitComponent): """Uses 2 procs and takes input var slices""" def initialize(self): @@ -107,7 +107,7 @@ def setup(self): self.add_output('outvec', np.ones(arr_size, float), shape=np.int32(arr_size)) -class DistribOverlappingInputComp(ExplicitComponent): +class DistribOverlappingInputComp(om.ExplicitComponent): """Uses 2 procs and takes input var slices""" def initialize(self): @@ -151,7 +151,7 @@ def setup(self): src_indices=np.arange(start, end, dtype=int)) -class DistribInputDistribOutputComp(ExplicitComponent): +class DistribInputDistribOutputComp(om.ExplicitComponent): """Uses 2 procs and takes input var slices.""" def initialize(self): @@ -179,7 +179,7 @@ def setup(self): self.add_output('outvec', np.ones(sizes[rank], float)) -class DistribNoncontiguousComp(ExplicitComponent): +class DistribNoncontiguousComp(om.ExplicitComponent): """Uses 2 procs and takes non-contiguous input var slices and has output var slices as well """ @@ -207,7 +207,7 @@ def setup(self): self.add_output('outvec', np.ones(len(idxs), float)) -class DistribGatherComp(ExplicitComponent): +class DistribGatherComp(om.ExplicitComponent): """Uses 2 procs gathers a distrib input into a full output""" def initialize(self): @@ -242,7 +242,7 @@ def setup(self): self.add_output('outvec', np.ones(arr_size, float)) -class NonDistribGatherComp(ExplicitComponent): +class NonDistribGatherComp(om.ExplicitComponent): """Uses 2 procs gathers a distrib output into a full input""" def initialize(self): @@ -265,7 +265,7 @@ class NOMPITests(unittest.TestCase): def test_distrib_idx_in_full_out(self): size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribInputComp(arr_size=size)) @@ -276,7 +276,7 @@ def test_distrib_idx_in_full_out(self): "available. The default non-distributed vectors will be used." with assert_warning(UserWarning, msg): - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -296,13 +296,13 @@ class MPITests(unittest.TestCase): def test_distrib_full_in_out(self): size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribCompSimple(arr_size=size)) top.connect('C1.outvec', 'C2.invec') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -316,13 +316,13 @@ def test_distrib_full_in_out(self): def test_distrib_idx_in_full_out(self): size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribInputComp(arr_size=size)) top.connect('C1.outvec', 'C2.invec') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -336,15 +336,15 @@ def test_distrib_idx_in_full_out(self): def test_distrib_1D_dist_output(self): size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribInputComp(arr_size=size)) - C3 = top.add_subsystem("C3", ExecComp("y=x", x=np.zeros(size*commsize), - y=np.zeros(size*commsize))) + C3 = top.add_subsystem("C3", om.ExecComp("y=x", x=np.zeros(size*commsize), + y=np.zeros(size*commsize))) top.connect('C1.outvec', 'C2.invec') top.connect('C2.outvec', 'C3.x') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -359,14 +359,14 @@ def test_distrib_idx_in_distrb_idx_out(self): # normal comp to distrib comp to distrb gather comp size = 3 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribInputDistribOutputComp(arr_size=size)) C3 = top.add_subsystem("C3", DistribGatherComp(arr_size=size)) top.connect('C1.outvec', 'C2.invec') top.connect('C2.outvec', 'C3.invec') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -381,14 +381,14 @@ def test_noncontiguous_idxs(self): # take even input indices in 0 rank and odd ones in 1 rank size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribNoncontiguousComp(arr_size=size)) C3 = top.add_subsystem("C3", DistribGatherComp(arr_size=size)) top.connect('C1.outvec', 'C2.invec') top.connect('C2.outvec', 'C3.invec') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -417,12 +417,12 @@ def test_overlapping_inputs_idxs(self): # entries are distributed to multiple processes size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribOverlappingInputComp(arr_size=size)) top.connect('C1.outvec', 'C2.invec') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -443,14 +443,14 @@ def test_nondistrib_gather(self): # automagically gather the full vector without declaring src_indices size = 11 - p = Problem(model=Group()) + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) C2 = top.add_subsystem("C2", DistribInputDistribOutputComp(arr_size=size)) C3 = top.add_subsystem("C3", NonDistribGatherComp(size=size)) top.connect('C1.outvec', 'C2.invec') top.connect('C2.outvec', 'C3.invec') - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -469,7 +469,7 @@ class DeprecatedMPITests(unittest.TestCase): def test_distrib_idx_in_full_out_deprecated(self): - class DeprecatedDistribInputComp(ExplicitComponent): + class DeprecatedDistribInputComp(om.ExplicitComponent): """Deprecated version of DistribInputComp, uses attribute instead of option.""" def __init__(self, arr_size=11): @@ -500,7 +500,7 @@ def setup(self): size = 11 - p = Problem() + p = om.Problem() top = p.model C1 = top.add_subsystem("C1", InOutArrayComp(arr_size=size)) @@ -525,9 +525,9 @@ def setup(self): if PETScVector is None: with assert_warning(UserWarning, msg): - p.setup(check=False) + p.setup() else: - p.setup(check=False) + p.setup() p.final_setup() @@ -547,12 +547,12 @@ class ProbRemoteTests(unittest.TestCase): def test_prob_getitem_err(self): size = 3 - p = Problem(model=Group()) + p = om.Problem() top = p.model - par = top.add_subsystem('par', ParallelGroup()) + par = top.add_subsystem('par', om.ParallelGroup()) C1 = par.add_subsystem("C1", DistribInputDistribOutputComp(arr_size=size)) C2 = par.add_subsystem("C2", DistribInputDistribOutputComp(arr_size=size)) - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -593,7 +593,7 @@ class MPIFeatureTests(unittest.TestCase): def test_distribcomp_feature(self): import numpy as np - from openmdao.api import Problem, ExplicitComponent, Group, IndepVarComp + import openmdao.api as om from openmdao.utils.mpi import MPI from openmdao.utils.array_utils import evenly_distrib_idxs @@ -603,7 +603,7 @@ def test_distribcomp_feature(self): rank = MPI.COMM_WORLD.rank size = 15 - class DistribComp(ExplicitComponent): + class DistribComp(om.ExplicitComponent): def initialize(self): self.options['distributed'] = True @@ -632,7 +632,7 @@ def compute(self, inputs, outputs): else: outputs['outvec'] = inputs['invec'] * -3.0 - class Summer(ExplicitComponent): + class Summer(om.ExplicitComponent): """Sums a distributed input.""" def initialize(self): @@ -668,9 +668,9 @@ def compute(self, inputs, outputs): outputs['out'] = total[0] - p = Problem(model=Group()) + p = om.Problem() top = p.model - top.add_subsystem("indep", IndepVarComp('x', np.zeros(size))) + top.add_subsystem("indep", om.IndepVarComp('x', np.zeros(size))) top.add_subsystem("C2", DistribComp(size=size)) top.add_subsystem("C3", Summer(size=size)) @@ -693,9 +693,9 @@ class TestGroupMPI(unittest.TestCase): def test_promote_distrib(self): import numpy as np - from openmdao.api import Problem, ExplicitComponent, IndepVarComp + import openmdao.api as om - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): # decide what parts of the array we want based on our rank if self.comm.rank == 0: @@ -711,9 +711,9 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x'])*2.0 - p = Problem() + p = om.Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.arange(5, dtype=float)), + p.model.add_subsystem('indep', om.IndepVarComp('x', np.arange(5, dtype=float)), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), diff --git a/openmdao/core/tests/test_driver.py b/openmdao/core/tests/test_driver.py index 72b44095cd..8dbcfd20ba 100644 --- a/openmdao/core/tests/test_driver.py +++ b/openmdao/core/tests/test_driver.py @@ -29,7 +29,7 @@ def test_basic_get(self): model.add_constraint('con1', lower=0) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_driver() designvars = prob.driver.get_design_var_values() @@ -51,7 +51,7 @@ def test_scaled_design_vars(self): model.add_constraint('con1', lower=0) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() @@ -74,7 +74,7 @@ def test_scaled_constraints(self): model.add_constraint('con1', lower=0, ref=2.0, ref0=3.0) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() cv = prob.driver.get_constraint_values()['con_cmp1.con1'][0] @@ -91,7 +91,7 @@ def test_scaled_objectves(self): model.add_constraint('con1', lower=0) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() cv = prob.driver.get_objective_values()['obj_cmp.obj'][0] @@ -108,7 +108,7 @@ def test_scaled_derivs(self): model.add_constraint('con1') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() base = prob.compute_totals(of=['obj', 'con1'], wrt=['z']) @@ -121,7 +121,7 @@ def test_scaled_derivs(self): model.add_constraint('con1', lower=0, ref=2.0, ref0=0.0) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() derivs = prob.driver._compute_totals(of=['obj_cmp.obj', 'con_cmp1.con1'], wrt=['pz.z'], @@ -132,7 +132,7 @@ def test_scaled_derivs(self): def test_vector_scaled_derivs(self): prob = Problem() - prob.model = model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) comp = model.add_subsystem('comp', DoubleArrayComp()) @@ -142,7 +142,7 @@ def test_vector_scaled_derivs(self): model.add_objective('comp.y1', ref=np.array([[7.0, 11.0]]), ref0=np.array([5.2, 6.3])) model.add_constraint('comp.y2', lower=0.0, upper=1.0, ref=np.array([[2.0, 4.0]]), ref0=np.array([1.2, 2.3])) - prob.setup(check=False) + prob.setup() prob.run_driver() derivs = prob.driver._compute_totals(of=['comp.y1'], wrt=['px.x'], @@ -171,7 +171,7 @@ def test_vector_bounds_inf(self): # make sure no overflow when there is no specified upper/lower bound and significatn scaling prob = Problem() - prob.model = model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) comp = model.add_subsystem('comp', DoubleArrayComp()) @@ -195,7 +195,7 @@ def test_vector_bounds_inf(self): def test_vector_scaled_derivs_diff_sizes(self): prob = Problem() - prob.model = model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) comp = model.add_subsystem('comp', NonSquareArrayComp()) @@ -205,7 +205,7 @@ def test_vector_scaled_derivs_diff_sizes(self): model.add_objective('comp.y1', ref=np.array([[7.0, 11.0, 2.0]]), ref0=np.array([5.2, 6.3, 1.2])) model.add_constraint('comp.y2', lower=0.0, upper=1.0, ref=np.array([[2.0]]), ref0=np.array([1.2])) - prob.setup(check=False) + prob.setup() prob.run_driver() derivs = prob.driver._compute_totals(of=['comp.y1'], wrt=['px.x'], @@ -243,7 +243,7 @@ def test_debug_print_option(self): model.add_constraint('con2', lower=0, linear=True) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # Make sure nothing prints if debug_print is the default of empty list stdout = sys.stdout @@ -280,7 +280,7 @@ def test_debug_print_option(self): def test_debug_print_desvar_physical_with_indices(self): prob = Problem() - model = prob.model = Group() + model = prob.model size = 3 model.add_subsystem('p1', IndepVarComp('x', np.array([50.0] * size))) @@ -309,7 +309,7 @@ def test_debug_print_desvar_physical_with_indices(self): model.add_objective('comp.f_xy', index=1) model.add_constraint('con.c', indices=[1], upper=-15.0) - prob.setup(check=False) + prob.setup() prob.driver.options['debug_print'] = ['desvars',] stdout = sys.stdout @@ -332,7 +332,7 @@ def test_debug_print_desvar_physical_with_indices(self): def test_debug_print_response_physical(self): prob = Problem() - model = prob.model = Group() + model = prob.model size = 3 model.add_subsystem('p1', IndepVarComp('x', np.array([50.0] * size))) @@ -361,7 +361,7 @@ def test_debug_print_response_physical(self): model.add_objective('comp.f_xy', index=1, ref=1.5) model.add_constraint('con.c', indices=[1], upper=-15.0, ref=1.02) - prob.setup(check=False) + prob.setup() prob.driver.options['debug_print'] = ['objs', 'nl_cons'] stdout = sys.stdout @@ -427,7 +427,7 @@ def test_unsupported_discrete_desvar(self): prob.driver = ScipyOptimizeDriver() - prob.setup(check=False) + prob.setup() with self.assertRaises(RuntimeError) as context: prob.final_setup() diff --git a/openmdao/core/tests/test_expl_comp.py b/openmdao/core/tests/test_expl_comp.py index 57b4808f1a..c2398983a0 100644 --- a/openmdao/core/tests/test_expl_comp.py +++ b/openmdao/core/tests/test_expl_comp.py @@ -8,18 +8,17 @@ import numpy as np -from openmdao.api import Problem, ExplicitComponent, NewtonSolver, ScipyKrylov, Group, \ - IndepVarComp, LinearBlockGS, AnalysisError -from openmdao.utils.assert_utils import assert_rel_error +import openmdao.api as om from openmdao.test_suite.components.double_sellar import SubSellar from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimple, \ TestExplCompSimpleDense +from openmdao.utils.assert_utils import assert_rel_error from openmdao.utils.general_utils import printoptions # Note: The following class definitions are used in feature docs -class RectangleComp(ExplicitComponent): +class RectangleComp(om.ExplicitComponent): """ A simple Explicit Component that computes the area of a rectangle. """ @@ -59,10 +58,10 @@ def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode): d_inputs['width'] += inputs['length'] * d_outputs['area'] -class RectangleGroup(Group): +class RectangleGroup(om.Group): def setup(self): - comp1 = self.add_subsystem('comp1', IndepVarComp()) + comp1 = self.add_subsystem('comp1', om.IndepVarComp()) comp1.add_output('length', 1.0) comp1.add_output('width', 1.0) @@ -78,21 +77,21 @@ def setup(self): class ExplCompTestCase(unittest.TestCase): def test_simple(self): - prob = Problem(RectangleComp()) - prob.setup(check=False) + prob = om.Problem(RectangleComp()) + prob.setup() prob.run_model() def test_feature_simple(self): - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_expl_comp import RectangleComp - prob = Problem(RectangleComp()) - prob.setup(check=False) + prob = om.Problem(RectangleComp()) + prob.setup() prob.run_model() def test_compute_and_list(self): - prob = Problem(RectangleGroup()) - prob.setup(check=False) + prob = om.Problem(RectangleGroup()) + prob.setup() msg = "Unable to list inputs until model has been run." try: @@ -156,23 +155,23 @@ def test_compute_and_list(self): def test_simple_list_vars_options(self): - from openmdao.api import IndepVarComp, Group, Problem, ExecComp - - prob = Problem() - prob.model = model = Group() - - model.add_subsystem('p1', IndepVarComp('x', 12.0, - lower=1.0, upper=100.0, - ref=1.1, ref0=2.1, - units='inch')) - model.add_subsystem('p2', IndepVarComp('y', 1.0, - lower=2.0, upper=200.0, - ref=1.2, res_ref=2.2, - units='ft')) - model.add_subsystem('comp', ExecComp('z=x+y', - x={'value': 0.0, 'units': 'inch'}, - y={'value': 0.0, 'units': 'inch'}, - z={'value': 0.0, 'units': 'inch'})) + import openmdao.api as om + + prob = om.Problem() + model = prob.model + + model.add_subsystem('p1', om.IndepVarComp('x', 12.0, + lower=1.0, upper=100.0, + ref=1.1, ref0=2.1, + units='inch')) + model.add_subsystem('p2', om.IndepVarComp('y', 1.0, + lower=2.0, upper=200.0, + ref=1.2, res_ref=2.2, + units='ft')) + model.add_subsystem('comp', om.ExecComp('z=x+y', + x={'value': 0.0, 'units': 'inch'}, + y={'value': 0.0, 'units': 'inch'}, + z={'value': 0.0, 'units': 'inch'})) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') @@ -261,25 +260,25 @@ def test_simple_list_vars_options(self): def test_for_feature_docs_list_vars_options(self): - from openmdao.api import IndepVarComp, Group, Problem, ExecComp - - prob = Problem() - prob.model = model = Group() - - model.add_subsystem('p1', IndepVarComp('x', 12.0, - lower=1.0, upper=100.0, - ref=1.1, ref0=2.1, - units='inch', - )) - model.add_subsystem('p2', IndepVarComp('y', 1.0, - lower=2.0, upper=200.0, - ref=1.2, res_ref=2.2, - units='ft', - )) - model.add_subsystem('comp', ExecComp('z=x+y', - x={'value': 0.0, 'units': 'inch'}, - y={'value': 0.0, 'units': 'inch'}, - z={'value': 0.0, 'units': 'inch'})) + import openmdao.api as om + + prob = om.Problem() + model = prob.model + + model.add_subsystem('p1', om.IndepVarComp('x', 12.0, + lower=1.0, upper=100.0, + ref=1.1, ref0=2.1, + units='inch', + )) + model.add_subsystem('p2', om.IndepVarComp('y', 1.0, + lower=2.0, upper=200.0, + ref=1.2, res_ref=2.2, + units='ft', + )) + model.add_subsystem('comp', om.ExecComp('z=x+y', + x={'value': 0.0, 'units': 'inch'}, + y={'value': 0.0, 'units': 'inch'}, + z={'value': 0.0, 'units': 'inch'})) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') @@ -321,13 +320,13 @@ def test_for_feature_docs_list_vars_options(self): def test_hierarchy_list_vars_options(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -335,20 +334,20 @@ def test_hierarchy_list_vars_options(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = LinearBlockGS() + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.LinearBlockGS() - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = ScipyKrylov() - g2.linear_solver.precon = LinearBlockGS() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.ScipyKrylov() + g2.linear_solver.precon = om.LinearBlockGS() g2.linear_solver.precon.options['maxiter'] = 2 - prob.setup(check=False) + prob.setup() prob.run_driver() # logging inputs @@ -434,7 +433,7 @@ def test_hierarchy_list_vars_options(self): def test_array_list_vars_options(self): - class ArrayAdder(ExplicitComponent): + class ArrayAdder(om.ExplicitComponent): """ Just a simple component that has array inputs and outputs """ @@ -452,14 +451,13 @@ def compute(self, inputs, outputs): size = 100 # how many items in the array - prob = Problem() - prob.model = Group() + prob = om.Problem() - prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size), units='inch'), + prob.model.add_subsystem('des_vars', om.IndepVarComp('x', np.ones(size), units='inch'), promotes=['x']) prob.model.add_subsystem('mult', ArrayAdder(size), promotes=['x', 'y']) - prob.setup(check=False) + prob.setup() prob['x'] = np.ones(size) @@ -613,10 +611,11 @@ def compute(self, inputs, outputs): def test_for_docs_array_list_vars_options(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + + import openmdao.api as om from openmdao.utils.general_utils import printoptions - class ArrayAdder(ExplicitComponent): + class ArrayAdder(om.ExplicitComponent): """ Just a simple component that has array inputs and outputs """ @@ -634,13 +633,12 @@ def compute(self, inputs, outputs): size = 30 - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size), units='inch'), + prob = om.Problem() + prob.model.add_subsystem('des_vars', om.IndepVarComp('x', np.ones(size), units='inch'), promotes=['x']) prob.model.add_subsystem('mult', ArrayAdder(size), promotes=['x', 'y']) - prob.setup(check=False) + prob.setup() prob['x'] = np.arange(size) prob.run_driver() @@ -679,7 +677,7 @@ def compute(self, inputs, outputs): super(BadComp, self).compute(inputs, outputs) inputs['length'] = 0. # should not be allowed - prob = Problem(BadComp()) + prob = om.Problem(BadComp()) prob.setup() with self.assertRaises(ValueError) as cm: @@ -693,11 +691,11 @@ def test_compute_inputs_read_only_reset(self): class BadComp(TestExplCompSimple): def compute(self, inputs, outputs): super(BadComp, self).compute(inputs, outputs) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem(BadComp()) + prob = om.Problem(BadComp()) prob.setup() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.run_model() # verify read_only status is reset after AnalysisError @@ -709,7 +707,7 @@ def compute_partials(self, inputs, partials): super(BadComp, self).compute_partials(inputs, partials) inputs['length'] = 0. # should not be allowed - prob = Problem(BadComp()) + prob = om.Problem(BadComp()) prob.setup() prob.run_model() @@ -724,13 +722,13 @@ def test_compute_partials_inputs_read_only_reset(self): class BadComp(TestExplCompSimpleDense): def compute_partials(self, inputs, partials): super(BadComp, self).compute_partials(inputs, partials) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem(BadComp()) + prob = om.Problem(BadComp()) prob.setup() prob.run_model() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.check_partials() # verify read_only status is reset after AnalysisError @@ -742,7 +740,7 @@ def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode): super(BadComp, self).compute_jacvec_product(inputs, d_inputs, d_outputs, mode) inputs['length'] = 0. # should not be allowed - prob = Problem(BadComp()) + prob = om.Problem(BadComp()) prob.setup() prob.run_model() @@ -757,13 +755,13 @@ def test_compute_jacvec_product_inputs_read_only_reset(self): class BadComp(RectangleJacVec): def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode): super(BadComp, self).compute_jacvec_product(inputs, d_inputs, d_outputs, mode) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem(BadComp()) + prob = om.Problem(BadComp()) prob.setup() prob.run_model() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.check_partials() # verify read_only status is reset after AnalysisError diff --git a/openmdao/core/tests/test_fd_color.py b/openmdao/core/tests/test_fd_color.py index 8ae4d23036..36f10cf0c3 100644 --- a/openmdao/core/tests/test_fd_color.py +++ b/openmdao/core/tests/test_fd_color.py @@ -443,7 +443,7 @@ def tearDown(self): ) def test_simple_semitotals(self, method, isplit, osplit): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model sparsity = setup_sparsity(_BIGMASK) indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'sub.comp') @@ -481,7 +481,7 @@ def test_simple_semitotals(self, method, isplit, osplit): ) def test_simple_semitotals_static(self, method, isplit, osplit): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model sparsity = setup_sparsity(_BIGMASK) indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'sub.comp') @@ -507,7 +507,7 @@ def test_simple_semitotals_static(self, method, isplit, osplit): # now create a second problem and use the static coloring prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'sub.comp') @@ -818,7 +818,7 @@ def test_partials_explicit_shape_bug(self, method): ) def test_simple_totals_static(self, method, isplit, osplit): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model sparsity = setup_sparsity(_BIGMASK) indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'comp') @@ -845,7 +845,7 @@ def test_simple_totals_static(self, method, isplit, osplit): # new Problem, loading the coloring we just computed prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'comp') @@ -885,7 +885,7 @@ def test_simple_totals_static(self, method, isplit, osplit): ) def test_totals_over_implicit_comp(self, method, isplit, osplit): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model sparsity = setup_sparsity(_BIGMASK) indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'comp') @@ -911,7 +911,7 @@ def test_totals_over_implicit_comp(self, method, isplit, osplit): model._save_coloring(compute_total_coloring(prob)) prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, _BIGMASK.shape[1], 'indeps', 'comp') @@ -951,7 +951,7 @@ def test_totals_over_implicit_comp(self, method, isplit, osplit): ) def test_totals_of_indices(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model mask = np.array( [[1, 0, 0, 1, 1], @@ -983,7 +983,7 @@ def test_totals_of_indices(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, mask.shape[1], 'indeps', 'comp') @@ -1019,7 +1019,7 @@ def test_totals_of_indices(self, method): ) def test_totals_wrt_indices(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model mask = np.array( [[1, 0, 0, 1, 1], @@ -1052,7 +1052,7 @@ def test_totals_wrt_indices(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, mask.shape[1], 'indeps', 'comp') @@ -1090,7 +1090,7 @@ def test_totals_wrt_indices(self, method): ) def test_totals_of_wrt_indices(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model mask = np.array( [[1, 0, 0, 1, 1], @@ -1125,7 +1125,7 @@ def test_totals_of_wrt_indices(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, mask.shape[1], 'indeps', 'comp') @@ -1186,7 +1186,7 @@ def tearDown(self): ) def test_simple_semitotals_all_local_vars(self, method): prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model mask = np.array( [[1, 0, 0, 1, 1], @@ -1227,7 +1227,7 @@ def test_simple_semitotals_all_local_vars(self, method): # now create a second problem and use the static coloring prob = Problem(coloring_dir=self.tempdir) - model = prob.model = Group() + model = prob.model indeps, conns = setup_indeps(isplit, mask.shape[1], 'indeps', 'comp') diff --git a/openmdao/core/tests/test_feature_cache_linear_solution.py b/openmdao/core/tests/test_feature_cache_linear_solution.py index b8253752c3..6618a32c99 100644 --- a/openmdao/core/tests/test_feature_cache_linear_solution.py +++ b/openmdao/core/tests/test_feature_cache_linear_solution.py @@ -5,15 +5,16 @@ import unittest from copy import deepcopy from six.moves import cStringIO + import numpy as np import scipy from scipy.sparse.linalg import gmres -from openmdao.api import Problem, Group, ImplicitComponent, IndepVarComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -class CacheLinearTestCase(unittest.TestCase): +class CacheLinearTestCase(unittest.TestCase): def test_feature_cache_linear(self): @@ -22,10 +23,10 @@ def test_feature_cache_linear(self): import scipy from scipy.sparse.linalg import gmres - from openmdao.api import ImplicitComponent, Group, IndepVarComp, Problem + import openmdao.api as om - class QuadraticComp(ImplicitComponent): + class QuadraticComp(om.ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. @@ -88,9 +89,8 @@ def solve_linear(self, d_outputs, d_residuals, mode): else: d_residuals['states'] = gmres(self.state_jac, d_outputs['states'], x0=d_residuals['states'], atol='legacy')[0] - p = Problem() - p.model = Group() - indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['a', 'b', 'c']) + p = om.Problem() + indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['a', 'b', 'c']) indeps.add_output('a', 1.) indeps.add_output('b', 4.) indeps.add_output('c', 1.) @@ -113,6 +113,6 @@ def solve_linear(self, d_outputs, d_residuals, mode): assert_rel_error(self, derivs['states', 'a'], [[-0.02072594],[4.]], 1e-6) -if __name__ == "__main__": +if __name__ == "__main__": unittest.main() diff --git a/openmdao/core/tests/test_getset_vars.py b/openmdao/core/tests/test_getset_vars.py index 67235ee938..804ec71989 100644 --- a/openmdao/core/tests/test_getset_vars.py +++ b/openmdao/core/tests/test_getset_vars.py @@ -21,7 +21,7 @@ def test_no_promotion(self): model.add_subsystem('g', g) p = Problem(model) - p.setup(check=False) + p.setup() # ------------------------------------------------------------------- @@ -66,7 +66,7 @@ def test_with_promotion(self): model.add_subsystem('g', g, promotes=['*']) p = Problem(model) - p.setup(check=False) + p.setup() # ------------------------------------------------------------------- @@ -109,7 +109,7 @@ def test_no_promotion_errors(self): p = Problem() model = p.model model.add_subsystem('g', g) - p.setup(check=False) + p.setup() # ------------------------------------------------------------------- @@ -199,7 +199,7 @@ def test_with_promotion_errors(self): model.add_subsystem('g', g, promotes=['*']) p = Problem(model) - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -274,7 +274,7 @@ def test_nested_promotion_errors(self): model.add_subsystem('g', g) p = Problem(model) - p.setup(check=False) + p.setup() # ------------------------------------------------------------------- @@ -291,7 +291,7 @@ def test_nested_promotion_errors(self): # Repeat test for post final_setup when vectors are allocated. p = Problem(model) - p.setup(check=False) + p.setup() p.final_setup() # ------------------------------------------------------------------- @@ -304,7 +304,7 @@ def test_nested_promotion_errors(self): # Start from a clean state again p = Problem(model) - p.setup(check=False) + p.setup() with self.assertRaises(Exception) as context: self.assertEqual(p['g.x'], 5.0) @@ -327,7 +327,7 @@ def test_nested_promotion_errors(self): # Repeat test for post final_setup when vectors are allocated. p = Problem(model) - p.setup(check=False) + p.setup() p.final_setup() with self.assertRaises(Exception) as context: @@ -352,7 +352,7 @@ def test_nested_promotion_errors(self): model.connect('x', 'g.x') p = Problem(model) - p.setup(check=False) + p.setup() # inputs (g.x is connected to x) p['g.x'] = 5.0 @@ -362,7 +362,7 @@ def test_nested_promotion_errors(self): # Repeat test for post final_setup when vectors are allocated. p = Problem(model) - p.setup(check=False) + p.setup() p.final_setup() # inputs (g.x is connected to x) @@ -372,7 +372,7 @@ def test_nested_promotion_errors(self): # Final test, the getitem p = Problem(model) - p.setup(check=False) + p.setup() with self.assertRaises(Exception) as context: self.assertEqual(p['g.x'], 5.0) @@ -389,7 +389,7 @@ def test_nested_promotion_errors(self): # Repeat test for post final_setup when vectors are allocated. p = Problem(model) - p.setup(check=False) + p.setup() p.final_setup() with self.assertRaises(Exception) as context: diff --git a/openmdao/core/tests/test_group.py b/openmdao/core/tests/test_group.py index 0dfcd38f36..163184571b 100644 --- a/openmdao/core/tests/test_group.py +++ b/openmdao/core/tests/test_group.py @@ -1,12 +1,14 @@ +""" +Unit tests for Group. +""" from __future__ import print_function +import itertools import unittest from six import assertRaisesRegex, iteritems from six.moves import range -import itertools - import numpy as np try: @@ -14,42 +16,41 @@ except ImportError: from openmdao.utils.assert_utils import SkipParameterized as parameterized -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ExplicitComponent, \ - NonlinearRunOnce, NonLinearRunOnce, BalanceComp, NewtonSolver, DirectSolver -from openmdao.utils.assert_utils import assert_rel_error, assert_warning +import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis2 +from openmdao.utils.assert_utils import assert_rel_error, assert_warning -class SimpleGroup(Group): +class SimpleGroup(om.Group): def __init__(self): super(SimpleGroup, self).__init__() - self.add_subsystem('comp1', IndepVarComp('x', 5.0)) - self.add_subsystem('comp2', ExecComp('b=2*a')) + self.add_subsystem('comp1', om.IndepVarComp('x', 5.0)) + self.add_subsystem('comp2', om.ExecComp('b=2*a')) self.connect('comp1.x', 'comp2.a') -class BranchGroup(Group): +class BranchGroup(om.Group): def __init__(self): super(BranchGroup, self).__init__() - b1 = self.add_subsystem('Branch1', Group()) - g1 = b1.add_subsystem('G1', Group()) - g2 = g1.add_subsystem('G2', Group()) - g2.add_subsystem('comp1', ExecComp('b=2.0*a', a=3.0, b=6.0)) + b1 = self.add_subsystem('Branch1', om.Group()) + g1 = b1.add_subsystem('G1', om.Group()) + g2 = g1.add_subsystem('G2', om.Group()) + g2.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0)) - b2 = self.add_subsystem('Branch2', Group()) - g3 = b2.add_subsystem('G3', Group()) - g3.add_subsystem('comp2', ExecComp('b=3.0*a', a=4.0, b=12.0)) + b2 = self.add_subsystem('Branch2', om.Group()) + g3 = b2.add_subsystem('G3', om.Group()) + g3.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0)) -class SetOrderGroup(Group): +class SetOrderGroup(om.Group): def setup(self): - self.add_subsystem('C1', ExecComp('y=2.0*x')) - self.add_subsystem('C2', ExecComp('y=2.0*x')) - self.add_subsystem('C3', ExecComp('y=2.0*x')) + self.add_subsystem('C1', om.ExecComp('y=2.0*x')) + self.add_subsystem('C2', om.ExecComp('y=2.0*x')) + self.add_subsystem('C3', om.ExecComp('y=2.0*x')) self.set_order(['C1', 'C3', 'C2']) @@ -57,7 +58,7 @@ def setup(self): self.connect('C3.y', 'C2.x') -class ReportOrderComp(ExplicitComponent): +class ReportOrderComp(om.ExplicitComponent): def __init__(self, order_list): super(ReportOrderComp, self).__init__() self._order_list = order_list @@ -73,9 +74,9 @@ def compute(self, inputs, outputs): class TestGroup(unittest.TestCase): def test_add_subsystem_class(self): - p = Problem() + p = om.Problem() try: - p.model.add_subsystem('comp', IndepVarComp) + p.model.add_subsystem('comp', om.IndepVarComp) except TypeError as err: self.assertEqual(str(err), "Subsystem 'comp' should be an instance, " "but a class object was found.") @@ -84,32 +85,32 @@ def test_add_subsystem_class(self): def test_same_sys_name(self): """Test error checking for the case where we add two subsystems with the same name.""" - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp('x', 5.0)) - p.model.add_subsystem('comp2', ExecComp('b=2*a')) + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0)) + p.model.add_subsystem('comp2', om.ExecComp('b=2*a')) try: - p.model.add_subsystem('comp2', ExecComp('b=2*a')) + p.model.add_subsystem('comp2', om.ExecComp('b=2*a')) except Exception as err: self.assertEqual(str(err), "Subsystem name 'comp2' is already used.") else: self.fail('Exception expected.') def test_deprecated_runonce(self): - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('x', 5.0)) - p.model.add_subsystem('comp', ExecComp('b=2*a')) + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('x', 5.0)) + p.model.add_subsystem('comp', om.ExecComp('b=2*a')) msg = "NonLinearRunOnce is deprecated. Use NonlinearRunOnce instead." with assert_warning(DeprecationWarning, msg): - p.model.nonlinear_solver = NonLinearRunOnce() + p.model.nonlinear_solver = om.NonLinearRunOnce() def test_group_simple(self): - from openmdao.api import ExecComp, Problem + import openmdao.api as om - p = Problem() - p.model.add_subsystem('comp1', ExecComp('b=2.0*a', a=3.0, b=6.0)) + p = om.Problem() + p.model.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0)) p.setup() @@ -117,8 +118,8 @@ def test_group_simple(self): self.assertEqual(p['comp1.b'], 6.0) def test_group_add(self): - model = Group() - ecomp = ExecComp('b=2.0*a', a=3.0, b=6.0) + model = om.Group() + ecomp = om.ExecComp('b=2.0*a', a=3.0, b=6.0) msg = "The 'add' method provides backwards compatibility with OpenMDAO <= 1.x ; " \ "use 'add_subsystem' instead." @@ -129,12 +130,12 @@ def test_group_add(self): self.assertTrue(ecomp is comp1) def test_group_simple_promoted(self): - from openmdao.api import ExecComp, Problem, IndepVarComp + import openmdao.api as om - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('a', 3.0), + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('a', 3.0), promotes_outputs=['a']) - p.model.add_subsystem('comp1', ExecComp('b=2.0*a'), + p.model.add_subsystem('comp1', om.ExecComp('b=2.0*a'), promotes_inputs=['a']) p.setup() @@ -144,10 +145,10 @@ def test_group_simple_promoted(self): self.assertEqual(p['comp1.b'], 6.0) def test_inner_connect_w_extern_promote(self): - p = Problem() - g = p.model.add_subsystem('g', Group(), promotes_inputs=['c0.x']) - g.add_subsystem('ivc', IndepVarComp('x', 2.)) - g.add_subsystem('c0', ExecComp('y = 2*x')) + p = om.Problem() + g = p.model.add_subsystem('g', om.Group(), promotes_inputs=['c0.x']) + g.add_subsystem('ivc', om.IndepVarComp('x', 2.)) + g.add_subsystem('c0', om.ExecComp('y = 2*x')) g.connect('ivc.x', 'c0.x') p.setup() @@ -163,11 +164,11 @@ def test_inner_connect_w_extern_promote(self): self.assertEqual(mans, [('c0.x', 'g')]) def test_inner_connect_w_2extern_promotes(self): - p = Problem() - g0 = p.model.add_subsystem('g0', Group(), promotes_inputs=['c0.x']) - g = g0.add_subsystem('g', Group(), promotes_inputs=['c0.x']) - g.add_subsystem('ivc', IndepVarComp('x', 2.)) - g.add_subsystem('c0', ExecComp('y = 2*x')) + p = om.Problem() + g0 = p.model.add_subsystem('g0', om.Group(), promotes_inputs=['c0.x']) + g = g0.add_subsystem('g', om.Group(), promotes_inputs=['c0.x']) + g.add_subsystem('ivc', om.IndepVarComp('x', 2.)) + g.add_subsystem('c0', om.ExecComp('y = 2*x')) g.connect('ivc.x', 'c0.x') p.setup() @@ -183,17 +184,17 @@ def test_inner_connect_w_2extern_promotes(self): self.assertEqual(mans, [('c0.x', 'g0.g')]) def test_group_rename_connect(self): - from openmdao.api import Problem, IndepVarComp, ExecComp + import openmdao.api as om - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('aa', 3.0), + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('aa', 3.0), promotes=['aa']) - p.model.add_subsystem('comp1', ExecComp('b=2.0*aa'), + p.model.add_subsystem('comp1', om.ExecComp('b=2.0*aa'), promotes_inputs=['aa']) # here we alias 'a' to 'aa' so that it will be automatically # connected to the independent variable 'aa'. - p.model.add_subsystem('comp2', ExecComp('b=3.0*a'), + p.model.add_subsystem('comp2', om.ExecComp('b=3.0*a'), promotes_inputs=[('a', 'aa')]) p.setup() @@ -203,13 +204,13 @@ def test_group_rename_connect(self): self.assertEqual(p['comp2.b'], 9.0) def test_subsys_attributes(self): - p = Problem() + p = om.Problem() - class MyGroup(Group): + class MyGroup(om.Group): def setup(self): # two subsystems added during setup - self.add_subsystem('comp1', ExecComp('b=2.0*a', a=3.0, b=6.0)) - self.add_subsystem('comp2', ExecComp('b=3.0*a', a=4.0, b=12.0)) + self.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0)) + self.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0)) # subsystems become attributes my_group = p.model.add_subsystem('gg', MyGroup()) @@ -228,25 +229,25 @@ def setup(self): # name cannot start with an underscore with self.assertRaises(Exception) as err: - p.model.add_subsystem('_bad_name', Group()) + p.model.add_subsystem('_bad_name', om.Group()) self.assertEqual(str(err.exception), "'_bad_name' is not a valid system name.") # 'name', 'pathname', 'comm' and 'options' are reserved names for reserved in ['name', 'pathname', 'comm', 'options']: with self.assertRaises(Exception) as err: - p.model.add_subsystem(reserved, Group()) + p.model.add_subsystem(reserved, om.Group()) self.assertEqual(str(err.exception), "Group '' already has an attribute '%s'." % reserved) def test_group_nested(self): - from openmdao.api import ExecComp, Problem, Group + import openmdao.api as om - p = Problem() - p.model.add_subsystem('G1', Group()) - p.model.G1.add_subsystem('comp1', ExecComp('b=2.0*a', a=3.0, b=6.0)) - p.model.G1.add_subsystem('comp2', ExecComp('b=3.0*a', a=4.0, b=12.0)) + p = om.Problem() + p.model.add_subsystem('G1', om.Group()) + p.model.G1.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0)) + p.model.G1.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0)) p.setup() @@ -256,10 +257,10 @@ def test_group_nested(self): self.assertEqual(p['G1.comp2.b'], 12.0) def test_group_getsystem_top(self): - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_group import BranchGroup - p = Problem(model=BranchGroup()) + p = om.Problem(model=BranchGroup()) p.setup() c1 = p.model.Branch1.G1.G2.comp1 @@ -269,14 +270,14 @@ def test_group_getsystem_top(self): self.assertEqual(c2.pathname, 'Branch2.G3.comp2') def test_group_nested_promoted1(self): - from openmdao.api import Problem, Group, ExecComp + import openmdao.api as om # promotes from bottom level up 1 - p = Problem() - g1 = p.model.add_subsystem('G1', Group()) - g1.add_subsystem('comp1', ExecComp('b=2.0*a', a=3.0, b=6.0), + p = om.Problem() + g1 = p.model.add_subsystem('G1', om.Group()) + g1.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0), promotes_inputs=['a'], promotes_outputs=['b']) - g1.add_subsystem('comp2', ExecComp('b=3.0*a', a=4.0, b=12.0), + g1.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0), promotes_inputs=['a']) p.setup() @@ -290,13 +291,13 @@ def test_group_nested_promoted1(self): self.assertEqual(p['G1.comp2.a'], 4.0) def test_group_nested_promoted2(self): - from openmdao.api import Problem, Group, ExecComp + import openmdao.api as om # promotes up from G1 level - p = Problem() - g1 = Group() - g1.add_subsystem('comp1', ExecComp('b=2.0*a', a=3.0, b=6.0)) - g1.add_subsystem('comp2', ExecComp('b=3.0*a', a=4.0, b=12.0)) + p = om.Problem() + g1 = om.Group() + g1.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0)) + g1.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0)) # use glob pattern 'comp?.a' to promote both comp1.a and comp2.a # use glob pattern 'comp?.b' to promote both comp1.b and comp2.b @@ -316,10 +317,10 @@ def test_group_nested_promoted2(self): def test_group_promotes(self): """Promoting a single variable.""" - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp([('a', 2.0), ('x', 5.0)]), + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp([('a', 2.0), ('x', 5.0)]), promotes_outputs=['x']) - p.model.add_subsystem('comp2', ExecComp('y=2*x'), promotes_inputs=['x']) + p.model.add_subsystem('comp2', om.ExecComp('y=2*x'), promotes_inputs=['x']) p.setup() p.set_solver_print(level=0) @@ -330,10 +331,10 @@ def test_group_promotes(self): self.assertEqual(p['comp2.y'], 10) def test_group_renames(self): - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp('x', 5.0), + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0), promotes_outputs=[('x', 'foo')]) - p.model.add_subsystem('comp2', ExecComp('y=2*foo'), promotes_inputs=['foo']) + p.model.add_subsystem('comp2', om.ExecComp('y=2*foo'), promotes_inputs=['foo']) p.setup() p.set_solver_print(level=0) @@ -343,43 +344,43 @@ def test_group_renames(self): self.assertEqual(p['comp2.y'], 10) def test_group_renames_errors_single_string(self): - p = Problem() + p = om.Problem() with self.assertRaises(Exception) as err: - p.model.add_subsystem('comp1', IndepVarComp('x', 5.0), + p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0), promotes_outputs='x') self.assertEqual(str(err.exception), ": promotes must be an iterator of strings and/or tuples.") def test_group_renames_errors_not_found(self): - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp('x', 5.0), + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0), promotes_outputs=[('xx', 'foo')]) - p.model.add_subsystem('comp2', ExecComp('y=2*foo'), promotes_inputs=['foo']) + p.model.add_subsystem('comp2', om.ExecComp('y=2*foo'), promotes_inputs=['foo']) with self.assertRaises(Exception) as err: - p.setup(check=False) + p.setup() self.assertEqual(str(err.exception), "comp1: 'promotes_outputs' failed to find any matches for " "the following names or patterns: ['xx'].") def test_group_renames_errors_bad_tuple(self): - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp('x', 5.0), + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0), promotes_outputs=[('x', 'foo', 'bar')]) - p.model.add_subsystem('comp2', ExecComp('y=2*foo'), promotes_inputs=['foo']) + p.model.add_subsystem('comp2', om.ExecComp('y=2*foo'), promotes_inputs=['foo']) with self.assertRaises(Exception) as err: - p.setup(check=False) + p.setup() self.assertEqual(str(err.exception), "when adding subsystem 'comp1', entry '('x', 'foo', 'bar')' " "is not a string or tuple of size 2") def test_group_promotes_multiple(self): """Promoting multiple variables.""" - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp([('a', 2.0), ('x', 5.0)]), + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp([('a', 2.0), ('x', 5.0)]), promotes_outputs=['a', 'x']) - p.model.add_subsystem('comp2', ExecComp('y=2*x'), + p.model.add_subsystem('comp2', om.ExecComp('y=2*x'), promotes_inputs=['x']) p.setup() @@ -392,10 +393,10 @@ def test_group_promotes_multiple(self): def test_group_promotes_all(self): """Promoting all variables with asterisk.""" - p = Problem() - p.model.add_subsystem('comp1', IndepVarComp([('a', 2.0), ('x', 5.0)]), + p = om.Problem() + p.model.add_subsystem('comp1', om.IndepVarComp([('a', 2.0), ('x', 5.0)]), promotes_outputs=['*']) - p.model.add_subsystem('comp2', ExecComp('y=2*x'), + p.model.add_subsystem('comp2', om.ExecComp('y=2*x'), promotes_inputs=['x']) p.setup() @@ -408,9 +409,9 @@ def test_group_promotes_all(self): def test_group_promotes2(self): - class Sellar(Group): + class Sellar(om.Group): def setup(self): - dv = self.add_subsystem('des_vars', IndepVarComp(), promotes=['*']) + dv = self.add_subsystem('des_vars', om.IndepVarComp(), promotes=['*']) dv.add_output('x', 1.0) dv.add_output('z', np.array([5.0, 2.0])) @@ -418,32 +419,32 @@ def setup(self): promotes_inputs=['y1'], promotes_outputs=['foo']) self.add_subsystem('d2', SellarDis2()) - p = Problem() + p = om.Problem() p.model = Sellar() with self.assertRaises(Exception) as err: - p.setup(check=False) + p.setup() self.assertEqual(str(err.exception), "d1: 'promotes_outputs' failed to find any matches for " "the following names or patterns: ['foo'].") def test_group_nested_conn(self): """Example of adding subsystems and issuing connections with nested groups.""" - g1 = Group() - c1_1 = g1.add_subsystem('comp1', IndepVarComp('x', 5.0)) - c1_2 = g1.add_subsystem('comp2', ExecComp('b=2*a')) + g1 = om.Group() + c1_1 = g1.add_subsystem('comp1', om.IndepVarComp('x', 5.0)) + c1_2 = g1.add_subsystem('comp2', om.ExecComp('b=2*a')) g1.connect('comp1.x', 'comp2.a') - g2 = Group() - c2_1 = g2.add_subsystem('comp1', ExecComp('b=2*a')) - c2_2 = g2.add_subsystem('comp2', ExecComp('b=2*a')) + g2 = om.Group() + c2_1 = g2.add_subsystem('comp1', om.ExecComp('b=2*a')) + c2_2 = g2.add_subsystem('comp2', om.ExecComp('b=2*a')) g2.connect('comp1.b', 'comp2.a') - model = Group() + model = om.Group() model.add_subsystem('group1', g1) model.add_subsystem('group2', g2) model.connect('group1.comp2.b', 'group2.comp1.a') - p = Problem(model=model) + p = om.Problem(model=model) p.setup() c1_1 = p.model.group1.comp1 @@ -476,28 +477,28 @@ def test_group_nested_conn(self): self.assertEqual(p['group2.comp2.b'], 40.0) def test_reused_output_promoted_names(self): - prob = Problem() - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0)) - G1 = prob.model.add_subsystem('G1', Group()) - G1.add_subsystem("C1", ExecComp("y=2.0*x"), promotes=['y']) - G1.add_subsystem("C2", ExecComp("y=2.0*x"), promotes=['y']) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0)) + G1 = prob.model.add_subsystem('G1', om.Group()) + G1.add_subsystem("C1", om.ExecComp("y=2.0*x"), promotes=['y']) + G1.add_subsystem("C2", om.ExecComp("y=2.0*x"), promotes=['y']) msg = r"Output name 'y' refers to multiple outputs: \['G1.C1.y', 'G1.C2.y'\]." with assertRaisesRegex(self, Exception, msg): - prob.setup(check=False) + prob.setup() def test_basic_connect_units(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp + import openmdao.api as om - p = Problem() + p = om.Problem() - indep_comp = IndepVarComp() + indep_comp = om.IndepVarComp() indep_comp.add_output('x', np.ones(5), units='ft') - exec_comp = ExecComp('y=sum(x)', - x={'value': np.zeros(5), 'units': 'inch'}, - y={'units': 'inch'}) + exec_comp = om.ExecComp('y=sum(x)', + x={'value': np.zeros(5), 'units': 'inch'}, + y={'units': 'inch'}) p.model.add_subsystem('indep', indep_comp) p.model.add_subsystem('comp1', exec_comp) @@ -513,14 +514,14 @@ def test_basic_connect_units(self): def test_connect_1_to_many(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp + import openmdao.api as om - p = Problem() + p = om.Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5))) - p.model.add_subsystem('C1', ExecComp('y=sum(x)*2.0', x=np.zeros(5))) - p.model.add_subsystem('C2', ExecComp('y=sum(x)*4.0', x=np.zeros(5))) - p.model.add_subsystem('C3', ExecComp('y=sum(x)*6.0', x=np.zeros(5))) + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5))) + p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros(5))) + p.model.add_subsystem('C2', om.ExecComp('y=sum(x)*4.0', x=np.zeros(5))) + p.model.add_subsystem('C3', om.ExecComp('y=sum(x)*6.0', x=np.zeros(5))) p.model.connect('indep.x', ['C1.x', 'C2.x', 'C3.x']) @@ -532,7 +533,7 @@ def test_connect_1_to_many(self): assert_rel_error(self, p['C3.y'], 30.) def test_double_src_indices(self): - class MyComp1(ExplicitComponent): + class MyComp1(om.ExplicitComponent): def setup(self): self.add_input('x', np.ones(3), src_indices=[0, 1, 2]) self.add_output('y', 1.0) @@ -540,14 +541,14 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x'])*2.0 - p = Problem() + p = om.Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5))) + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5))) p.model.add_subsystem('C1', MyComp1()) p.model.connect('indep.x', 'C1.x', src_indices=[1, 0, 2]) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), ": src_indices has been defined in both " "connect('indep.x', 'C1.x') and add_input('C1.x', ...).") @@ -555,13 +556,13 @@ def compute(self, inputs, outputs): def test_connect_src_indices(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp + import openmdao.api as om - p = Problem() + p = om.Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5))) - p.model.add_subsystem('C1', ExecComp('y=sum(x)*2.0', x=np.zeros(3))) - p.model.add_subsystem('C2', ExecComp('y=sum(x)*4.0', x=np.zeros(2))) + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5))) + p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros(3))) + p.model.add_subsystem('C2', om.ExecComp('y=sum(x)*4.0', x=np.zeros(2))) # connect C1.x to the first 3 entries of indep.x p.model.connect('indep.x', 'C1.x', src_indices=[0, 1, 2]) @@ -581,12 +582,12 @@ def test_connect_src_indices(self): def test_connect_src_indices_noflat(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp + import openmdao.api as om - p = Problem() + p = om.Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.arange(12).reshape((4, 3)))) - p.model.add_subsystem('C1', ExecComp('y=sum(x)*2.0', x=np.zeros((2, 2)))) + p.model.add_subsystem('indep', om.IndepVarComp('x', np.arange(12).reshape((4, 3)))) + p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros((2, 2)))) # connect C1.x to entries (0,0), (-1,1), (2,1), (1,1) of indep.x p.model.connect('indep.x', 'C1.x', @@ -601,70 +602,70 @@ def test_connect_src_indices_noflat(self): assert_rel_error(self, p['C1.y'], 42.) def test_promote_not_found1(self): - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5)), + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)), promotes_outputs=['x']) - p.model.add_subsystem('C1', ExecComp('y=x'), promotes_inputs=['x']) - p.model.add_subsystem('C2', ExecComp('y=x'), promotes_outputs=['x*']) + p.model.add_subsystem('C1', om.ExecComp('y=x'), promotes_inputs=['x']) + p.model.add_subsystem('C2', om.ExecComp('y=x'), promotes_outputs=['x*']) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), "C2: 'promotes_outputs' failed to find any matches for " "the following names or patterns: ['x*'].") def test_promote_not_found2(self): - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5)), + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)), promotes_outputs=['x']) - p.model.add_subsystem('C1', ExecComp('y=x'), promotes_inputs=['x']) - p.model.add_subsystem('C2', ExecComp('y=x'), promotes_inputs=['xx']) + p.model.add_subsystem('C1', om.ExecComp('y=x'), promotes_inputs=['x']) + p.model.add_subsystem('C2', om.ExecComp('y=x'), promotes_inputs=['xx']) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), "C2: 'promotes_inputs' failed to find any matches for " "the following names or patterns: ['xx'].") def test_promote_not_found3(self): - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5)), + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)), promotes_outputs=['x']) - p.model.add_subsystem('C1', ExecComp('y=x'), promotes=['x']) - p.model.add_subsystem('C2', ExecComp('y=x'), promotes=['xx']) + p.model.add_subsystem('C1', om.ExecComp('y=x'), promotes=['x']) + p.model.add_subsystem('C2', om.ExecComp('y=x'), promotes=['xx']) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), "C2: 'promotes' failed to find any matches for " "the following names or patterns: ['xx'].") def test_missing_promote_var(self): - p = Problem() + p = om.Problem() - indep_var_comp = IndepVarComp('z', val=2.) + indep_var_comp = om.IndepVarComp('z', val=2.) p.model.add_subsystem('indep_vars', indep_var_comp, promotes=['*']) - p.model.add_subsystem('d1', ExecComp("y1=z+bar"), + p.model.add_subsystem('d1', om.ExecComp("y1=z+bar"), promotes_inputs=['z', 'foo']) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), "d1: 'promotes_inputs' failed to find any matches for " "the following names or patterns: ['foo'].") def test_missing_promote_var2(self): - p = Problem() + p = om.Problem() - indep_var_comp = IndepVarComp('z', val=2.) + indep_var_comp = om.IndepVarComp('z', val=2.) p.model.add_subsystem('indep_vars', indep_var_comp, promotes=['*']) - p.model.add_subsystem('d1', ExecComp("y1=z+bar"), + p.model.add_subsystem('d1', om.ExecComp("y1=z+bar"), promotes_outputs=['y1', 'blammo', ('bar', 'blah')]) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), "d1: 'promotes_outputs' failed to find any matches for " "the following names or patterns: ['bar', 'blammo'].") @@ -672,9 +673,9 @@ def test_missing_promote_var2(self): def test_promote_src_indices(self): import numpy as np - from openmdao.api import ExplicitComponent, Problem, IndepVarComp + import openmdao.api as om - class MyComp1(ExplicitComponent): + class MyComp1(om.ExplicitComponent): def setup(self): # this input will connect to entries 0, 1, and 2 of its source self.add_input('x', np.ones(3), src_indices=[0, 1, 2]) @@ -683,7 +684,7 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x'])*2.0 - class MyComp2(ExplicitComponent): + class MyComp2(om.ExplicitComponent): def setup(self): # this input will connect to entries 3 and 4 of its source self.add_input('x', np.ones(2), src_indices=[3, 4]) @@ -692,11 +693,11 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x'])*4.0 - p = Problem() + p = om.Problem() # by promoting the following output and inputs to 'x', they will # be automatically connected - p.model.add_subsystem('indep', IndepVarComp('x', np.ones(5)), + p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp1(), promotes_inputs=['x']) p.model.add_subsystem('C2', MyComp2(), promotes_inputs=['x']) @@ -712,9 +713,9 @@ def compute(self, inputs, outputs): def test_promote_src_indices_nonflat(self): import numpy as np - from openmdao.api import ExplicitComponent, Problem, IndepVarComp + import openmdao.api as om - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): # We want to pull the following 4 values out of the source: # [(0,0), (3,1), (2,1), (1,1)]. @@ -732,12 +733,12 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x']) - p = Problem() + p = om.Problem() # by promoting the following output and inputs to 'x', they will # be automatically connected p.model.add_subsystem('indep', - IndepVarComp('x', np.arange(12).reshape((4, 3))), + om.IndepVarComp('x', np.arange(12).reshape((4, 3))), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x']) @@ -751,7 +752,7 @@ def compute(self, inputs, outputs): assert_rel_error(self, p['C1.y'], 21.) def test_promote_src_indices_nonflat_to_scalars(self): - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x', 1.0, src_indices=[(3, 1)], shape=(1,)) self.add_output('y', 1.0) @@ -759,10 +760,10 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = inputs['x']*2.0 - p = Problem() + p = om.Problem() p.model.add_subsystem('indep', - IndepVarComp('x', np.arange(12).reshape((4, 3))), + om.IndepVarComp('x', np.arange(12).reshape((4, 3))), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x']) @@ -773,7 +774,7 @@ def compute(self, inputs, outputs): assert_rel_error(self, p['C1.y'], 20.) def test_promote_src_indices_nonflat_error(self): - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x', 1.0, src_indices=[(3, 1)]) self.add_output('y', 1.0) @@ -781,15 +782,15 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x']) - p = Problem() + p = om.Problem() p.model.add_subsystem('indep', - IndepVarComp('x', np.arange(12).reshape((4, 3))), + om.IndepVarComp('x', np.arange(12).reshape((4, 3))), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x']) with self.assertRaises(Exception) as context: - p.setup(check=False) + p.setup() self.assertEqual(str(context.exception), "src_indices for 'x' is not flat, so its input shape " "must be provided. src_indices may contain an extra " @@ -806,7 +807,7 @@ def compute(self, inputs, outputs): def test_promote_src_indices_param(self, src_info, tgt_shape): src_shape, idxvals = src_info - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): if len(tgt_shape) == 1: tshape = None # don't need to set shape if input is flat @@ -828,24 +829,24 @@ def setup(self): def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x']) - p = Problem() + p = om.Problem() p.model.add_subsystem('indep', - IndepVarComp('x', np.arange(12).reshape(src_shape)), + om.IndepVarComp('x', np.arange(12).reshape(src_shape)), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x']) p.set_solver_print(level=0) - p.setup(check=False) + p.setup() p.run_model() assert_rel_error(self, p['C1.x'], np.array([0., 10., 7., 4.]).reshape(tgt_shape)) assert_rel_error(self, p['C1.y'], 21.) def test_set_order_feature(self): - from openmdao.api import Problem, IndepVarComp, ExplicitComponent + import openmdao.api as om - class ReportOrderComp(ExplicitComponent): + class ReportOrderComp(om.ExplicitComponent): """Adds name to list.""" def __init__(self, order_list): @@ -858,10 +859,10 @@ def compute(self, inputs, outputs): # this list will record the execution order of our C1, C2, and C3 components order_list = [] - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', 1.)) + model.add_subsystem('indeps', om.IndepVarComp('x', 1.)) model.add_subsystem('C1', ReportOrderComp(order_list)) model.add_subsystem('C2', ReportOrderComp(order_list)) model.add_subsystem('C3', ReportOrderComp(order_list)) @@ -886,10 +887,10 @@ def compute(self, inputs, outputs): def test_set_order(self): order_list = [] - prob = Problem() + prob = om.Problem() model = prob.model - model.nonlinear_solver = NonlinearRunOnce() - model.add_subsystem('indeps', IndepVarComp('x', 1.)) + model.nonlinear_solver = om.NonlinearRunOnce() + model.add_subsystem('indeps', om.IndepVarComp('x', 1.)) model.add_subsystem('C1', ReportOrderComp(order_list)) model.add_subsystem('C2', ReportOrderComp(order_list)) model.add_subsystem('C3', ReportOrderComp(order_list)) @@ -901,7 +902,7 @@ def test_set_order(self): self.assertEqual(['indeps', 'C1', 'C2', 'C3'], [s.name for s in model._static_subsystems_allprocs]) - prob.setup(check=False) + prob.setup() prob.run_model() self.assertEqual(['C1', 'C2', 'C3'], order_list) @@ -911,7 +912,7 @@ def test_set_order(self): # Big boy rules model.set_order(['indeps', 'C2', 'C1', 'C3']) - prob.setup(check=False) + prob.setup() prob.run_model() self.assertEqual(['C2', 'C1', 'C3'], order_list) @@ -946,26 +947,26 @@ def test_set_order(self): ": Duplicate name(s) found in subsystem order list: ['C1']") def test_set_order_init_subsystems(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', 1.)) + model.add_subsystem('indeps', om.IndepVarComp('x', 1.)) model.add_subsystem('G1', SetOrderGroup()) - prob.setup(check=False) + prob.setup() prob.run_model() # this test passes if it doesn't raise an exception def test_guess_nonlinear_feature(self): - from openmdao.api import Problem, Group, ExecComp, IndepVarComp, BalanceComp, NewtonSolver, DirectSolver + import openmdao.api as om - class Discipline(Group): + class Discipline(om.Group): def setup(self): - self.add_subsystem('comp0', ExecComp('y=x**2')) - self.add_subsystem('comp1', ExecComp('z=2*external_input'), + self.add_subsystem('comp0', om.ExecComp('y=x**2')) + self.add_subsystem('comp1', om.ExecComp('z=2*external_input'), promotes_inputs=['external_input']) - self.add_subsystem('balance', BalanceComp('x', lhs_name='y', rhs_name='z'), + self.add_subsystem('balance', om.BalanceComp('x', lhs_name='y', rhs_name='z'), promotes_outputs=['x']) self.connect('comp0.y', 'balance.y') @@ -973,8 +974,8 @@ def setup(self): self.connect('x', 'comp0.x') - self.nonlinear_solver = NewtonSolver(iprint=2, solve_subsystems=True) - self.linear_solver = DirectSolver() + self.nonlinear_solver = om.NewtonSolver(iprint=2, solve_subsystems=True) + self.linear_solver = om.DirectSolver() def guess_nonlinear(self, inputs, outputs, residuals): # inputs are addressed using full path name, regardless of promotion @@ -986,9 +987,9 @@ def guess_nonlinear(self, inputs, outputs, residuals): # outputs are addressed by the their promoted names outputs['x'] = x_guess # perfect guess should converge in 0 iterations - p = Problem() + p = om.Problem() - p.model.add_subsystem('parameters', IndepVarComp('input_value', 1.)) + p.model.add_subsystem('parameters', om.IndepVarComp('input_value', 1.)) p.model.add_subsystem('discipline', Discipline()) p.model.connect('parameters.input_value', 'discipline.external_input') @@ -1002,14 +1003,14 @@ def guess_nonlinear(self, inputs, outputs, residuals): def test_guess_nonlinear_complex_step(self): - class Discipline(Group): + class Discipline(om.Group): def setup(self): - self.add_subsystem('comp0', ExecComp('y=x**2')) - self.add_subsystem('comp1', ExecComp('z=2*external_input'), + self.add_subsystem('comp0', om.ExecComp('y=x**2')) + self.add_subsystem('comp1', om.ExecComp('z=2*external_input'), promotes_inputs=['external_input']) - self.add_subsystem('balance', BalanceComp('x', lhs_name='y', rhs_name='z'), + self.add_subsystem('balance', om.BalanceComp('x', lhs_name='y', rhs_name='z'), promotes_outputs=['x']) self.connect('comp0.y', 'balance.y') @@ -1017,8 +1018,8 @@ def setup(self): self.connect('x', 'comp0.x') - self.nonlinear_solver = NewtonSolver(iprint=2, solve_subsystems=True) - self.linear_solver = DirectSolver() + self.nonlinear_solver = om.NewtonSolver(iprint=2, solve_subsystems=True) + self.linear_solver = om.DirectSolver() def guess_nonlinear(self, inputs, outputs, residuals): @@ -1034,9 +1035,9 @@ def guess_nonlinear(self, inputs, outputs, residuals): # outputs are addressed by the their promoted names outputs['x'] = x_guess # perfect guess should converge in 0 iterations - p = Problem() + p = om.Problem() - p.model.add_subsystem('parameters', IndepVarComp('input_value', 1.)) + p.model.add_subsystem('parameters', om.IndepVarComp('input_value', 1.)) p.model.add_subsystem('discipline', Discipline()) p.model.connect('parameters.input_value', 'discipline.external_input') @@ -1054,7 +1055,7 @@ def guess_nonlinear(self, inputs, outputs, residuals): assert_rel_error(self, val['rel error'][0], 0.0, 1e-15) -class MyComp(ExplicitComponent): +class MyComp(om.ExplicitComponent): def __init__(self, input_shape, src_indices=None, flat_src_indices=False): super(MyComp, self).__init__() self._input_shape = input_shape @@ -1072,8 +1073,8 @@ def compute(self, inputs, outputs): def src_indices_model(src_shape, tgt_shape, src_indices=None, flat_src_indices=False, promotes=None): - prob = Problem() - prob.model.add_subsystem('indeps', IndepVarComp('x', shape=src_shape), + prob = om.Problem() + prob.model.add_subsystem('indeps', om.IndepVarComp('x', shape=src_shape), promotes=promotes) prob.model.add_subsystem('C1', MyComp(tgt_shape, src_indices=src_indices if promotes else None, @@ -1082,24 +1083,24 @@ def src_indices_model(src_shape, tgt_shape, src_indices=None, flat_src_indices=F if promotes is None: prob.model.connect('indeps.x', 'C1.x', src_indices=src_indices, flat_src_indices=flat_src_indices) - prob.setup(check=False) + prob.setup() return prob class TestConnect(unittest.TestCase): def setUp(self): - prob = Problem(Group()) + prob = om.Problem(om.Group()) - sub = prob.model.add_subsystem('sub', Group()) + sub = prob.model.add_subsystem('sub', om.Group()) - idv = sub.add_subsystem('src', IndepVarComp()) + idv = sub.add_subsystem('src', om.IndepVarComp()) idv.add_output('x', np.arange(15).reshape((5, 3))) # array idv.add_output('s', 3.) # scalar - sub.add_subsystem('tgt', ExecComp('y = x')) - sub.add_subsystem('cmp', ExecComp('z = x')) - sub.add_subsystem('arr', ExecComp('a = x', x=np.zeros(2))) + sub.add_subsystem('tgt', om.ExecComp('y = x')) + sub.add_subsystem('cmp', om.ExecComp('z = x')) + sub.add_subsystem('arr', om.ExecComp('a = x', x=np.zeros(2))) self.sub = sub self.prob = prob @@ -1146,7 +1147,7 @@ def test_invalid_source(self): # because setup is not called until then self.sub.connect('src.z', 'tgt.x', src_indices=[1]) with assertRaisesRegex(self, NameError, msg): - self.prob.setup(check=False) + self.prob.setup() def test_invalid_target(self): msg = "Input 'tgt.z' does not exist for connection " + \ @@ -1156,7 +1157,7 @@ def test_invalid_target(self): # because setup is not called until then self.sub.connect('src.x', 'tgt.z', src_indices=[1]) with assertRaisesRegex(self, NameError, msg): - self.prob.setup(check=False) + self.prob.setup() def test_connect_within_system(self): msg = "Output and input are in the same System for connection " + \ @@ -1166,23 +1167,23 @@ def test_connect_within_system(self): self.sub.connect('tgt.y', 'tgt.x', src_indices=[1]) def test_connect_within_system_with_promotes(self): - prob = Problem(Group()) + prob = om.Problem() - sub = prob.model.add_subsystem('sub', Group()) - sub.add_subsystem('tgt', ExecComp('y = x'), promotes_outputs=['y']) + sub = prob.model.add_subsystem('sub', om.Group()) + sub.add_subsystem('tgt', om.ExecComp('y = x'), promotes_outputs=['y']) sub.connect('y', 'tgt.x', src_indices=[1]) msg = "Output and input are in the same System for connection " + \ "in 'sub' from 'y' to 'tgt.x'." with assertRaisesRegex(self, RuntimeError, msg): - prob.setup(check=False) + prob.setup() def test_connect_units_with_unitless(self): - prob = Problem(Group()) - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0)) - prob.model.add_subsystem('src', ExecComp('x2 = 2 * x1', x2={'units': 'degC'})) - prob.model.add_subsystem('tgt', ExecComp('y = 3 * x', x={'units': 'unitless'})) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0)) + prob.model.add_subsystem('src', om.ExecComp('x2 = 2 * x1', x2={'units': 'degC'})) + prob.model.add_subsystem('tgt', om.ExecComp('y = 3 * x', x={'units': 'unitless'})) prob.model.connect('px1.x1', 'src.x1') prob.model.connect('src.x2', 'tgt.x') @@ -1191,28 +1192,28 @@ def test_connect_units_with_unitless(self): "to input 'tgt.x' which has no units." with assert_warning(UserWarning, msg): - prob.setup(check=False) + prob.setup() def test_connect_incompatible_units(self): msg = "Output units of 'degC' for 'src.x2' are incompatible " \ "with input units of 'm' for 'tgt.x'." - prob = Problem(Group()) - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0)) - prob.model.add_subsystem('src', ExecComp('x2 = 2 * x1', x2={'units': 'degC'})) - prob.model.add_subsystem('tgt', ExecComp('y = 3 * x', x={'units': 'm'})) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0)) + prob.model.add_subsystem('src', om.ExecComp('x2 = 2 * x1', x2={'units': 'degC'})) + prob.model.add_subsystem('tgt', om.ExecComp('y = 3 * x', x={'units': 'm'})) prob.model.connect('px1.x1', 'src.x1') prob.model.connect('src.x2', 'tgt.x') with assertRaisesRegex(self, RuntimeError, msg): - prob.setup(check=False) + prob.setup() def test_connect_units_with_nounits(self): - prob = Problem(Group()) - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0)) - prob.model.add_subsystem('src', ExecComp('x2 = 2 * x1')) - prob.model.add_subsystem('tgt', ExecComp('y = 3 * x', x={'units': 'degC'})) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0)) + prob.model.add_subsystem('src', om.ExecComp('x2 = 2 * x1')) + prob.model.add_subsystem('tgt', om.ExecComp('y = 3 * x', x={'units': 'degC'})) prob.model.connect('px1.x1', 'src.x1') prob.model.connect('src.x2', 'tgt.x') @@ -1223,17 +1224,17 @@ def test_connect_units_with_nounits(self): "connected to output 'src.x2' which has no units." with assert_warning(UserWarning, msg): - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['tgt.y'], 600.) def test_connect_units_with_nounits_prom(self): - prob = Problem(Group()) - prob.model.add_subsystem('px1', IndepVarComp('x', 100.0), promotes_outputs=['x']) - prob.model.add_subsystem('src', ExecComp('y = 2 * x'), promotes=['x', 'y']) - prob.model.add_subsystem('tgt', ExecComp('z = 3 * y', y={'units': 'degC'}), promotes=['y']) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x', 100.0), promotes_outputs=['x']) + prob.model.add_subsystem('src', om.ExecComp('y = 2 * x'), promotes=['x', 'y']) + prob.model.add_subsystem('tgt', om.ExecComp('z = 3 * y', y={'units': 'degC'}), promotes=['y']) prob.set_solver_print(level=0) @@ -1241,46 +1242,46 @@ def test_connect_units_with_nounits_prom(self): "connected to output 'src.y' which has no units." with assert_warning(UserWarning, msg): - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['tgt.z'], 600.) def test_mix_promotes_types(self): - prob = Problem() - prob.model.add_subsystem('src', ExecComp(['y = 2 * x', 'y2 = 3 * x']), + prob = om.Problem() + prob.model.add_subsystem('src', om.ExecComp(['y = 2 * x', 'y2 = 3 * x']), promotes=['x', 'y'], promotes_outputs=['y2']) with self.assertRaises(RuntimeError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "src: 'promotes' cannot be used at the same time as " "'promotes_inputs' or 'promotes_outputs'.") def test_mix_promotes_types2(self): - prob = Problem() - prob.model.add_subsystem('src', ExecComp(['y = 2 * x', 'y2 = 3 * x2']), + prob = om.Problem() + prob.model.add_subsystem('src', om.ExecComp(['y = 2 * x', 'y2 = 3 * x2']), promotes=['x', 'y'], promotes_inputs=['x2']) with self.assertRaises(RuntimeError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(str(context.exception), "src: 'promotes' cannot be used at the same time as " "'promotes_inputs' or 'promotes_outputs'.") def test_nested_nested_conn(self): - prob = Problem() + prob = om.Problem() root = prob.model - root.add_subsystem('p', IndepVarComp('x', 1.0)) + root.add_subsystem('p', om.IndepVarComp('x', 1.0)) - G1 = root.add_subsystem('G1', Group()) - par1 = G1.add_subsystem('par1', Group()) + G1 = root.add_subsystem('G1', om.Group()) + par1 = G1.add_subsystem('par1', om.Group()) - par1.add_subsystem('c2', ExecComp('y = x * 2.0')) - par1.add_subsystem('c4', ExecComp('y = x * 4.0')) + par1.add_subsystem('c2', om.ExecComp('y = x * 2.0')) + par1.add_subsystem('c4', om.ExecComp('y = x * 4.0')) prob.model.add_design_var('p.x') prob.model.add_constraint('G1.par1.c4.y', upper=0.0) @@ -1288,7 +1289,7 @@ def test_nested_nested_conn(self): root.connect('p.x', 'G1.par1.c2.x') root.connect('G1.par1.c2.y', 'G1.par1.c4.x') - prob.setup(check=False) + prob.setup() prob.run_driver() assert_rel_error(self, prob['G1.par1.c4.y'], 8.0) @@ -1300,12 +1301,12 @@ def test_bad_shapes(self): "'sub.src.s' to 'sub.arr.x'.") with assertRaisesRegex(self, ValueError, msg): - self.prob.setup(check=False) + self.prob.setup() def test_bad_indices_shape(self): - p = Problem() - p.model.add_subsystem('IV', IndepVarComp('x', np.arange(12).reshape((4, 3)))) - p.model.add_subsystem('C1', ExecComp('y=sum(x)*2.0', x=np.zeros((2, 2)))) + p = om.Problem() + p.model.add_subsystem('IV', om.IndepVarComp('x', np.arange(12).reshape((4, 3)))) + p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros((2, 2)))) p.model.connect('IV.x', 'C1.x', src_indices=[(1, 1)]) @@ -1314,7 +1315,7 @@ def test_bad_indices_shape(self): r"shape is \(2.*, 2.*\) but indices are \(1.*, 2.*\).") with assertRaisesRegex(self, ValueError, msg): - p.setup(check=False) + p.setup() def test_bad_indices_dimensions(self): self.sub.connect('src.x', 'arr.x', src_indices=[(2, -1, 2), (2, 2, 2)], @@ -1325,7 +1326,7 @@ def test_bad_indices_dimensions(self): "The source has 2 dimensions but the indices expect 3.") try: - self.prob.setup(check=False) + self.prob.setup() except ValueError as err: self.assertEqual(str(err), msg) else: @@ -1341,7 +1342,7 @@ def test_bad_indices_index(self): "is out of range for source dimension of size 3.") try: - self.prob.setup(check=False) + self.prob.setup() except ValueError as err: self.assertEqual(str(err), msg) else: diff --git a/openmdao/core/tests/test_impl_comp.py b/openmdao/core/tests/test_impl_comp.py index bf29a1c9e7..49228eac61 100644 --- a/openmdao/core/tests/test_impl_comp.py +++ b/openmdao/core/tests/test_impl_comp.py @@ -8,14 +8,13 @@ import numpy as np -from openmdao.api import Problem, Group, ImplicitComponent, IndepVarComp, \ - NewtonSolver, ScipyKrylov, AnalysisError, ExecComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error # Note: The following class definitions are used in feature docs -class QuadraticComp(ImplicitComponent): +class QuadraticComp(om.ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. @@ -114,9 +113,9 @@ def solve_linear(self, d_outputs, d_residuals, mode): class ImplicitCompTestCase(unittest.TestCase): def setUp(self): - group = Group() + group = om.Group() - comp1 = group.add_subsystem('comp1', IndepVarComp()) + comp1 = group.add_subsystem('comp1', om.IndepVarComp()) comp1.add_output('a', 1.0) comp1.add_output('b', -4.0) comp1.add_output('c', 3.0) @@ -132,8 +131,8 @@ def setUp(self): group.connect('comp1.b', 'comp3.b') group.connect('comp1.c', 'comp3.c') - prob = Problem(model=group) - prob.setup(check=False) + prob = om.Problem(model=group) + prob.setup() self.prob = prob @@ -290,23 +289,23 @@ def guess_nonlinear(self, inputs, outputs, resids): # we set it to a value that will take us to the x=3 solution. outputs['x'] = 5.0 - group = Group() + group = om.Group() - group.add_subsystem('pa', IndepVarComp('a', 1.0)) - group.add_subsystem('pb', IndepVarComp('b', 1.0)) - group.add_subsystem('pc', IndepVarComp('c', 1.0)) + group.add_subsystem('pa', om.IndepVarComp('a', 1.0)) + group.add_subsystem('pb', om.IndepVarComp('b', 1.0)) + group.add_subsystem('pc', om.IndepVarComp('c', 1.0)) group.add_subsystem('comp2', ImpWithInitial()) group.connect('pa.a', 'comp2.a') group.connect('pb.b', 'comp2.b') group.connect('pc.c', 'comp2.c') - prob = Problem(model=group) - group.nonlinear_solver = NewtonSolver() + prob = om.Problem(model=group) + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['solve_subsystems'] = True group.nonlinear_solver.options['max_sub_solves'] = 1 - group.linear_solver = ScipyKrylov() + group.linear_solver = om.ScipyKrylov() - prob.setup(check=False) + prob.setup() prob['pa.a'] = 1. prob['pb.b'] = -4. @@ -320,7 +319,7 @@ def guess_nonlinear(self, inputs, outputs, resids): def test_guess_nonlinear_complex_step(self): - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): """ An implicit component to solve the quadratic equation: x^2 - 4x + 3 (solutions at x=1 and x=3) @@ -361,16 +360,16 @@ def guess_nonlinear(self, inputs, outputs, resids): # Here we set it to a value that will take us to the x=3 solution. outputs['x'] = 5.0 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('a', 1.0) indep.add_output('b', -4.0) indep.add_output('c', 3.0) model.add_subsystem('p', indep) model.add_subsystem('comp', ImpWithInitial()) - model.add_subsystem('fn', ExecComp(['y = .03*a*x*x - .04*a*a*b*x - c'])) + model.add_subsystem('fn', om.ExecComp(['y = .03*a*x*x - .04*a*a*b*x - c'])) model.connect('p.a', 'comp.a') model.connect('p.a', 'fn.a') @@ -378,11 +377,11 @@ def guess_nonlinear(self, inputs, outputs, resids): model.connect('p.c', 'fn.c') model.connect('comp.x', 'fn.x') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() model.nonlinear_solver.options['rtol'] = 1e-12 model.nonlinear_solver.options['atol'] = 1e-12 model.nonlinear_solver.options['maxiter'] = 15 - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() prob.setup(force_alloc_complex=True) prob.run_model() @@ -397,7 +396,7 @@ def guess_nonlinear(self, inputs, outputs, resids): def test_guess_nonlinear_transfer(self): # Test that data is transfered to a component before calling guess_nonlinear. - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): def setup(self): self.add_input('x', 3.0) @@ -415,20 +414,20 @@ def guess_nonlinear(self, inputs, outputs, resids): # Passthrough outputs['y'] = inputs['x'] - group = Group() + group = om.Group() - group.add_subsystem('px', IndepVarComp('x', 77.0)) + group.add_subsystem('px', om.IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') - group.nonlinear_solver = NewtonSolver() + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 - prob = Problem(model=group) + prob = om.Problem(model=group) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['comp2.y'], 77., 1e-5) @@ -436,7 +435,7 @@ def guess_nonlinear(self, inputs, outputs, resids): def test_guess_nonlinear_transfer_subbed(self): # Test that data is transfered to a component before calling guess_nonlinear. - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): def setup(self): self.add_input('x', 3.0) @@ -455,10 +454,10 @@ def guess_nonlinear(self, inputs, outputs, resids): # Passthrough outputs['y'] = inputs['x'] - group = Group() - sub = Group() + group = om.Group() + sub = om.Group() - group.add_subsystem('px', IndepVarComp('x', 77.0)) + group.add_subsystem('px', om.IndepVarComp('x', 77.0)) sub.add_subsystem('comp1', ImpWithInitial()) sub.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'sub.comp1.x') @@ -466,12 +465,12 @@ def guess_nonlinear(self, inputs, outputs, resids): group.add_subsystem('sub', sub) - group.nonlinear_solver = NewtonSolver() + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 - prob = Problem(model=group) + prob = om.Problem(model=group) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['sub.comp2.y'], 77., 1e-5) @@ -479,7 +478,7 @@ def guess_nonlinear(self, inputs, outputs, resids): def test_guess_nonlinear_transfer_subbed2(self): # Test that data is transfered to a component before calling guess_nonlinear. - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): def setup(self): self.add_input('x', 3.0) @@ -498,10 +497,10 @@ def guess_nonlinear(self, inputs, outputs, resids): # Passthrough outputs['y'] = inputs['x'] - group = Group() - sub = Group() + group = om.Group() + sub = om.Group() - group.add_subsystem('px', IndepVarComp('x', 77.0)) + group.add_subsystem('px', om.IndepVarComp('x', 77.0)) sub.add_subsystem('comp1', ImpWithInitial()) sub.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'sub.comp1.x') @@ -509,20 +508,20 @@ def guess_nonlinear(self, inputs, outputs, resids): group.add_subsystem('sub', sub) - sub.nonlinear_solver = NewtonSolver() + sub.nonlinear_solver = om.NewtonSolver() sub.nonlinear_solver.options['maxiter'] = 1 - prob = Problem(model=group) + prob = om.Problem(model=group) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['sub.comp2.y'], 77., 1e-5) def test_guess_nonlinear_feature(self): - from openmdao.api import Problem, Group, ImplicitComponent, IndepVarComp, NewtonSolver, ScipyKrylov + import openmdao.api as om - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): """ An implicit component to solve the quadratic equation: x^2 - 4x + 3 (solutions at x=1 and x=3) @@ -559,13 +558,13 @@ def guess_nonlinear(self, inputs, outputs, resids): # Here we set it to a value that will take us to the x=3 solution. outputs['x'] = 5.0 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('comp', ImpWithInitial()) - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() prob.setup() prob.run_model() @@ -573,7 +572,7 @@ def guess_nonlinear(self, inputs, outputs, resids): assert_rel_error(self, prob['comp.x'], 3.) def test_guess_nonlinear_inputs_read_only(self): - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): def setup(self): self.add_input('x', 3.0) @@ -583,20 +582,20 @@ def guess_nonlinear(self, inputs, outputs, resids): # inputs is read_only, should not be allowed inputs['x'] = 0. - group = Group() + group = om.Group() - group.add_subsystem('px', IndepVarComp('x', 77.0)) + group.add_subsystem('px', om.IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') - group.nonlinear_solver = NewtonSolver() + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 - prob = Problem(model=group) + prob = om.Problem(model=group) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() with self.assertRaises(ValueError) as cm: prob.run_model() @@ -606,38 +605,38 @@ def guess_nonlinear(self, inputs, outputs, resids): "when it is read only.") def test_guess_nonlinear_inputs_read_only_reset(self): - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): def setup(self): self.add_input('x', 3.0) self.add_output('y', 4.0) def guess_nonlinear(self, inputs, outputs, resids): - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - group = Group() + group = om.Group() - group.add_subsystem('px', IndepVarComp('x', 77.0)) + group.add_subsystem('px', om.IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') - group.nonlinear_solver = NewtonSolver() + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 - prob = Problem(model=group) + prob = om.Problem(model=group) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.run_model() # verify read_only status is reset after AnalysisError prob['comp1.x'] = 111. def test_guess_nonlinear_resids_read_only(self): - class ImpWithInitial(ImplicitComponent): + class ImpWithInitial(om.ImplicitComponent): def setup(self): self.add_input('x', 3.0) @@ -647,20 +646,20 @@ def guess_nonlinear(self, inputs, outputs, resids): # inputs is read_only, should not be allowed resids['y'] = 0. - group = Group() + group = om.Group() - group.add_subsystem('px', IndepVarComp('x', 77.0)) + group.add_subsystem('px', om.IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') - group.nonlinear_solver = NewtonSolver() + group.nonlinear_solver = om.NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 - prob = Problem(model=group) + prob = om.Problem(model=group) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() with self.assertRaises(ValueError) as cm: prob.run_model() @@ -678,7 +677,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): super(BadComp, self).apply_nonlinear(inputs, outputs, residuals) inputs['a'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -697,7 +696,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): super(BadComp, self).apply_nonlinear(inputs, outputs, residuals) outputs['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -714,14 +713,14 @@ def test_apply_nonlinear_read_only_reset(self): class BadComp(QuadraticComp): def apply_nonlinear(self, inputs, outputs, residuals): super(BadComp, self).apply_nonlinear(inputs, outputs, residuals) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.model.run_apply_nonlinear() # verify read_only status is reset after AnalysisError @@ -734,7 +733,7 @@ def solve_nonlinear(self, inputs, outputs): super(BadComp, self).solve_nonlinear(inputs, outputs) inputs['a'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() @@ -750,13 +749,13 @@ def test_solve_nonlinear_inputs_read_only_reset(self): class BadComp(QuadraticComp): def solve_nonlinear(self, inputs, outputs): super(BadComp, self).solve_nonlinear(inputs, outputs) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.run_model() # verify read_only status is reset after AnalysisError @@ -768,7 +767,7 @@ def linearize(self, inputs, outputs, partials): super(BadComp, self).linearize(inputs, outputs, partials) inputs['a'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -787,7 +786,7 @@ def linearize(self, inputs, outputs, partials): super(BadComp, self).linearize(inputs, outputs, partials) outputs['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -804,14 +803,14 @@ def test_linearize_read_only_reset(self): class BadComp(QuadraticLinearize): def linearize(self, inputs, outputs, partials): super(BadComp, self).linearize(inputs, outputs, partials) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.model.run_linearize() # verify read_only status is reset after AnalysisError @@ -825,7 +824,7 @@ def apply_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, mode): d_inputs, d_outputs, d_residuals, mode) inputs['a'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -845,7 +844,7 @@ def apply_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, mode): d_inputs, d_outputs, d_residuals, mode) outputs['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -865,7 +864,7 @@ def apply_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, mode): d_inputs, d_outputs, d_residuals, mode) d_inputs['a'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -885,7 +884,7 @@ def apply_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, mode): d_inputs, d_outputs, d_residuals, mode) d_outputs['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -905,7 +904,7 @@ def apply_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, mode): d_inputs, d_outputs, d_residuals, mode) d_residuals['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -923,14 +922,14 @@ class BadComp(QuadraticJacVec): def apply_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, mode): super(BadComp, self).apply_linear(inputs, outputs, d_inputs, d_outputs, d_residuals, mode) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.model.run_apply_linear(['linear'], 'rev') # verify read_only status is reset after AnalysisError @@ -944,7 +943,7 @@ def solve_linear(self, d_outputs, d_residuals, mode): super(BadComp, self).solve_linear(d_outputs, d_residuals, mode) d_outputs['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -964,7 +963,7 @@ def solve_linear(self, d_outputs, d_residuals, mode): super(BadComp, self).solve_linear(d_outputs, d_residuals, mode) d_residuals['x'] = 0. # should not be allowed - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() @@ -982,15 +981,15 @@ def test_solve_linear_read_only_reset(self): class BadComp(QuadraticJacVec): def solve_linear(self, d_outputs, d_residuals, mode): super(BadComp, self).solve_linear(d_outputs, d_residuals, mode) - raise AnalysisError("It's just a scratch.") + raise om.AnalysisError("It's just a scratch.") - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('bad', BadComp()) prob.setup() prob.run_model() prob.model.run_linearize() - with self.assertRaises(AnalysisError): + with self.assertRaises(om.AnalysisError): prob.model.run_solve_linear(['linear'], 'fwd') # verify read_only status is reset after AnalysisError @@ -1000,17 +999,17 @@ def solve_linear(self, d_outputs, d_residuals, mode): class ListFeatureTestCase(unittest.TestCase): def setUp(self): - from openmdao.api import Group, Problem, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_impl_comp import QuadraticComp - group = Group() + group = om.Group() - comp1 = group.add_subsystem('comp1', IndepVarComp()) + comp1 = group.add_subsystem('comp1', om.IndepVarComp()) comp1.add_output('a', 1.0) comp1.add_output('b', 1.0) comp1.add_output('c', 1.0) - sub = group.add_subsystem('sub', Group()) + sub = group.add_subsystem('sub', om.Group()) sub.add_subsystem('comp2', QuadraticComp()) sub.add_subsystem('comp3', QuadraticComp()) @@ -1023,7 +1022,7 @@ def setUp(self): group.connect('comp1.c', 'sub.comp3.c') global prob - prob = Problem(model=group) + prob = om.Problem(model=group) prob.setup() prob['comp1.a'] = 1. @@ -1096,9 +1095,9 @@ def test_list_no_values(self): ]) def test_simple_list_vars_options(self): - from openmdao.api import Group, Problem, IndepVarComp + import openmdao.api as om - class QuadraticComp(ImplicitComponent): + class QuadraticComp(om.ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. @@ -1132,14 +1131,14 @@ def solve_nonlinear(self, inputs, outputs): c = inputs['c'] outputs['x'] = (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a) - group = Group() + group = om.Group() - comp1 = group.add_subsystem('comp1', IndepVarComp()) + comp1 = group.add_subsystem('comp1', om.IndepVarComp()) comp1.add_output('a', 1.0, units='ft') comp1.add_output('b', 1.0, units='inch') comp1.add_output('c', 1.0, units='ft') - sub = group.add_subsystem('sub', Group()) + sub = group.add_subsystem('sub', om.Group()) sub.add_subsystem('comp2', QuadraticComp()) sub.add_subsystem('comp3', QuadraticComp()) @@ -1152,7 +1151,7 @@ def solve_nonlinear(self, inputs, outputs): group.connect('comp1.c', 'sub.comp3.c') global prob - prob = Problem(model=group) + prob = om.Problem(model=group) prob.setup() prob['comp1.a'] = 1. @@ -1198,23 +1197,23 @@ def solve_nonlinear(self, inputs, outputs): ]) def test_list_residuals_with_tol(self): + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarImplicitDis1, SellarImplicitDis2 - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, LinearBlockGS - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 1.0)) model.add_subsystem('d1', SellarImplicitDis1()) model.add_subsystem('d2', SellarImplicitDis2()) model.connect('d1.y1', 'd2.y1') model.connect('d2.y2', 'd1.y2') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() model.nonlinear_solver.options['maxiter'] = 5 - model.linear_solver = ScipyKrylov() - model.linear_solver.precon = LinearBlockGS() + model.linear_solver = om.ScipyKrylov() + model.linear_solver.precon = om.LinearBlockGS() - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=-1) prob.run_model() @@ -1223,7 +1222,7 @@ def test_list_residuals_with_tol(self): print(outputs) -class CacheUsingComp(ImplicitComponent): +class CacheUsingComp(om.ImplicitComponent): def setup(self): self.cache = {} self.lin_sol_count = 0 @@ -1274,8 +1273,8 @@ def solve_linear(self, d_outputs, d_residuals, mode): class CacheLinSolutionTestCase(unittest.TestCase): def test_caching_fwd(self): - p = Problem() - p.model.add_subsystem('indeps', IndepVarComp('x', val=np.arange(10, dtype=float))) + p = om.Problem() + p.model.add_subsystem('indeps', om.IndepVarComp('x', val=np.arange(10, dtype=float))) p.model.add_subsystem('C1', CacheUsingComp()) p.model.connect('indeps.x', 'C1.x') p.model.add_design_var('indeps.x', cache_linear_solution=True) @@ -1294,8 +1293,8 @@ def test_caching_fwd(self): p.driver._compute_totals(of=['C1.y'], wrt=['indeps.x']) def test_caching_rev(self): - p = Problem() - p.model.add_subsystem('indeps', IndepVarComp('x', val=np.arange(10, dtype=float))) + p = om.Problem() + p.model.add_subsystem('indeps', om.IndepVarComp('x', val=np.arange(10, dtype=float))) p.model.add_subsystem('C1', CacheUsingComp()) p.model.connect('indeps.x', 'C1.x') p.model.add_design_var('indeps.x') diff --git a/openmdao/core/tests/test_indep_var_comp.py b/openmdao/core/tests/test_indep_var_comp.py index b7b74e2ebd..d2da916831 100644 --- a/openmdao/core/tests/test_indep_var_comp.py +++ b/openmdao/core/tests/test_indep_var_comp.py @@ -3,7 +3,7 @@ import unittest -from openmdao.api import Problem, IndepVarComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error @@ -11,10 +11,10 @@ class TestIndepVarComp(unittest.TestCase): def test_simple(self): """Define one independent variable and set its value.""" - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - comp = IndepVarComp('indep_var') - prob = Problem(comp).setup(check=False) + comp = om.IndepVarComp('indep_var') + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var'], 1.0) @@ -23,19 +23,19 @@ def test_simple(self): def test_simple_default(self): """Define one independent variable with a default value.""" - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - comp = IndepVarComp('indep_var', val=2.0) - prob = Problem(comp).setup(check=False) + comp = om.IndepVarComp('indep_var', val=2.0) + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var'], 2.0) def test_simple_kwargs(self): """Define one independent variable with a default value and additional options.""" - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - comp = IndepVarComp('indep_var', val=2.0, units='m', lower=0, upper=10) - prob = Problem(comp).setup(check=False) + comp = om.IndepVarComp('indep_var', val=2.0, units='m', lower=0, upper=10) + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var'], 2.0) @@ -43,62 +43,62 @@ def test_simple_array(self): """Define one independent array variable.""" import numpy as np - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om array = np.array([ [1., 2.], [3., 4.], ]) - comp = IndepVarComp('indep_var', val=array) - prob = Problem(comp).setup(check=False) + comp = om.IndepVarComp('indep_var', val=array) + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var'], array) def test_multiple_default(self): """Define two independent variables at once.""" - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - comp = IndepVarComp(( + comp = om.IndepVarComp(( ('indep_var_1', 1.0), ('indep_var_2', 2.0), )) - prob = Problem(comp).setup(check=False) + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var_1'], 1.0) assert_rel_error(self, prob['indep_var_2'], 2.0) def test_multiple_kwargs(self): """Define two independent variables at once and additional options.""" - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - comp = IndepVarComp(( + comp = om.IndepVarComp(( ('indep_var_1', 1.0, {'lower': 0, 'upper': 10}), ('indep_var_2', 2.0, {'lower': 1., 'upper': 20}), )) - prob = Problem(comp).setup(check=False) + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var_1'], 1.0) assert_rel_error(self, prob['indep_var_2'], 2.0) def test_add_output(self): """Define two independent variables using the add_output method.""" - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('indep_var_1', val=1.0, lower=0, upper=10) comp.add_output('indep_var_2', val=2.0, lower=1, upper=20) - prob = Problem(comp).setup(check=False) + prob = om.Problem(comp).setup() assert_rel_error(self, prob['indep_var_1'], 1.0) assert_rel_error(self, prob['indep_var_2'], 2.0) def test_error_novars(self): try: - prob = Problem(IndepVarComp()).setup(check=False) + prob = om.Problem(om.IndepVarComp()).setup() except Exception as err: self.assertEqual(str(err), "No outputs (independent variables) have been declared for " @@ -109,11 +109,11 @@ def test_error_novars(self): def test_error_badtup(self): try: - comp = IndepVarComp(( + comp = om.IndepVarComp(( ('indep_var_1', 1.0, {'lower': 0, 'upper': 10}), 'indep_var_2', )) - prob = Problem(comp).setup(check=False) + prob = om.Problem(comp).setup() except Exception as err: self.assertEqual(str(err), "IndepVarComp init: arg indep_var_2 must be a tuple of the " @@ -123,8 +123,8 @@ def test_error_badtup(self): def test_error_bad_arg(self): try: - comp = IndepVarComp(1.0) - prob = Problem(comp).setup(check=False) + comp = om.IndepVarComp(1.0) + prob = om.Problem(comp).setup() except Exception as err: self.assertEqual(str(err), "first argument to IndepVarComp init must be either of type " @@ -134,10 +134,10 @@ def test_error_bad_arg(self): self.fail('Exception expected.') def test_add_output_type_bug(self): - prob = Problem() + prob = om.Problem() model = prob.model - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output('x1', val=[1, 2, 3], lower=0, upper=10) model.add_subsystem('p', ivc) diff --git a/openmdao/core/tests/test_matmat.py b/openmdao/core/tests/test_matmat.py index 800857eaed..abe27e25d5 100644 --- a/openmdao/core/tests/test_matmat.py +++ b/openmdao/core/tests/test_matmat.py @@ -4,12 +4,11 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent, \ - ScipyOptimizeDriver, ImplicitComponent, LinearBlockGS +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -class QuadraticCompVectorized(ImplicitComponent): +class QuadraticCompVectorized(om.ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. @@ -79,7 +78,7 @@ def solve_linear(self, d_outputs, d_residuals, mode): d_residuals['x'] = self.inv_jac * d_outputs['x'] -class QCVProblem(Problem): +class QCVProblem(om.Problem): """ A QuadraticCompVectorized problem with configurable component class. """ @@ -89,7 +88,7 @@ def __init__(self, comp_class=QuadraticCompVectorized): model = self.model - comp1 = model.add_subsystem('p', IndepVarComp()) + comp1 = model.add_subsystem('p', om.IndepVarComp()) comp1.add_output('a', np.array([1.0, 2.0, 3.0])) comp1.add_output('b', np.array([2.0, 3.0, 4.0])) comp1.add_output('c', np.array([-1.0, -2.0, -3.0])) @@ -104,10 +103,10 @@ def __init__(self, comp_class=QuadraticCompVectorized): model.add_design_var('p.c', vectorize_derivs=True) model.add_constraint('comp.x', vectorize_derivs=True) - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() -class RectangleCompVectorized(ExplicitComponent): +class RectangleCompVectorized(om.ExplicitComponent): """ A simple Explicit Component that computes the area of a rectangle. """ @@ -283,7 +282,7 @@ def lagrange_matrices(x_disc, x_interp): return Li, Di -class LGLFit(ExplicitComponent): +class LGLFit(om.ExplicitComponent): """ Given values at discretization nodes, provide interpolated values at midpoint nodes and an approximation of arclength. @@ -316,7 +315,7 @@ def compute(self, inputs, outputs): outputs['yp_lgl'] = np.dot(self.D_lgl, inputs['y_lgl'])/np.pi -class DefectComp(ExplicitComponent): +class DefectComp(om.ExplicitComponent): def initialize(self): self.options.declare(name='num_nodes', types=int) @@ -336,7 +335,7 @@ def compute(self, inputs, outputs): outputs['defect'] = inputs['y_truth'] - inputs['y_approx'] -class ArcLengthFunction(ExplicitComponent): +class ArcLengthFunction(om.ExplicitComponent): def initialize(self): self.options.declare(name='num_nodes', types=int) @@ -357,7 +356,7 @@ def compute_partials(self, inputs, partials): partials['f_arclength', 'yp_lgl'] = inputs['yp_lgl'] / np.sqrt(1 + inputs['yp_lgl']**2) -class ArcLengthQuadrature(ExplicitComponent): +class ArcLengthQuadrature(om.ExplicitComponent): """ Computes the arclength of a polynomial segment whose values are given at the LGL nodes. """ @@ -391,7 +390,7 @@ def compute(self, inputs, outputs): outputs['arclength'] = outputs['arclength']*np.pi -class Phase(Group): +class Phase(om.Group): def initialize(self): self.options.declare('order', types=int, default=10) @@ -401,16 +400,16 @@ def setup(self): n = order + 1 # Step 1: Make an indep var comp that provides the approximated values at the LGL nodes. - self.add_subsystem('y_lgl_ivc', IndepVarComp('y_lgl', val=np.zeros(n), desc='values at LGL nodes'), + self.add_subsystem('y_lgl_ivc', om.IndepVarComp('y_lgl', val=np.zeros(n), desc='values at LGL nodes'), promotes_outputs=['y_lgl']) # Step 2: Make an indep var comp that provides the 'truth' values at the midpoint nodes. x_lgl, _ = lgl(n) x_lgl = x_lgl * np.pi # put x_lgl on [-pi, pi] x_mid = (x_lgl[1:] + x_lgl[:-1]) * 0.5 # midpoints on [-pi, pi] - self.add_subsystem('truth', IndepVarComp('y_mid', - val=np.sin(x_mid), - desc='truth values at midpoint nodes')) + self.add_subsystem('truth', om.IndepVarComp('y_mid', + val=np.sin(x_mid), + desc='truth values at midpoint nodes')) # Step 3: Make a polynomial fitting component self.add_subsystem('lgl_fit', LGLFit(num_nodes=n)) @@ -429,7 +428,7 @@ def setup(self): self.connect('arclength_func.f_arclength', 'arclength_quad.f_arclength') -class Summer(ExplicitComponent): +class Summer(om.ExplicitComponent): def initialize(self): self.options.declare('n_phases', types=int) @@ -451,20 +450,20 @@ def compute(self, inputs, outputs): def simple_model(order, dvgroup='pardv', congroup='parc', vectorize=False): n = order + 1 - p = Problem(model=Group()) + p = om.Problem() # Step 1: Make an indep var comp that provides the approximated values at the LGL nodes. - p.model.add_subsystem('y_lgl_ivc', IndepVarComp('y_lgl', val=np.zeros(n), - desc='values at LGL nodes'), + p.model.add_subsystem('y_lgl_ivc', om.IndepVarComp('y_lgl', val=np.zeros(n), + desc='values at LGL nodes'), promotes_outputs=['y_lgl']) # Step 2: Make an indep var comp that provides the 'truth' values at the midpoint nodes. x_lgl, _ = lgl(n) x_lgl = x_lgl * np.pi # put x_lgl on [-pi, pi] x_mid = (x_lgl[1:] + x_lgl[:-1])/2.0 # midpoints on [-pi, pi] - p.model.add_subsystem('truth', IndepVarComp('y_mid', - val=np.sin(x_mid), - desc='truth values at midpoint nodes')) + p.model.add_subsystem('truth', om.IndepVarComp('y_mid', + val=np.sin(x_mid), + desc='truth values at midpoint nodes')) # Step 3: Make a polynomial fitting component p.model.add_subsystem('lgl_fit', LGLFit(num_nodes=n)) @@ -487,7 +486,7 @@ def simple_model(order, dvgroup='pardv', congroup='parc', vectorize=False): p.model.add_constraint('defect.defect', lower=-1e-6, upper=1e-6, parallel_deriv_color=congroup, vectorize_derivs=vectorize) p.model.add_objective('arclength_quad.arclength') - p.driver = ScipyOptimizeDriver() + p.driver = om.ScipyOptimizeDriver() return p, np.sin(x_lgl) @@ -497,7 +496,7 @@ def phase_model(order, nphases, dvgroup='pardv', congroup='parc', vectorize=Fals n = PHASE_ORDER + 1 - p = Problem() + p = om.Problem() # Step 1: Make an indep var comp that provides the approximated values at the LGL nodes. for i in range(N_PHASES): @@ -513,7 +512,7 @@ def phase_model(order, nphases, dvgroup='pardv', congroup='parc', vectorize=Fals p.model.add_subsystem('sum', Summer(n_phases=N_PHASES)) p.model.add_objective('sum.total_arc_length') - p.driver = ScipyOptimizeDriver() + p.driver = om.ScipyOptimizeDriver() x_lgl, _ = lgl(n) x_lgl = x_lgl * np.pi # put x_lgl on [-pi, pi] @@ -526,11 +525,11 @@ class MatMatTestCase(unittest.TestCase): def test_feature_vectorized_derivs(self): import numpy as np - from openmdao.api import ExplicitComponent, IndepVarComp, Problem, ScipyOptimizeDriver + import openmdao.api as om SIZE = 5 - class ExpensiveAnalysis(ExplicitComponent): + class ExpensiveAnalysis(om.ExplicitComponent): def setup(self): @@ -551,7 +550,7 @@ def compute_partials(self, inputs, J): J['f', 'x'] = inputs['y']*inputs['x']**(inputs['y']-1) J['f', 'y'] = (inputs['x']**inputs['y'])*np.log(inputs['x']) - class CheapConstraint(ExplicitComponent): + class CheapConstraint(om.ExplicitComponent): def setup(self): @@ -571,9 +570,9 @@ def compute_partials(self, inputs, J): J['g', 'y'] = 2*inputs['y'] - p = Problem() + p = om.Problem() - dvs = p.model.add_subsystem('des_vars', IndepVarComp(), promotes=['*']) + dvs = p.model.add_subsystem('des_vars', om.IndepVarComp(), promotes=['*']) dvs.add_output('x', 2*np.ones(SIZE)) dvs.add_output('y', 2*np.ones(SIZE)) @@ -589,7 +588,7 @@ def compute_partials(self, inputs, J): p.run_model() - p.driver = ScipyOptimizeDriver() + p.driver = om.ScipyOptimizeDriver() p.run_driver() assert_rel_error(self, p['x'], [0.10000691, 0.1, 0.1, 0.1, 0.1], 1e-5) @@ -654,10 +653,10 @@ def test_phases_multi_rev(self): def test_feature_declaration(self): # Tests the code that shows the signature for compute_multi_jacvec - prob = Problem() + prob = om.Problem() model = prob.model - comp1 = model.add_subsystem('p', IndepVarComp()) + comp1 = model.add_subsystem('p', om.IndepVarComp()) comp1.add_output('length', np.array([3.0, 4.0, 5.0])) comp1.add_output('width', np.array([1.0, 2.0, 3.0])) @@ -785,7 +784,7 @@ def apply_multi_linear(self, inputs, outputs, d_inputs, d_outputs, d_residuals, "when it is read only.") -class JacVec(ExplicitComponent): +class JacVec(om.ExplicitComponent): def __init__(self, size): super(JacVec, self).__init__() @@ -822,10 +821,10 @@ def compute_multi_jacvec_product(self, inputs, d_inputs, d_outputs, mode): class ComputeMultiJacVecTestCase(unittest.TestCase): def setup_model(self, size, comp_class, vectorize, mode): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('px', IndepVarComp('x', val=(np.arange(5, dtype=float) + 1.) * 3.0)) - model.add_subsystem('py', IndepVarComp('y', val=(np.arange(5, dtype=float) + 1.) * 2.0)) + model.add_subsystem('px', om.IndepVarComp('x', val=(np.arange(5, dtype=float) + 1.) * 3.0)) + model.add_subsystem('py', om.IndepVarComp('y', val=(np.arange(5, dtype=float) + 1.) * 2.0)) model.add_subsystem('comp', comp_class(size)) model.connect('px.x', 'comp.x') diff --git a/openmdao/core/tests/test_parallel_derivatives.py b/openmdao/core/tests/test_parallel_derivatives.py index 5f47106cc8..c285df4bbf 100644 --- a/openmdao/core/tests/test_parallel_derivatives.py +++ b/openmdao/core/tests/test_parallel_derivatives.py @@ -11,13 +11,12 @@ import numpy as np -from openmdao.api import Group, ParallelGroup, Problem, IndepVarComp, LinearBlockGS, \ - ExecComp, ExplicitComponent, PETScVector, ScipyKrylov, NonlinearBlockGS -from openmdao.utils.mpi import MPI +import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives, \ SellarDis1withDerivatives, SellarDis2withDerivatives from openmdao.test_suite.groups.parallel_groups import FanOutGrouped, FanInGrouped from openmdao.utils.assert_utils import assert_rel_error +from openmdao.utils.mpi import MPI if MPI: @@ -34,10 +33,10 @@ class ParDerivTestCase(unittest.TestCase): def test_fan_in_serial_sets_rev(self): - prob = Problem() + prob = om.Problem() prob.model = FanInGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x1') prob.model.add_design_var('iv.x2') @@ -55,10 +54,10 @@ def test_fan_in_serial_sets_rev(self): def test_fan_in_serial_sets_fwd(self): - prob = Problem() + prob = om.Problem() prob.model = FanInGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x1') prob.model.add_design_var('iv.x2') @@ -76,10 +75,10 @@ def test_fan_in_serial_sets_fwd(self): def test_fan_out_serial_sets_fwd(self): - prob = Problem() + prob = om.Problem() prob.model = FanOutGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x') prob.model.add_constraint('c2.y', upper=0.0) @@ -97,10 +96,10 @@ def test_fan_out_serial_sets_fwd(self): def test_fan_out_serial_sets_rev(self): - prob = Problem() + prob = om.Problem() prob.model = FanOutGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x') prob.model.add_constraint('c2.y', upper=0.0) @@ -118,10 +117,10 @@ def test_fan_out_serial_sets_rev(self): def test_fan_in_parallel_sets_fwd(self): - prob = Problem() + prob = om.Problem() prob.model = FanInGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x1', parallel_deriv_color='par_dv') prob.model.add_design_var('iv.x2', parallel_deriv_color='par_dv') @@ -140,10 +139,10 @@ def test_fan_in_parallel_sets_fwd(self): def test_debug_print_option_totals_color(self): - prob = Problem() + prob = om.Problem() prob.model = FanInGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x1', parallel_deriv_color='par_dv') prob.model.add_design_var('iv.x2', parallel_deriv_color='par_dv') @@ -176,10 +175,10 @@ def test_debug_print_option_totals_color(self): def test_fan_out_parallel_sets_rev(self): - prob = Problem() + prob = om.Problem() prob.model = FanOutGrouped() - prob.model.linear_solver = LinearBlockGS() - prob.model.sub.linear_solver = LinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + prob.model.sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('iv.x') prob.model.add_constraint('c2.y', upper=0.0, parallel_deriv_color='par_resp') @@ -203,24 +202,24 @@ class DecoupledTestCase(unittest.TestCase): def setup_model(self): asize = self.asize - prob = Problem() + prob = om.Problem() root = prob.model - root.linear_solver = LinearBlockGS() - - Indep1 = root.add_subsystem('Indep1', IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) - Indep2 = root.add_subsystem('Indep2', IndepVarComp('x', np.arange(asize+2, dtype=float)+1.0)) - G1 = root.add_subsystem('G1', ParallelGroup()) - G1.linear_solver = LinearBlockGS() - - c1 = G1.add_subsystem('c1', ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', - x=np.zeros(asize), y=np.zeros(asize))) - c2 = G1.add_subsystem('c2', ExecComp('y = x[:%d] * 2.0' % asize, - x=np.zeros(asize+2), y=np.zeros(asize))) - - Con1 = root.add_subsystem('Con1', ExecComp('y = x * 5.0', - x=np.zeros(asize), y=np.zeros(asize))) - Con2 = root.add_subsystem('Con2', ExecComp('y = x * 4.0', - x=np.zeros(asize), y=np.zeros(asize))) + root.linear_solver = om.LinearBlockGS() + + Indep1 = root.add_subsystem('Indep1', om.IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) + Indep2 = root.add_subsystem('Indep2', om.IndepVarComp('x', np.arange(asize+2, dtype=float)+1.0)) + G1 = root.add_subsystem('G1', om.ParallelGroup()) + G1.linear_solver = om.LinearBlockGS() + + c1 = G1.add_subsystem('c1', om.ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', + x=np.zeros(asize), y=np.zeros(asize))) + c2 = G1.add_subsystem('c2', om.ExecComp('y = x[:%d] * 2.0' % asize, + x=np.zeros(asize+2), y=np.zeros(asize))) + + Con1 = root.add_subsystem('Con1', om.ExecComp('y = x * 5.0', + x=np.zeros(asize), y=np.zeros(asize))) + Con2 = root.add_subsystem('Con2', om.ExecComp('y = x * 4.0', + x=np.zeros(asize), y=np.zeros(asize))) root.connect('Indep1.x', 'G1.c1.x') root.connect('Indep2.x', 'G1.c2.x') root.connect('G1.c1.y', 'Con1.x') @@ -337,22 +336,22 @@ class IndicesTestCase(unittest.TestCase): def setup_model(self, mode): asize = 3 - prob = Problem() + prob = om.Problem() root = prob.model - root.linear_solver = LinearBlockGS() + root.linear_solver = om.LinearBlockGS() - p = root.add_subsystem('p', IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) - G1 = root.add_subsystem('G1', ParallelGroup()) - G1.linear_solver = LinearBlockGS() + p = root.add_subsystem('p', om.IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) + G1 = root.add_subsystem('G1', om.ParallelGroup()) + G1.linear_solver = om.LinearBlockGS() - c2 = G1.add_subsystem('c2', ExecComp('y = x * 2.0', - x=np.zeros(asize), y=np.zeros(asize))) - c3 = G1.add_subsystem('c3', ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', - x=np.zeros(asize), y=np.zeros(asize))) - c4 = root.add_subsystem('c4', ExecComp('y = x * 4.0', - x=np.zeros(asize), y=np.zeros(asize))) - c5 = root.add_subsystem('c5', ExecComp('y = x * 5.0', - x=np.zeros(asize), y=np.zeros(asize))) + c2 = G1.add_subsystem('c2', om.ExecComp('y = x * 2.0', + x=np.zeros(asize), y=np.zeros(asize))) + c3 = G1.add_subsystem('c3', om.ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', + x=np.zeros(asize), y=np.zeros(asize))) + c4 = root.add_subsystem('c4', om.ExecComp('y = x * 4.0', + x=np.zeros(asize), y=np.zeros(asize))) + c5 = root.add_subsystem('c5', om.ExecComp('y = x * 5.0', + x=np.zeros(asize), y=np.zeros(asize))) prob.model.add_design_var('p.x', indices=[1, 2]) prob.model.add_constraint('c4.y', upper=0.0, indices=[1], parallel_deriv_color='par_resp') @@ -393,30 +392,30 @@ class IndicesTestCase2(unittest.TestCase): def setup_model(self, mode): asize = 3 - prob = Problem() + prob = om.Problem() root = prob.model - root.linear_solver = LinearBlockGS() + root.linear_solver = om.LinearBlockGS() - G1 = root.add_subsystem('G1', ParallelGroup()) - G1.linear_solver = LinearBlockGS() + G1 = root.add_subsystem('G1', om.ParallelGroup()) + G1.linear_solver = om.LinearBlockGS() - par1 = G1.add_subsystem('par1', Group()) - par1.linear_solver = LinearBlockGS() - par2 = G1.add_subsystem('par2', Group()) - par2.linear_solver = LinearBlockGS() + par1 = G1.add_subsystem('par1', om.Group()) + par1.linear_solver = om.LinearBlockGS() + par2 = G1.add_subsystem('par2', om.Group()) + par2.linear_solver = om.LinearBlockGS() - p1 = par1.add_subsystem('p', IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) - p2 = par2.add_subsystem('p', IndepVarComp('x', np.arange(asize, dtype=float)+10.0)) + p1 = par1.add_subsystem('p', om.IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) + p2 = par2.add_subsystem('p', om.IndepVarComp('x', np.arange(asize, dtype=float)+10.0)) - c2 = par1.add_subsystem('c2', ExecComp('y = x * 2.0', - x=np.zeros(asize), y=np.zeros(asize))) - c3 = par2.add_subsystem('c3', ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', - x=np.zeros(asize), y=np.zeros(asize))) - c4 = par1.add_subsystem('c4', ExecComp('y = x * 4.0', - x=np.zeros(asize), y=np.zeros(asize))) - c5 = par2.add_subsystem('c5', ExecComp('y = x * 5.0', - x=np.zeros(asize), y=np.zeros(asize))) + c2 = par1.add_subsystem('c2', om.ExecComp('y = x * 2.0', + x=np.zeros(asize), y=np.zeros(asize))) + c3 = par2.add_subsystem('c3', om.ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', + x=np.zeros(asize), y=np.zeros(asize))) + c4 = par1.add_subsystem('c4', om.ExecComp('y = x * 4.0', + x=np.zeros(asize), y=np.zeros(asize))) + c5 = par2.add_subsystem('c5', om.ExecComp('y = x * 5.0', + x=np.zeros(asize), y=np.zeros(asize))) prob.model.add_design_var('G1.par1.p.x', indices=[1, 2]) prob.model.add_design_var('G1.par2.p.x', indices=[1, 2]) @@ -466,24 +465,24 @@ class MatMatTestCase(unittest.TestCase): def setup_model(self): asize = self.asize - prob = Problem() + prob = om.Problem() root = prob.model - root.linear_solver = LinearBlockGS() + root.linear_solver = om.LinearBlockGS() - p1 = root.add_subsystem('p1', IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) - p2 = root.add_subsystem('p2', IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) - G1 = root.add_subsystem('G1', ParallelGroup()) - G1.linear_solver = LinearBlockGS() + p1 = root.add_subsystem('p1', om.IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) + p2 = root.add_subsystem('p2', om.IndepVarComp('x', np.arange(asize, dtype=float)+1.0)) + G1 = root.add_subsystem('G1', om.ParallelGroup()) + G1.linear_solver = om.LinearBlockGS() - c1 = G1.add_subsystem('c1', ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', - x=np.zeros(asize), y=np.zeros(asize))) - c2 = G1.add_subsystem('c2', ExecComp('y = x * 2.0', - x=np.zeros(asize), y=np.zeros(asize))) + c1 = G1.add_subsystem('c1', om.ExecComp('y = ones(3).T*x.dot(arange(3.,6.))', + x=np.zeros(asize), y=np.zeros(asize))) + c2 = G1.add_subsystem('c2', om.ExecComp('y = x * 2.0', + x=np.zeros(asize), y=np.zeros(asize))) - c3 = root.add_subsystem('c3', ExecComp('y = x * 5.0', - x=np.zeros(asize), y=np.zeros(asize))) - c4 = root.add_subsystem('c4', ExecComp('y = x * 4.0', - x=np.zeros(asize), y=np.zeros(asize))) + c3 = root.add_subsystem('c3', om.ExecComp('y = x * 5.0', + x=np.zeros(asize), y=np.zeros(asize))) + c4 = root.add_subsystem('c4', om.ExecComp('y = x * 4.0', + x=np.zeros(asize), y=np.zeros(asize))) root.connect('p1.x', 'G1.c1.x') root.connect('p2.x', 'G1.c2.x') root.connect('G1.c1.y', 'c3.x') @@ -568,7 +567,7 @@ def test_parallel_multi_rev(self): assert_rel_error(self, J['c4.y', 'p2.x'], expected, 1e-6) -class SumComp(ExplicitComponent): +class SumComp(om.ExplicitComponent): def __init__(self, size): super(SumComp, self).__init__() self.size = size @@ -586,7 +585,7 @@ def compute_partials(self, inputs, partials): partials['y', 'x'] = np.ones(inputs['x'].size) -class SlowComp(ExplicitComponent): +class SlowComp(om.ExplicitComponent): """ Component with a delay that multiplies the input by a multiplier. """ @@ -614,17 +613,17 @@ def _apply_linear(self, jac, vec_names, rel_systems, mode, scope_out=None, scope super(SlowComp, self)._apply_linear(jac, vec_names, rel_systems, mode, scope_out, scope_in) -class PartialDependGroup(Group): +class PartialDependGroup(om.Group): def setup(self): size = 4 - Indep1 = self.add_subsystem('Indep1', IndepVarComp('x', np.arange(size, dtype=float)+1.0)) + Indep1 = self.add_subsystem('Indep1', om.IndepVarComp('x', np.arange(size, dtype=float)+1.0)) Comp1 = self.add_subsystem('Comp1', SumComp(size)) - pargroup = self.add_subsystem('ParallelGroup1', ParallelGroup()) + pargroup = self.add_subsystem('ParallelGroup1', om.ParallelGroup()) - self.linear_solver = LinearBlockGS() + self.linear_solver = om.LinearBlockGS() self.linear_solver.options['iprint'] = -1 - pargroup.linear_solver = LinearBlockGS() + pargroup.linear_solver = om.LinearBlockGS() pargroup.linear_solver.options['iprint'] = -1 delay = .1 @@ -653,7 +652,7 @@ def test_feature_rev(self): import numpy as np - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_parallel_derivatives import PartialDependGroup size = 4 @@ -662,7 +661,7 @@ def test_feature_rev(self): wrt = ['Indep1.x'] # run first in fwd mode - p = Problem(model=PartialDependGroup()) + p = om.Problem(model=PartialDependGroup()) p.setup(mode='rev') p.run_model() @@ -676,7 +675,7 @@ def test_fwd_vs_rev(self): import numpy as np - from openmdao.api import Problem + import openmdao.api as om from openmdao.core.tests.test_parallel_derivatives import PartialDependGroup size = 4 @@ -685,7 +684,7 @@ def test_fwd_vs_rev(self): wrt = ['Indep1.x'] # run first in fwd mode - p = Problem(model=PartialDependGroup()) + p = om.Problem(model=PartialDependGroup()) p.setup(mode='fwd') p.run_model() @@ -697,7 +696,7 @@ def test_fwd_vs_rev(self): assert_rel_error(self, J['ParallelGroup1.Con2.y']['Indep1.x'][0], np.ones(size)*-3., 1e-6) # now run in rev mode and compare times for deriv calculation - p = Problem(model=PartialDependGroup()) + p = om.Problem(model=PartialDependGroup()) p.setup(check=False, mode='rev') p.run_model() @@ -718,29 +717,29 @@ class CleanupTestCase(unittest.TestCase): # to converge. The problem was due to garbage in the doutputs vector that # was coming from transfers to irrelevant variables during Group._apply_linear. def setUp(self): - p = self.p = Problem() + p = self.p = om.Problem() root = p.model - root.linear_solver = LinearBlockGS() + root.linear_solver = om.LinearBlockGS() root.linear_solver.options['err_on_maxiter'] = True - inputs = root.add_subsystem("inputs", IndepVarComp("x", 1.0)) - G1 = root.add_subsystem("G1", Group()) - dparam = G1.add_subsystem("dparam", ExecComp("y = .5*x")) - G1_inputs = G1.add_subsystem("inputs", IndepVarComp("x", 1.5)) - start = G1.add_subsystem("start", ExecComp("y = .7*x")) - timecomp = G1.add_subsystem("time", ExecComp("y = -.2*x")) + inputs = root.add_subsystem("inputs", om.IndepVarComp("x", 1.0)) + G1 = root.add_subsystem("G1", om.Group()) + dparam = G1.add_subsystem("dparam", om.ExecComp("y = .5*x")) + G1_inputs = G1.add_subsystem("inputs", om.IndepVarComp("x", 1.5)) + start = G1.add_subsystem("start", om.ExecComp("y = .7*x")) + timecomp = G1.add_subsystem("time", om.ExecComp("y = -.2*x")) - G2 = G1.add_subsystem("G2", Group()) + G2 = G1.add_subsystem("G2", om.Group()) stage_step = G2.add_subsystem("stage_step", - ExecComp("y = -0.1*x + .5*x2 - .4*x3 + .9*x4")) - ode = G2.add_subsystem("ode", ExecComp("y = .8*x - .6*x2")) - dummy = G2.add_subsystem("dummy", IndepVarComp("x", 1.3)) + om.ExecComp("y = -0.1*x + .5*x2 - .4*x3 + .9*x4")) + ode = G2.add_subsystem("ode", om.ExecComp("y = .8*x - .6*x2")) + dummy = G2.add_subsystem("dummy", om.IndepVarComp("x", 1.3)) - step = G1.add_subsystem("step", ExecComp("y = -.2*x + .4*x2 - .4*x3")) - output = G1.add_subsystem("output", ExecComp("y = .6*x")) + step = G1.add_subsystem("step", om.ExecComp("y = -.2*x + .4*x2 - .4*x3")) + output = G1.add_subsystem("output", om.ExecComp("y = .6*x")) - con = root.add_subsystem("con", ExecComp("y = .2 * x")) - obj = root.add_subsystem("obj", ExecComp("y = .3 * x")) + con = root.add_subsystem("con", om.ExecComp("y = .2 * x")) + obj = root.add_subsystem("obj", om.ExecComp("y = .3 * x")) root.connect("inputs.x", "G1.dparam.x") diff --git a/openmdao/core/tests/test_parallel_groups.py b/openmdao/core/tests/test_parallel_groups.py index 7f6a364aab..d2c33dc519 100644 --- a/openmdao/core/tests/test_parallel_groups.py +++ b/openmdao/core/tests/test_parallel_groups.py @@ -5,9 +5,7 @@ import unittest import numpy as np -from openmdao.api import Problem, Group, ParallelGroup, ExecComp, IndepVarComp, \ - ExplicitComponent, ImplicitComponent, DefaultVector - +import openmdao.api as om from openmdao.utils.mpi import MPI try: @@ -29,7 +27,7 @@ class TestParallelGroups(unittest.TestCase): N_PROCS = 2 def test_fan_out_grouped(self): - prob = Problem(FanOutGrouped()) + prob = om.Problem(FanOutGrouped()) of=['c2.y', "c3.y"] wrt=['iv.x'] @@ -59,7 +57,7 @@ def test_fan_out_grouped(self): def test_fan_in_grouped(self): - prob = Problem() + prob = om.Problem() prob.model = FanInGrouped2() prob.setup(check=False, mode='fwd') prob.set_solver_print(level=0) @@ -90,19 +88,19 @@ def test_fan_in_grouped(self): def test_fan_in_grouped_feature(self): - from openmdao.api import Problem, IndepVarComp, ParallelGroup, ExecComp, PETScVector + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 1.0)) - model.add_subsystem('p2', IndepVarComp('x', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 1.0)) + model.add_subsystem('p2', om.IndepVarComp('x', 1.0)) - parallel = model.add_subsystem('parallel', ParallelGroup()) - parallel.add_subsystem('c1', ExecComp(['y=-2.0*x'])) - parallel.add_subsystem('c2', ExecComp(['y=5.0*x'])) + parallel = model.add_subsystem('parallel', om.ParallelGroup()) + parallel.add_subsystem('c1', om.ExecComp(['y=-2.0*x'])) + parallel.add_subsystem('c2', om.ExecComp(['y=5.0*x'])) - model.add_subsystem('c3', ExecComp(['y=3.0*x1+7.0*x2'])) + model.add_subsystem('c3', om.ExecComp(['y=3.0*x1+7.0*x2'])) model.connect("parallel.c1.y", "c3.x1") model.connect("parallel.c2.y", "c3.x2") @@ -117,7 +115,7 @@ def test_fan_in_grouped_feature(self): def test_diamond(self): - prob = Problem() + prob = om.Problem() prob.model = Diamond() prob.setup(check=False, mode='fwd') prob.set_solver_print(level=0) @@ -145,7 +143,7 @@ def test_diamond(self): def test_converge_diverge(self): - prob = Problem() + prob = om.Problem() prob.model = ConvergeDiverge() prob.setup(check=False, mode='fwd') prob.set_solver_print(level=0) @@ -190,13 +188,13 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['y', 'x'] = np.array([self.mult]) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('iv', IndepVarComp('x', 1.0)) + model.add_subsystem('iv', om.IndepVarComp('x', 1.0)) model.add_subsystem('c1', MultComp(3.0)) - model.sub = model.add_subsystem('sub', ParallelGroup()) + model.sub = model.add_subsystem('sub', om.ParallelGroup()) model.sub.add_subsystem('c2', MultComp(-2.0)) model.sub.add_subsystem('c3', MultComp(5.0)) @@ -245,14 +243,14 @@ def check_config(self, logger): logger.warning(msg) logger.info(msg) - prob = Problem(Noisy()) + prob = om.Problem(Noisy()) # check that error is thrown if not using PETScVector if MPI: msg = ("The `distributed_vector_class` argument must be `PETScVector` when " "running in parallel under MPI but 'DefaultVector' was specified.") with self.assertRaises(ValueError) as cm: - prob.setup(check=False, mode='fwd', distributed_vector_class=DefaultVector) + prob.setup(check=False, mode='fwd', distributed_vector_class=om.DefaultVector) self.assertEqual(str(cm.exception), msg) else: @@ -284,7 +282,7 @@ class TestParallelListStates(unittest.TestCase): N_PROCS = 4 def test_list_states_allprocs(self): - class StateComp(ImplicitComponent): + class StateComp(om.ImplicitComponent): def initialize(self): self.mtx = np.array([ @@ -304,10 +302,10 @@ def apply_nonlinear(self, inputs, outputs, residuals): def solve_nonlinear(self, inputs, outputs): outputs['x'] = np.linalg.solve(self.mtx, inputs['rhs']) - p = Problem(model=ParallelGroup()) + p = om.Problem(model=om.ParallelGroup()) p.model.add_subsystem('C1', StateComp()) p.model.add_subsystem('C2', StateComp()) - p.model.add_subsystem('C3', ExecComp('y=2.0*x')) + p.model.add_subsystem('C3', om.ExecComp('y=2.0*x')) p.model.add_subsystem('C4', StateComp()) p.setup() p.final_setup() @@ -319,12 +317,12 @@ class MatMatParDevTestCase(unittest.TestCase): N_PROCS = 2 def test_size_1_matmat(self): - p = Problem() - indeps = p.model.add_subsystem('indeps', IndepVarComp('x', np.ones(2))) + p = om.Problem() + indeps = p.model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(2))) indeps.add_output('y', 1.0) - par = p.model.add_subsystem('par', ParallelGroup()) - par.add_subsystem('C1', ExecComp('y=2*x', x=np.zeros(2), y=np.zeros(2))) - par.add_subsystem('C2', ExecComp('y=3*x')) + par = p.model.add_subsystem('par', om.ParallelGroup()) + par.add_subsystem('C1', om.ExecComp('y=2*x', x=np.zeros(2), y=np.zeros(2))) + par.add_subsystem('C2', om.ExecComp('y=3*x')) p.model.connect("indeps.x", "par.C1.x") p.model.connect("indeps.y", "par.C2.x") p.model.add_design_var('indeps.x', vectorize_derivs=True, parallel_deriv_color='foo') diff --git a/openmdao/core/tests/test_prob_remote.py b/openmdao/core/tests/test_prob_remote.py index 6ce3ec7560..993da182e1 100644 --- a/openmdao/core/tests/test_prob_remote.py +++ b/openmdao/core/tests/test_prob_remote.py @@ -133,7 +133,7 @@ def test_prob_split_comm(self): self.assertEqual(comm.size, 2) prob = Problem(comm=comm) - model = prob.model = Group() + model = prob.model p1 = model.add_subsystem('p1', IndepVarComp('x', 99.0)) p1.add_design_var('x', lower=-50.0, upper=50.0) @@ -156,7 +156,7 @@ def test_prob_split_comm(self): prob.driver.options['optimizer'] = OPTIMIZER prob.driver.options['print_results'] = False - prob.setup(check=False) + prob.setup() prob.run_model() failed = prob.run_driver() diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py index 7ad3f49d5a..8b36080ca7 100644 --- a/openmdao/core/tests/test_problem.py +++ b/openmdao/core/tests/test_problem.py @@ -7,16 +7,15 @@ import numpy as np +import openmdao.api as om from openmdao.core.group import get_relevant_vars from openmdao.core.driver import Driver -from openmdao.api import Problem, IndepVarComp, NonlinearBlockGS, ScipyOptimizeDriver, DirectSolver, \ - ExecComp, Group, NewtonSolver, ImplicitComponent, ScipyKrylov, ExplicitComponent, NonlinearRunOnce from openmdao.utils.assert_utils import assert_rel_error, assert_warning from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.sellar import SellarDerivatives -class SellarOneComp(ImplicitComponent): +class SellarOneComp(om.ImplicitComponent): def initialize(self): self.options.declare('solve_y1', types=bool, default=True) @@ -115,14 +114,14 @@ def solve_nonlinear(self, inputs, outputs): class TestProblem(unittest.TestCase): def test_feature_simple_run_once_no_promote(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'comp.x') @@ -134,13 +133,13 @@ def test_feature_simple_run_once_no_promote(self): assert_rel_error(self, prob['comp.f_xy'], -15.0) def test_feature_simple_run_once_input_input(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) # promote the two inputs to the same name model.add_subsystem('comp1', Paraboloid(), promotes_inputs=['x']) @@ -156,14 +155,14 @@ def test_feature_simple_run_once_input_input(self): assert_rel_error(self, prob['comp2.f_xy'], 13.0) def test_feature_simple_run_once_compute_totals(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'comp.x') @@ -181,14 +180,14 @@ def test_feature_simple_run_once_compute_totals(self): assert_rel_error(self, totals['comp.f_xy']['p2.y'][0][0], 3.0) def test_feature_simple_run_once_compute_totals_scaled(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'comp.x') @@ -206,14 +205,14 @@ def test_feature_simple_run_once_compute_totals_scaled(self): assert_rel_error(self, totals[('comp.f_xy', 'p2.y')][0][0], 3.0) def test_feature_simple_run_once_set_deriv_mode(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'comp.x') @@ -228,13 +227,13 @@ def test_feature_simple_run_once_set_deriv_mode(self): prob.compute_totals(of=['comp.f_xy'], wrt=['p1.x', 'p2.y']) def test_compute_totals_cleanup(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indeps1', IndepVarComp('x', np.ones(5))) - model.add_subsystem('indeps2', IndepVarComp('x', np.ones(3))) + model.add_subsystem('indeps1', om.IndepVarComp('x', np.ones(5))) + model.add_subsystem('indeps2', om.IndepVarComp('x', np.ones(3))) - model.add_subsystem('MP1', ExecComp('y=7*x', x=np.zeros(5), y=np.zeros(5))) - model.add_subsystem('MP2', ExecComp('y=-3*x', x=np.zeros(3), y=np.zeros(3))) + model.add_subsystem('MP1', om.ExecComp('y=7*x', x=np.zeros(5), y=np.zeros(5))) + model.add_subsystem('MP2', om.ExecComp('y=-3*x', x=np.zeros(3), y=np.zeros(3))) model.add_design_var('indeps1.x') model.add_design_var('indeps2.x') @@ -259,12 +258,12 @@ def test_compute_totals_cleanup(self): def test_set_2d_array(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, Group + import openmdao.api as om - prob = Problem() + prob = om.Problem() model = prob.model model.add_subsystem(name='indeps', - subsys=IndepVarComp(name='X_c', shape=(3, 1))) + subsys=om.IndepVarComp(name='X_c', shape=(3, 1))) prob.setup() new_val = -5*np.ones((3, 1)) @@ -282,13 +281,13 @@ def test_set_2d_array(self): def test_set_checks_shape(self): - model = Group() + model = om.Group() - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_output('num') indep.add_output('arr', shape=(10, 1)) - prob = Problem(model) + prob = om.Problem(model) prob.setup() msg = "Incompatible shape for '.*': Expected (.*) but got (.*)" @@ -334,10 +333,10 @@ def test_set_checks_shape(self): def test_compute_totals_basic(self): # Basic test for the method using default solvers on simple model. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) prob.setup(check=False, mode='fwd') @@ -364,10 +363,10 @@ def test_compute_totals_basic(self): def test_compute_totals_basic_return_dict(self): # Make sure 'dict' return_format works. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) prob.setup(check=False, mode='fwd') @@ -392,12 +391,12 @@ def test_compute_totals_basic_return_dict(self): assert_rel_error(self, derivs['f_xy']['y'], [[8.0]], 1e-6) def test_compute_totals_no_args_no_desvar(self): - p = Problem() + p = om.Problem() - dv = p.model.add_subsystem('des_vars', IndepVarComp()) + dv = p.model.add_subsystem('des_vars', om.IndepVarComp()) dv.add_output('x', val=2.) - p.model.add_subsystem('calc', ExecComp('y=2*x')) + p.model.add_subsystem('calc', om.ExecComp('y=2*x')) p.model.connect('des_vars.x', 'calc.x') @@ -413,12 +412,12 @@ def test_compute_totals_no_args_no_desvar(self): "Driver is not providing any design variables for compute_totals.") def test_compute_totals_no_args_no_response(self): - p = Problem() + p = om.Problem() - dv = p.model.add_subsystem('des_vars', IndepVarComp()) + dv = p.model.add_subsystem('des_vars', om.IndepVarComp()) dv.add_output('x', val=2.) - p.model.add_subsystem('calc', ExecComp('y=2*x')) + p.model.add_subsystem('calc', om.ExecComp('y=2*x')) p.model.connect('des_vars.x', 'calc.x') @@ -434,12 +433,12 @@ def test_compute_totals_no_args_no_response(self): "Driver is not providing any response variables for compute_totals.") def test_compute_totals_no_args(self): - p = Problem() + p = om.Problem() - dv = p.model.add_subsystem('des_vars', IndepVarComp()) + dv = p.model.add_subsystem('des_vars', om.IndepVarComp()) dv.add_output('x', val=2.) - p.model.add_subsystem('calc', ExecComp('y=2*x')) + p.model.add_subsystem('calc', om.ExecComp('y=2*x')) p.model.connect('des_vars.x', 'calc.x') @@ -454,12 +453,12 @@ def test_compute_totals_no_args(self): assert_rel_error(self, derivs['calc.y', 'des_vars.x'], [[2.0]], 1e-6) def test_compute_totals_no_args_promoted(self): - p = Problem() + p = om.Problem() - dv = p.model.add_subsystem('des_vars', IndepVarComp(), promotes=['*']) + dv = p.model.add_subsystem('des_vars', om.IndepVarComp(), promotes=['*']) dv.add_output('x', val=2.) - p.model.add_subsystem('calc', ExecComp('y=2*x'), promotes=['*']) + p.model.add_subsystem('calc', om.ExecComp('y=2*x'), promotes=['*']) p.model.add_design_var('x') p.model.add_objective('y') @@ -472,14 +471,14 @@ def test_compute_totals_no_args_promoted(self): assert_rel_error(self, derivs['calc.y', 'des_vars.x'], [[2.0]], 1e-6) def test_feature_set_indeps(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) prob.setup() @@ -490,13 +489,13 @@ def test_feature_set_indeps(self): assert_rel_error(self, prob['f_xy'], 214.0, 1e-6) def test_feature_basic_setup(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) prob.setup() @@ -512,7 +511,7 @@ def test_feature_basic_setup(self): assert_rel_error(self, prob['f_xy'], 22.0, 1e-6) # skip the setup error checking - prob.setup(check=False) + prob.setup() prob['x'] = 4 prob['y'] = 8. @@ -520,13 +519,13 @@ def test_feature_basic_setup(self): assert_rel_error(self, prob['f_xy'], 174.0, 1e-6) def test_feature_petsc_setup(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) # PETScVectors will be used automatically where needed. No need to set manually. @@ -538,12 +537,12 @@ def test_feature_petsc_setup(self): assert_rel_error(self, prob['f_xy'], 214.0, 1e-6) def test_feature_check_totals_manual(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() prob.run_model() @@ -552,12 +551,12 @@ def test_feature_check_totals_manual(self): prob.check_totals(of=['obj', 'con1'], wrt=['x', 'z']) def test_feature_check_totals_from_driver_compact(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -575,12 +574,12 @@ def test_feature_check_totals_from_driver_compact(self): prob.check_totals(compact_print=True) def test_feature_check_totals_from_driver(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -598,12 +597,12 @@ def test_feature_check_totals_from_driver(self): prob.check_totals() def test_feature_check_totals_from_driver_scaled(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100, ref=100.0, ref0=-100.0) prob.model.add_design_var('z', lower=-100, upper=100) @@ -621,12 +620,12 @@ def test_feature_check_totals_from_driver_scaled(self): prob.check_totals(driver_scaling=True) def test_feature_check_totals_suppress(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -645,12 +644,12 @@ def test_feature_check_totals_suppress(self): print(totals) def test_feature_check_totals_cs(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -672,7 +671,7 @@ def test_feature_check_totals_cs(self): def test_check_totals_user_detect(self): - class SimpleComp(ExplicitComponent): + class SimpleComp(om.ExplicitComponent): def setup(self): self.add_input('x', val=1.0) @@ -692,8 +691,8 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['y', 'x'] = 3. - prob = Problem() - prob.model.add_subsystem('px', IndepVarComp('x', 2.0)) + prob = om.Problem() + prob.model.add_subsystem('px', om.IndepVarComp('x', 2.0)) prob.model.add_subsystem('comp', SimpleComp()) prob.model.connect('px.x', 'comp.x') @@ -710,9 +709,9 @@ def compute_partials(self, inputs, partials): msg="The under_complex_step flag should be reset.") def test_feature_check_totals_user_detect_forced(self): - from openmdao.api import Problem, ExplicitComponent, IndepVarComp + import openmdao.api as om - class SimpleComp(ExplicitComponent): + class SimpleComp(om.ExplicitComponent): def setup(self): self.add_input('x', val=1.0) @@ -729,8 +728,8 @@ def compute(self, inputs, outputs): def compute_partials(self, inputs, partials): partials['y', 'x'] = 3. - prob = Problem() - prob.model.add_subsystem('px', IndepVarComp('x', val=1.0)) + prob = om.Problem() + prob.model.add_subsystem('px', om.IndepVarComp('x', val=1.0)) prob.model.add_subsystem('comp', SimpleComp()) prob.model.connect('px.x', 'comp.x') @@ -746,14 +745,14 @@ def compute_partials(self, inputs, partials): def test_feature_run_driver(self): import numpy as np - from openmdao.api import Problem, NonlinearBlockGS, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 @@ -773,11 +772,11 @@ def test_feature_run_driver(self): assert_rel_error(self, prob['obj'], 3.18339395, 1e-2) def test_feature_promoted_sellar_set_get_outputs(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob = om.Problem(model=SellarDerivatives()) + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() @@ -790,11 +789,11 @@ def test_feature_promoted_sellar_set_get_outputs(self): assert_rel_error(self, prob['y1'], 27.3049178437, 1e-6) def test_feature_not_promoted_sellar_set_get_outputs(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesConnected - prob = Problem(model= SellarDerivativesConnected()) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob = om.Problem(model= SellarDerivativesConnected()) + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() @@ -807,11 +806,11 @@ def test_feature_not_promoted_sellar_set_get_outputs(self): assert_rel_error(self, prob['d1.y1'], 27.3049178437, 1e-6) def test_feature_promoted_sellar_set_get_inputs(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob = om.Problem(model=SellarDerivatives()) + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() @@ -827,25 +826,25 @@ def test_feature_promoted_sellar_set_get_inputs(self): assert_rel_error(self, prob['d2.y1'], 27.3049178437, 1e-6) def test_get_set_with_units_exhaustive(self): - from openmdao.api import Problem, ExecComp - - prob = Problem() - prob.model.add_subsystem('comp', ExecComp('y=x-25.', - x={'value': 77.0, 'units': 'degF'}, - y={'value': 0.0, 'units': 'degC'})) - prob.model.add_subsystem('prom', ExecComp('yy=xx-25.', - xx={'value': 77.0, 'units': 'degF'}, - yy={'value': 0.0, 'units': 'degC'}), + import openmdao.api as om + + prob = om.Problem() + prob.model.add_subsystem('comp', om.ExecComp('y=x-25.', + x={'value': 77.0, 'units': 'degF'}, + y={'value': 0.0, 'units': 'degC'})) + prob.model.add_subsystem('prom', om.ExecComp('yy=xx-25.', + xx={'value': 77.0, 'units': 'degF'}, + yy={'value': 0.0, 'units': 'degC'}), promotes=['xx', 'yy']) - prob.model.add_subsystem('acomp', ExecComp('y=x-25.', - x={'value': np.array([77.0, 95.0]), 'units': 'degF'}, - y={'value': 0.0, 'units': 'degC'})) - prob.model.add_subsystem('aprom', ExecComp('ayy=axx-25.', - axx={'value': np.array([77.0, 95.0]), 'units': 'degF'}, - ayy={'value': 0.0, 'units': 'degC'}), + prob.model.add_subsystem('acomp', om.ExecComp('y=x-25.', + x={'value': np.array([77.0, 95.0]), 'units': 'degF'}, + y={'value': 0.0, 'units': 'degC'})) + prob.model.add_subsystem('aprom', om.ExecComp('ayy=axx-25.', + axx={'value': np.array([77.0, 95.0]), 'units': 'degF'}, + ayy={'value': 0.0, 'units': 'degC'}), promotes=['axx', 'ayy']) - prob.setup(check=False) + prob.setup() # Make sure everything works before final setup with caching system. @@ -942,13 +941,13 @@ def test_get_set_with_units_exhaustive(self): assert_rel_error(self, prob.get_val('axx', 'degC', indices=np.array([0])), 35.0, 1e-6) def test_get_set_with_units_error_messages(self): - from openmdao.api import Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model.add_subsystem('comp', ExecComp('y=x+1.', - x={'value': 100.0, 'units': 'cm'}, - y={'units': 'm'})) - prob.model.add_subsystem('no_unit', ExecComp('y=x+1.', x={'value': 100.0})) + prob = om.Problem() + prob.model.add_subsystem('comp', om.ExecComp('y=x+1.', + x={'value': 100.0, 'units': 'cm'}, + y={'units': 'm'})) + prob.model.add_subsystem('no_unit', om.ExecComp('y=x+1.', x={'value': 100.0})) prob.setup() prob.run_model() @@ -970,12 +969,12 @@ def test_get_set_with_units_error_messages(self): prob.set_val('no_unit.x', 55.0, 'degK') def test_feature_get_set_with_units(self): - from openmdao.api import Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model.add_subsystem('comp', ExecComp('y=x+1.', - x={'value': 100.0, 'units': 'cm'}, - y={'units': 'm'})) + prob = om.Problem() + prob.model.add_subsystem('comp', om.ExecComp('y=x+1.', + x={'value': 100.0, 'units': 'cm'}, + y={'units': 'm'})) prob.setup() prob.run_model() @@ -988,12 +987,12 @@ def test_feature_get_set_with_units(self): def test_feature_get_set_array_with_units(self): import numpy as np - from openmdao.api import Problem, ExecComp + import openmdao.api as om - prob = Problem() - prob.model.add_subsystem('comp', ExecComp('y=x+1.', - x={'value': np.array([100.0, 33.3]), 'units': 'cm'}, - y={'shape': (2, ), 'units': 'm'})) + prob = om.Problem() + prob.model.add_subsystem('comp', om.ExecComp('y=x+1.', + x={'value': np.array([100.0, 33.3]), 'units': 'cm'}, + y={'shape': (2, ), 'units': 'm'})) prob.setup() prob.run_model() @@ -1013,11 +1012,11 @@ def test_feature_get_set_array_with_units(self): def test_feature_set_get_array(self): import numpy as np - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob = om.Problem(model=SellarDerivatives()) + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() @@ -1045,11 +1044,11 @@ def test_feature_set_get_array(self): assert_rel_error(self, prob['y2'], 8.14191301549, 1e-6) def test_feature_residuals(self): - from openmdao.api import Problem, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) - prob.model.nonlinear_solver = NonlinearBlockGS() + prob = om.Problem(model=SellarDerivatives()) + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() @@ -1064,7 +1063,7 @@ def test_feature_residuals(self): def test_setup_bad_mode(self): # Test error message when passing bad mode to setup. - prob = Problem() + prob = om.Problem() try: prob.setup(mode='junk') @@ -1076,9 +1075,9 @@ def test_setup_bad_mode(self): def test_setup_bad_mode_direction_fwd(self): - prob = Problem() - prob.model.add_subsystem("indep", IndepVarComp("x", np.ones(99))) - prob.model.add_subsystem("C1", ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) + prob = om.Problem() + prob.model.add_subsystem("indep", om.IndepVarComp("x", np.ones(99))) + prob.model.add_subsystem("C1", om.ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) prob.model.connect("indep.x", "C1.x", src_indices=list(range(10))) @@ -1096,10 +1095,10 @@ def test_setup_bad_mode_direction_fwd(self): def test_setup_bad_mode_direction_rev(self): - prob = Problem() - prob.model.add_subsystem("indep", IndepVarComp("x", np.ones(10))) - prob.model.add_subsystem("C1", ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) - prob.model.add_subsystem("C2", ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) + prob = om.Problem() + prob.model.add_subsystem("indep", om.IndepVarComp("x", np.ones(10))) + prob.model.add_subsystem("C1", om.ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) + prob.model.add_subsystem("C2", om.ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) prob.model.connect("indep.x", ["C1.x", "C2.x"]) @@ -1119,7 +1118,7 @@ def test_setup_bad_mode_direction_rev(self): def test_run_before_setup(self): # Test error message when running before setup. - prob = Problem() + prob = om.Problem() try: prob.run_model() @@ -1142,7 +1141,7 @@ def test_run_with_invalid_prefix(self): msg = "The 'case_prefix' argument should be a string." - prob = Problem() + prob = om.Problem() try: prob.setup() @@ -1165,18 +1164,18 @@ def test_root_deprecated(self): msg = "The 'root' property provides backwards compatibility " \ "with OpenMDAO <= 1.x ; use 'model' instead." - prob = Problem() + prob = om.Problem() # check deprecation on setter & getter with assert_warning(DeprecationWarning, msg): - prob.root = Group() + prob.root = om.Group() with assert_warning(DeprecationWarning, msg): prob.root # testing the root kwarg with self.assertRaises(ValueError) as cm: - prob = Problem(root=Group(), model=Group()) + prob = om.Problem(root=om.Group(), model=om.Group()) self.assertEqual(str(cm.exception), "Cannot specify both 'root' and 'model'. " @@ -1186,60 +1185,60 @@ def test_root_deprecated(self): "compatibility with OpenMDAO <= 1.x ; use 'model' instead." with assert_warning(DeprecationWarning, msg): - prob = Problem(root=Group()) + prob = om.Problem(root=om.Group()) def test_args(self): # defaults - prob = Problem() - self.assertTrue(isinstance(prob.model, Group)) + prob = om.Problem() + self.assertTrue(isinstance(prob.model, om.Group)) self.assertTrue(isinstance(prob.driver, Driver)) # model - prob = Problem(SellarDerivatives()) + prob = om.Problem(SellarDerivatives()) self.assertTrue(isinstance(prob.model, SellarDerivatives)) self.assertTrue(isinstance(prob.driver, Driver)) # driver - prob = Problem(driver=ScipyOptimizeDriver()) - self.assertTrue(isinstance(prob.model, Group)) - self.assertTrue(isinstance(prob.driver, ScipyOptimizeDriver)) + prob = om.Problem(driver=om.ScipyOptimizeDriver()) + self.assertTrue(isinstance(prob.model, om.Group)) + self.assertTrue(isinstance(prob.driver, om.ScipyOptimizeDriver)) # model and driver - prob = Problem(model=SellarDerivatives(), driver=ScipyOptimizeDriver()) + prob = om.Problem(model=SellarDerivatives(), driver=om.ScipyOptimizeDriver()) self.assertTrue(isinstance(prob.model, SellarDerivatives)) - self.assertTrue(isinstance(prob.driver, ScipyOptimizeDriver)) + self.assertTrue(isinstance(prob.driver, om.ScipyOptimizeDriver)) # invalid model with self.assertRaises(TypeError) as cm: - prob = Problem(ScipyOptimizeDriver()) + prob = om.Problem(om.ScipyOptimizeDriver()) self.assertEqual(str(cm.exception), "The value provided for 'model' is not a valid System.") # invalid driver with self.assertRaises(TypeError) as cm: - prob = Problem(driver=SellarDerivatives()) + prob = om.Problem(driver=SellarDerivatives()) self.assertEqual(str(cm.exception), "The value provided for 'driver' is not a valid Driver.") def test_relevance(self): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem("indep1", IndepVarComp('x', 1.0)) - G1 = model.add_subsystem('G1', Group()) - G1.add_subsystem('C1', ExecComp(['x=2.0*a', 'y=2.0*b', 'z=2.0*a'])) - G1.add_subsystem('C2', ExecComp(['x=2.0*a', 'y=2.0*b', 'z=2.0*b'])) - model.add_subsystem("C3", ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c'])) - model.add_subsystem("C4", ExecComp(['x=2.0*a', 'y=2.0*b'])) - model.add_subsystem("indep2", IndepVarComp('x', 1.0)) - G2 = model.add_subsystem('G2', Group()) - G2.add_subsystem('C5', ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c'])) - G2.add_subsystem('C6', ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c'])) - G2.add_subsystem('C7', ExecComp(['x=2.0*a', 'y=2.0*b'])) - model.add_subsystem("C8", ExecComp(['y=1.5*a+2.0*b'])) - model.add_subsystem("Unconnected", ExecComp('y=99.*x')) + model.add_subsystem("indep1", om.IndepVarComp('x', 1.0)) + G1 = model.add_subsystem('G1', om.Group()) + G1.add_subsystem('C1', om.ExecComp(['x=2.0*a', 'y=2.0*b', 'z=2.0*a'])) + G1.add_subsystem('C2', om.ExecComp(['x=2.0*a', 'y=2.0*b', 'z=2.0*b'])) + model.add_subsystem("C3", om.ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c'])) + model.add_subsystem("C4", om.ExecComp(['x=2.0*a', 'y=2.0*b'])) + model.add_subsystem("indep2", om.IndepVarComp('x', 1.0)) + G2 = model.add_subsystem('G2', om.Group()) + G2.add_subsystem('C5', om.ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c'])) + G2.add_subsystem('C6', om.ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c'])) + G2.add_subsystem('C7', om.ExecComp(['x=2.0*a', 'y=2.0*b'])) + model.add_subsystem("C8", om.ExecComp(['y=1.5*a+2.0*b'])) + model.add_subsystem("Unconnected", om.ExecComp('y=99.*x')) model.connect('indep1.x', 'G1.C1.a') model.connect('indep2.x', 'G2.C6.a') @@ -1311,18 +1310,18 @@ def test_relevance_with_component_model(self): SOLVE_Y1 = False SOLVE_Y2 = True - p_opt = Problem() + p_opt = om.Problem() p_opt.model = SellarOneComp(solve_y1=SOLVE_Y1, solve_y2=SOLVE_Y2) if SOLVE_Y1 or SOLVE_Y2: - newton = p_opt.model.nonlinear_solver = NewtonSolver() + newton = p_opt.model.nonlinear_solver = om.NewtonSolver() newton.options['iprint'] = 0 # NOTE: need to have this direct solver attached to the sellar comp until I define a solve_linear for it - p_opt.model.linear_solver = DirectSolver(assemble_jac=True) + p_opt.model.linear_solver = om.DirectSolver(assemble_jac=True) - p_opt.driver = ScipyOptimizeDriver() + p_opt.driver = om.ScipyOptimizeDriver() p_opt.driver.options['disp'] = False if not SOLVE_Y1: @@ -1353,7 +1352,7 @@ def test_system_setup_and_configure(self): # Test that we can change solver settings on a subsystem in a system's setup method. # Also assures that highest system's settings take precedence. - class ImplSimple(ImplicitComponent): + class ImplSimple(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) @@ -1368,39 +1367,39 @@ def linearize(self, inputs, outputs, jacobian): 2 * inputs['a']**2 * outputs['x'] jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 - class Sub(Group): + class Sub(om.Group): def setup(self): self.add_subsystem('comp', ImplSimple()) # This will not solve it - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() def configure(self): # This will not solve it either. - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() - class Super(Group): + class Super(om.Group): def setup(self): self.add_subsystem('sub', Sub()) def configure(self): # This will solve it. - self.sub.nonlinear_solver = NewtonSolver() - self.sub.linear_solver = ScipyKrylov() + self.sub.nonlinear_solver = om.NewtonSolver() + self.sub.linear_solver = om.ScipyKrylov() - top = Problem(model=Super()) + top = om.Problem(model=Super()) - top.setup(check=False) + top.setup() - self.assertTrue(isinstance(top.model.sub.nonlinear_solver, NewtonSolver)) - self.assertTrue(isinstance(top.model.sub.linear_solver, ScipyKrylov)) + self.assertTrue(isinstance(top.model.sub.nonlinear_solver, om.NewtonSolver)) + self.assertTrue(isinstance(top.model.sub.linear_solver, om.ScipyKrylov)) def test_post_setup_solver_configure(self): # Test that we can change solver settings after we have instantiated our model. - class ImplSimple(ImplicitComponent): + class ImplSimple(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) @@ -1415,38 +1414,38 @@ def linearize(self, inputs, outputs, jacobian): 2 * inputs['a']**2 * outputs['x'] jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 - class Sub(Group): + class Sub(om.Group): def setup(self): self.add_subsystem('comp', ImplSimple()) # This solver will get over-ridden below - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() def configure(self): # This solver will get over-ridden below - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() - class Super(Group): + class Super(om.Group): def setup(self): self.add_subsystem('sub', Sub()) - top = Problem(model=Super()) + top = om.Problem(model=Super()) - top.setup(check=False) + top.setup() # These solvers override the ones set in the setup method of the 'sub' groups - top.model.sub.nonlinear_solver = NewtonSolver() - top.model.sub.linear_solver = ScipyKrylov() + top.model.sub.nonlinear_solver = om.NewtonSolver() + top.model.sub.linear_solver = om.ScipyKrylov() - self.assertTrue(isinstance(top.model.sub.nonlinear_solver, NewtonSolver)) - self.assertTrue(isinstance(top.model.sub.linear_solver, ScipyKrylov)) + self.assertTrue(isinstance(top.model.sub.nonlinear_solver, om.NewtonSolver)) + self.assertTrue(isinstance(top.model.sub.linear_solver, om.ScipyKrylov)) def test_feature_system_configure(self): - from openmdao.api import Problem, Group, ImplicitComponent, NewtonSolver, ScipyKrylov, NonlinearBlockGS + import openmdao.api as om - class ImplSimple(ImplicitComponent): + class ImplSimple(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) @@ -1461,35 +1460,35 @@ def linearize(self, inputs, outputs, jacobian): 2 * inputs['a']**2 * outputs['x'] jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 - class Sub(Group): + class Sub(om.Group): def setup(self): self.add_subsystem('comp', ImplSimple()) def configure(self): # This solver won't solve the system. We want # to override it in the parent. - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() - class Super(Group): + class Super(om.Group): def setup(self): self.add_subsystem('sub', Sub()) def configure(self): # This will solve it. - self.sub.nonlinear_solver = NewtonSolver() - self.sub.linear_solver = ScipyKrylov() + self.sub.nonlinear_solver = om.NewtonSolver() + self.sub.linear_solver = om.ScipyKrylov() - top = Problem(model=Super()) + top = om.Problem(model=Super()) - top.setup(check=False) + top.setup() - print(isinstance(top.model.sub.nonlinear_solver, NewtonSolver)) - print(isinstance(top.model.sub.linear_solver, ScipyKrylov)) + print(isinstance(top.model.sub.nonlinear_solver, om.NewtonSolver)) + print(isinstance(top.model.sub.linear_solver, om.ScipyKrylov)) def test_feature_post_setup_solver_configure(self): - from openmdao.api import Problem, Group, ImplicitComponent, NewtonSolver, ScipyKrylov, NonlinearBlockGS + import openmdao.api as om - class ImplSimple(ImplicitComponent): + class ImplSimple(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) @@ -1504,46 +1503,46 @@ def linearize(self, inputs, outputs, jacobian): 2 * inputs['a']**2 * outputs['x'] jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 - class Sub(Group): + class Sub(om.Group): def setup(self): self.add_subsystem('comp', ImplSimple()) # This will not solve it - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() def configure(self): # This will not solve it either. - self.nonlinear_solver = NonlinearBlockGS() + self.nonlinear_solver = om.NonlinearBlockGS() - class Super(Group): + class Super(om.Group): def setup(self): self.add_subsystem('sub', Sub()) - top = Problem(model=Super()) + top = om.Problem(model=Super()) - top.setup(check=False) + top.setup() # This will solve it. - top.model.sub.nonlinear_solver = NewtonSolver() - top.model.sub.linear_solver = ScipyKrylov() + top.model.sub.nonlinear_solver = om.NewtonSolver() + top.model.sub.linear_solver = om.ScipyKrylov() - self.assertTrue(isinstance(top.model.sub.nonlinear_solver, NewtonSolver)) - self.assertTrue(isinstance(top.model.sub.linear_solver, ScipyKrylov)) + self.assertTrue(isinstance(top.model.sub.nonlinear_solver, om.NewtonSolver)) + self.assertTrue(isinstance(top.model.sub.linear_solver, om.ScipyKrylov)) def test_post_setup_hook(self): def hook_func(prob): prob['p2.y'] = 5.0 - prob = Problem() + prob = om.Problem() model = prob.model - Problem._post_setup_func = hook_func + om.Problem._post_setup_func = hook_func try: - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) - model.add_subsystem('comp', ExecComp("f_xy=2.0*x+3.0*y")) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) + model.add_subsystem('comp', om.ExecComp("f_xy=2.0*x+3.0*y")) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') @@ -1554,14 +1553,14 @@ def hook_func(prob): assert_rel_error(self, prob['p2.y'], 5.0) assert_rel_error(self, prob['comp.f_xy'], 21.0) finally: - Problem._post_setup_func = None + om.Problem._post_setup_func = None def test_list_problem_vars(self): model = SellarDerivatives() - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - prob = Problem(model) - prob.driver = ScipyOptimizeDriver() + prob = om.Problem(model) + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 @@ -1670,14 +1669,14 @@ def test_list_problem_vars(self): def test_feature_list_problem_vars(self): import numpy as np - from openmdao.api import Problem, ScipyOptimizeDriver, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 @@ -1708,22 +1707,22 @@ class NestedProblemTestCase(unittest.TestCase): def test_nested_prob(self): - class _ProblemSolver(NonlinearRunOnce): + class _ProblemSolver(om.NonlinearRunOnce): def solve(self): # create a simple subproblem and run it to test for global solver_info bug - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('x', 1.0)) - p.model.add_subsystem('comp', ExecComp('y=2*x')) + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('x', 1.0)) + p.model.add_subsystem('comp', om.ExecComp('y=2*x')) p.model.connect('indep.x', 'comp.x') p.setup() p.run_model() return super(_ProblemSolver, self).solve() - p = Problem() - p.model.add_subsystem('indep', IndepVarComp('x', 1.0)) - G = p.model.add_subsystem('G', Group()) - G.add_subsystem('comp', ExecComp('y=2*x')) + p = om.Problem() + p.model.add_subsystem('indep', om.IndepVarComp('x', 1.0)) + G = p.model.add_subsystem('G', om.Group()) + G.add_subsystem('comp', om.ExecComp('y=2*x')) G.nonlinear_solver = _ProblemSolver() p.model.connect('indep.x', 'G.comp.x') p.setup() diff --git a/openmdao/core/tests/test_proc_alloc.py b/openmdao/core/tests/test_proc_alloc.py index 1ab7362fe1..e4106fa635 100644 --- a/openmdao/core/tests/test_proc_alloc.py +++ b/openmdao/core/tests/test_proc_alloc.py @@ -158,7 +158,7 @@ def test_4_subs_with_mins_serial_plus_2_par(self): model.add_design_var('indep.x') model.add_objective('objective.y') - p.setup(check=False) + p.setup() p.final_setup() all_inds = _get_which_procs(p.model) diff --git a/openmdao/core/tests/test_reconf.py b/openmdao/core/tests/test_reconf.py index 67bd5edf91..43ad9122b7 100644 --- a/openmdao/core/tests/test_reconf.py +++ b/openmdao/core/tests/test_reconf.py @@ -52,7 +52,6 @@ class Test(unittest.TestCase): def test(self): p = Problem() - p.model = Group() p.model.add_subsystem('c1', IndepVarComp('x', 1.0), promotes_outputs=['x']) p.model.add_subsystem('c2', ReconfComp(), promotes_inputs=['x'], promotes_outputs=['y']) p.model.add_subsystem('c3', Comp(), promotes_inputs=['x'], promotes_outputs=['z']) diff --git a/openmdao/core/tests/test_reconf_dynamic.py b/openmdao/core/tests/test_reconf_dynamic.py index 698e81887a..0433afbdc5 100644 --- a/openmdao/core/tests/test_reconf_dynamic.py +++ b/openmdao/core/tests/test_reconf_dynamic.py @@ -58,7 +58,6 @@ class Test(unittest.TestCase): def ttest_reconf_comp(self): p = Problem() - p.model = Group() p.model.add_subsystem('c1', IndepVarComp('x', 1.0), promotes_outputs=['x']) p.model.add_subsystem('c2', ReconfComp(), promotes_inputs=['x'], promotes_outputs=['y']) p.model.add_subsystem('c3', Comp(), promotes_inputs=['x'], promotes_outputs=['z']) @@ -86,7 +85,6 @@ def ttest_reconf_comp(self): def test_reconf_group(self): p = Problem() - p.model = Group() p.model.add_subsystem('s1', IndepVarComp('x', 1.0), promotes_outputs=['x']) s2 = p.model.add_subsystem('s2', ReconfGroup(), promotes=['*']) p.model.add_subsystem('s3', ExecComp('z=3*x'), promotes=['*']) diff --git a/openmdao/core/tests/test_reconf_group.py b/openmdao/core/tests/test_reconf_group.py index 080a4bdde2..14b8a3dabb 100644 --- a/openmdao/core/tests/test_reconf_group.py +++ b/openmdao/core/tests/test_reconf_group.py @@ -28,10 +28,10 @@ def setup(self): class Test(unittest.TestCase): def test(self): - prob = Problem(model=Group()) + prob = Problem() prob.model.add_subsystem('Cx', IndepVarComp('x', 1.0), promotes=['x']) prob.model.add_subsystem('g', ReconfGroup(), promotes=['*']) - prob.setup(check=False) + prob.setup() # First run with the initial setup. prob['x'] = 2.0 diff --git a/openmdao/core/tests/test_reconf_parallel_group.py b/openmdao/core/tests/test_reconf_parallel_group.py index c8b494f73a..4a77f91126 100644 --- a/openmdao/core/tests/test_reconf_parallel_group.py +++ b/openmdao/core/tests/test_reconf_parallel_group.py @@ -43,11 +43,11 @@ class Test(unittest.TestCase): N_PROCS = 2 def test(self): - prob = Problem(model=Group()) + prob = Problem() prob.model.add_subsystem('Cx0', IndepVarComp('x0'), promotes=['x0']) prob.model.add_subsystem('Cx1', IndepVarComp('x1'), promotes=['x1']) prob.model.add_subsystem('g', ReconfGroup(), promotes=['*']) - prob.setup(check=False) + prob.setup() # First, run with full setup, so ReconfGroup should be a parallel group prob['x0'] = 6. diff --git a/openmdao/core/tests/test_scaling.py b/openmdao/core/tests/test_scaling.py index c7fa61ecc8..18d70b25f1 100644 --- a/openmdao/core/tests/test_scaling.py +++ b/openmdao/core/tests/test_scaling.py @@ -7,16 +7,15 @@ import numpy as np -from openmdao.api import Problem, Group, ExplicitComponent, ImplicitComponent, IndepVarComp -from openmdao.api import NewtonSolver, ScipyKrylov, NonlinearBlockGS, DirectSolver +import openmdao.api as om from openmdao.core.driver import Driver -from openmdao.utils.assert_utils import assert_rel_error from openmdao.test_suite.components.expl_comp_array import TestExplCompArrayDense from openmdao.test_suite.components.impl_comp_array import TestImplCompArrayDense +from openmdao.utils.assert_utils import assert_rel_error -class PassThroughLength(ExplicitComponent): +class PassThroughLength(om.ExplicitComponent): """Units/scaling test component taking length in cm and passing it through in km.""" def setup(self): @@ -30,7 +29,7 @@ def compute(self, inputs, outputs): outputs['new_length'] = length_km -class ScalingExample1(ImplicitComponent): +class ScalingExample1(om.ImplicitComponent): def setup(self): self.add_input('x1', val=100.0) @@ -48,7 +47,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): residuals['y2'] = 1e-5 * (x2 - y2)/y2 -class ScalingExample2(ImplicitComponent): +class ScalingExample2(om.ImplicitComponent): def setup(self): self.add_input('x1', val=100.0) @@ -66,7 +65,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): residuals['y2'] = 1e-5 * (x2 - y2)/y2 -class ScalingExample3(ImplicitComponent): +class ScalingExample3(om.ImplicitComponent): def setup(self): self.add_input('x1', val=100.0) @@ -84,7 +83,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): residuals['y2'] = 1e-5 * (x2 - y2)/y2 -class ScalingExampleVector(ImplicitComponent): +class ScalingExampleVector(om.ImplicitComponent): def setup(self): self.add_input('x', val=np.array([100., 5000.])) @@ -100,7 +99,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): residuals['y'][1] = 1e-5 * (x[1] - y[1])/y[1] -class SpeedComputationWithUnits(ExplicitComponent): +class SpeedComputationWithUnits(om.ExplicitComponent): """Simple speed computation from distance and time with unit conversations.""" def setup(self): @@ -119,7 +118,7 @@ def compute(self, inputs, outputs): outputs['speed'] = speed_kph -class ScalingTestComp(ImplicitComponent): +class ScalingTestComp(om.ImplicitComponent): """Explicit component used to test output and residual scaling. This component helps assemble a system of the following form with @@ -194,55 +193,55 @@ class TestScaling(unittest.TestCase): def test_error_messages(self): - class EComp(ImplicitComponent): + class EComp(om.ImplicitComponent): def setup(self): self.add_output('zz', val=np.ones((4, 2)), ref=np.ones((3, 5))) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('comp', EComp()) msg = "'comp': When adding output 'zz', expected shape (4, 2) but got shape (3, 5) for argument 'ref'." with self.assertRaises(ValueError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(_winfix(str(context.exception)), msg) - class EComp(ImplicitComponent): + class EComp(om.ImplicitComponent): def setup(self): self.add_output('zz', val=np.ones((4, 2)), ref0=np.ones((3, 5))) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('comp', EComp()) msg = "'comp': When adding output 'zz', expected shape (4, 2) but got shape (3, 5) for argument 'ref0'." with self.assertRaises(ValueError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(_winfix(str(context.exception)), msg) - class EComp(ImplicitComponent): + class EComp(om.ImplicitComponent): def setup(self): self.add_output('zz', val=np.ones((4, 2)), res_ref=np.ones((3, 5))) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('comp', EComp()) msg = "'comp': When adding output 'zz', expected shape (4, 2) but got shape (3, 5) for argument 'res_ref'." with self.assertRaises(ValueError) as context: - prob.setup(check=False) + prob.setup() self.assertEqual(_winfix(str(context.exception)), msg) def test_pass_through(self): - group = Group() - group.add_subsystem('sys1', IndepVarComp('old_length', 1.0, - units='mm', ref=1e5)) + group = om.Group() + group.add_subsystem('sys1', om.IndepVarComp('old_length', 1.0, + units='mm', ref=1e5)) group.add_subsystem('sys2', PassThroughLength()) group.connect('sys1.old_length', 'sys2.old_length') - prob = Problem(group) + prob = om.Problem(group) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob['sys1.old_length'] = 3.e5 @@ -255,18 +254,18 @@ def test_pass_through(self): assert_rel_error(self, prob.model._outputs['sys2.new_length'], 3.e-1) def test_speed(self): - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('distance', 1., units='km') comp.add_output('time', 1., units='h') - group = Group() + group = om.Group() group.add_subsystem('c1', comp) group.add_subsystem('c2', SpeedComputationWithUnits()) group.connect('c1.distance', 'c2.distance') group.connect('c1.time', 'c2.time') - prob = Problem(model=group) - prob.setup(check=False) + prob = om.Problem(model=group) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -279,19 +278,19 @@ def test_speed(self): def test_scaling(self): """Test convergence in essentially one Newton iteration to atol=1e-5.""" def runs_successfully(use_scal, coeffs): - prob = Problem(model=Group()) + prob = om.Problem() prob.model.add_subsystem('row1', ScalingTestComp(row=1, coeffs=coeffs, use_scal=use_scal)) prob.model.add_subsystem('row2', ScalingTestComp(row=2, coeffs=coeffs, use_scal=use_scal)) prob.model.connect('row1.y', 'row2.x') prob.model.connect('row2.y', 'row1.x') - prob.model.nonlinear_solver = NewtonSolver(maxiter=2, atol=1e-5, rtol=0) - prob.model.nonlinear_solver.linear_solver = ScipyKrylov(maxiter=1) + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=2, atol=1e-5, rtol=0) + prob.model.nonlinear_solver.linear_solver = om.ScipyKrylov(maxiter=1) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() return np.linalg.norm(prob.model._residuals._data) < 1e-5 @@ -334,7 +333,7 @@ def test_resid_scale_default(self): # The model is a cycle that iterates once, so the first component in the cycle carries # a residual. - class Simple(ExplicitComponent): + class Simple(om.ExplicitComponent): def initialize(self): self.options.declare('ref', default=1.0) @@ -365,20 +364,20 @@ def compute_partials(self, inputs, partials): # Baseline - all should be equal. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('p1', Simple()) model.add_subsystem('p2', Simple()) model.connect('p1.y', 'p2.x') model.connect('p2.y', 'p1.x') - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() model.nonlinear_solver.options['maxiter'] = 1 model.nonlinear_solver.options['use_apply_nonlinear'] = True prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() res1 = -model.p1._residuals._data[0] @@ -404,20 +403,20 @@ def compute_partials(self, inputs, partials): ref = 1.0 ref0 = 1.5 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('p1', Simple(ref=ref, ref0=ref0)) model.add_subsystem('p2', Simple(ref=ref, ref0=ref0)) model.connect('p1.y', 'p2.x') model.connect('p2.y', 'p1.x') - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() model.nonlinear_solver.options['maxiter'] = 1 model.nonlinear_solver.options['use_apply_nonlinear'] = True prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() res1 = -model.p1._residuals._data[0] @@ -439,20 +438,20 @@ def compute_partials(self, inputs, partials): res_ref = 4.0 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('p1', Simple(res_ref=res_ref)) model.add_subsystem('p2', Simple(res_ref=res_ref)) model.connect('p1.y', 'p2.x') model.connect('p2.y', 'p1.x') - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() model.nonlinear_solver.options['maxiter'] = 1 model.nonlinear_solver.options['use_apply_nonlinear'] = True prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() res1 = -model.p1._residuals._data[0] @@ -476,20 +475,20 @@ def compute_partials(self, inputs, partials): ref0 = 2.75 res_ref = 4.0 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model model.add_subsystem('p1', Simple(ref=ref, ref0=ref0, res_ref=res_ref)) model.add_subsystem('p2', Simple(ref=ref, ref0=ref0, res_ref=res_ref)) model.connect('p1.y', 'p2.x') model.connect('p2.y', 'p1.x') - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() model.nonlinear_solver.options['maxiter'] = 1 model.nonlinear_solver.options['use_apply_nonlinear'] = True prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() res1 = -model.p1._residuals._data[0] @@ -522,14 +521,14 @@ def compute(self, inputs, outputs): super(ExpCompArrayScale, self).compute(inputs, outputs) outputs['stuff'] = inputs['widths'] + inputs['lengths'] - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.ones((2, 2)))) + model.add_subsystem('p1', om.IndepVarComp('x', np.ones((2, 2)))) model.add_subsystem('comp', ExpCompArrayScale()) model.connect('p1.x', 'comp.lengths') - prob.setup(check=False) + prob.setup() prob['comp.widths'] = np.ones((2, 2)) prob.run_model() @@ -564,14 +563,14 @@ def compute(self, inputs, outputs): super(ExpCompArrayScale, self).compute(inputs, outputs) outputs['stuff'] = inputs['widths'] + inputs['lengths'] - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.ones((2, 2)))) + model.add_subsystem('p1', om.IndepVarComp('x', np.ones((2, 2)))) model.add_subsystem('comp', ExpCompArrayScale()) model.connect('p1.x', 'comp.lengths') - prob.setup(check=False) + prob.setup() prob['comp.widths'] = np.ones((2, 2)) prob.run_model() @@ -609,14 +608,14 @@ def compute(self, inputs, outputs): super(ExpCompArrayScale, self).compute(inputs, outputs) outputs['stuff'] = inputs['widths'] + inputs['lengths'] - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.ones((2, 2)))) + model.add_subsystem('p1', om.IndepVarComp('x', np.ones((2, 2)))) model.add_subsystem('comp', ExpCompArrayScale()) model.connect('p1.x', 'comp.lengths') - prob.setup(check=False) + prob.setup() prob['comp.widths'] = np.ones((2, 2)) prob.run_model() @@ -685,14 +684,14 @@ def linearize(self, inputs, outputs, jacobian): jacobian['x', 'rhs'] = -np.eye(2) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.ones(2))) + model.add_subsystem('p1', om.IndepVarComp('x', np.ones(2))) comp = model.add_subsystem('comp', ImpCompArrayScale()) model.connect('p1.x', 'comp.rhs') - prob.setup(check=False) + prob.setup() prob.run_model() base_x = model.comp._outputs['x'].copy() @@ -744,14 +743,14 @@ def linearize(self, inputs, outputs, jacobian): jacobian['x', 'rhs'] = -np.eye(2) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.ones(2))) + model.add_subsystem('p1', om.IndepVarComp('x', np.ones(2))) comp = model.add_subsystem('comp', ImpCompArrayScale()) model.connect('p1.x', 'comp.rhs') - prob.setup(check=False) + prob.setup() prob.run_model() base_x = model.comp._outputs['x'].copy() @@ -811,11 +810,11 @@ def compute(self, inputs, outputs): outputs['total_volume'] = np.sum(outputs['areas']) + np.sum(outputs['stuff']) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.ones((2, 2)))) - model.add_subsystem('p2', IndepVarComp('x', np.ones((1, 3)))) + model.add_subsystem('p1', om.IndepVarComp('x', np.ones((2, 2)))) + model.add_subsystem('p2', om.IndepVarComp('x', np.ones((1, 3)))) model.add_subsystem('comp1', ExpCompArrayScale()) model.add_subsystem('comp2', ExpCompArrayScale()) model.connect('p1.x', 'comp1.lengths') @@ -823,7 +822,7 @@ def compute(self, inputs, outputs): model.connect('comp1.areas', 'comp2.lengths') model.connect('comp1.stuff', 'comp2.widths') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['comp1.total_volume'], 14.) @@ -831,7 +830,7 @@ def compute(self, inputs, outputs): def test_newton_resid_scaling(self): - class SimpleComp(ImplicitComponent): + class SimpleComp(om.ImplicitComponent): def setup(self): self.add_input('x', val=6.0) @@ -847,54 +846,54 @@ def linearize(self, inputs, outputs, jacobian): jacobian['y', 'x'] = -1.0 jacobian['y', 'y'] = 3.0 - prob = Problem() - model = prob.model = Group(assembled_jac_type='dense') + prob = om.Problem() + model = prob.model = om.Group(assembled_jac_type='dense') - model.add_subsystem('p1', IndepVarComp('x', 6.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 6.0)) model.add_subsystem('comp', SimpleComp()) model.connect('p1.x', 'comp.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = DirectSolver() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.DirectSolver() - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['comp.y'], 2.0) # Now, let's try with an AssembledJacobian. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 6.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 6.0)) model.add_subsystem('comp', SimpleComp()) model.connect('p1.x', 'comp.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = DirectSolver(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.DirectSolver(assemble_jac=True) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['comp.y'], 2.0) def test_feature1(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_scaling import ScalingExample1 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x1', 1.0)) - model.add_subsystem('p2', IndepVarComp('x2', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x1', 1.0)) + model.add_subsystem('p2', om.IndepVarComp('x2', 1.0)) comp = model.add_subsystem('comp', ScalingExample1()) model.connect('p1.x1', 'comp.x1') model.connect('p2.x2', 'comp.x2') - prob.setup(check=False) + prob.setup() prob.run_model() model.run_apply_nonlinear() @@ -906,19 +905,19 @@ def test_feature1(self): assert_rel_error(self, val, 6.0) def test_feature2(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_scaling import ScalingExample2 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x1', 1.0)) - model.add_subsystem('p2', IndepVarComp('x2', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x1', 1.0)) + model.add_subsystem('p2', om.IndepVarComp('x2', 1.0)) comp = model.add_subsystem('comp', ScalingExample2()) model.connect('p1.x1', 'comp.x1') model.connect('p2.x2', 'comp.x2') - prob.setup(check=False) + prob.setup() prob.run_model() model.run_apply_nonlinear() @@ -930,19 +929,19 @@ def test_feature2(self): assert_rel_error(self, val, 0.5) def test_feature3(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_scaling import ScalingExample3 - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x1', 1.0)) - model.add_subsystem('p2', IndepVarComp('x2', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x1', 1.0)) + model.add_subsystem('p2', om.IndepVarComp('x2', 1.0)) comp = model.add_subsystem('comp', ScalingExample3()) model.connect('p1.x1', 'comp.x1') model.connect('p2.x2', 'comp.x2') - prob.setup(check=False) + prob.setup() prob.run_model() model.run_apply_nonlinear() @@ -954,17 +953,17 @@ def test_feature3(self): assert_rel_error(self, val, (1-6000.)/6000.) def test_feature_vector(self): - from openmdao.api import Problem, Group, IndepVarComp + import openmdao.api as om from openmdao.core.tests.test_scaling import ScalingExampleVector - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p', IndepVarComp('x', np.ones((2)))) + model.add_subsystem('p', om.IndepVarComp('x', np.ones((2)))) comp = model.add_subsystem('comp', ScalingExampleVector()) model.connect('p.x', 'comp.x') - prob.setup(check=False) + prob.setup() prob.run_model() model.run_apply_nonlinear() @@ -978,7 +977,7 @@ def test_feature_vector(self): assert_rel_error(self, val[1], 6.0) -class MyComp(ExplicitComponent): +class MyComp(om.ExplicitComponent): def setup(self): @@ -1029,7 +1028,7 @@ def compute(self, inputs, outputs, discrete_inputs=None, outputs['x3_s_s'] = self.J[3, 0] * inputs['x2_u_u'] + self.J[3, 1] * inputs['x2_u_s'] + self.J[3, 2] * inputs['x2_s_u'] + self.J[3, 3] * inputs['x2_s_s'] -class MyImplicitComp(ImplicitComponent): +class MyImplicitComp(om.ImplicitComponent): def setup(self): @@ -1082,10 +1081,10 @@ class TestScalingOverhaul(unittest.TestCase): def test_in_driver(self): # This test assures that the driver is correctly seeing unscaled (physical) data. - prob = Problem() + prob = om.Problem() model = prob.model - inputs_comp = IndepVarComp() + inputs_comp = om.IndepVarComp() inputs_comp.add_output('x1_u_u', val=1.0) inputs_comp.add_output('x1_u_s', val=1.0) inputs_comp.add_output('x1_s_u', val=1.0, ref=3.0) @@ -1187,10 +1186,10 @@ def test_in_driver(self): def test_iimplicit(self): # Testing that our scale/unscale contexts leave the output vector in the correct state when # linearize is called on implicit components. - prob = Problem() + prob = om.Problem() model = prob.model - inputs_comp = IndepVarComp() + inputs_comp = om.IndepVarComp() inputs_comp.add_output('x1_u', val=1.0) model.add_subsystem('p', inputs_comp) @@ -1198,8 +1197,8 @@ def test_iimplicit(self): model.connect('p.x1_u', 'comp.x2_u') - model.linear_solver = DirectSolver() - model.nonlinear_solver = NewtonSolver() + model.linear_solver = om.DirectSolver() + model.nonlinear_solver = om.NewtonSolver() model.nonlinear_solver.options['atol'] = 1e-12 model.nonlinear_solver.options['rtol'] = 1e-12 diff --git a/openmdao/core/tests/test_simple_impl_comp.py b/openmdao/core/tests/test_simple_impl_comp.py index 9c99ef3c57..e3c89f5c4d 100644 --- a/openmdao/core/tests/test_simple_impl_comp.py +++ b/openmdao/core/tests/test_simple_impl_comp.py @@ -85,7 +85,7 @@ def setUp(self): self.p = Problem(group) self.p.model.linear_solver = LinearBlockGS() - self.p.setup(check=False) + self.p.setup() # Conclude setup but don't run model. self.p.final_setup() diff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py index 21cdbfdd2f..aa4c27e9f8 100644 --- a/openmdao/core/tests/test_system.py +++ b/openmdao/core/tests/test_system.py @@ -6,6 +6,7 @@ import numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExecComp +from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error, assert_warning @@ -236,9 +237,6 @@ class DummySolver(): self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): - from openmdao.api import Problem, IndepVarComp - from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp - prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) diff --git a/openmdao/core/tests/test_units.py b/openmdao/core/tests/test_units.py index 98c5d50131..3133a01de9 100644 --- a/openmdao/core/tests/test_units.py +++ b/openmdao/core/tests/test_units.py @@ -4,14 +4,13 @@ from six import iteritems -from openmdao.api import Problem, Group, ExplicitComponent, IndepVarComp, DirectSolver -from openmdao.api import ExecComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error, assert_warning from openmdao.test_suite.components.unit_conv import UnitConvGroup, SrcComp, TgtCompC, TgtCompF, \ TgtCompK, SrcCompFD, TgtCompCFD, TgtCompFFD, TgtCompKFD, TgtCompFMulti -class SpeedComp(ExplicitComponent): +class SpeedComp(om.ExplicitComponent): """Simple speed computation from distance and time with unit conversations.""" def setup(self): @@ -28,9 +27,9 @@ class TestUnitConversion(unittest.TestCase): def test_basic_dense_jac(self): """Test that output values and total derivatives are correct.""" - prob = Problem(model=UnitConvGroup(assembled_jac_type='dense')) + prob = om.Problem(model=UnitConvGroup(assembled_jac_type='dense')) - prob.model.linear_solver = DirectSolver(assemble_jac=True) + prob.model.linear_solver = om.DirectSolver(assemble_jac=True) # Check the outputs after running to test the unit conversions prob.setup(check=False, mode='fwd') @@ -60,24 +59,24 @@ def test_basic_dense_jac(self): assert_rel_error(self, J['tgtK.x3', 'px1.x1'][0][0], 1.0, 1e-6) def test_dangling_input_w_units(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('y=x', x={'units': 'ft'}, y={'units': 'm'})) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('y=x', x={'units': 'ft'}, y={'units': 'm'})) prob.setup() prob.run_model() # this test passes as long as it doesn't raise an exception def test_speed(self): - from openmdao.api import Problem, Group, IndepVarComp, ExecComp + import openmdao.api as om from openmdao.core.tests.test_units import SpeedComp - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('distance', val=1., units='m') comp.add_output('time', val=1., units='s') - prob = Problem(model=Group()) + prob = om.Problem() prob.model.add_subsystem('c1', comp) prob.model.add_subsystem('c2', SpeedComp()) - prob.model.add_subsystem('c3', ExecComp('f=speed',speed={'units': 'm/s'})) + prob.model.add_subsystem('c3', om.ExecComp('f=speed',speed={'units': 'm/s'})) prob.model.connect('c1.distance', 'c2.distance') prob.model.connect('c1.time', 'c2.time') prob.model.connect('c2.speed', 'c3.speed') @@ -96,7 +95,7 @@ def test_speed(self): def test_basic(self): """Test that output values and total derivatives are correct.""" - prob = Problem(model=UnitConvGroup()) + prob = om.Problem(model=UnitConvGroup()) # Check the outputs after running to test the unit conversions prob.setup(check=False, mode='fwd') @@ -140,7 +139,7 @@ def test_basic(self): def test_basic_apply(self): """Test that output values and total derivatives are correct.""" - class SrcCompa(ExplicitComponent): + class SrcCompa(om.ExplicitComponent): """Source provides degrees Celsius.""" def setup(self): @@ -159,7 +158,7 @@ def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode): else: d_inputs['x1'] += d_outputs['x2'] - class TgtCompFa(ExplicitComponent): + class TgtCompFa(om.ExplicitComponent): """Target expressed in degrees F.""" def setup(self): @@ -178,10 +177,10 @@ def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode): else: d_inputs['x2'] += d_outputs['x3'] - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px1', IndepVarComp('x1', 100.0)) + model.add_subsystem('px1', om.IndepVarComp('x1', 100.0)) model.add_subsystem('src', SrcCompa()) model.add_subsystem('tgtF', TgtCompFa()) @@ -211,9 +210,8 @@ def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode): def test_basic_fd_comps(self): - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1']) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) prob.model.add_subsystem('src', SrcCompFD()) prob.model.add_subsystem('tgtF', TgtCompFFD()) prob.model.add_subsystem('tgtC', TgtCompCFD()) @@ -223,7 +221,7 @@ def test_basic_fd_comps(self): prob.model.connect('src.x2', 'tgtC.x2') prob.model.connect('src.x2', 'tgtK.x2') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['src.x2'], 100.0, 1e-6) @@ -270,54 +268,54 @@ def test_basic_fd_comps(self): def test_bad_units(self): """Test error handling when invalid units are declared.""" - class Comp1(ExplicitComponent): + class Comp1(om.ExplicitComponent): def setup(self): self.add_input('x', 0.0, units='junk') - class Comp2(ExplicitComponent): + class Comp2(om.ExplicitComponent): def setup(self): self.add_output('x', 0.0, units='junk') with self.assertRaises(Exception) as cm: - prob = Problem(model=Comp1()) + prob = om.Problem(model=Comp1()) prob.setup() expected_msg = "The units 'junk' are invalid" self.assertTrue(expected_msg in str(cm.exception)) with self.assertRaises(Exception) as cm: - prob = Problem(model=Comp2()) + prob = om.Problem(model=Comp2()) prob.setup() expected_msg = "The units 'junk' are invalid" self.assertTrue(expected_msg in str(cm.exception)) def test_add_unitless_output(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('indep', IndepVarComp('x', 0.0, units='unitless')) + prob = om.Problem() + prob.model.add_subsystem('indep', om.IndepVarComp('x', 0.0, units='unitless')) msg = "Output 'x' has units='unitless' but 'unitless' has been deprecated. " \ "Use units=None instead. Note that connecting a unitless variable to " \ "one with units is no longer an error, but will issue a warning instead." with assert_warning(DeprecationWarning, msg): - prob.setup(check=False) + prob.setup() def test_add_unitless_input(self): - prob = Problem(model=Group()) - prob.model.add_subsystem('C1', ExecComp('y=x', x={'units': 'unitless'})) + prob = om.Problem() + prob.model.add_subsystem('C1', om.ExecComp('y=x', x={'units': 'unitless'})) msg = "Input 'x' has units='unitless' but 'unitless' has been deprecated. " \ "Use units=None instead. Note that connecting a unitless variable to " \ "one with units is no longer an error, but will issue a warning instead." with assert_warning(DeprecationWarning, msg): - prob.setup(check=False) + prob.setup() def test_incompatible_units(self): """Test error handling when only one of src and tgt have units.""" - prob = Problem(model=Group()) - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes_outputs=['x1']) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes_outputs=['x1']) prob.model.add_subsystem('src', SrcComp(), promotes_inputs=['x1']) - prob.model.add_subsystem('tgt', ExecComp('yy=xx', xx={'value': 0.0, 'units': 'unitless'})) + prob.model.add_subsystem('tgt', om.ExecComp('yy=xx', xx={'value': 0.0, 'units': 'unitless'})) prob.model.connect('src.x2', 'tgt.xx') msg = "Output 'src.x2' with units of 'degC' is connected to input 'tgt.xx' which has no units." @@ -327,15 +325,15 @@ def test_incompatible_units(self): def test_basic_implicit_conn(self): """Test units with all implicit connections.""" - prob = Problem(model=Group()) - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes_outputs=['x1']) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes_outputs=['x1']) prob.model.add_subsystem('src', SrcComp(), promotes_inputs=['x1'], promotes_outputs=['x2']) prob.model.add_subsystem('tgtF', TgtCompF(), promotes_inputs=['x2']) prob.model.add_subsystem('tgtC', TgtCompC(), promotes_inputs=['x2']) prob.model.add_subsystem('tgtK', TgtCompK(), promotes_inputs=['x2']) # Check the outputs after running to test the unit conversions - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['x2'], 100.0, 1e-6) @@ -363,11 +361,10 @@ def test_basic_implicit_conn(self): def test_basic_grouped(self): - prob = Problem() - prob.model = Group() - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1']) - sub1 = prob.model.add_subsystem('sub1', Group()) - sub2 = prob.model.add_subsystem('sub2', Group()) + prob = om.Problem() + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) + sub1 = prob.model.add_subsystem('sub1', om.Group()) + sub2 = prob.model.add_subsystem('sub2', om.Group()) sub1.add_subsystem('src', SrcComp()) sub2.add_subsystem('tgtF', TgtCompF()) @@ -379,7 +376,7 @@ def test_basic_grouped(self): prob.model.connect('sub1.src.x2', 'sub2.tgtC.x2') prob.model.connect('sub1.src.x2', 'sub2.tgtK.x2') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['sub1.src.x2'], 100.0, 1e-6) @@ -406,11 +403,11 @@ def test_basic_grouped(self): def test_basic_grouped_bug_from_pycycle(self): - prob = Problem() - root = prob.model = Group() + prob = om.Problem() + root = prob.model - prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1']) - sub1 = prob.model.add_subsystem('sub1', Group(), promotes=['x2']) + prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) + sub1 = prob.model.add_subsystem('sub1', om.Group(), promotes=['x2']) sub1.add_subsystem('src', SrcComp(), promotes=['x2']) root.add_subsystem('tgtF', TgtCompFMulti()) root.add_subsystem('tgtC', TgtCompC()) @@ -421,7 +418,7 @@ def test_basic_grouped_bug_from_pycycle(self): prob.model.connect('x2', 'tgtC.x2') prob.model.connect('x2', 'tgtK.x2') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['x2'], 100.0, 1e-6) @@ -448,18 +445,18 @@ def test_basic_grouped_bug_from_pycycle(self): #def test_basic_grouped_grouped_implicit(self): - #prob = Problem() - #root = prob.model = Group() - #sub1 = prob.model.add('sub1', Group(), promotes=['x2']) - #sub2 = prob.model.add('sub2', Group(), promotes=['x2']) + #prob = om.Problem() + #root = prob.model + #sub1 = prob.model.add('sub1', om.Group(), promotes=['x2']) + #sub2 = prob.model.add('sub2', om.Group(), promotes=['x2']) #sub1.add('src', SrcComp(), promotes = ['x2']) #sub2.add('tgtF', TgtCompFMulti(), promotes=['x2']) #sub2.add('tgtC', TgtCompC(), promotes=['x2']) #sub2.add('tgtK', TgtCompK(), promotes=['x2']) - #prob.model.add('px1', IndepVarComp('x1', 100.0), promotes=['x1']) + #prob.model.add('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) #prob.model.connect('x1', 'sub1.src.x1') - #prob.setup(check=False) + #prob.setup() #prob.run() #assert_rel_error(self, prob['x2'], 100.0, 1e-6) @@ -576,13 +573,13 @@ def test_basic_grouped_bug_from_pycycle(self): #dinputs['Odot_BI'][i, j, :] -= -self.dw_dOdot[:, k, i, j] * \ #dw_B[k, :] - #prob = Problem() - #root = prob.model = Group() + #prob = om.Problem() + #root = prob.model #prob.model.add('comp', Attitude_Angular(n=5), promotes=['*']) - #prob.model.add('p1', IndepVarComp('O_BI', np.ones((3, 3, 5))), promotes=['*']) - #prob.model.add('p2', IndepVarComp('Odot_BI', np.ones((3, 3, 5))), promotes=['*']) + #prob.model.add('p1', om.IndepVarComp('O_BI', np.ones((3, 3, 5))), promotes=['*']) + #prob.model.add('p2', om.IndepVarComp('Odot_BI', np.ones((3, 3, 5))), promotes=['*']) - #prob.setup(check=False) + #prob.setup() #prob.run() #indep_list = ['O_BI', 'Odot_BI'] @@ -602,31 +599,29 @@ def test_basic_grouped_bug_from_pycycle(self): def test_incompatible_connections(self): - class BadComp(ExplicitComponent): + class BadComp(om.ExplicitComponent): def setup(self): self.add_input('x2', 100.0, units='m') self.add_output('x3', 100.0) # Explicit Connection - prob = Problem() - prob.model = Group() + prob = om.Problem() prob.model.add_subsystem('src', SrcComp()) prob.model.add_subsystem('dest', BadComp()) prob.model.connect('src.x2', 'dest.x2') with self.assertRaises(Exception) as cm: - prob.setup(check=False) + prob.setup() expected_msg = "Output units of 'degC' for 'src.x2' are incompatible with input units of 'm' for 'dest.x2'." self.assertEqual(expected_msg, str(cm.exception)) # Implicit Connection - prob = Problem() - prob.model = Group() + prob = om.Problem() prob.model.add_subsystem('src', SrcComp(), promotes=['x2']) prob.model.add_subsystem('dest', BadComp(),promotes=['x2']) with self.assertRaises(Exception) as cm: - prob.setup(check=False) + prob.setup() expected_msg = "Output units of 'degC' for 'src.x2' are incompatible with input units of 'm' for 'dest.x2'." @@ -638,14 +633,14 @@ def setup(self): ## "rest" of the problem that the others are testing, namely that ## outscope vars could sometimes cause a problem even absent any units. - #prob = Problem() - #root = prob.model = Group() - #root.add('p1', IndepVarComp('xx', 3.0)) - #root.add('c1', ExecComp(['y1=0.5*x + 0.1*xx', 'y2=0.3*x - 1.0*xx'])) - #root.add('c2', ExecComp(['y=0.5*x'])) - #sub = root.add('sub', Group()) - #sub.add('cc1', ExecComp(['y=0.1*x1 + 0.01*x2'])) - #sub.add('cc2', ExecComp(['y=0.1*x'])) + #prob = om.Problem() + #root = prob.model + #root.add('p1', om.IndepVarComp('xx', 3.0)) + #root.add('c1', om.ExecComp(['y1=0.5*x + 0.1*xx', 'y2=0.3*x - 1.0*xx'])) + #root.add('c2', om.ExecComp(['y=0.5*x'])) + #sub = root.add('sub', om.Group()) + #sub.add('cc1', om.ExecComp(['y=0.1*x1 + 0.01*x2'])) + #sub.add('cc2', om.ExecComp(['y=0.1*x'])) #root.connect('p1.xx', 'c1.xx') #root.connect('c1.y1', 'c2.x') @@ -658,12 +653,12 @@ def setup(self): #root.linear_solver = ScipyKrylov() #sub.nonlinear_solver = Newton() - #sub.linear_solver = DirectSolver() + #sub.linear_solver = om.DirectSolver() #prob.driver.add_desvar('p1.xx') #prob.driver.add_objective('c1.y2') - #prob.setup(check=False) + #prob.setup() #prob.run() @@ -684,14 +679,14 @@ def setup(self): ## higher scopes aren't sitting there converting themselves during sub ## iterations. - #prob = Problem() - #root = prob.model = Group() - #root.add('p1', IndepVarComp('xx', 3.0)) - #root.add('c1', ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) - #root.add('c2', ExecComp(['y=0.5*x'])) - #sub = root.add('sub', Group()) - #sub.add('cc1', ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'nm'})) - #sub.add('cc2', ExecComp(['y=1.01*x'])) + #prob = om.Problem() + #root = prob.model + #root.add('p1', om.IndepVarComp('xx', 3.0)) + #root.add('c1', om.ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) + #root.add('c2', om.ExecComp(['y=0.5*x'])) + #sub = root.add('sub', om.Group()) + #sub.add('cc1', om.ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'nm'})) + #sub.add('cc2', om.ExecComp(['y=1.01*x'])) #root.connect('p1.xx', 'c1.xx') #root.connect('c1.y1', 'c2.x') @@ -706,12 +701,12 @@ def setup(self): #root.linear_solver.options['maxiter'] = 1 #sub.nonlinear_solver = Newton() - #sub.linear_solver = DirectSolver() + #sub.linear_solver = om.DirectSolver() #prob.driver.add_desvar('p1.xx') #prob.driver.add_objective('sub.cc2.y') - #prob.setup(check=False) + #prob.setup() #prob.run() #self.assertTrue(not np.isnan(prob['sub.cc2.y'])) @@ -722,14 +717,14 @@ def setup(self): ## higher scopes aren't sitting there converting themselves during sub ## iterations. - #prob = Problem() - #root = prob.model = Group() - #root.add('p1', IndepVarComp('xx', 3.0)) - #root.add('c1', ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) - #root.add('c2', ExecComp(['y=0.5*x'])) - #sub = root.add('sub', Group()) - #sub.add('cc1', ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'nm'})) - #sub.add('cc2', ExecComp(['y=1.01*x'])) + #prob = om.Problem() + #root = prob.model + #root.add('p1', om.IndepVarComp('xx', 3.0)) + #root.add('c1', om.ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) + #root.add('c2', om.ExecComp(['y=0.5*x'])) + #sub = root.add('sub', om.Group()) + #sub.add('cc1', om.ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'nm'})) + #sub.add('cc2', om.ExecComp(['y=1.01*x'])) #root.connect('p1.xx', 'c1.xx') #root.connect('c1.y1', 'c2.x') @@ -745,12 +740,12 @@ def setup(self): #root.linear_solver.options['mode'] = 'rev' #sub.nonlinear_solver = Newton() - #sub.linear_solver = DirectSolver() + #sub.linear_solver = om.DirectSolver() #prob.driver.add_desvar('p1.xx') #prob.driver.add_objective('sub.cc2.y') - #prob.setup(check=False) + #prob.setup() #prob.run() #self.assertTrue(not np.isnan(prob['sub.cc2.y'])) @@ -801,14 +796,14 @@ def setup(self): #dinputs['x2'] = 1.01*dresids['y'] #self.dx2count += 1 - #prob = Problem() - #root = prob.model = Group() - #root.add('p1', IndepVarComp('xx', 3.0)) - #root.add('c1', ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) - #root.add('c2', ExecComp(['y=0.5*x'])) - #sub = root.add('sub', Group()) + #prob = om.Problem() + #root = prob.model + #root.add('p1', om.IndepVarComp('xx', 3.0)) + #root.add('c1', om.ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) + #root.add('c2', om.ExecComp(['y=0.5*x'])) + #sub = root.add('sub', om.Group()) #sub.add('cc1', TestComp()) - #sub.add('cc2', ExecComp(['y=1.01*x'])) + #sub.add('cc2', om.ExecComp(['y=1.01*x'])) #root.connect('p1.xx', 'c1.xx') #root.connect('c1.y1', 'c2.x') @@ -824,12 +819,12 @@ def setup(self): #root.linear_solver.options['mode'] = 'rev' #sub.nonlinear_solver = Newton() - #sub.linear_solver = DirectSolver() + #sub.linear_solver = om.DirectSolver() #prob.driver.add_desvar('p1.xx') #prob.driver.add_objective('sub.cc2.y') - #prob.setup(check=False) + #prob.setup() #prob.run() ## x1 deriv code should be called less if the dinputs vec only @@ -842,14 +837,14 @@ def setup(self): ## higher scopes aren't sitting there converting themselves during sub ## iterations. - #prob = Problem() - #root = prob.model = Group() - #root.add('p1', IndepVarComp('xx', 3.0)) - #root.add('c1', ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) - #root.add('c2', ExecComp(['y=0.5*x'])) - #sub = root.add('sub', Group()) - #sub.add('cc1', ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'fm'})) - #sub.add('cc2', ExecComp(['y=1.01*x'])) + #prob = om.Problem() + #root = prob.model + #root.add('p1', om.IndepVarComp('xx', 3.0)) + #root.add('c1', om.ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) + #root.add('c2', om.ExecComp(['y=0.5*x'])) + #sub = root.add('sub', om.Group()) + #sub.add('cc1', om.ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'fm'})) + #sub.add('cc2', om.ExecComp(['y=1.01*x'])) #root.connect('p1.xx', 'c1.xx') #root.connect('c1.y1', 'c2.x') @@ -869,7 +864,7 @@ def setup(self): #prob.driver.add_desvar('p1.xx') #prob.driver.add_objective('sub.cc2.y') - #prob.setup(check=False) + #prob.setup() #prob.run() @@ -884,14 +879,14 @@ def setup(self): ## Make sure preconditioners also work - #prob = Problem() - #root = prob.model = Group() - #root.add('p1', IndepVarComp('xx', 3.0)) - #root.add('c1', ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) - #root.add('c2', ExecComp(['y=0.5*x'])) - #sub = root.add('sub', Group()) - #sub.add('cc1', ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'fm'})) - #sub.add('cc2', ExecComp(['y=1.01*x'])) + #prob = om.Problem() + #root = prob.model + #root.add('p1', om.IndepVarComp('xx', 3.0)) + #root.add('c1', om.ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'})) + #root.add('c2', om.ExecComp(['y=0.5*x'])) + #sub = root.add('sub', om.Group()) + #sub.add('cc1', om.ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'fm'})) + #sub.add('cc2', om.ExecComp(['y=1.01*x'])) #root.connect('p1.xx', 'c1.xx') #root.connect('c1.y1', 'c2.x') @@ -907,12 +902,12 @@ def setup(self): #sub.nonlinear_solver = Newton() #sub.linear_solver = ScipyKrylov() - #sub.linear_solver.precon = DirectSolver() + #sub.linear_solver.precon = om.DirectSolver() #prob.driver.add_desvar('p1.xx') #prob.driver.add_objective('sub.cc2.y') - #prob.setup(check=False) + #prob.setup() #prob.run() @@ -956,17 +951,16 @@ def setup(self): #def test_basic(self): - #prob = Problem() - #prob.model = Group() + #prob = om.Problem() #prob.model.add('src', PBOSrcComp()) #prob.model.add('tgtF', PBOTgtCompF()) - #prob.model.add('px1', IndepVarComp('x1', 100.0), promotes=['x1']) + #prob.model.add('px1', om.IndepVarComp('x1', 100.0), promotes=['x1']) #prob.model.connect('x1', 'src.x1') #prob.model.connect('src.x2', 'tgtF.x2') #prob.model.deriv_options['type'] = 'fd' - #prob.setup(check=False) + #prob.setup() #prob.run() #assert_rel_error(self, prob['src.x2'], 100.0, 1e-6) @@ -1015,8 +1009,8 @@ def setup(self): #""" No action.""" #pass - #top = Problem() - #root = top.root = Group() + #top = om.Problem() + #root = top.root = om.Group() #root.add('src', Src()) #root.add('tgt', Tgt()) @@ -1024,7 +1018,7 @@ def setup(self): #root.connect('src.x2', 'tgt.x2') #root.connect('src.x3', 'tgt.x3') - #top.setup(check=False) + #top.setup() #top.run() #assert_rel_error(self, top['tgt.x1'], np.pi, 1e-6) diff --git a/openmdao/devtools/problem_viewer/tests/test_viewmodeldata.py b/openmdao/devtools/problem_viewer/tests/test_viewmodeldata.py index 6b9abc454c..173464b7d0 100644 --- a/openmdao/devtools/problem_viewer/tests/test_viewmodeldata.py +++ b/openmdao/devtools/problem_viewer/tests/test_viewmodeldata.py @@ -94,7 +94,7 @@ def test_model_viewer_has_correct_data_from_problem(self): to the expected structure, using the SellarStateConnection model. """ p = Problem(model=SellarStateConnection()) - p.setup(check=False) + p.setup() model_viewer_data = _get_viewer_data(p) @@ -129,7 +129,7 @@ def test_model_viewer_has_correct_data_from_sqlite(self): r = SqliteRecorder(self.sqlite_db_filename) p.driver.add_recorder(r) - p.setup(check=False) + p.setup() p.final_setup() r.shutdown() @@ -161,7 +161,7 @@ def test_view_model_from_problem(self): """ p = Problem() p.model = SellarStateConnection() - p.setup(check=False) + p.setup() view_model(p, outfile=self.problem_html_filename, show_browser=DEBUG) # Check that the html file has been created and has something in it. @@ -177,7 +177,7 @@ def test_view_model_from_sqlite(self): p.model = SellarStateConnection() r = SqliteRecorder(self.sqlite_db_filename2) p.driver.add_recorder(r) - p.setup(check=False) + p.setup() p.final_setup() r.shutdown() view_model(self.sqlite_db_filename2, outfile=self.sqlite_html_filename, show_browser=DEBUG) @@ -204,7 +204,7 @@ def test_view_model_set_title(self): """ p = Problem() p.model = SellarStateConnection() - p.setup(check=False) + p.setup() view_model(p, outfile=self.problem_html_filename, show_browser=DEBUG, title="Sellar State Connection") diff --git a/openmdao/devtools/tests/test_viewconns.py b/openmdao/devtools/tests/test_viewconns.py index 5a176fd690..bd1e9511d7 100644 --- a/openmdao/devtools/tests/test_viewconns.py +++ b/openmdao/devtools/tests/test_viewconns.py @@ -12,7 +12,7 @@ def test_sellar(self): prob = Problem() prob.model = SellarNoDerivatives() - prob.setup(check=False) + prob.setup() prob.final_setup() # no output checking, just make sure no exceptions raised diff --git a/openmdao/devtools/tests/test_xdsm_viewer.py b/openmdao/devtools/tests/test_xdsm_viewer.py index 83cf701e47..6b213d85d7 100644 --- a/openmdao/devtools/tests/test_xdsm_viewer.py +++ b/openmdao/devtools/tests/test_xdsm_viewer.py @@ -6,10 +6,8 @@ import numpy as np from numpy.distutils.exec_command import find_executable -from openmdao.api import Problem, ExplicitComponent, IndepVarComp, ExecComp, ScipyOptimizeDriver, \ - Group, write_xdsm +import openmdao.api as om from openmdao.devtools.xdsm_viewer.html_writer import write_html -from openmdao.drivers.doe_driver import DOEDriver from openmdao.test_suite.components.sellar import SellarNoDerivatives, SellarDis1, SellarDis2 from openmdao.test_suite.components.sellar_feature import SellarMDA from openmdao.test_suite.scripts.circuit import Circuit @@ -51,7 +49,7 @@ def tearDown(self): def test_pyxdsm_output_sides(self): """Makes XDSM for the Sellar problem""" - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -60,29 +58,29 @@ def test_pyxdsm_output_sides(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output (outputs on the left) filename = 'xdsm_outputs_on_the_left' - write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, quiet=QUIET, - output_side='left') + om.write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, quiet=QUIET, + output_side='left') # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) filename = 'xdsm_outputs_on_the_right' # Write output (all outputs on the right) - write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, quiet=QUIET, - output_side='right') + om.write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, quiet=QUIET, + output_side='right') # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) filename = 'xdsm_outputs_side_mixed' # Write output (outputs mixed) - write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, quiet=QUIET, - output_side={'optimization': 'left', 'default': 'right'}) + om.write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, quiet=QUIET, + output_side={'optimization': 'left', 'default': 'right'}) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) @@ -92,12 +90,12 @@ def test_pyxdsm_case_reading(self): Writes a recorder file, and the XDSM writer makes the diagram based on the SQL file and not the Problem instance. """ - from openmdao.recorders.sqlite_recorder import SqliteRecorder + import openmdao.api as om filename = 'xdsm_from_sql' case_recording_filename = filename + '.sql' - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -106,15 +104,15 @@ def test_pyxdsm_case_reading(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - recorder = SqliteRecorder(case_recording_filename) + recorder = om.SqliteRecorder(case_recording_filename) prob.driver.add_recorder(recorder) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(case_recording_filename, filename=filename, out_format='tex', - show_browser=False, quiet=QUIET) + om.write_xdsm(case_recording_filename, filename=filename, out_format='tex', + show_browser=False, quiet=QUIET) # Check if file was created self.assertTrue(os.path.isfile(case_recording_filename)) @@ -127,7 +125,7 @@ def test_pyxdsm_sellar_no_recurse(self): """Makes XDSM for the Sellar problem, with no recursion.""" filename = 'xdsm1' - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -136,12 +134,12 @@ def test_pyxdsm_sellar_no_recurse(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, recurse=False, - quiet=QUIET) + om.write_xdsm(prob, filename=filename, out_format=PYXDSM_OUT, show_browser=SHOW, recurse=False, + quiet=QUIET) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) @@ -151,7 +149,7 @@ def test_pyxdsm_pdf(self): Makes an XDSM of the Sphere test case. It also adds a design variable, constraint and objective. """ - class Rosenbrock(ExplicitComponent): + class Rosenbrock(om.ExplicitComponent): def __init__(self, problem): super(Rosenbrock, self).__init__() @@ -170,25 +168,25 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x0 = np.array([1.2, 1.5]) filename = 'xdsm2' - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp(problem=prob), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(problem=prob), promotes=['*']) indeps.add_output('x', list(x0)) prob.model.add_subsystem('sphere', Rosenbrock(problem=prob), promotes=['*']) - prob.model.add_subsystem('con', ExecComp('c=sum(x)', x=np.ones(2)), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.model.add_subsystem('con', om.ExecComp('c=sum(x)', x=np.ones(2)), promotes=['*']) + prob.driver = om.ScipyOptimizeDriver() prob.model.add_design_var('x') prob.model.add_objective('f') prob.model.add_constraint('c', lower=1.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # requesting 'pdf', but if 'pdflatex' is not found we will only get 'tex' pdflatex = find_executable('pdflatex') # Write output - write_xdsm(prob, filename=filename, out_format='pdf', show_browser=SHOW, quiet=QUIET) + om.write_xdsm(prob, filename=filename, out_format='pdf', show_browser=SHOW, quiet=QUIET) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, 'tex']))) @@ -196,7 +194,7 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): self.assertTrue(not pdflatex or os.path.isfile('.'.join([filename, 'pdf']))) def test_pyxdsm_identical_relative_names(self): - class TimeComp(ExplicitComponent): + class TimeComp(om.ExplicitComponent): def setup(self): self.add_input('t_initial', val=0.) @@ -210,12 +208,12 @@ def compute(self, inputs, outputs): outputs['time'][0] = t_initial outputs['time'][1] = t_initial + t_duration - class Phase(Group): + class Phase(om.Group): def setup(self): super(Phase, self).setup() - indep = IndepVarComp() + indep = om.IndepVarComp() for var in ['t_initial', 't_duration']: indep.add_output(var, val=1.0) @@ -229,8 +227,8 @@ def setup(self): self.set_order(['time_extents', 'time']) - p = Problem() - p.driver = ScipyOptimizeDriver() + p = om.Problem() + p.driver = om.ScipyOptimizeDriver() orbit_phase = Phase() p.model.add_subsystem('orbit_phase', orbit_phase) @@ -242,41 +240,41 @@ def setup(self): p.model.add_design_var('orbit_phase.t_initial') p.model.add_design_var('orbit_phase.t_duration') p.model.add_objective('systems_phase.time.time') - p.setup(check=False) + p.setup() p.run_model() # Test non unique local names filename = 'pyxdsm_identical_rel_names' - write_xdsm(p, filename, out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW) + om.write_xdsm(p, filename, out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW) self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) # Check formatting # Max character box formatting filename = 'pyxdsm_cut_char' - write_xdsm(p, filename, out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, - box_stacking='cut_chars', box_width=15) + om.write_xdsm(p, filename, out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, + box_stacking='cut_chars', box_width=15) self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) # Cut characters box formatting filename = 'pyxdsm_max_chars' - write_xdsm(p, filename, out_format=PYXDSM_OUT, quiet=True, show_browser=SHOW, - box_stacking='max_chars', box_width=15) + om.write_xdsm(p, filename, out_format=PYXDSM_OUT, quiet=True, show_browser=SHOW, + box_stacking='max_chars', box_width=15) self.assertTrue(os.path.isfile('.'.join([filename, PYXDSM_OUT]))) def test_model_path_and_recursion(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - p = Problem() + p = om.Problem() model = p.model - group = model.add_subsystem('G1', Group(), promotes=['*']) - group2 = model.add_subsystem('G2', Group()) - group.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - group.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) - group2.add_subsystem('source2', IndepVarComp('I', 0.1, units='A')) + group = model.add_subsystem('G1', om.Group(), promotes=['*']) + group2 = model.add_subsystem('G2', om.Group()) + group.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + group.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) + group2.add_subsystem('source2', om.IndepVarComp('I', 0.1, units='A')) group.add_subsystem('circuit', Circuit()) group.connect('source.I', 'circuit.I_in') @@ -286,7 +284,7 @@ def test_model_path_and_recursion(self): model.add_design_var('source.I') model.add_objective('circuit.D1.I') - p.setup(check=False) + p.setup() # set some initial guesses p['circuit.n1.V'] = 10. @@ -295,71 +293,71 @@ def test_model_path_and_recursion(self): p.run_model() # No model path, no recursion - write_xdsm(p, 'xdsm_circuit', out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, - recurse=False) + om.write_xdsm(p, 'xdsm_circuit', out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, + recurse=False) self.assertTrue(os.path.isfile('.'.join(['xdsm_circuit', PYXDSM_OUT]))) # Model path given + recursion - write_xdsm(p, 'xdsm_circuit2', out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, - recurse=True, model_path='G2', include_external_outputs=False) + om.write_xdsm(p, 'xdsm_circuit2', out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, + recurse=True, model_path='G2', include_external_outputs=False) self.assertTrue(os.path.isfile('.'.join(['xdsm_circuit2', PYXDSM_OUT]))) # Model path given + no recursion - write_xdsm(p, 'xdsm_circuit3', out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, - recurse=False, model_path='G1') + om.write_xdsm(p, 'xdsm_circuit3', out_format=PYXDSM_OUT, quiet=QUIET, show_browser=SHOW, + recurse=False, model_path='G1') self.assertTrue(os.path.isfile('.'.join(['xdsm_circuit3', PYXDSM_OUT]))) # Invalid model path, should raise error with self.assertRaises(ValueError): - write_xdsm(p, 'xdsm_circuit4', out_format='tex', quiet=QUIET, show_browser=SHOW, - recurse=False, model_path='G3') + om.write_xdsm(p, 'xdsm_circuit4', out_format='tex', quiet=QUIET, show_browser=SHOW, + recurse=False, model_path='G3') def test_pyxdsm_solver(self): - from openmdao.api import NonlinearBlockGS + import openmdao.api as om out_format = PYXDSM_OUT - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() - model.nonlinear_solver = NonlinearBlockGS() - prob.driver = ScipyOptimizeDriver() + model.nonlinear_solver = om.NonlinearBlockGS() + prob.driver = om.ScipyOptimizeDriver() prob.model.add_objective('obj') - prob.setup(check=False) + prob.setup() prob.run_model() filename = 'pyxdsm_solver' # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, - show_browser=SHOW, include_solver=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, + show_browser=SHOW, include_solver=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) filename = 'pyxdsm_solver2' # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, - show_browser=SHOW, include_solver=True, recurse=False) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, + show_browser=SHOW, include_solver=True, recurse=False) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_pyxdsm_mda(self): filename = 'pyxdsm_mda' out_format = PYXDSM_OUT - prob = Problem(model=SellarMDA()) - prob.setup(check=False) + prob = om.Problem(model=SellarMDA()) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, - show_browser=SHOW, include_solver=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, + show_browser=SHOW, include_solver=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_pyxdsm_mdf(self): filename = 'pyxdsm_mdf' out_format = PYXDSM_OUT - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -368,50 +366,50 @@ def test_pyxdsm_mdf(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, - show_browser=SHOW, include_solver=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, + show_browser=SHOW, include_solver=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_parallel(self): - from openmdao.api import ParallelGroup, NonlinearBlockGS + import openmdao.api as om - class SellarMDA(Group): + class SellarMDA(om.Group): """ Group containing the Sellar MDA. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', ParallelGroup(), promotes=['*']) + cycle = self.add_subsystem('cycle', om.ParallelGroup(), promotes=['*']) cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], promotes_outputs=['y1']) cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) filename = 'pyxdsm_parallel' out_format = PYXDSM_OUT - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -420,63 +418,63 @@ def setup(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_execcomp(self): filename = 'pyxdsm_execcomp' out_format = PYXDSM_OUT - prob = Problem(model=Group()) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x') - prob.model.add_subsystem('C1', ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) + prob.driver = om.ScipyOptimizeDriver() prob.model.add_design_var('x', lower=0.0, upper=10.0) prob.model.add_objective('y') - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_doe(self): filename = 'pyxdsm_doe' out_format = PYXDSM_OUT - prob = Problem(model=Group()) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x') - prob.model.add_subsystem('C1', ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) - prob.driver = DOEDriver() + prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) + prob.driver = om.DOEDriver() prob.model.add_design_var('x', lower=0.0, upper=10.0) prob.model.add_objective('y') - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_meta_model(self): + import openmdao.api as om from openmdao.components.tests.test_meta_model_structured_comp import SampleMap - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp filename = 'pyxdsm_meta_model' out_format = PYXDSM_OUT - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -490,7 +488,7 @@ def test_meta_model(self): model.add_subsystem('des_vars', ivc, promotes=["*"]) - comp = MetaModelStructuredComp(method='slinear', extrapolate=True) + comp = om.MetaModelStructuredComp(method='slinear', extrapolate=True) for param in params: comp.add_input(param['name'], param['default'], param['values']) @@ -499,12 +497,12 @@ def test_meta_model(self): comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) - prob = Problem(model) - prob.setup(check=False) + prob = om.Problem(model) + prob.setup() prob.final_setup() - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) @@ -533,7 +531,7 @@ def test_xdsmjs(self): """ filename = 'xdsmjs' # this name is needed for XDSMjs - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -542,12 +540,12 @@ def test_xdsmjs(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format='html', subs=(), show_browser=SHOW, - embed_data=False) + om.write_xdsm(prob, filename=filename, out_format='html', subs=(), show_browser=SHOW, + embed_data=False) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, 'json']))) @@ -561,7 +559,7 @@ def test_xdsmjs_embed_data(self): """ filename = 'xdsmjs_embedded' # this name is needed for XDSMjs - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -570,12 +568,12 @@ def test_xdsmjs_embed_data(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format='html', subs=(), show_browser=SHOW, - embed_data=True) + om.write_xdsm(prob, filename=filename, out_format='html', subs=(), show_browser=SHOW, + embed_data=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, 'html']))) @@ -588,7 +586,7 @@ def test_xdsmjs_embeddable(self): """ filename = 'xdsmjs_embeddable' # this name is needed for XDSMjs - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -597,12 +595,12 @@ def test_xdsmjs_embeddable(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format='html', subs=(), show_browser=SHOW, - embed_data=True, embeddable=True) + om.write_xdsm(prob, filename=filename, out_format='html', subs=(), show_browser=SHOW, + embed_data=True, embeddable=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, 'html']))) @@ -668,7 +666,7 @@ def test_html_writer_str(self): self.assertTrue(os.path.isfile(outfile)) def test_pyxdsm_identical_relative_names(self): - class TimeComp(ExplicitComponent): + class TimeComp(om.ExplicitComponent): def setup(self): self.add_input('t_initial', val=0.) @@ -682,12 +680,12 @@ def compute(self, inputs, outputs): outputs['time'][0] = t_initial outputs['time'][1] = t_initial + t_duration - class Phase(Group): + class Phase(om.Group): def setup(self): super(Phase, self).setup() - indep = IndepVarComp() + indep = om.IndepVarComp() for var in ['t_initial', 't_duration']: indep.add_output(var, val=1.0) @@ -701,8 +699,8 @@ def setup(self): self.set_order(['time_extents', 'time']) - p = Problem() - p.driver = ScipyOptimizeDriver() + p = om.Problem() + p.driver = om.ScipyOptimizeDriver() orbit_phase = Phase() p.model.add_subsystem('orbit_phase', orbit_phase) @@ -714,32 +712,32 @@ def setup(self): p.model.add_design_var('orbit_phase.t_initial') p.model.add_design_var('orbit_phase.t_duration') p.model.add_objective('systems_phase.time.time') - p.setup(check=False) + p.setup() p.run_model() - write_xdsm(p, 'xdsmjs_orbit', out_format='html', show_browser=SHOW) + om.write_xdsm(p, 'xdsmjs_orbit', out_format='html', show_browser=SHOW) self.assertTrue(os.path.isfile('.'.join(['xdsmjs_orbit', 'html']))) def test_xdsmjs_mda(self): filename = 'xdsmjs_mda' out_format = 'html' - prob = Problem(model=SellarMDA()) - prob.setup(check=False) + prob = om.Problem(model=SellarMDA()) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, - show_browser=SHOW, embed_data=True, embeddable=True, include_solver=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, + show_browser=SHOW, embed_data=True, embeddable=True, include_solver=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_xdsmjs_mdf(self): filename = 'xdsmjs_mdf' out_format = 'html' - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -748,69 +746,69 @@ def test_xdsmjs_mdf(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, - show_browser=SHOW, include_solver=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, + show_browser=SHOW, include_solver=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_xdsm_solver(self): - from openmdao.api import NonlinearBlockGS + import openmdao.api as om filename = 'xdsmjs_solver' out_format = 'html' - prob = Problem(model=SellarNoDerivatives()) - prob.model.nonlinear_solver = NonlinearBlockGS() - prob.driver = ScipyOptimizeDriver() + prob = om.Problem(model=SellarNoDerivatives()) + prob.model.nonlinear_solver = om.NonlinearBlockGS() + prob.driver = om.ScipyOptimizeDriver() prob.model.add_objective('obj') - prob.setup(check=False) + prob.setup() prob.run_model() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, - show_browser=SHOW, include_solver=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, + show_browser=SHOW, include_solver=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_parallel(self): - from openmdao.api import ParallelGroup, NonlinearBlockGS + import openmdao.api as om - class SellarMDA(Group): + class SellarMDA(om.Group): """ Group containing the Sellar MDA. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', ParallelGroup(), promotes=['*']) + cycle = self.add_subsystem('cycle', om.ParallelGroup(), promotes=['*']) cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], promotes_outputs=['y1']) cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) filename = 'xdsmjs_parallel' out_format = 'html' - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -819,63 +817,63 @@ def setup(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() # Write output - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_execcomp(self): filename = 'xdsmjs_execcomp' out_format = 'html' - prob = Problem(model=Group()) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x') - prob.model.add_subsystem('C1', ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) + prob.driver = om.ScipyOptimizeDriver() prob.model.add_design_var('x', lower=0.0, upper=10.0) prob.model.add_objective('y') - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_doe(self): filename = 'xdsmjs_doe' out_format = 'html' - prob = Problem(model=Group()) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x') - prob.model.add_subsystem('C1', ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) - prob.driver = DOEDriver() + prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0), promotes=['*']) + prob.driver = om.DOEDriver() prob.model.add_design_var('x', lower=0.0, upper=10.0) prob.model.add_objective('y') - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_meta_model(self): + import openmdao.api as om from openmdao.components.tests.test_meta_model_structured_comp import SampleMap - from openmdao.components.meta_model_structured_comp import MetaModelStructuredComp filename = 'xdsmjs_meta_model' out_format = 'html' - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() mapdata = SampleMap() @@ -889,7 +887,7 @@ def test_meta_model(self): model.add_subsystem('des_vars', ivc, promotes=["*"]) - comp = MetaModelStructuredComp(method='slinear', extrapolate=True) + comp = om.MetaModelStructuredComp(method='slinear', extrapolate=True) for param in params: comp.add_input(param['name'], param['default'], param['values']) @@ -898,25 +896,25 @@ def test_meta_model(self): comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) - prob = Problem(model) - prob.setup(check=False) + prob = om.Problem(model) + prob.setup() prob.final_setup() - write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, - show_parallel=True) + om.write_xdsm(prob, filename=filename, out_format=out_format, quiet=QUIET, show_browser=SHOW, + show_parallel=True) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, out_format]))) def test_circuit_recurse(self): # Implicit component is also tested here - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -926,7 +924,7 @@ def test_circuit_recurse(self): model.add_design_var('source.I') model.add_objective('circuit.D1.I') - p.setup(check=False) + p.setup() # set some initial guesses p['circuit.n1.V'] = 10. @@ -934,18 +932,18 @@ def test_circuit_recurse(self): p.run_model() - write_xdsm(p, 'xdsmjs_circuit', out_format='html', quiet=QUIET, show_browser=SHOW, - recurse=True) + om.write_xdsm(p, 'xdsmjs_circuit', out_format='html', quiet=QUIET, show_browser=SHOW, + recurse=True) self.assertTrue(os.path.isfile('.'.join(['xdsmjs_circuit', 'html']))) def test_legend(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -955,7 +953,7 @@ def test_legend(self): model.add_design_var('source.I') model.add_objective('circuit.D1.I') - p.setup(check=False) + p.setup() # set some initial guesses p['circuit.n1.V'] = 10. @@ -963,14 +961,14 @@ def test_legend(self): p.run_model() - write_xdsm(p, 'xdsmjs_circuit_legend', out_format='html', quiet=QUIET, show_browser=SHOW, - recurse=True, legend=True) + om.write_xdsm(p, 'xdsmjs_circuit_legend', out_format='html', quiet=QUIET, show_browser=SHOW, + recurse=True, legend=True) self.assertTrue(os.path.isfile('.'.join(['xdsmjs_circuit_legend', 'html']))) def test_xdsmjs_right_outputs(self): """Makes XDSM for the Sellar problem""" filename = 'xdsmjs_outputs_on_the_right' - prob = Problem() + prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) @@ -979,15 +977,15 @@ def test_xdsmjs_right_outputs(self): model.add_constraint('con1', equals=np.zeros(1)) model.add_constraint('con2', upper=0.0) - prob.setup(check=False) + prob.setup() prob.final_setup() msg = 'Right side outputs not implemented for XDSMjs.' # Write output with assert_warning(Warning, msg): - write_xdsm(prob, filename=filename, out_format='html', show_browser=SHOW, quiet=QUIET, - output_side='right') + om.write_xdsm(prob, filename=filename, out_format='html', show_browser=SHOW, quiet=QUIET, + output_side='right') # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, 'html']))) @@ -996,15 +994,15 @@ def test_wrong_out_format(self): """Incorrect output format error.""" filename = 'xdsm_wrong_format' # this name is needed for XDSMjs - prob = Problem() + prob = om.Problem() prob.model = SellarNoDerivatives() - prob.setup(check=False) + prob.setup() prob.final_setup() # no output checking, just make sure no exceptions raised with self.assertRaises(ValueError): - write_xdsm(prob, filename=filename, out_format='jpg', subs=(), show_browser=SHOW) + om.write_xdsm(prob, filename=filename, out_format='jpg', subs=(), show_browser=SHOW) def test_command(self): """ @@ -1028,16 +1026,16 @@ def format_block(names, **kwargs): """This method is overwritten, to implement some different formatting.""" return [name.upper() for name in names] - prob = Problem() + prob = om.Problem() prob.model = SellarNoDerivatives() - prob.setup(check=False) + prob.setup() prob.final_setup() my_writer = CustomWriter() filename = 'xdsm_custom_writer' # this name is needed for XDSMjs # Write output - write_xdsm(prob, filename=filename, writer=my_writer, show_browser=SHOW) + om.write_xdsm(prob, filename=filename, writer=my_writer, show_browser=SHOW) # Check if file was created self.assertTrue(os.path.isfile('.'.join([filename, my_writer.extension]))) @@ -1045,7 +1043,7 @@ def format_block(names, **kwargs): # Check that error is raised in case of wrong writer type filename = 'xdsm_custom_writer2' # this name is needed for XDSMjs with self.assertRaises(TypeError): # Wrong type passed for writer - write_xdsm(prob, filename=filename, writer=1, subs=(), show_browser=SHOW) + om.write_xdsm(prob, filename=filename, writer=1, subs=(), show_browser=SHOW) # Check warning, if settings for custom writer are not found my_writer2 = CustomWriter(name='my_writer') @@ -1057,7 +1055,7 @@ def format_block(names, **kwargs): # Write output with assert_warning(Warning, msg): - write_xdsm(prob, filename=filename, writer=my_writer2, show_browser=SHOW) + om.write_xdsm(prob, filename=filename, writer=my_writer2, show_browser=SHOW) if __name__ == "__main__": diff --git a/openmdao/docs/advanced_guide/implicit_comps/implicit_with_balancecomp.rst b/openmdao/docs/advanced_guide/implicit_comps/implicit_with_balancecomp.rst index 3e9af25196..14ad1b3559 100644 --- a/openmdao/docs/advanced_guide/implicit_comps/implicit_with_balancecomp.rst +++ b/openmdao/docs/advanced_guide/implicit_comps/implicit_with_balancecomp.rst @@ -76,8 +76,8 @@ You can do the same thing programmatically by adding the following to your pytho p.setup() - from openmdao.api import view_model - view_model(p) + import openmdao.api as om + om.view_model(p) Here is what the resulting visualization would look like for the above model: diff --git a/openmdao/docs/basic_guide/first_analysis.rst b/openmdao/docs/basic_guide/first_analysis.rst index 8fca02f1a2..4ea1d05ac5 100644 --- a/openmdao/docs/basic_guide/first_analysis.rst +++ b/openmdao/docs/basic_guide/first_analysis.rst @@ -38,15 +38,16 @@ Preamble :: from __future__ import division, print_function - from openmdao.api import ExplicitComponent + import openmdao.api as om At the top of any script you'll see these lines (or lines very similar to these) which import needed classes and functions. On the first import line, the `print_function` is used so that the code in the script will work in either Python 2 or 3. If you want to know whats going on with the division operator, check out this `detailed explanation `_. -The second import line brings in OpenMDAO classes that are needed to build and run a model. -As you progress to more complex models, you can expect to import more classes from `openmdao.api`, -but for now we only need this one to define our paraboloid component. +The second import line make availabe the most common OpenMDAO classes that are needed to build and run a model. +The `openmdao.api` module contains the class `ExplicitComponent` that we need to define the Paraboloid model. This +can be accessed via "om.ExplicitComponent" when we need it. As you progress to more complex models, you will learn about +more classes available in `openmdao.api`,but for now we only need this one to define our paraboloid component. Defining a Component --------------------- @@ -111,12 +112,10 @@ In this case, there are no units on the source (i.e. `des_vars.x`). .. code:: if __name__ == "__main__": - from openmdao.api import Problem - from openmdao.api import Group - from openmdao.api import IndepVarComp + import openmdao.api as om - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() ivc.add_output('x', 3.0) ivc.add_output('y', -4.0) model.add_subsystem('des_vars', ivc) @@ -125,7 +124,7 @@ In this case, there are no units on the source (i.e. `des_vars.x`). model.connect('des_vars.x', 'parab_comp.x') model.connect('des_vars.y', 'parab_comp.y') - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob.run_model() print(prob['parab_comp.f_xy']) diff --git a/openmdao/docs/basic_guide/first_optimization.rst b/openmdao/docs/basic_guide/first_optimization.rst index c7ef97bfab..bb06caff85 100644 --- a/openmdao/docs/basic_guide/first_optimization.rst +++ b/openmdao/docs/basic_guide/first_optimization.rst @@ -55,7 +55,7 @@ Here we'll use the :ref:`ScipyOptimizeDriver `, and tell .. code:: - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' Defining the Design Variables and Objective diff --git a/openmdao/docs/basic_guide/sellar.rst b/openmdao/docs/basic_guide/sellar.rst index de3de7093a..fcd261847a 100644 --- a/openmdao/docs/basic_guide/sellar.rst +++ b/openmdao/docs/basic_guide/sellar.rst @@ -68,7 +68,7 @@ Then, inside the :code:`setup` method of :code:`SellarMDA` we're also working di .. code:: - cycle = self.add_subsystem('cycle', Group(), promotes=['*']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['*']) cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], promotes_outputs=['y1']) cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) diff --git a/openmdao/docs/features/building_blocks/components/add_subtract_comp.rst b/openmdao/docs/features/building_blocks/components/add_subtract_comp.rst index 1a57cef603..2964412c1f 100644 --- a/openmdao/docs/features/building_blocks/components/add_subtract_comp.rst +++ b/openmdao/docs/features/building_blocks/components/add_subtract_comp.rst @@ -24,7 +24,7 @@ AddSubtractComp Example In the following example AddSubtractComp is used to add thrust, drag, lift, and weight forces. Note the scaling factor of -1 for the drag force and weight force. .. embed-code:: - openmdao.components.tests.test_add_subtract_comp.TestForDocs.test + openmdao.components.tests.test_add_subtract_comp.TestFeature.test :layout: code, output .. tags:: AddSubtractComp, Component diff --git a/openmdao/docs/features/building_blocks/components/cross_product_comp.rst b/openmdao/docs/features/building_blocks/components/cross_product_comp.rst index ed3a9e9325..ce53c80c3a 100644 --- a/openmdao/docs/features/building_blocks/components/cross_product_comp.rst +++ b/openmdao/docs/features/building_blocks/components/cross_product_comp.rst @@ -46,6 +46,6 @@ Note that no internal checks are performed to ensure that `c_units` are consiste with `a_units` and `b_units`. .. embed-code:: - openmdao.components.tests.test_cross_product_comp.TestForDocs.test + openmdao.components.tests.test_cross_product_comp.TestFeature.test .. tags:: CrossProductComp, Component diff --git a/openmdao/docs/features/building_blocks/components/dot_product_comp.rst b/openmdao/docs/features/building_blocks/components/dot_product_comp.rst index 68b59eab02..b03cecd2a3 100644 --- a/openmdao/docs/features/building_blocks/components/dot_product_comp.rst +++ b/openmdao/docs/features/building_blocks/components/dot_product_comp.rst @@ -41,6 +41,6 @@ Note that no internal checks are performed to ensure that `c_units` are consiste with `a_units` and `b_units`. .. embed-code:: - openmdao.components.tests.test_dot_product_comp.TestForDocs.test + openmdao.components.tests.test_dot_product_comp.TestFeature.test .. tags:: DotProductComp, Component diff --git a/openmdao/docs/features/building_blocks/components/matrix_vector_product_comp.rst b/openmdao/docs/features/building_blocks/components/matrix_vector_product_comp.rst index 0d27402680..96250ad744 100644 --- a/openmdao/docs/features/building_blocks/components/matrix_vector_product_comp.rst +++ b/openmdao/docs/features/building_blocks/components/matrix_vector_product_comp.rst @@ -34,7 +34,7 @@ The following code demonstrates the use of the MatrixVectorProductComp, finding of a random 3x3 matrix `M` and a 3-vector `x` at 100 points simultaneously. .. embed-code:: - openmdao.components.tests.test_matrix_vector_product_comp.TestForDocs.test + openmdao.components.tests.test_matrix_vector_product_comp.TestFeature.test .. tags:: MatrixVectorProductComp, Component diff --git a/openmdao/docs/features/building_blocks/components/mux_demux_comps.rst b/openmdao/docs/features/building_blocks/components/mux_demux_comps.rst index b7a078ef21..ee1e27d7de 100644 --- a/openmdao/docs/features/building_blocks/components/mux_demux_comps.rst +++ b/openmdao/docs/features/building_blocks/components/mux_demux_comps.rst @@ -60,7 +60,7 @@ Earth-centered, Earth-fixed (ECEF) frame (n x 3), extract the three (n x 1) colu and use the first two to compute the longitude at the given position vector. .. embed-code:: - openmdao.components.tests.test_demux_comp.TestForDocs.test + openmdao.components.tests.test_demux_comp.TestFeature.test :layout: interleave Example: Muxing 3 (n x 1) columns into a single (n x 3) matrix @@ -72,7 +72,7 @@ along `axis = 1`. Like the previous example, this is somewhat contrived but is the capabilities of the MuxComp. .. embed-code:: - openmdao.components.tests.test_mux_comp.TestForDocs.test + openmdao.components.tests.test_mux_comp.TestFeature.test :layout: interleave .. tags:: DemuxComp, MuxComp, Component \ No newline at end of file diff --git a/openmdao/docs/features/building_blocks/components/vector_magnitude_comp.rst b/openmdao/docs/features/building_blocks/components/vector_magnitude_comp.rst index 449b7735e1..414712ed8d 100644 --- a/openmdao/docs/features/building_blocks/components/vector_magnitude_comp.rst +++ b/openmdao/docs/features/building_blocks/components/vector_magnitude_comp.rst @@ -37,6 +37,6 @@ Units are assigned using `units`. The units of the output magnitude are the sam the input. .. embed-code:: - openmdao.components.tests.test_vector_magnitude_comp.TestForDocs.test + openmdao.components.tests.test_vector_magnitude_comp.TestFeature.test .. tags:: VectorMagnitudeComp, Component diff --git a/openmdao/docs/features/experimental/xdsm_visualization.rst b/openmdao/docs/features/experimental/xdsm_visualization.rst index 7c1e094552..0a0087270d 100644 --- a/openmdao/docs/features/experimental/xdsm_visualization.rst +++ b/openmdao/docs/features/experimental/xdsm_visualization.rst @@ -74,8 +74,8 @@ You can do the same thing programmatically by calling the `write_xdsm` function. .. autofunction:: openmdao.devtools.xdsm_viewer.xdsm_writer.write_xdsm :noindex: -Notice that the data source can be either a :code:`Problem` containing the model or -or a case recorder database containing the model data. The latter is indicated by a string +Notice that the data source can be either a :code:`Problem` containing the model or +or a case recorder database containing the model data. The latter is indicated by a string giving the file path to the case recorder file. Here are some code snippets showing the two cases. @@ -88,8 +88,8 @@ Problem as Data Source p.setup() p.run_model() - from openmdao.api import write_xdsm - write_xdsm(p, 'xdsmjs_circuit', out_format='html', show_browser=False) + import openmdao.api as om + om.write_xdsm(p, 'xdsmjs_circuit', out_format='html', show_browser=False) Case Recorder as Data Source @@ -104,8 +104,8 @@ Case Recorder as Data Source p.final_setup() r.shutdown() - from openmdao.devtools.xdsm_viewer.xdsm_writer import write_xdsm - write_xdsm('circuit.sqlite', 'xdsmjs_circuit', out_format='html', show_browser=False) + import openmdao.api as om + om.write_xdsm('circuit.sqlite', 'xdsmjs_circuit', out_format='html', show_browser=False) In the latter case, you could view the XDSM diagram at a later time using the command: diff --git a/openmdao/docs/features/model_visualization/n2_basics.rst b/openmdao/docs/features/model_visualization/n2_basics.rst index 4407e28399..27bc380ed1 100644 --- a/openmdao/docs/features/model_visualization/n2_basics.rst +++ b/openmdao/docs/features/model_visualization/n2_basics.rst @@ -69,7 +69,7 @@ You can do the same thing programmatically by calling the :code:`view_model` fun :noindex: Notice that the data source can be either a :code:`Problem` or case recorder database containing -the model or model data. The latter is indicated by a string giving the file path to the case +the model or model data. The latter is indicated by a string giving the file path to the case recorder file. Here are some code snippets showing the two cases. @@ -81,8 +81,8 @@ Problem as Data Source p.setup() - from openmdao.api import view_model - view_model(p) + import openmdao.api as om + om.view_model(p) Case Recorder as Data Source **************************** @@ -96,9 +96,9 @@ Case Recorder as Data Source p.final_setup() r.shutdown() - from openmdao.api import view_model + import openmdao.api as om - view_model('circuit.sqlite', outfile='circuit.html') + om.view_model('circuit.sqlite', outfile='circuit.html') In the latter case, you could view the N2 diagram at a later time using the command: diff --git a/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.html b/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.html index 478401a665..5a69a39914 100644 --- a/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.html +++ b/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.html @@ -1,4 +1,5 @@ - - +} + +.tool-tip { + z-index: 10; + font-size: 11px; + padding: 5; + background-color: #fff; + border: solid 1px #dfdfdf; +} + + + + +
+

OpenMDAO Model Hierarchy and N2 diagram

+
-
-
-

OpenMDAO Partition Tree and N2 diagram.

-
- + +
-
-
- - - - -
-
- - - - - -
-
- - - - - - -
-
- -
-
- -
-
+
+ + + + + + + + + +
+ + +
+ + + + + + + + + + + + +
+ + +
+ + + + + + + + + + + + + + + +
+ + +
+
+ + +
+
+
+
@@ -478,6 +541,9 @@

OpenMDAO Partition Tree and N2 diagram.

+
+ Note: Derivative declarations ignored, so dense component connectivity is assumed +
@@ -500,7 +566,8 @@

OpenMDAO Partition Tree and N2 diagram.

- - - - - + + + + - + + - + - + + - + + - + + - + + \ No newline at end of file + + diff --git a/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.py b/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.py index 75aad7faed..0dcc17a409 100644 --- a/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.py +++ b/openmdao/docs/theory_manual/total_derivs/aerostruct_n2.py @@ -2,27 +2,26 @@ This is not a real run_file. It is only used to make the n2 diagram for the notional aerostructural problem used for demonstration in the docs. """ +import openmdao.api as om -from openmdao.api import Problem, Group, ExecComp, IndepVarComp, view_model, ImplicitComponent - -p = Problem() -dvs = p.model.add_subsystem('design_vars', IndepVarComp(), promotes=['*']) +p = om.Problem() +dvs = p.model.add_subsystem('design_vars', om.IndepVarComp(), promotes=['*']) dvs.add_output('x_aero') dvs.add_output('x_struct') -aerostruct = p.model.add_subsystem('aerostruct_cycle', Group(), promotes=['*']) +aerostruct = p.model.add_subsystem('aerostruct_cycle', om.Group(), promotes=['*']) #note the equations don't matter... just need a simple way to get inputs and outputs there aerostruct.add_subsystem('aero', - ExecComp(['w = u+x_aero', 'Cl=u+x_aero', 'Cd = u + x_aero']), + om.ExecComp(['w = u+x_aero', 'Cl=u+x_aero', 'Cd = u + x_aero']), promotes=['*']) -aerostruct.add_subsystem('struct', ExecComp(['u = w+x_struct', 'mass=x_struct']), +aerostruct.add_subsystem('struct', om.ExecComp(['u = w+x_struct', 'mass=x_struct']), promotes=['*']) -p.model.add_subsystem('objective', ExecComp('f=mass+Cl/Cd'), promotes=['*']) -p.model.add_subsystem('constraint', ExecComp('g=Cl'), promotes=['*']) +p.model.add_subsystem('objective', om.ExecComp('f=mass+Cl/Cd'), promotes=['*']) +p.model.add_subsystem('constraint', om.ExecComp('g=Cl'), promotes=['*']) p.setup() -view_model(p, outfile='aerostruct_n2.html', embeddable=True, show_browser=False) +om.view_model(p, outfile='aerostruct_n2.html', embeddable=True, show_browser=False) diff --git a/openmdao/drivers/tests/test_doe_driver.py b/openmdao/drivers/tests/test_doe_driver.py index cc4023450e..5dc696cd26 100644 --- a/openmdao/drivers/tests/test_doe_driver.py +++ b/openmdao/drivers/tests/test_doe_driver.py @@ -13,13 +13,7 @@ import numpy as np -from openmdao.api import Problem, ExplicitComponent, IndepVarComp, ExecComp, \ - SqliteRecorder, CaseReader, PETScVector - -from openmdao.drivers.doe_driver import DOEDriver -from openmdao.drivers.doe_generators import ListGenerator, CSVGenerator, \ - UniformGenerator, FullFactorialGenerator, PlackettBurmanGenerator, \ - BoxBehnkenGenerator, LatinHypercubeGenerator +import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.groups.parallel_groups import FanInGrouped @@ -30,7 +24,7 @@ from openmdao.utils.mpi import MPI -class ParaboloidArray(ExplicitComponent): +class ParaboloidArray(om.ExplicitComponent): """ Evaluates the equation f(x,y) = (x-3)^2 + x*y + (y+4)^2 - 3. @@ -55,17 +49,17 @@ def compute(self, inputs, outputs): class TestErrors(unittest.TestCase): def test_generator_check(self): - prob = Problem() + prob = om.Problem() with self.assertRaises(TypeError) as err: - prob.driver = DOEDriver(FullFactorialGenerator) + prob.driver = om.DOEDriver(om.FullFactorialGenerator) self.assertEqual(str(err.exception), "DOEDriver requires an instance of DOEGenerator, " "but a class object was found: FullFactorialGenerator") with self.assertRaises(TypeError) as err: - prob.driver = DOEDriver(Problem()) + prob.driver = om.DOEDriver(om.Problem()) self.assertEqual(str(err.exception), "DOEDriver requires an instance of DOEGenerator, " @@ -73,7 +67,7 @@ def test_generator_check(self): def test_lhc_criterion(self): with self.assertRaises(ValueError) as err: - LatinHypercubeGenerator(criterion='foo') + om.LatinHypercubeGenerator(criterion='foo') self.assertEqual(str(err.exception), "Invalid criterion 'foo' specified for LatinHypercubeGenerator. " @@ -96,35 +90,35 @@ def tearDown(self): pass def test_no_generator(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 0.), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_design_var('x', lower=-10, upper=10) model.add_design_var('y', lower=-10, upper=10) model.add_objective('f_xy') - prob.driver = DOEDriver() - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver() + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 0) def test_list(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) @@ -134,12 +128,12 @@ def test_list(self): prob.setup() # create a list of DOE cases - case_gen = FullFactorialGenerator(levels=3) + case_gen = om.FullFactorialGenerator(levels=3) cases = list(case_gen(model.get_design_vars(recurse=True))) # create DOEDriver using provided list of cases - prob.driver = DOEDriver(cases) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(cases) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.run_driver() prob.cleanup() @@ -158,7 +152,7 @@ def test_list(self): 8: {'x': np.array([1.]), 'y': np.array([1.]), 'f_xy': np.array([27.00])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 9) @@ -170,11 +164,11 @@ def test_list(self): self.assertEqual(outputs['f_xy'], expected[n]['f_xy']) def test_list_errors(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) @@ -187,13 +181,13 @@ def test_list_errors(self): cases = {'desvar': 1.0} with self.assertRaises(RuntimeError) as err: - prob.driver = DOEDriver(generator=ListGenerator(cases)) + prob.driver = om.DOEDriver(generator=om.ListGenerator(cases)) self.assertEqual(str(err.exception), "Invalid DOE case data, " "expected a list but got a dict.") # data contains a list of non-list cases = [{'desvar': 1.0}] - prob.driver = DOEDriver(generator=ListGenerator(cases)) + prob.driver = om.DOEDriver(generator=om.ListGenerator(cases)) with self.assertRaises(RuntimeError) as err: prob.run_driver() @@ -206,7 +200,7 @@ def test_list_errors(self): [['p1.x', 1.], ['p2.y', 1., 'foo']] ] - prob.driver = DOEDriver(generator=ListGenerator(cases)) + prob.driver = om.DOEDriver(generator=om.ListGenerator(cases)) with self.assertRaises(RuntimeError) as err: prob.run_driver() @@ -220,7 +214,7 @@ def test_list_errors(self): [['p1.x', 1.], ['p2.z', 1.]] ] - prob.driver = DOEDriver(generator=ListGenerator(cases)) + prob.driver = om.DOEDriver(generator=om.ListGenerator(cases)) with self.assertRaises(RuntimeError) as err: prob.run_driver() @@ -234,7 +228,7 @@ def test_list_errors(self): [['p1.y', 1.], ['p2.z', 1.]] ] - prob.driver = DOEDriver(generator=ListGenerator(cases)) + prob.driver = om.DOEDriver(generator=om.ListGenerator(cases)) with self.assertRaises(RuntimeError) as err: prob.run_driver() @@ -243,11 +237,11 @@ def test_list_errors(self): "[['p1.y', 1.0], ['p2.z', 1.0]]") def test_csv(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) @@ -258,7 +252,7 @@ def test_csv(self): # create a list of DOE cases cases = [] - case_gen = FullFactorialGenerator(levels=3) + case_gen = om.FullFactorialGenerator(levels=3) for case in case_gen(model.get_design_vars(recurse=True)): cases.append([(var, val) for (var, val) in case]) @@ -271,8 +265,8 @@ def test_csv(self): writer.writerow([val for (var, val) in case]) # create DOEDriver using generated CSV file - prob.driver = DOEDriver(CSVGenerator('cases.csv')) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.CSVGenerator('cases.csv')) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.run_driver() prob.cleanup() @@ -291,7 +285,7 @@ def test_csv(self): 8: {'x': np.array([1.]), 'y': np.array([1.]), 'f_xy': np.array([27.00])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 9) @@ -303,11 +297,11 @@ def test_csv(self): self.assertEqual(outputs['f_xy'], expected[n]['f_xy']) def test_csv_array(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', [0., 1.])) - model.add_subsystem('p2', IndepVarComp('y', [0., 1.])) + model.add_subsystem('p1', om.IndepVarComp('x', [0., 1.])) + model.add_subsystem('p2', om.IndepVarComp('y', [0., 1.])) model.add_subsystem('comp1', Paraboloid()) model.add_subsystem('comp2', Paraboloid()) @@ -324,7 +318,7 @@ def test_csv_array(self): # create a list of DOE cases cases = [] - case_gen = FullFactorialGenerator(levels=2) + case_gen = om.FullFactorialGenerator(levels=2) for case in case_gen(model.get_design_vars(recurse=True)): cases.append([(var, val) for (var, val) in case]) @@ -337,8 +331,8 @@ def test_csv_array(self): writer.writerow([val for (var, val) in case]) # create DOEDriver using generated CSV file - prob.driver = DOEDriver(CSVGenerator('cases.csv')) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.CSVGenerator('cases.csv')) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.run_driver() prob.cleanup() @@ -362,7 +356,7 @@ def test_csv_array(self): 15: {'p1.x': np.array([1., 1.]), 'p2.y': np.array([1., 1.])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 16) @@ -377,22 +371,22 @@ def test_csv_array(self): def test_csv_errors(self): # test invalid file name with self.assertRaises(RuntimeError) as err: - CSVGenerator(1.23) + om.CSVGenerator(1.23) self.assertEqual(str(err.exception), "'1.23' is not a valid file name.") # test file not found with self.assertRaises(RuntimeError) as err: - CSVGenerator('nocases.csv') + om.CSVGenerator('nocases.csv') self.assertEqual(str(err.exception), "File not found: nocases.csv") # create problem and a list of DOE cases - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) @@ -402,7 +396,7 @@ def test_csv_errors(self): prob.setup() cases = [] - case_gen = FullFactorialGenerator(levels=2) + case_gen = om.FullFactorialGenerator(levels=2) for case in case_gen(model.get_design_vars(recurse=True)): cases.append([(var, val) for (var, val) in case]) @@ -415,7 +409,7 @@ def test_csv_errors(self): for case in cases: writer.writerow([val for (var, val) in case]) - prob.driver = DOEDriver(CSVGenerator('cases.csv')) + prob.driver = om.DOEDriver(om.CSVGenerator('cases.csv')) with self.assertRaises(RuntimeError) as err: prob.run_driver() self.assertEqual(str(err.exception), "Invalid DOE case file, " @@ -457,19 +451,19 @@ def test_csv_errors(self): "could not broadcast input array from shape (4) into shape (1)") def test_uniform(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 0.), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_design_var('x', lower=-10, upper=10) model.add_design_var('y', lower=-10, upper=10) model.add_objective('f_xy') - prob.driver = DOEDriver(UniformGenerator(num_samples=5, seed=0)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.UniformGenerator(num_samples=5, seed=0)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -484,7 +478,7 @@ def test_uniform(self): 4: {'x': np.array([ 9.27325521]), 'y': np.array([-2.33116962])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 5) @@ -495,19 +489,19 @@ def test_uniform(self): assert_rel_error(self, outputs['y'], expected[n]['y'], 1e-4) def test_full_factorial(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) model.add_design_var('y', lower=0.0, upper=1.0) model.add_objective('f_xy') - prob.driver = DOEDriver(generator=FullFactorialGenerator(levels=3)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(generator=om.FullFactorialGenerator(levels=3)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -527,7 +521,7 @@ def test_full_factorial(self): 8: {'x': np.array([1.]), 'y': np.array([1.]), 'f_xy': np.array([27.00])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 9) @@ -539,17 +533,17 @@ def test_full_factorial(self): self.assertEqual(outputs['f_xy'], expected[n]['f_xy']) def test_full_factorial_array(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('xy', np.array([0., 0.])), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('xy', np.array([0., 0.])), promotes=['*']) model.add_subsystem('comp', ParaboloidArray(), promotes=['*']) model.add_design_var('xy', lower=np.array([-50., -50.]), upper=np.array([50., 50.])) model.add_objective('f_xy') - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -567,7 +561,7 @@ def test_full_factorial_array(self): 8: {'xy': np.array([ 50., 50.])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 9) @@ -578,19 +572,19 @@ def test_full_factorial_array(self): self.assertEqual(outputs['xy'][1], expected[n]['xy'][1]) def test_plackett_burman(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) model.add_design_var('y', lower=0.0, upper=1.0) model.add_objective('f_xy') - prob.driver = DOEDriver(PlackettBurmanGenerator()) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.PlackettBurmanGenerator()) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -603,7 +597,7 @@ def test_plackett_burman(self): 3: {'x': np.array([1.]), 'y': np.array([1.]), 'f_xy': np.array([27.00])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 4) @@ -618,15 +612,15 @@ def test_box_behnken(self): upper = 10. center = 1 - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*']) + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes=['*']) indep.add_output('x', 0.0) indep.add_output('y', 0.0) indep.add_output('z', 0.0) - model.add_subsystem('comp', ExecComp('a = x**2 + y - z'), promotes=['*']) + model.add_subsystem('comp', om.ExecComp('a = x**2 + y - z'), promotes=['*']) model.add_design_var('x', lower=0., upper=upper) model.add_design_var('y', lower=0., upper=upper) @@ -634,14 +628,14 @@ def test_box_behnken(self): model.add_objective('a') - prob.driver = DOEDriver(BoxBehnkenGenerator(center=center)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.BoxBehnkenGenerator(center=center)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') # The Box-Behnken design for 3 factors involves three blocks, in each of @@ -685,21 +679,21 @@ def test_latin_hypercube(self): xlb, xub = bounds[0][0], bounds[1][0] ylb, yub = bounds[0][1], bounds[1][1] - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=xlb, upper=xub) model.add_design_var('y', lower=ylb, upper=yub) model.add_objective('f_xy') - prob.driver = DOEDriver() - prob.driver.options['generator'] = LatinHypercubeGenerator(samples=4, seed=0) + prob.driver = om.DOEDriver() + prob.driver.options['generator'] = om.LatinHypercubeGenerator(samples=4, seed=0) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -727,7 +721,7 @@ def test_latin_hypercube(self): 3: {'x': np.array([-0.72559325]), 'y': np.array([-2.27558409])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 4) @@ -757,17 +751,17 @@ def test_latin_hypercube_array(self): [ 10, 50] # upper bounds for x and y ]) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('xy', np.array([50., 50.])), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('xy', np.array([50., 50.])), promotes=['*']) model.add_subsystem('comp', ParaboloidArray(), promotes=['*']) model.add_design_var('xy', lower=bounds[0], upper=bounds[1]) model.add_objective('f_xy') - prob.driver = DOEDriver(LatinHypercubeGenerator(samples=4, seed=0)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.LatinHypercubeGenerator(samples=4, seed=0)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -795,7 +789,7 @@ def test_latin_hypercube_array(self): 3: {'xy': np.array([-7.25593248, -11.37792043])}, } - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 4) @@ -821,10 +815,10 @@ def test_latin_hypercube_center(self): samples = 4 upper = 10. - prob = Problem() + prob = om.Problem() model = prob.model - indep = model.add_subsystem('indep', IndepVarComp()) + indep = model.add_subsystem('indep', om.IndepVarComp()) indep.add_output('x', 0.0) indep.add_output('y', 0.0) @@ -838,14 +832,14 @@ def test_latin_hypercube_center(self): model.add_objective('comp.f_xy') - prob.driver = DOEDriver(LatinHypercubeGenerator(samples=samples, criterion='c')) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.LatinHypercubeGenerator(samples=samples, criterion='c')) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), samples) @@ -876,7 +870,7 @@ def test_latin_hypercube_center(self): self.assertEqual(y_buckets_filled, all_buckets) -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") class TestParallelDOE(unittest.TestCase): N_PROCS = 4 @@ -894,9 +888,9 @@ def tearDown(self): pass def test_indivisible_error(self): - prob = Problem() + prob = om.Problem() - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = 3 @@ -910,13 +904,13 @@ def test_indivisible_error(self): "of processors per model that divides into 4.") def test_minprocs_error(self): - prob = Problem(FanInGrouped()) + prob = om.Problem(FanInGrouped()) # require 2 procs for the ParallelGroup prob.model._proc_info['sub'] = (2, None, 1.0) # run cases on all procs - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = 1 @@ -928,20 +922,20 @@ def test_minprocs_error(self): "required for the following subsystems: ['sub']") def test_full_factorial(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) model.add_design_var('y', lower=0.0, upper=1.0) model.add_objective('f_xy') - prob.driver = DOEDriver(FullFactorialGenerator(levels=3), procs_per_model=1, + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3), procs_per_model=1, run_parallel=True) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() @@ -973,7 +967,7 @@ def test_full_factorial(self): expect_msg = "Cases from rank %d are being written to %s." % (rank, filename) self.assertTrue(expect_msg in output) - cr = CaseReader(filename) + cr = om.CaseReader(filename) cases = cr.list_cases('driver') # cases recorded on this proc @@ -996,7 +990,7 @@ def test_fan_in_grouped(self): # run 2 cases at a time, each using 2 of our 4 procs doe_parallel = 2 - prob = Problem(FanInGrouped()) + prob = om.Problem(FanInGrouped()) model = prob.model model.add_design_var('iv.x1', lower=0.0, upper=1.0) @@ -1004,8 +998,8 @@ def test_fan_in_grouped(self): model.add_objective('c3.y') - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = doe_parallel @@ -1042,7 +1036,7 @@ def test_fan_in_grouped(self): expect_msg = "Cases from rank %d are being written to %s." % (rank, filename) self.assertTrue(expect_msg in output) - cr = CaseReader(filename) + cr = om.CaseReader(filename) cases = cr.list_cases('driver') # cases recorded on this proc @@ -1068,7 +1062,7 @@ def test_fan_in_grouped_serial(self): # run cases on all procs (parallel model will run on single proc) doe_parallel = 1 - prob = Problem(FanInGrouped()) + prob = om.Problem(FanInGrouped()) model = prob.model model.add_design_var('iv.x1', lower=0.0, upper=1.0) @@ -1076,8 +1070,8 @@ def test_fan_in_grouped_serial(self): model.add_objective('c3.y') - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = doe_parallel @@ -1113,7 +1107,7 @@ def test_fan_in_grouped_serial(self): expect_msg = "Cases from rank %d are being written to %s." % (rank, filename) self.assertTrue(expect_msg in output) - cr = CaseReader(filename) + cr = om.CaseReader(filename) cases = cr.list_cases('driver') # cases recorded on this proc @@ -1204,30 +1198,28 @@ def tearDown(self): pass def test_uniform(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - from openmdao.api import DOEDriver, UniformGenerator, SqliteRecorder, CaseReader - - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 0.), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_design_var('x', lower=-10, upper=10) model.add_design_var('y', lower=-10, upper=10) model.add_objective('f_xy') - prob.driver = DOEDriver(UniformGenerator(num_samples=5)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.UniformGenerator(num_samples=5)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') self.assertEqual(len(cases), 5) @@ -1240,16 +1232,14 @@ def test_uniform(self): print("\n".join(["x: %5.2f, y: %5.2f, f_xy: %6.2f" % (x, y, f_xy) for x, y, f_xy in values])) def test_csv(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - from openmdao.api import DOEDriver, CSVGenerator, SqliteRecorder, CaseReader - - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) @@ -1263,13 +1253,13 @@ def test_csv(self): self.assertEqual(f.read(), self.expected_csv) # run problem with DOEDriver using the CSV file - prob.driver = DOEDriver(CSVGenerator('cases.csv')) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.CSVGenerator('cases.csv')) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') values = [] @@ -1281,18 +1271,16 @@ def test_csv(self): self.expected_text) def test_list(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - from openmdao.api import DOEDriver, ListGenerator, SqliteRecorder, CaseReader - import json - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) @@ -1312,17 +1300,17 @@ def test_list(self): self.assertEqual(case_list, json.loads(json_data)) # create DOEDriver using provided list of cases - prob.driver = DOEDriver(case_list) + prob.driver = om.DOEDriver(case_list) # a ListGenerator was created - self.assertEqual(type(prob.driver.options['generator']), ListGenerator) + self.assertEqual(type(prob.driver.options['generator']), om.ListGenerator) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') values = [] @@ -1334,7 +1322,7 @@ def test_list(self): self.expected_text) -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") class TestParallelDOEFeature(unittest.TestCase): N_PROCS = 2 @@ -1385,30 +1373,27 @@ def tearDown(self): pass def test_full_factorial(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - from openmdao.api import DOEDriver, FullFactorialGenerator - from openmdao.api import SqliteRecorder, CaseReader - from mpi4py import MPI - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=0.0, upper=1.0) model.add_design_var('y', lower=0.0, upper=1.0) model.add_objective('f_xy') - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = 1 - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -1421,7 +1406,7 @@ def test_full_factorial(self): filename = "cases.sql_%d" % rank self.assertEqual(filename, "cases.sql_%d" % rank) - cr = CaseReader(filename) + cr = om.CaseReader(filename) cases = cr.list_cases('driver') self.assertEqual(len(cases), 5 if rank == 0 else 4) @@ -1434,7 +1419,7 @@ def test_full_factorial(self): self.expect_text) -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") class TestParallelDOEFeature2(unittest.TestCase): N_PROCS = 4 @@ -1485,15 +1470,12 @@ def tearDown(self): pass def test_fan_in_grouped(self): - from openmdao.api import Problem + import openmdao.api as om from openmdao.test_suite.groups.parallel_groups import FanInGrouped - from openmdao.api import DOEDriver, FullFactorialGenerator - from openmdao.api import SqliteRecorder, CaseReader - from mpi4py import MPI - prob = Problem(FanInGrouped()) + prob = om.Problem(FanInGrouped()) model = prob.model model.add_design_var('iv.x1', lower=0.0, upper=1.0) @@ -1501,8 +1483,8 @@ def test_fan_in_grouped(self): model.add_objective('c3.y') - prob.driver = DOEDriver(FullFactorialGenerator(levels=3)) - prob.driver.add_recorder(SqliteRecorder("cases.sql")) + prob.driver = om.DOEDriver(om.FullFactorialGenerator(levels=3)) + prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.driver.options['run_parallel'] = True # run 2 cases at a time, each using 2 of our 4 procs @@ -1518,7 +1500,7 @@ def test_fan_in_grouped(self): if rank < doe_parallel: filename = "cases.sql_%d" % rank - cr = CaseReader(filename) + cr = om.CaseReader(filename) cases = cr.list_cases('driver') values = [] diff --git a/openmdao/drivers/tests/test_genetic_algorithm_driver.py b/openmdao/drivers/tests/test_genetic_algorithm_driver.py index 541e5ac8e6..0f456769d5 100644 --- a/openmdao/drivers/tests/test_genetic_algorithm_driver.py +++ b/openmdao/drivers/tests/test_genetic_algorithm_driver.py @@ -4,15 +4,13 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent, ExecComp, \ - PETScVector, ParallelGroup -from openmdao.drivers.genetic_algorithm_driver import SimpleGADriver,\ - GeneticAlgorithm +import openmdao.api as om +from openmdao.drivers.genetic_algorithm_driver import GeneticAlgorithm from openmdao.test_suite.components.branin import Branin, BraninDiscrete +from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.three_bar_truss import ThreeBarTruss from openmdao.utils.assert_utils import assert_rel_error from openmdao.utils.mpi import MPI -from openmdao.test_suite.components.paraboloid import Paraboloid class TestSimpleGA(unittest.TestCase): @@ -20,7 +18,7 @@ class TestSimpleGA(unittest.TestCase): def test_simple_test_func(self): np.random.seed(11) - class MyComp(ExplicitComponent): + class MyComp(om.ExplicitComponent): def setup(self): self.add_input('x', np.zeros((2, ))) @@ -38,12 +36,12 @@ def compute(self, inputs, outputs): outputs['c'] = (x[0] + x[1] + 1.0)**2 outputs['d'] = 19.0 - 14.0*x[0] + 3.0*x[0]**2 - 14.0*x[1] + 6.0*x[0]*x[1] + 3.0*x[1]**2 - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', np.array([0.2, -0.2]))) + model.add_subsystem('px', om.IndepVarComp('x', np.array([0.2, -0.2]))) model.add_subsystem('comp', MyComp()) - model.add_subsystem('obj', ExecComp('f=(30 + a*b)*(1 + c*d)')) + model.add_subsystem('obj', om.ExecComp('f=(30 + a*b)*(1 + c*d)')) model.connect('px.x', 'comp.x') model.connect('comp.a', 'obj.a') @@ -55,13 +53,13 @@ def compute(self, inputs, outputs): model.add_design_var('px.x', lower=np.array([0.2, -1.0]), upper=np.array([1.0, -0.2])) model.add_objective('obj.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'px.x': 16} prob.driver.options['max_gen'] = 75 prob.driver._randomstate = 11 - prob.setup(check=False) + prob.setup() prob.run_driver() # TODO: Satadru listed this solution, but I get a way better one. @@ -73,11 +71,11 @@ def compute(self, inputs, outputs): def test_mixed_integer_branin(self): np.random.seed(1) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -87,12 +85,12 @@ def test_mixed_integer_branin(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver(max_gen=75, pop_size=25) + prob.driver = om.SimpleGADriver(max_gen=75, pop_size=25) prob.driver.options['bits'] = {'p1.xC': 8} prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution @@ -102,10 +100,10 @@ def test_mixed_integer_branin(self): def test_mixed_integer_branin_discrete(self): np.random.seed(1) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - indep = IndepVarComp() + indep = om.IndepVarComp() indep.add_output('xC', val=7.5) indep.add_discrete_output('xI', val=0) @@ -119,12 +117,12 @@ def test_mixed_integer_branin_discrete(self): model.add_design_var('p.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver(max_gen=75, pop_size=25) + prob.driver = om.SimpleGADriver(max_gen=75, pop_size=25) prob.driver.options['bits'] = {'p.xC': 8} prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution @@ -135,7 +133,7 @@ def test_mixed_integer_branin_discrete(self): def test_mixed_integer_3bar(self): np.random.seed(1) - class ObjPenalty(ExplicitComponent): + class ObjPenalty(om.ExplicitComponent): """ Weight objective with penalty on stress constraint. """ @@ -157,15 +155,15 @@ def compute(self, inputs, outputs): outputs['weighted'] = obj + pen - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('xc_a1', IndepVarComp('area1', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xc_a2', IndepVarComp('area2', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xc_a3', IndepVarComp('area3', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xi_m1', IndepVarComp('mat1', 1), promotes=['*']) - model.add_subsystem('xi_m2', IndepVarComp('mat2', 1), promotes=['*']) - model.add_subsystem('xi_m3', IndepVarComp('mat3', 1), promotes=['*']) + model.add_subsystem('xc_a1', om.IndepVarComp('area1', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xc_a2', om.IndepVarComp('area2', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xc_a3', om.IndepVarComp('area3', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xi_m1', om.IndepVarComp('mat1', 1), promotes=['*']) + model.add_subsystem('xi_m2', om.IndepVarComp('mat2', 1), promotes=['*']) + model.add_subsystem('xi_m3', om.IndepVarComp('mat3', 1), promotes=['*']) model.add_subsystem('comp', ThreeBarTruss(), promotes=['*']) model.add_subsystem('obj_with_penalty', ObjPenalty(), promotes=['*']) @@ -176,14 +174,14 @@ def compute(self, inputs, outputs): model.add_design_var('mat3', lower=1, upper=4) model.add_objective('weighted') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'area1': 6, 'area2': 6} prob.driver.options['max_gen'] = 75 prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob['area3'] = 0.0005 prob.run_driver() @@ -201,7 +199,7 @@ def test_mixed_integer_3bar_default_bits(self): np.random.seed(1) - class ObjPenalty(ExplicitComponent): + class ObjPenalty(om.ExplicitComponent): """ Weight objective with penalty on stress constraint. """ @@ -223,15 +221,15 @@ def compute(self, inputs, outputs): outputs['weighted'] = obj + pen - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('xc_a1', IndepVarComp('area1', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xc_a2', IndepVarComp('area2', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xc_a3', IndepVarComp('area3', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xi_m1', IndepVarComp('mat1', 1), promotes=['*']) - model.add_subsystem('xi_m2', IndepVarComp('mat2', 1), promotes=['*']) - model.add_subsystem('xi_m3', IndepVarComp('mat3', 1), promotes=['*']) + model.add_subsystem('xc_a1', om.IndepVarComp('area1', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xc_a2', om.IndepVarComp('area2', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xc_a3', om.IndepVarComp('area3', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xi_m1', om.IndepVarComp('mat1', 1), promotes=['*']) + model.add_subsystem('xi_m2', om.IndepVarComp('mat2', 1), promotes=['*']) + model.add_subsystem('xi_m3', om.IndepVarComp('mat3', 1), promotes=['*']) model.add_subsystem('comp', ThreeBarTruss(), promotes=['*']) model.add_subsystem('obj_with_penalty', ObjPenalty(), promotes=['*']) @@ -242,14 +240,14 @@ def compute(self, inputs, outputs): model.add_design_var('mat3', lower=1, upper=4) model.add_objective('weighted') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'area1': 6, 'area2': 6} prob.driver.options['max_gen'] = 75 prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob['area3'] = 0.0005 prob.run_driver() @@ -264,7 +262,7 @@ def compute(self, inputs, outputs): def test_analysis_error(self): np.random.seed(1) - class ValueErrorComp(ExplicitComponent): + class ValueErrorComp(om.ExplicitComponent): def setup(self): self.add_input('x', 1.0) self.add_output('f', 1.0) @@ -272,10 +270,10 @@ def setup(self): def compute(self, inputs, outputs): raise ValueError - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p', IndepVarComp('x', 0.0)) + model.add_subsystem('p', om.IndepVarComp('x', 0.0)) model.add_subsystem('comp', ValueErrorComp()) model.connect('p.x', 'comp.x') @@ -283,9 +281,9 @@ def compute(self, inputs, outputs): model.add_design_var('p.x', lower=-5.0, upper=10.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver(max_gen=75, pop_size=25) + prob.driver = om.SimpleGADriver(max_gen=75, pop_size=25) prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() # prob.run_driver() self.assertRaises(ValueError, prob.run_driver) @@ -314,21 +312,21 @@ def test_encode_and_decode(self): np.testing.assert_array_almost_equal(gen[1], ga.encode(x[1], vlb, vub, bits)) def test_vector_desvars_multiobj(self): - prob = Problem() + prob = om.Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp()) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 3) indeps.add_output('y', [4.0, -4]) prob.model.add_subsystem('paraboloid1', - ExecComp('f = (x+5)**2- 3')) + om.ExecComp('f = (x+5)**2- 3')) prob.model.add_subsystem('paraboloid2', - ExecComp('f = (y[0]-3)**2 + (y[1]-1)**2 - 3', - y=[0, 0])) + om.ExecComp('f = (y[0]-3)**2 + (y[1]-1)**2 - 3', + y=[0, 0])) prob.model.connect('indeps.x', 'paraboloid1.x') prob.model.connect('indeps.y', 'paraboloid2.y') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.model.add_design_var('indeps.x', lower=-5, upper=5) prob.model.add_design_var('indeps.y', lower=[-10, 0], upper=[10, 3]) @@ -341,18 +339,18 @@ def test_vector_desvars_multiobj(self): np.testing.assert_array_almost_equal(prob['indeps.y'], [3, 1]) def test_SimpleGADriver_missing_objective(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('x', IndepVarComp('x', 2.0), promotes=['*']) + model.add_subsystem('x', om.IndepVarComp('x', 2.0), promotes=['*']) model.add_subsystem('f_x', Paraboloid(), promotes=['*']) - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.model.add_design_var('x', lower=0) prob.model.add_constraint('x', lower=0) - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception) as raises_msg: prob.run_driver() @@ -368,19 +366,19 @@ class TestDriverOptionsSimpleGA(unittest.TestCase): def test_driver_options(self): """Tests if Pm and Pc options can be set.""" - prob = Problem() + prob = om.Problem() model = prob.model - indeps = model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.) - model.add_subsystem('model', ExecComp('y=x**2'), promotes=['*']) - driver = prob.driver = SimpleGADriver() + model.add_subsystem('model', om.ExecComp('y=x**2'), promotes=['*']) + driver = prob.driver = om.SimpleGADriver() driver.options['Pm'] = 0.1 driver.options['Pc'] = 0.01 driver.options['max_gen'] = 5 driver.options['bits'] = {'x': 8} prob.model.add_design_var('x', lower=-10., upper=10.) prob.model.add_objective('y') - prob.setup(check=False) + prob.setup() prob.run_driver() self.assertEqual(driver.options['Pm'], 0.1) self.assertEqual(driver.options['Pc'], 0.01) @@ -390,7 +388,7 @@ class TestMultiObjectiveSimpleGA(unittest.TestCase): def test_multi_obj(self): - class Box(ExplicitComponent): + class Box(om.ExplicitComponent): def setup(self): self.add_input('length', val=1.) @@ -412,16 +410,16 @@ def compute(self, inputs, outputs): outputs['area'] = 2*length*height + 2*length*width + 2*height*width outputs['volume'] = length*height*width - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('box', Box(), promotes=['*']) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('length', 1.5) indeps.add_output('width', 1.5) indeps.add_output('height', 1.5) # setup the optimization - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['max_gen'] = 100 prob.driver.options['bits'] = {'length': 8, 'width': 8, 'height': 8} prob.driver.options['multi_obj_exponent'] = 1. @@ -451,16 +449,16 @@ def compute(self, inputs, outputs): # run #2 # weights changed - prob2 = Problem() + prob2 = om.Problem() prob2.model.add_subsystem('box', Box(), promotes=['*']) - indeps2 = prob2.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps2 = prob2.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps2.add_output('length', 1.5) indeps2.add_output('width', 1.5) indeps2.add_output('height', 1.5) # setup the optimization - prob2.driver = SimpleGADriver() + prob2.driver = om.SimpleGADriver() prob2.driver.options['max_gen'] = 100 prob2.driver.options['bits'] = {'length': 8, 'width': 8, 'height': 8} prob2.driver.options['multi_obj_exponent'] = 1. @@ -495,7 +493,7 @@ class TestConstrainedSimpleGA(unittest.TestCase): def test_constrained_with_penalty(self): - class Cylinder(ExplicitComponent): + class Cylinder(om.ExplicitComponent): """Main class""" def setup(self): @@ -514,15 +512,15 @@ def compute(self, inputs, outputs): outputs['Area'] = area outputs['Volume'] = volume - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('cylinder', Cylinder(), promotes=['*']) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('radius', 2.) # height indeps.add_output('height', 3.) # radius # setup the optimization - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() prob.driver.options['penalty_parameter'] = 3. prob.driver.options['penalty_exponent'] = 1. prob.driver.options['max_gen'] = 50 @@ -547,7 +545,7 @@ def compute(self, inputs, outputs): def test_constrained_without_penalty(self): - class Cylinder(ExplicitComponent): + class Cylinder(om.ExplicitComponent): """Main class""" def setup(self): @@ -566,15 +564,15 @@ def compute(self, inputs, outputs): outputs['Area'] = area outputs['Volume'] = volume - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('cylinder', Cylinder(), promotes=['*']) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('radius', 2.) # height indeps.add_output('height', 3.) # radius # setup the optimization - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() prob.driver.options['penalty_parameter'] = 0. # no penalty, same as unconstrained prob.driver.options['penalty_exponent'] = 1. prob.driver.options['max_gen'] = 50 @@ -599,7 +597,7 @@ def compute(self, inputs, outputs): def test_no_constraint(self): - class Cylinder(ExplicitComponent): + class Cylinder(om.ExplicitComponent): """Main class""" def setup(self): @@ -618,15 +616,15 @@ def compute(self, inputs, outputs): outputs['Area'] = area outputs['Volume'] = volume - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('cylinder', Cylinder(), promotes=['*']) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('radius', 2.) # height indeps.add_output('height', 3.) # radius # setup the optimization - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() prob.driver.options['penalty_parameter'] = 10. # will have no effect prob.driver.options['penalty_exponent'] = 1. prob.driver.options['max_gen'] = 50 @@ -648,7 +646,7 @@ def compute(self, inputs, outputs): self.assertAlmostEqual(prob['height'], 0.5, 1) # it is going to the unconstrained optimum -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") class MPITestSimpleGA(unittest.TestCase): N_PROCS = 2 @@ -656,11 +654,11 @@ class MPITestSimpleGA(unittest.TestCase): def test_mixed_integer_branin(self): np.random.seed(1) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -670,7 +668,7 @@ def test_mixed_integer_branin(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['max_gen'] = 50 prob.driver.options['pop_size'] = 25 @@ -678,7 +676,7 @@ def test_mixed_integer_branin(self): prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution @@ -688,12 +686,12 @@ def test_mixed_integer_branin(self): def test_two_branin_parallel_model(self): np.random.seed(1) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) - par = model.add_subsystem('par', ParallelGroup()) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) + par = model.add_subsystem('par', om.ParallelGroup()) par.add_subsystem('comp1', Branin()) par.add_subsystem('comp2', Branin()) @@ -703,7 +701,7 @@ def test_two_branin_parallel_model(self): model.connect('p2.xI', 'par.comp2.x0') model.connect('p1.xC', 'par.comp2.x1') - model.add_subsystem('comp', ExecComp('f = f1 + f2')) + model.add_subsystem('comp', om.ExecComp('f = f1 + f2')) model.connect('par.comp1.f', 'comp.f1') model.connect('par.comp2.f', 'comp.f2') @@ -711,7 +709,7 @@ def test_two_branin_parallel_model(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['max_gen'] = 40 prob.driver.options['pop_size'] = 25 @@ -720,7 +718,7 @@ def test_two_branin_parallel_model(self): prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution @@ -732,7 +730,7 @@ def test_mixed_integer_3bar_default_bits(self): # was a power of 2. np.random.seed(1) - class ObjPenalty(ExplicitComponent): + class ObjPenalty(om.ExplicitComponent): """ Weight objective with penalty on stress constraint. """ @@ -754,15 +752,15 @@ def compute(self, inputs, outputs): outputs['weighted'] = obj + pen - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('xc_a1', IndepVarComp('area1', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xc_a2', IndepVarComp('area2', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xc_a3', IndepVarComp('area3', 5.0, units='cm**2'), promotes=['*']) - model.add_subsystem('xi_m1', IndepVarComp('mat1', 1), promotes=['*']) - model.add_subsystem('xi_m2', IndepVarComp('mat2', 1), promotes=['*']) - model.add_subsystem('xi_m3', IndepVarComp('mat3', 1), promotes=['*']) + model.add_subsystem('xc_a1', om.IndepVarComp('area1', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xc_a2', om.IndepVarComp('area2', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xc_a3', om.IndepVarComp('area3', 5.0, units='cm**2'), promotes=['*']) + model.add_subsystem('xi_m1', om.IndepVarComp('mat1', 1), promotes=['*']) + model.add_subsystem('xi_m2', om.IndepVarComp('mat2', 1), promotes=['*']) + model.add_subsystem('xi_m3', om.IndepVarComp('mat3', 1), promotes=['*']) model.add_subsystem('comp', ThreeBarTruss(), promotes=['*']) model.add_subsystem('obj_with_penalty', ObjPenalty(), promotes=['*']) @@ -773,14 +771,14 @@ def compute(self, inputs, outputs): model.add_design_var('mat3', lower=1, upper=4) model.add_objective('weighted') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'area1': 6, 'area2': 6} prob.driver.options['max_gen'] = 75 prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob['area3'] = 0.0005 prob.run_driver() @@ -793,7 +791,7 @@ def compute(self, inputs, outputs): # Material 3 can be anything -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") class MPITestSimpleGA4Procs(unittest.TestCase): N_PROCS = 4 @@ -801,12 +799,12 @@ class MPITestSimpleGA4Procs(unittest.TestCase): def test_two_branin_parallel_model(self): np.random.seed(1) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) - par = model.add_subsystem('par', ParallelGroup()) + model.add_subsystem('p1', om.IndepVarComp('xC', 5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) + par = model.add_subsystem('par', om.ParallelGroup()) par.add_subsystem('comp1', Branin()) par.add_subsystem('comp2', Branin()) @@ -816,7 +814,7 @@ def test_two_branin_parallel_model(self): model.connect('p2.xI', 'par.comp2.x0') model.connect('p1.xC', 'par.comp2.x1') - model.add_subsystem('comp', ExecComp('f = f1 + f2')) + model.add_subsystem('comp', om.ExecComp('f = f1 + f2')) model.connect('par.comp1.f', 'comp.f1') model.connect('par.comp2.f', 'comp.f2') @@ -824,7 +822,7 @@ def test_two_branin_parallel_model(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['max_gen'] = 10 prob.driver.options['pop_size'] = 25 @@ -833,7 +831,7 @@ def test_two_branin_parallel_model(self): prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution @@ -841,11 +839,11 @@ def test_two_branin_parallel_model(self): self.assertTrue(int(prob['p2.xI']) in [3, -3]) def test_indivisible_error(self): - prob = Problem() - model = prob.model = Group() - model.add_subsystem('par', ParallelGroup()) + prob = om.Problem() + model = prob.model + model.add_subsystem('par', om.ParallelGroup()) - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = 3 @@ -862,25 +860,25 @@ def test_concurrent_eval_padded(self): # This test only makes sure we don't lock up if we overallocate our integer desvar space # to the next power of 2. - class GAGroup(Group): + class GAGroup(om.Group): def setup(self): - self.add_subsystem('p1', IndepVarComp('x', 1.0)) - self.add_subsystem('p2', IndepVarComp('y', 1.0)) - self.add_subsystem('p3', IndepVarComp('z', 1.0)) + self.add_subsystem('p1', om.IndepVarComp('x', 1.0)) + self.add_subsystem('p2', om.IndepVarComp('y', 1.0)) + self.add_subsystem('p3', om.IndepVarComp('z', 1.0)) - self.add_subsystem('comp', ExecComp(['f = x + y + z'])) + self.add_subsystem('comp', om.ExecComp(['f = x + y + z'])) self.add_design_var('p1.x', lower=-100, upper=100) self.add_design_var('p2.y', lower=-100, upper=100) self.add_design_var('p3.z', lower=-100, upper=100) self.add_objective('comp.f') - prob = Problem() + prob = om.Problem() prob.model = GAGroup() - driver = prob.driver = SimpleGADriver() + driver = prob.driver = om.SimpleGADriver() driver.options['max_gen'] = 5 driver.options['pop_size'] = 40 driver.options['run_parallel'] = True @@ -901,14 +899,14 @@ def setUp(self): os.environ['SimpleGADriver_seed'] = '11' def test_basic(self): - from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver + import openmdao.api as om from openmdao.test_suite.components.branin import Branin - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -918,7 +916,7 @@ def test_basic(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.setup() @@ -930,14 +928,14 @@ def test_basic(self): print('p1.xC', prob['p1.xC']) def test_basic_with_assert(self): - from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver + import openmdao.api as om from openmdao.test_suite.components.branin import Branin - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -947,7 +945,7 @@ def test_basic_with_assert(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver._randomstate = 1 @@ -959,14 +957,14 @@ def test_basic_with_assert(self): assert_rel_error(self, prob['comp.f'], 0.49399549, 1e-4) def test_option_max_gen(self): - from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver + import openmdao.api as om from openmdao.test_suite.components.branin import Branin - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -976,7 +974,7 @@ def test_option_max_gen(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['max_gen'] = 5 @@ -989,14 +987,14 @@ def test_option_max_gen(self): print('p1.xC', prob['p1.xC']) def test_option_pop_size(self): - from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver + import openmdao.api as om from openmdao.test_suite.components.branin import Branin - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -1006,7 +1004,7 @@ def test_option_pop_size(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['pop_size'] = 10 @@ -1019,9 +1017,9 @@ def test_option_pop_size(self): print('p1.xC', prob['p1.xC']) def test_constrained_with_penalty(self): - from openmdao.api import ExplicitComponent, Problem, IndepVarComp, SimpleGADriver + import openmdao.api as om - class Cylinder(ExplicitComponent): + class Cylinder(om.ExplicitComponent): """Main class""" def setup(self): @@ -1040,15 +1038,15 @@ def compute(self, inputs, outputs): outputs['Area'] = area outputs['Volume'] = volume - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('cylinder', Cylinder(), promotes=['*']) - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('radius', 2.) # height indeps.add_output('height', 3.) # radius # setup the optimization - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['penalty_parameter'] = 3. prob.driver.options['penalty_exponent'] = 1. prob.driver.options['max_gen'] = 50 @@ -1068,20 +1066,20 @@ def compute(self, inputs, outputs): self.assertGreater(prob['height'], 1.) -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") @unittest.skipUnless(MPI, "MPI is required.") class MPIFeatureTests(unittest.TestCase): N_PROCS = 2 def test_option_parallel(self): - from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver + import openmdao.api as om from openmdao.test_suite.components.branin import Branin - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') @@ -1091,12 +1089,12 @@ def test_option_parallel(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['max_gen'] = 10 prob.driver.options['run_parallel'] = True - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution @@ -1105,21 +1103,21 @@ def test_option_parallel(self): print('p1.xC', prob['p1.xC']) -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") @unittest.skipUnless(MPI, "MPI is required.") class MPIFeatureTests4(unittest.TestCase): N_PROCS = 4 def test_option_procs_per_model(self): - from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver, ParallelGroup + import openmdao.api as om from openmdao.test_suite.components.branin import Branin - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('xC', 7.5)) - model.add_subsystem('p2', IndepVarComp('xI', 0.0)) - par = model.add_subsystem('par', ParallelGroup()) + model.add_subsystem('p1', om.IndepVarComp('xC', 7.5)) + model.add_subsystem('p2', om.IndepVarComp('xI', 0.0)) + par = model.add_subsystem('par', om.ParallelGroup()) par.add_subsystem('comp1', Branin()) par.add_subsystem('comp2', Branin()) @@ -1129,7 +1127,7 @@ def test_option_procs_per_model(self): model.connect('p2.xI', 'par.comp2.x0') model.connect('p1.xC', 'par.comp2.x1') - model.add_subsystem('comp', ExecComp('f = f1 + f2')) + model.add_subsystem('comp', om.ExecComp('f = f1 + f2')) model.connect('par.comp1.f', 'comp.f1') model.connect('par.comp2.f', 'comp.f2') @@ -1137,7 +1135,7 @@ def test_option_procs_per_model(self): model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') - prob.driver = SimpleGADriver() + prob.driver = om.SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.driver.options['max_gen'] = 10 prob.driver.options['pop_size'] = 25 @@ -1146,7 +1144,7 @@ def test_option_procs_per_model(self): prob.driver._randomstate = 1 - prob.setup(check=False) + prob.setup() prob.run_driver() # Optimal solution diff --git a/openmdao/drivers/tests/test_pyoptsparse_driver.py b/openmdao/drivers/tests/test_pyoptsparse_driver.py index 0bde239ec9..e62390fa39 100644 --- a/openmdao/drivers/tests/test_pyoptsparse_driver.py +++ b/openmdao/drivers/tests/test_pyoptsparse_driver.py @@ -8,12 +8,11 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, AnalysisError, ExplicitComponent, \ - ScipyKrylov, NonlinearBlockGS, LinearBlockGS, DirectSolver -from openmdao.utils.assert_utils import assert_rel_error +import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.expl_comp_array import TestExplCompArrayDense from openmdao.test_suite.components.sellar import SellarDerivativesGrouped +from openmdao.utils.assert_utils import assert_rel_error from openmdao.utils.general_utils import set_pyoptsparse_opt, run_driver from openmdao.utils.testing_utils import use_tempdirs @@ -25,7 +24,7 @@ from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver -class ParaboloidAE(ExplicitComponent): +class ParaboloidAE(om.ExplicitComponent): """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 This version raises an analysis error 50% of the time. The AE in ParaboloidAE stands for AnalysisError.""" @@ -58,7 +57,7 @@ def compute(self, inputs, outputs): if self.fail_hard: raise RuntimeError('This should error.') else: - raise AnalysisError('Try again.') + raise om.AnalysisError('Try again.') x = inputs['x'] y = inputs['y'] @@ -75,7 +74,7 @@ def compute_partials(self, inputs, partials): if self.fail_hard: raise RuntimeError('This should error.') else: - raise AnalysisError('Try again.') + raise om.AnalysisError('Try again.') x = inputs['x'] y = inputs['y'] @@ -85,7 +84,7 @@ def compute_partials(self, inputs, partials): self.grad_iter_count += 1 -class DataSave(ExplicitComponent): +class DataSave(om.ExplicitComponent): """ Saves run points so that we can verify that initial point is run.""" def setup(self): @@ -112,13 +111,13 @@ class TestPyoptSparse(unittest.TestCase): def test_simple_paraboloid_upper(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -131,7 +130,7 @@ def test_simple_paraboloid_upper(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -144,18 +143,18 @@ def test_simple_paraboloid_upper(self): def test_simple_paraboloid_upper_indices(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model size = 3 - model.add_subsystem('p1', IndepVarComp('x', np.array([50.0]*size))) - model.add_subsystem('p2', IndepVarComp('y', np.array([50.0]*size))) - model.add_subsystem('comp', ExecComp('f_xy = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0', - x=np.zeros(size), y=np.zeros(size), - f_xy=np.zeros(size))) - model.add_subsystem('con', ExecComp('c = - x + y', - c=np.zeros(size), x=np.zeros(size), - y=np.zeros(size))) + model.add_subsystem('p1', om.IndepVarComp('x', np.array([50.0]*size))) + model.add_subsystem('p2', om.IndepVarComp('y', np.array([50.0]*size))) + model.add_subsystem('comp', om.ExecComp('f_xy = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0', + x=np.zeros(size), y=np.zeros(size), + f_xy=np.zeros(size))) + model.add_subsystem('con', om.ExecComp('c = - x + y', + c=np.zeros(size), x=np.zeros(size), + y=np.zeros(size))) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') @@ -175,7 +174,7 @@ def test_simple_paraboloid_upper_indices(self): model.add_objective('comp.f_xy', index=1) model.add_constraint('con.c', indices=[1], upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -188,13 +187,13 @@ def test_simple_paraboloid_upper_indices(self): def test_simple_paraboloid_lower(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -210,7 +209,7 @@ def test_simple_paraboloid_lower(self): model.add_objective('f_xy') model.add_constraint('c', lower=15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -223,13 +222,13 @@ def test_simple_paraboloid_lower(self): def test_simple_paraboloid_lower_linear(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -244,7 +243,7 @@ def test_simple_paraboloid_lower_linear(self): model.add_objective('f_xy') model.add_constraint('c', lower=15.0, linear=True) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -259,13 +258,13 @@ def test_simple_paraboloid_lower_linear(self): def test_simple_paraboloid_equality(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -280,7 +279,7 @@ def test_simple_paraboloid_equality(self): model.add_objective('f_xy') model.add_constraint('c', equals=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -293,13 +292,13 @@ def test_simple_paraboloid_equality(self): def test_simple_paraboloid_equality_linear(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -314,7 +313,7 @@ def test_simple_paraboloid_equality_linear(self): model.add_objective('f_xy') model.add_constraint('c', equals=-15.0, linear=True) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -327,13 +326,13 @@ def test_simple_paraboloid_equality_linear(self): def test_simple_paraboloid_double_sided_low(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -346,7 +345,7 @@ def test_simple_paraboloid_double_sided_low(self): model.add_objective('f_xy') model.add_constraint('c', lower=-11.0, upper=-10.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -358,13 +357,13 @@ def test_simple_paraboloid_double_sided_low(self): def test_simple_paraboloid_double_sided_high(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -389,14 +388,14 @@ def test_simple_paraboloid_double_sided_high(self): def test_simple_array_comp2D(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), + model.add_subsystem('con', om.ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) @@ -409,7 +408,7 @@ def test_simple_array_comp2D(self): model.add_objective('o') model.add_constraint('c', equals=0.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -421,14 +420,14 @@ def test_simple_array_comp2D(self): def test_simple_array_comp2D_array_lo_hi(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), + model.add_subsystem('con', om.ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) @@ -441,7 +440,7 @@ def test_simple_array_comp2D_array_lo_hi(self): model.add_objective('o') model.add_constraint('c', equals=0.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -455,18 +454,18 @@ def test_fan_out(self): # This tests sparse-response specification. # This is a slightly modified FanOut - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 1.0)) - model.add_subsystem('p2', IndepVarComp('x', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 1.0)) + model.add_subsystem('p2', om.IndepVarComp('x', 1.0)) - model.add_subsystem('comp1', ExecComp('y = 3.0*x')) - model.add_subsystem('comp2', ExecComp('y = 5.0*x')) + model.add_subsystem('comp1', om.ExecComp('y = 3.0*x')) + model.add_subsystem('comp2', om.ExecComp('y = 5.0*x')) - model.add_subsystem('obj', ExecComp('o = i1 + i2')) - model.add_subsystem('con1', ExecComp('c = 15.0 - x')) - model.add_subsystem('con2', ExecComp('c = 15.0 - x')) + model.add_subsystem('obj', om.ExecComp('o = i1 + i2')) + model.add_subsystem('con1', om.ExecComp('c = 15.0 - x')) + model.add_subsystem('con2', om.ExecComp('c = 15.0 - x')) # hook up explicitly model.connect('p1.x', 'comp1.x') @@ -488,7 +487,7 @@ def test_fan_out(self): model.add_constraint('con1.c', equals=0.0) model.add_constraint('con2.c', equals=0.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -510,13 +509,13 @@ def test_inf_as_desvar_bounds(self): # may do it anyway, so make sure SLSQP doesn't blow up with it (bug # reported by rfalck) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -530,7 +529,7 @@ def test_inf_as_desvar_bounds(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -543,15 +542,15 @@ def test_inf_as_desvar_bounds(self): def test_pyopt_fd_solution(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -565,7 +564,7 @@ def test_pyopt_fd_solution(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -583,15 +582,15 @@ def apply_linear(params, unknowns, resids): raise Exception("OpenMDAO's finite difference has been called." " pyopt_fd option has failed.") - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', ParaboloidApplyLinear(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -605,7 +604,7 @@ def apply_linear(params, unknowns, resids): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -618,15 +617,15 @@ def apply_linear(params, unknowns, resids): def test_snopt_fd_option_error(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -640,7 +639,7 @@ def test_snopt_fd_option_error(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception) as raises_cm: prob.run_driver() @@ -652,16 +651,16 @@ def test_snopt_fd_option_error(self): self.assertEqual(exception.args[0], msg) def test_unsupported_multiple_obj(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_subsystem('comp2', Paraboloid()) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -680,7 +679,7 @@ def test_unsupported_multiple_obj(self): ' but the selected optimizer (SLSQP) does not support' \ ' multiple objectives.' - prob.setup(check=False) + prob.setup() with self.assertRaises(RuntimeError) as cm: prob.final_setup() @@ -689,13 +688,13 @@ def test_unsupported_multiple_obj(self): def test_simple_paraboloid_scaled_desvars_fwd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -721,13 +720,13 @@ def test_simple_paraboloid_scaled_desvars_fwd(self): assert_rel_error(self, prob['x'] - prob['y'], 11.0, 1e-6) def test_simple_paraboloid_scaled_desvars_fd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -744,7 +743,7 @@ def test_simple_paraboloid_scaled_desvars_fd(self): model.approx_totals(method='fd') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -755,13 +754,13 @@ def test_simple_paraboloid_scaled_desvars_fd(self): assert_rel_error(self, prob['x'] - prob['y'], 11.0, 1e-6) def test_simple_paraboloid_scaled_desvars_cs(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -778,7 +777,7 @@ def test_simple_paraboloid_scaled_desvars_cs(self): model.approx_totals(method='cs') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -790,13 +789,13 @@ def test_simple_paraboloid_scaled_desvars_cs(self): def test_simple_paraboloid_scaled_desvars_rev(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -823,13 +822,13 @@ def test_simple_paraboloid_scaled_desvars_rev(self): def test_simple_paraboloid_scaled_constraint_fwd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -855,13 +854,13 @@ def test_simple_paraboloid_scaled_constraint_fwd(self): assert_rel_error(self, prob['x'] - prob['y'], 11.0, 1e-6) def test_simple_paraboloid_scaled_constraint_fd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -878,7 +877,7 @@ def test_simple_paraboloid_scaled_constraint_fd(self): model.approx_totals(method='fd') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -889,13 +888,13 @@ def test_simple_paraboloid_scaled_constraint_fd(self): assert_rel_error(self, prob['x'] - prob['y'], 11.0, 1e-6) def test_simple_paraboloid_scaled_constraint_cs(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -912,7 +911,7 @@ def test_simple_paraboloid_scaled_constraint_cs(self): model.approx_totals(method='cs') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -924,13 +923,13 @@ def test_simple_paraboloid_scaled_constraint_cs(self): def test_simple_paraboloid_scaled_constraint_rev(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) @@ -957,15 +956,15 @@ def test_simple_paraboloid_scaled_constraint_rev(self): def test_simple_paraboloid_scaled_objective_fwd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model prob.set_solver_print(level=0) - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER @@ -990,15 +989,15 @@ def test_simple_paraboloid_scaled_objective_fwd(self): def test_simple_paraboloid_scaled_objective_rev(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model prob.set_solver_print(level=0) - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER @@ -1023,7 +1022,7 @@ def test_simple_paraboloid_scaled_objective_rev(self): def test_sellar_mdf(self): - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() prob.driver = pyOptSparseDriver() @@ -1055,7 +1054,7 @@ def test_sellar_mdf_linear_con_directsolver(self): # This test makes sure that we call solve_nonlinear first if we have any linear constraints # to cache. - class SellarDis1withDerivatives(ExplicitComponent): + class SellarDis1withDerivatives(om.ExplicitComponent): def setup(self): self.add_input('z', val=np.zeros(2)) @@ -1079,7 +1078,7 @@ def compute_partials(self, inputs, partials): partials['y1', 'x'] = 1.0 - class SellarDis2withDerivatives(ExplicitComponent): + class SellarDis2withDerivatives(om.ExplicitComponent): def setup(self): self.add_input('z', val=np.zeros(2)) @@ -1107,28 +1106,28 @@ def compute_partials(self, inputs, J): J['y2', 'z'] = np.array([[1.0, 1.0]]) - class MySellarGroup(Group): + class MySellarGroup(om.Group): def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) - self.mda = mda = self.add_subsystem('mda', Group(), promotes=['x', 'z', 'y1', 'y2']) + self.mda = mda = self.add_subsystem('mda', om.Group(), promotes=['x', 'z', 'y1', 'y2']) mda.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) mda.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - self.linear_solver = DirectSolver() - self.nonlinear_solver = NonlinearBlockGS() + self.linear_solver = om.DirectSolver() + self.nonlinear_solver = om.NonlinearBlockGS() - prob = Problem() + prob = om.Problem() model = prob.model = MySellarGroup() prob.driver = pyOptSparseDriver() @@ -1165,15 +1164,15 @@ def test_analysis_error_objfunc(self): # Component raises an analysis error during some runs, and pyopt # attempts to recover. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', ParaboloidAE(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER @@ -1188,7 +1187,7 @@ def test_analysis_error_objfunc(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -1211,15 +1210,15 @@ def test_raised_error_objfunc(self): # Component fails hard this time during execution, so we expect # pyoptsparse to raise. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) comp = model.add_subsystem('comp', ParaboloidAE(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.driver = pyOptSparseDriver() @@ -1237,7 +1236,7 @@ def test_raised_error_objfunc(self): comp.fail_hard = True - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception): prob.run_driver() @@ -1249,15 +1248,15 @@ def test_analysis_error_sensfunc(self): # Component raises an analysis error during some linearize calls, and # pyopt attempts to recover. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) comp = model.add_subsystem('comp', ParaboloidAE(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER @@ -1275,7 +1274,7 @@ def test_analysis_error_sensfunc(self): comp.grad_fail_at = 2 comp.eval_fail_at = 100 - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -1302,14 +1301,14 @@ def test_raised_error_sensfunc(self): # Component fails hard this time during gradient eval, so we expect # pyoptsparse to raise. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) comp = model.add_subsystem('comp', ParaboloidAE(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.driver = pyOptSparseDriver() @@ -1329,7 +1328,7 @@ def test_raised_error_sensfunc(self): comp.grad_fail_at = 2 comp.eval_fail_at = 100 - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception): prob.run_driver() @@ -1338,13 +1337,13 @@ def test_raised_error_sensfunc(self): def test_debug_print_option_totals(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -1371,13 +1370,13 @@ def test_debug_print_option_totals(self): self.assertTrue('Solving variable: comp.f_xy' in output) self.assertTrue('Solving variable: con.c' in output) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -1406,13 +1405,13 @@ def test_debug_print_option_totals(self): def test_debug_print_option(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -1429,7 +1428,7 @@ def test_debug_print_option(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed, output = run_driver(prob) @@ -1458,13 +1457,13 @@ def test_debug_print_option(self): def test_show_exception_bad_opt(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -1477,7 +1476,7 @@ def test_show_exception_bad_opt(self): # We generally don't hae a working IPOPT install. prob.driver.options['optimizer'] = 'IPOPT' - prob.setup(check=False) + prob.setup() # Test that we get exception. with self.assertRaises(ImportError) as raises_cm: @@ -1494,9 +1493,9 @@ def test_initial_run_NSGA2(self): raise unittest.SkipTest("pyoptsparse is not providing NSGA2") # Make sure all our opts have run the initial point just once. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', val=1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', val=1.0)) comp = model.add_subsystem('comp1', DataSave()) model.connect('p1.x', 'comp1.x') @@ -1521,9 +1520,9 @@ def test_initial_run_SLSQP(self): raise unittest.SkipTest("pyoptsparse is not providing SLSQP") # Make sure all our opts have run the initial point just once. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', val=1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', val=1.0)) comp = model.add_subsystem('comp1', DataSave()) model.connect('p1.x', 'comp1.x') @@ -1547,9 +1546,9 @@ def test_initial_run_SNOPT(self): raise unittest.SkipTest("pyoptsparse is not providing SNOPT") # Make sure all our opts have run the initial point just once. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', val=1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', val=1.0)) comp = model.add_subsystem('comp1', DataSave()) model.connect('p1.x', 'comp1.x') @@ -1576,9 +1575,9 @@ def test_initial_run_ALPSO(self): raise unittest.SkipTest("pyoptsparse is not providing ALPSO") # Make sure all our opts have run the initial point just once. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', val=1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', val=1.0)) comp = model.add_subsystem('comp1', DataSave()) model.connect('p1.x', 'comp1.x') @@ -1602,9 +1601,9 @@ def test_initial_run_PSQP(self): raise unittest.SkipTest("pyoptsparse is not providing PSQP") # Make sure all our opts have run the initial point just once. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', val=1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', val=1.0)) comp = model.add_subsystem('comp1', DataSave()) model.connect('p1.x', 'comp1.x') @@ -1629,9 +1628,9 @@ def test_initial_run_CONMIN(self): raise unittest.SkipTest("pyoptsparse is not providing CONMIN") # Make sure all our opts have run the initial point just once. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', val=1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', val=1.0)) comp = model.add_subsystem('comp1', DataSave()) model.connect('p1.x', 'comp1.x') @@ -1651,10 +1650,10 @@ def test_initial_run_CONMIN(self): self.assertNotEqual(comp.visited_points[1], 1.0) def test_pyoptsparse_missing_objective(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('x', IndepVarComp('x', 2.0), promotes=['*']) + model.add_subsystem('x', om.IndepVarComp('x', 2.0), promotes=['*']) model.add_subsystem('f_x', Paraboloid(), promotes=['*']) prob.driver = pyOptSparseDriver() @@ -1663,7 +1662,7 @@ def test_pyoptsparse_missing_objective(self): prob.model.add_design_var('x', lower=0) prob.model.add_constraint('x', lower=0) - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception) as raises_msg: prob.run_driver() @@ -1689,13 +1688,13 @@ def setUp(self): def test_basic(self): import numpy as np - from openmdao.api import Problem, pyOptSparseDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesGrouped - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = pyOptSparseDriver() + prob.driver = om.pyOptSparseDriver() prob.driver.options['optimizer'] = "SLSQP" model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) @@ -1714,13 +1713,13 @@ def test_basic(self): def test_settings_print(self): import numpy as np - from openmdao.api import Problem, pyOptSparseDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesGrouped - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = pyOptSparseDriver(optimizer='SLSQP') + prob.driver = om.pyOptSparseDriver(optimizer='SLSQP') prob.driver.options['print_results'] = False @@ -1740,13 +1739,13 @@ def test_settings_print(self): def test_slsqp_atol(self): import numpy as np - from openmdao.api import Problem, pyOptSparseDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesGrouped - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = pyOptSparseDriver() + prob.driver = om.pyOptSparseDriver() prob.driver.options['optimizer'] = "SLSQP" prob.driver.opt_settings['ACC'] = 1e-9 @@ -1767,13 +1766,13 @@ def test_slsqp_atol(self): def test_slsqp_maxit(self): import numpy as np - from openmdao.api import Problem, pyOptSparseDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesGrouped - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = pyOptSparseDriver() + prob.driver = om.pyOptSparseDriver() prob.driver.options['optimizer'] = "SLSQP" prob.driver.opt_settings['MAXIT'] = 3 @@ -1803,13 +1802,13 @@ def setUp(self): def test_snopt_atol(self): import numpy as np - from openmdao.api import Problem, pyOptSparseDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesGrouped - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = pyOptSparseDriver() + prob.driver = om.pyOptSparseDriver() prob.driver.options['optimizer'] = "SNOPT" prob.driver.opt_settings['Major feasibility tolerance'] = 1e-9 @@ -1830,13 +1829,13 @@ def test_snopt_atol(self): def test_snopt_maxit(self): import numpy as np - from openmdao.api import Problem, pyOptSparseDriver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivativesGrouped - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = pyOptSparseDriver() + prob.driver = om.pyOptSparseDriver() prob.driver.options['optimizer'] = "SNOPT" # after upgrading to SNOPT 7.5-1.1, this test failed unless iter limit raised from 4 to 5 @@ -1858,15 +1857,15 @@ def test_snopt_maxit(self): def test_snopt_fd_solution(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -1880,7 +1879,7 @@ def test_snopt_fd_solution(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -1898,15 +1897,15 @@ def apply_linear(params, unknowns, resids): raise Exception("OpenMDAO's finite difference has been called." " snopt_fd option has failed.") - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', ParaboloidApplyLinear(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) @@ -1920,7 +1919,7 @@ def apply_linear(params, unknowns, resids): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -1935,7 +1934,7 @@ def test_sellar_analysis_error(self): # One discipline of Sellar will something raise analysis error. This is to test that # the iprinting doesn't get out-of-whack. - class SellarDis1AE(ExplicitComponent): + class SellarDis1AE(om.ExplicitComponent): def setup(self): self.add_input('z', val=np.zeros(2)) self.add_input('x', val=0.) @@ -1962,13 +1961,13 @@ def compute_partials(self, inputs, partials): self.count_iter += 1 if self.count_iter in self.fail_deriv: self.failed += 1 - raise AnalysisError('Try again.') + raise om.AnalysisError('Try again.') partials['y1', 'y2'] = -0.2 partials['y1', 'z'] = np.array([[2.0 * inputs['z'][0], 1.0]]) partials['y1', 'x'] = 1.0 - class SellarDis2AE(ExplicitComponent): + class SellarDis2AE(om.ExplicitComponent): def setup(self): self.add_input('z', val=np.zeros(2)) self.add_input('y1', val=1.0) @@ -1997,13 +1996,13 @@ def compute_partials(self, inputs, J): J['y2', 'y1'] = .5*y1**-.5 J['y2', 'z'] = np.array([[1.0, 1.0]]) - class SellarMDAAE(Group): + class SellarMDAAE(om.Group): def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group(), promotes=['*']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['*']) cycle.add_subsystem('d1', SellarDis1AE(), promotes_inputs=['x', 'z', 'y2'], @@ -2012,18 +2011,18 @@ def setup(self): promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) - self.linear_solver = LinearBlockGS() - cycle.linear_solver = ScipyKrylov() - cycle.nonlinear_solver = NonlinearBlockGS() + self.linear_solver = om.LinearBlockGS() + cycle.linear_solver = om.ScipyKrylov() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - prob = Problem() + prob = om.Problem() model = prob.model = SellarMDAAE() prob.driver = pyOptSparseDriver() diff --git a/openmdao/drivers/tests/test_scipy_optimizer.py b/openmdao/drivers/tests/test_scipy_optimizer.py index 2ea3908200..1f41ff6707 100644 --- a/openmdao/drivers/tests/test_scipy_optimizer.py +++ b/openmdao/drivers/tests/test_scipy_optimizer.py @@ -8,15 +8,14 @@ import numpy as np from scipy import __version__ as scipy_version -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ScipyOptimizeDriver, \ - ScipyOptimizer, ExplicitComponent, DirectSolver, NonlinearBlockGS -from openmdao.utils.assert_utils import assert_rel_error, assert_warning -from openmdao.utils.general_utils import run_driver +import openmdao.api as om from openmdao.test_suite.components.expl_comp_array import TestExplCompArrayDense from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.sellar import SellarDerivativesGrouped, SellarDerivatives from openmdao.test_suite.components.simple_comps import NonSquareArrayComp from openmdao.test_suite.groups.sin_fitter import SineFitter +from openmdao.utils.assert_utils import assert_rel_error, assert_warning +from openmdao.utils.general_utils import run_driver class TestScipyOptimizeDriver(unittest.TestCase): @@ -27,15 +26,15 @@ def test_scipyoptimizer_deprecation(self): "with OpenMDAO <= 2.2 ; use 'ScipyOptimizeDriver' instead." with assert_warning(DeprecationWarning, msg): - ScipyOptimizer() + om.ScipyOptimizer() def test_compute_totals_basic_return_array(self): # Make sure 'array' return_format works. - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + prob = om.Problem() + model = prob.model + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) model.add_design_var('x', lower=-50.0, upper=50.0) @@ -69,10 +68,10 @@ def test_compute_totals_basic_return_array(self): def test_compute_totals_return_array_non_square(self): - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) + model.add_subsystem('px', om.IndepVarComp(name="x", val=np.ones((2, )))) comp = model.add_subsystem('comp', NonSquareArrayComp()) model.connect('px.x', 'comp.x1') @@ -104,15 +103,15 @@ def test_compute_totals_return_array_non_square(self): def test_deriv_wrt_self(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp(name="x", val=np.ones((2, )))) + model.add_subsystem('px', om.IndepVarComp(name="x", val=np.ones((2, )))) model.add_design_var('px.x') model.add_objective('px.x') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -127,22 +126,22 @@ def test_deriv_wrt_self(self): def test_scipy_optimizer_simple_paraboloid_unconstrained(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizer(optimizer='SLSQP', tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizer(optimizer='SLSQP', tol=1e-9, disp=False) model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -154,16 +153,16 @@ def test_scipy_optimizer_simple_paraboloid_unconstrained(self): def test_simple_paraboloid_unconstrained(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -172,7 +171,7 @@ def test_simple_paraboloid_unconstrained(self): model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -183,16 +182,16 @@ def test_simple_paraboloid_unconstrained(self): assert_rel_error(self, prob['y'], -7.3333333, 1e-6) def test_simple_paraboloid_unconstrained_COBYLA(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -201,7 +200,7 @@ def test_simple_paraboloid_unconstrained_COBYLA(self): model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -213,17 +212,17 @@ def test_simple_paraboloid_unconstrained_COBYLA(self): def test_simple_paraboloid_upper(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -233,7 +232,7 @@ def test_simple_paraboloid_upper(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -246,17 +245,17 @@ def test_simple_paraboloid_upper(self): def test_simple_paraboloid_lower(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -267,7 +266,7 @@ def test_simple_paraboloid_lower(self): model.add_objective('f_xy') model.add_constraint('c', lower=15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -280,17 +279,17 @@ def test_simple_paraboloid_lower(self): def test_simple_paraboloid_equality(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -300,7 +299,7 @@ def test_simple_paraboloid_equality(self): model.add_objective('f_xy') model.add_constraint('c', equals=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -314,17 +313,17 @@ def test_simple_paraboloid_equality(self): def test_unsupported_equality(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -334,7 +333,7 @@ def test_unsupported_equality(self): model.add_objective('f_xy') model.add_constraint('c', equals=-15.0) - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception) as raises_cm: prob.run_driver() @@ -347,19 +346,19 @@ def test_unsupported_equality(self): def test_scipy_missing_objective(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('x', IndepVarComp('x', 2.0), promotes=['*']) + model.add_subsystem('x', om.IndepVarComp('x', 2.0), promotes=['*']) model.add_subsystem('f_x', Paraboloid(), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('x', lower=0) # prob.model.add_constraint('x', lower=0) - prob.setup(check=False) + prob.setup() with self.assertRaises(Exception) as raises_msg: prob.run_driver() @@ -372,17 +371,17 @@ def test_scipy_missing_objective(self): def test_simple_paraboloid_double_sided_low(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -392,7 +391,7 @@ def test_simple_paraboloid_double_sided_low(self): model.add_objective('f_xy') model.add_constraint('c', lower=-11.0, upper=-10.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -403,17 +402,17 @@ def test_simple_paraboloid_double_sided_low(self): def test_simple_paraboloid_double_sided_high(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -423,7 +422,7 @@ def test_simple_paraboloid_double_sided_high(self): model.add_objective('f_xy') model.add_constraint('c', lower=10.0, upper=11.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -434,19 +433,20 @@ def test_simple_paraboloid_double_sided_high(self): def test_simple_array_comp2D(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), + model.add_subsystem('con', om.ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), + areas=np.zeros((2, 2))), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -455,7 +455,7 @@ def test_simple_array_comp2D(self): model.add_objective('o') model.add_constraint('c', equals=0.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -467,17 +467,17 @@ def test_simple_array_comp2D(self): def test_simple_array_comp2D_eq_con(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0] + areas[1, 1]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0] + areas[1, 1]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -486,7 +486,7 @@ def test_simple_array_comp2D_eq_con(self): model.add_objective('o') model.add_constraint('areas', equals=np.array([24.0, 21.0, 3.5, 17.5])) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -498,17 +498,17 @@ def test_simple_array_comp2D_eq_con(self): def test_simple_array_comp2D_dbl_sided_con(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -517,7 +517,7 @@ def test_simple_array_comp2D_dbl_sided_con(self): model.add_objective('o') model.add_constraint('areas', lower=np.array([24.0, 21.0, 3.5, 17.5]), upper=np.array([24.0, 21.0, 3.5, 17.5])) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -529,17 +529,17 @@ def test_simple_array_comp2D_dbl_sided_con(self): def test_simple_array_comp2D_dbl_sided_con_array(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -548,7 +548,7 @@ def test_simple_array_comp2D_dbl_sided_con_array(self): model.add_objective('o') model.add_constraint('areas', lower=20.0, upper=20.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -560,19 +560,19 @@ def test_simple_array_comp2D_dbl_sided_con_array(self): def test_simple_array_comp2D_array_lo_hi(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), + model.add_subsystem('con', om.ExecComp('c = areas - 20.0', c=np.zeros((2, 2)), areas=np.zeros((2, 2))), promotes=['*']) - model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), + model.add_subsystem('obj', om.ExecComp('o = areas[0, 0]', areas=np.zeros((2, 2))), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -581,7 +581,7 @@ def test_simple_array_comp2D_array_lo_hi(self): model.add_objective('o') model.add_constraint('c', equals=0.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -593,17 +593,17 @@ def test_simple_array_comp2D_array_lo_hi(self): def test_simple_paraboloid_scaled_desvars_fwd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -624,17 +624,17 @@ def test_simple_paraboloid_scaled_desvars_fwd(self): def test_simple_paraboloid_scaled_desvars_rev(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -655,17 +655,17 @@ def test_simple_paraboloid_scaled_desvars_rev(self): def test_simple_paraboloid_scaled_constraint_fwd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -686,17 +686,17 @@ def test_simple_paraboloid_scaled_constraint_fwd(self): def test_simple_paraboloid_scaled_objective_fwd(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model prob.set_solver_print(level=0) - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -717,17 +717,17 @@ def test_simple_paraboloid_scaled_objective_fwd(self): def test_simple_paraboloid_scaled_objective_rev(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model prob.set_solver_print(level=0) - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -748,10 +748,10 @@ def test_simple_paraboloid_scaled_objective_rev(self): def test_sellar_mdf(self): - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -776,17 +776,17 @@ def test_sellar_mdf(self): def test_bug_in_eq_constraints(self): # We were getting extra constraints created because lower and upper are maxfloat instead of # None when unused. - p = Problem(model=SineFitter()) - p.driver = ScipyOptimizeDriver() + p = om.Problem(model=SineFitter()) + p.driver = om.ScipyOptimizeDriver() - p.setup(check=False) + p.setup() p.run_driver() max_defect = np.max(np.abs(p['defect.defect'])) assert_rel_error(self, max_defect, 0.0, 1e-10) def test_reraise_exception_from_callbacks(self): - class ReducedActuatorDisc(ExplicitComponent): + class ReducedActuatorDisc(om.ExplicitComponent): def setup(self): @@ -809,8 +809,8 @@ def compute_partials(self, inputs, J): J['Vd', 'a'] = -2.0 * Vu - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('a', .5) indeps.add_output('Vu', 10.0, units='m/s') @@ -818,7 +818,7 @@ def compute_partials(self, inputs, J): promotes_inputs=['a', 'Vu']) # setup the optimization - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('a', lower=0., upper=1.) @@ -835,17 +835,17 @@ def compute_partials(self, inputs, J): def test_simple_paraboloid_upper_COBYLA(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -855,7 +855,7 @@ def test_simple_paraboloid_upper_COBYLA(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -868,10 +868,10 @@ def test_simple_paraboloid_upper_COBYLA(self): def test_sellar_mdf_COBYLA(self): - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivativesGrouped() - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -902,7 +902,7 @@ def rosenbrock(x): x_1 = x[1:] return sum((1 - x_0) ** 2) + 100 * sum((x_1 - x_0 ** 2) ** 2) - class Rosenbrock(ExplicitComponent): + class Rosenbrock(om.ExplicitComponent): def setup(self): self.add_input('x', np.array([1.5, 1.5, 1.5])) @@ -915,14 +915,14 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x0 = np.array([1.2, 0.8, 1.3]) - prob = Problem() + prob = om.Problem() model = prob.model - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', list(x0)) prob.model.add_subsystem('rosen', Rosenbrock(), promotes=['*']) - prob.model.add_subsystem('con', ExecComp('c=sum(x)', x=np.ones(3)), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.model.add_subsystem('con', om.ExecComp('c=sum(x)', x=np.ones(3)), promotes=['*']) + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'trust-constr' driver.options['tol'] = 1e-8 driver.options['maxiter'] = 2000 @@ -949,7 +949,7 @@ def rosenbrock(x): x_1 = x[1:] return sum((1 - x_0) ** 2) + 100 * sum((x_1 - x_0 ** 2) ** 2) - class Rosenbrock(ExplicitComponent): + class Rosenbrock(om.ExplicitComponent): def setup(self): self.add_input('x', np.array([1.5, 1.5, 1.5])) @@ -962,14 +962,14 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x0 = np.array([1.2, 0.8, 1.3]) - prob = Problem() + prob = om.Problem() model = prob.model - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', list(x0)) prob.model.add_subsystem('rosen', Rosenbrock(), promotes=['*']) - prob.model.add_subsystem('con', ExecComp('c=sum(x)', x=np.ones(3)), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.model.add_subsystem('con', om.ExecComp('c=sum(x)', x=np.ones(3)), promotes=['*']) + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'trust-constr' driver.options['tol'] = 1e-8 driver.options['maxiter'] = 2000 @@ -997,7 +997,7 @@ def rosenbrock(x): x_1 = x[1:] return sum((1 - x_0) ** 2) + 100 * sum((x_1 - x_0 ** 2) ** 2) - class Rosenbrock(ExplicitComponent): + class Rosenbrock(om.ExplicitComponent): def setup(self): self.add_input('x', np.array([1.5, 1.5, 1.5])) @@ -1010,16 +1010,16 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x0 = np.array([0.5, 0.8, 1.4]) - prob = Problem() + prob = om.Problem() model = prob.model - indeps = prob.model.add_subsystem('indeps', IndepVarComp()) + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', list(x0)) model.add_subsystem('rosen', Rosenbrock()) - model.add_subsystem('con', ExecComp('c=sum(x)', x=np.ones(3))) + model.add_subsystem('con', om.ExecComp('c=sum(x)', x=np.ones(3))) model.connect('indeps.x', 'rosen.x') model.connect('indeps.x', 'con.x') - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'trust-constr' driver.options['tol'] = 1e-5 driver.options['maxiter'] = 2000 @@ -1038,7 +1038,7 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): "scipy >= 1.2 is required.") def test_trust_constr_inequality_con(self): - class Sphere(ExplicitComponent): + class Sphere(om.ExplicitComponent): def setup(self): self.add_input('x', np.array([1.5, 1.5])) @@ -1051,13 +1051,13 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x0 = np.array([1.2, 1.5]) - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', list(x0)) prob.model.add_subsystem('sphere', Sphere(), promotes=['*']) - prob.model.add_subsystem('con', ExecComp('c=sum(x)', x=np.ones(2)), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.model.add_subsystem('con', om.ExecComp('c=sum(x)', x=np.ones(2)), promotes=['*']) + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'trust-constr' prob.driver.options['tol'] = 1e-5 prob.driver.options['maxiter'] = 2000 @@ -1075,7 +1075,7 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): @unittest.skipUnless(LooseVersion(scipy_version) >= LooseVersion("1.2"), "scipy >= 1.2 is required.") def test_trust_constr_bounds(self): - class Rosenbrock(ExplicitComponent): + class Rosenbrock(om.ExplicitComponent): def setup(self): self.add_input('x', np.array([-1.5, -1.5])) @@ -1088,12 +1088,12 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x0 = np.array([-1.5, -1.5]) - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', list(x0)) prob.model.add_subsystem('sphere', Rosenbrock(), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'trust-constr' prob.driver.options['tol'] = 1e-7 prob.driver.options['maxiter'] = 2000 @@ -1110,17 +1110,17 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): def test_simple_paraboloid_lower_linear(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1130,7 +1130,7 @@ def test_simple_paraboloid_lower_linear(self): model.add_objective('f_xy') model.add_constraint('c', lower=15.0, linear=True) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -1145,17 +1145,17 @@ def test_simple_paraboloid_lower_linear(self): def test_simple_paraboloid_equality_linear(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1165,7 +1165,7 @@ def test_simple_paraboloid_equality_linear(self): model.add_objective('f_xy') model.add_constraint('c', equals=-15.0, linear=True) - prob.setup(check=False) + prob.setup() failed = prob.run_driver() @@ -1178,17 +1178,17 @@ def test_simple_paraboloid_equality_linear(self): def test_debug_print_option_totals(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1209,17 +1209,17 @@ def test_debug_print_option_totals(self): self.assertTrue('Solving variable: comp.f_xy' in output) self.assertTrue('Solving variable: con.c' in output) - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1242,17 +1242,17 @@ def test_debug_print_option_totals(self): def test_debug_print_option(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1264,7 +1264,7 @@ def test_debug_print_option(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() failed, output = run_driver(prob) @@ -1292,10 +1292,10 @@ def test_debug_print_option(self): def test_sellar_mdf_linear_con_directsolver(self): # This test makes sure that we call solve_nonlinear first if we have any linear constraints # to cache. - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivatives() - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-3 prob.driver.options['disp'] = False @@ -1324,17 +1324,17 @@ def test_sellar_mdf_linear_con_directsolver(self): def test_call_final_setup(self): # Make sure we call final setup if our model hasn't been setup. - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1344,7 +1344,7 @@ def test_call_final_setup(self): model.add_objective('f_xy') model.add_constraint('c', equals=-15.0) - prob.setup(check=False) + prob.setup() with self.assertRaises(RuntimeError) as cm: totals = prob.check_totals(method='fd', out_stream=False) @@ -1357,17 +1357,17 @@ def test_call_final_setup(self): class TestScipyOptimizeDriverFeatures(unittest.TestCase): def test_feature_basic(self): - from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True @@ -1384,23 +1384,23 @@ def test_feature_basic(self): assert_rel_error(self, prob['y'], -7.3333333, 1e-6) def test_feature_optimizer(self): - from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - prob.driver = ScipyOptimizeDriver(optimizer='COBYLA') + prob.driver = om.ScipyOptimizeDriver(optimizer='COBYLA') model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') - prob.setup(check=False) + prob.setup() prob.run_driver() @@ -1408,24 +1408,24 @@ def test_feature_optimizer(self): assert_rel_error(self, prob['y'], -7.3333333, 1e-6) def test_feature_maxiter(self): - from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['maxiter'] = 20 model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') - prob.setup(check=False) + prob.setup() prob.run_driver() @@ -1433,24 +1433,24 @@ def test_feature_maxiter(self): assert_rel_error(self, prob['y'], -7.3333333, 1e-6) def test_feature_tol(self): - from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['tol'] = 1.0e-9 model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') - prob.setup(check=False) + prob.setup() prob.run_driver() @@ -1459,20 +1459,20 @@ def test_feature_tol(self): def test_debug_print_option(self): - from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver, ExecComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1484,26 +1484,26 @@ def test_debug_print_option(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() prob.run_driver() def test_debug_print_option_totals(self): - from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver, ExecComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1515,26 +1515,26 @@ def test_debug_print_option_totals(self): model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - prob.setup(check=False) + prob.setup() prob.run_driver() def test_multiple_objectives_error(self): - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver, ExecComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1546,7 +1546,7 @@ def test_multiple_objectives_error(self): model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') model.add_objective('c') # Second objective - prob.setup(check=False) + prob.setup() with self.assertRaises(RuntimeError): prob.run_model() @@ -1556,9 +1556,9 @@ def test_multiple_objectives_error(self): def test_basinhopping(self): - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om - class Func2d(ExplicitComponent): + class Func2d(om.ExplicitComponent): def setup(self): self.add_input('x', np.ones(2)) @@ -1576,13 +1576,13 @@ def compute_partials(self, inputs, partials): df[1] = 2. * x[1] + 0.2 partials['f', 'x'] = df - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(2)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(2)), promotes=['*']) model.add_subsystem('func2d', Func2d(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'basinhopping' driver.options['disp'] = False driver.opt_settings['niter'] = 1000 @@ -1598,9 +1598,9 @@ def compute_partials(self, inputs, partials): def test_basinhopping_bounded(self): # It should find the local minimum, which is inside the bounds - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om - class Func2d(ExplicitComponent): + class Func2d(om.ExplicitComponent): def setup(self): self.add_input('x', np.ones(2)) @@ -1618,13 +1618,13 @@ def compute_partials(self, inputs, partials): df[1] = 2. * x[1] + 0.2 partials['f', 'x'] = df - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(2)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(2)), promotes=['*']) model.add_subsystem('func2d', Func2d(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'basinhopping' driver.options['disp'] = False driver.opt_settings['niter'] = 200 @@ -1641,7 +1641,7 @@ def compute_partials(self, inputs, partials): "scipy >= 1.2 is required.") def test_dual_annealing(self): - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om size = 6 # size of the design variable @@ -1650,7 +1650,7 @@ def rosenbrock(x): x_1 = x[1:] return sum((1 - x_0) ** 2) + 100 * sum((x_1 - x_0 ** 2) ** 2) - class Rosenbrock(ExplicitComponent): + class Rosenbrock(om.ExplicitComponent): def setup(self): self.add_input('x', 1.5*np.ones(size)) @@ -1660,13 +1660,13 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x = inputs['x'] outputs['f'] = rosenbrock(x) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(size)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(size)), promotes=['*']) model.add_subsystem('rosen', Rosenbrock(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'dual_annealing' driver.options['disp'] = False driver.options['tol'] = 1e-9 @@ -1684,7 +1684,7 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): @unittest.skipUnless(LooseVersion(scipy_version) >= LooseVersion("1.2"), "scipy >= 1.2 is required.") def test_dual_annealing_rastrigin(self): - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om # Example from the Scipy documentation size = 3 # size of the design variable @@ -1693,7 +1693,7 @@ def rastrigin(x): a = 10 # constant return np.sum(np.square(x) - a * np.cos(2 * np.pi * x)) + a * np.size(x) - class Rastrigin(ExplicitComponent): + class Rastrigin(om.ExplicitComponent): def setup(self): self.add_input('x', 0.5 * np.ones(size)) @@ -1703,13 +1703,13 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x = inputs['x'] outputs['f'] = rastrigin(x) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(size)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(size)), promotes=['*']) model.add_subsystem('rastrigin', Rastrigin(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'dual_annealing' driver.options['disp'] = False driver.options['tol'] = 1e-9 @@ -1728,7 +1728,7 @@ def test_differential_evolution(self): # Source of example: # https://scipy.github.io/devdocs/generated/scipy.optimize.dual_annealing.html - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om size = 3 # size of the design variable @@ -1736,7 +1736,7 @@ def rastrigin(x): a = 10 # constant return np.sum(np.square(x) - a * np.cos(2 * np.pi * x)) + a * np.size(x) - class Rastrigin(ExplicitComponent): + class Rastrigin(om.ExplicitComponent): def setup(self): self.add_input('x', 0.5 * np.ones(size)) @@ -1746,13 +1746,13 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x = inputs['x'] outputs['f'] = rastrigin(x) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(size)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(size)), promotes=['*']) model.add_subsystem('rastrigin', Rastrigin(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'differential_evolution' driver.options['disp'] = False driver.options['tol'] = 1e-9 @@ -1769,7 +1769,7 @@ def test_differential_evolution_bounded(self): # https://scipy.github.io/devdocs/generated/scipy.optimize.dual_annealing.html # In this example the minimum is not the unbounded global minimum. - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om size = 3 # size of the design variable @@ -1777,7 +1777,7 @@ def rastrigin(x): a = 10 # constant return np.sum(np.square(x) - a * np.cos(2 * np.pi * x)) + a * np.size(x) - class Rastrigin(ExplicitComponent): + class Rastrigin(om.ExplicitComponent): def setup(self): self.add_input('x', 0.5 * np.ones(size)) @@ -1787,13 +1787,13 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x = inputs['x'] outputs['f'] = rastrigin(x) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(size)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(size)), promotes=['*']) model.add_subsystem('rastrigin', Rastrigin(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'differential_evolution' driver.options['disp'] = False driver.options['tol'] = 1e-9 @@ -1812,7 +1812,7 @@ def test_shgo(self): # Source of example: # https://scipy.github.io/devdocs/generated/scipy.optimize.dual_annealing.html - from openmdao.api import Problem, IndepVarComp, ScipyOptimizeDriver + import openmdao.api as om size = 3 # size of the design variable @@ -1820,7 +1820,7 @@ def rastrigin(x): a = 10 # constant return np.sum(np.square(x) - a*np.cos(2*np.pi*x)) + a*np.size(x) - class Rastrigin(ExplicitComponent): + class Rastrigin(om.ExplicitComponent): def setup(self): self.add_input('x', np.ones(size)) @@ -1830,13 +1830,13 @@ def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None): x = inputs['x'] outputs['f'] = rastrigin(x) - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('indeps', IndepVarComp('x', np.ones(size)), promotes=['*']) + model.add_subsystem('indeps', om.IndepVarComp('x', np.ones(size)), promotes=['*']) model.add_subsystem('rastrigin', Rastrigin(), promotes=['*']) - prob.driver = driver = ScipyOptimizeDriver() + prob.driver = driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'shgo' driver.options['disp'] = False driver.options['maxiter'] = 100 diff --git a/openmdao/jacobians/tests/test_jacobian.py b/openmdao/jacobians/tests/test_jacobian.py index 97bcd74093..772dce7f38 100644 --- a/openmdao/jacobians/tests/test_jacobian.py +++ b/openmdao/jacobians/tests/test_jacobian.py @@ -223,7 +223,7 @@ def test_src_indices(self, assembled_jac, comp_jac_class, nested, lincalls): self._check_rev(self.prob, rev_check) def _setup_model(self, assembled_jac, comp_jac_class, nested, lincalls): - self.prob = prob = Problem(model=Group()) + self.prob = prob = Problem() if nested: top = prob.model.add_subsystem('G1', Group()) else: @@ -248,7 +248,7 @@ def _setup_model(self, assembled_jac, comp_jac_class, nested, lincalls): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() @@ -312,10 +312,10 @@ def test_jacobian_set_item(self, dtypes, shapes): shape, constructor, expected_shape = shapes dtype, value = dtypes - prob = Problem(model=Group()) + prob = Problem() comp = ExplicitSetItemComp(dtype, value, shape, constructor) prob.model.add_subsystem('C1', comp) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -400,7 +400,7 @@ def compute_partials(self, inputs, J): prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('px', IndepVarComp('x', np.array([1.0, 1.0])), promotes=['x']) model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) @@ -450,7 +450,7 @@ def test_assembled_jac_bad_key(self): prob.model.connect('C1.c', 'C2.b') prob.model.connect('C2.d', 'C3.a') prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['C3.ee'], 8.0, 0000.1) @@ -476,7 +476,7 @@ def test_assembled_jacobian_submat_indexing_dense(self): prob.model.connect('indeps.y', 'G1.C1.x') prob.model.connect('indeps.z', 'G1.C2.x') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['G1.C1.y'], 50.0) @@ -507,7 +507,7 @@ def test_assembled_jacobian_submat_indexing_csc(self): prob.model.connect('indeps.y', 'G1.C1.x') prob.model.connect('indeps.z', 'G1.C2.x') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['G1.C1.y'], 50.0) @@ -723,7 +723,7 @@ def compute_partials(self, inputs, partials): prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('p1', IndepVarComp('x', val=1.0)) model.add_subsystem('comp', Undeclared()) @@ -754,7 +754,7 @@ def test_one_src_2_tgts_with_src_indices_densejac(self): prob.model.connect('indeps.x', 'G1.C1.x', src_indices=[0,1]) prob.model.connect('indeps.x', 'G1.C1.y', src_indices=[2,3]) - prob.setup(check=False) + prob.setup() prob.run_model() J = prob.compute_totals(of=['G1.C1.z'], wrt=['indeps.x']) diff --git a/openmdao/jacobians/tests/test_jacobian_features.py b/openmdao/jacobians/tests/test_jacobian_features.py index 2edbdcac11..58cc7fffba 100644 --- a/openmdao/jacobians/tests/test_jacobian_features.py +++ b/openmdao/jacobians/tests/test_jacobian_features.py @@ -1,24 +1,26 @@ +""" +Unit and feature doc tests for partial derivative specifiation. +""" from __future__ import print_function, division - +import itertools import unittest +from six import iteritems + import numpy as np import scipy as sp -import itertools -from six import iteritems try: from parameterized import parameterized except ImportError: from openmdao.utils.assert_utils import SkipParameterized as parameterized -from openmdao.api import IndepVarComp, Group, Problem, ExplicitComponent, \ - ScipyKrylov, DirectSolver +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -class SimpleComp(ExplicitComponent): +class SimpleComp(om.ExplicitComponent): def setup(self): self.add_input('x', shape=1) self.add_input('y1', shape=2) @@ -80,7 +82,7 @@ def setup(self): self.declare_partials('g', 'y[13]', val=[[1, 0], [1, 0], [0, 1], [0, 1]]) -class SimpleCompConst(ExplicitComponent): +class SimpleCompConst(om.ExplicitComponent): def setup(self): self.add_input('x', shape=1) self.add_input('y1', shape=2) @@ -167,8 +169,8 @@ def compute_partials(self, inputs, partials): class TestJacobianFeatures(unittest.TestCase): def setUp(self): - self.model = model = Group() - comp = IndepVarComp() + self.model = model = om.Group() + comp = om.IndepVarComp() variables = ( ('x', 1.), ('y1', np.ones(2)), @@ -180,16 +182,16 @@ def setUp(self): comp.add_output(name, val) model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z']) - self.problem = Problem(model=model) + self.problem = om.Problem(model=model) self.problem.set_solver_print(level=0) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) def test_dependence(self): problem = self.problem model = problem.model model.add_subsystem('simple', SimpleCompConst(), promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g']) - problem.setup(check=False) + problem.setup() problem.run_model() # Note: since this test is looking for something not user-facing, it is inherently fragile @@ -240,7 +242,7 @@ def test_bad_sizes(self, partials_kwargs, error_msg): # Some of the tests are expected to fail in setup, and some in final_setup, so put them # both under the assert. with self.assertRaises(ValueError) as ex: - problem.setup(check=False) + problem.setup() problem.run_model() self.assertRegexpMatches(str(ex.exception), error_msg) @@ -255,25 +257,25 @@ def test_bad_names(self, partials_kwargs, error_msg): problem = self.problem model = problem.model model.add_subsystem('simple', comp, promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g']) - problem.setup(check=False) + problem.setup() with self.assertRaises(ValueError) as ex: problem.run_model() self.assertEquals(str(ex.exception), error_msg) def test_const_jacobian(self): - model = Group() - comp = IndepVarComp() + model = om.Group() + comp = om.IndepVarComp() for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)), ('y3', np.ones(2)), ('z', np.ones((2, 2)))): comp.add_output(name, val) model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z']) - problem = Problem(model=model) + problem = om.Problem(model=model) problem.set_solver_print(level=0) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.add_subsystem('simple', SimpleCompConst(), promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g']) - problem.setup(check=False) + problem.setup() problem.run_model() totals = problem.compute_totals(['f', 'g'], ['x', 'y1', 'y2', 'y3', 'z']) @@ -353,7 +355,7 @@ def test_mixed_fd(self): assert_rel_error(self, totals, jacobian, 1e-6) def test_units_fd(self): - class UnitCompBase(ExplicitComponent): + class UnitCompBase(om.ExplicitComponent): def setup(self): self.add_input('T', val=284., units="degR", desc="Temperature") self.add_input('P', val=1., units='lbf/inch**2', desc="Pressure") @@ -367,9 +369,9 @@ def compute(self, inputs, outputs): outputs['flow:T'] = inputs['T'] outputs['flow:P'] = inputs['P'] - p = Problem() - model = p.model = Group() - indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*']) + p = om.Problem() + model = p.model + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes=['*']) indep.add_output('T', val=100., units='degK') indep.add_output('P', val=1., units='bar') @@ -399,15 +401,15 @@ def compute(self, inputs, outputs): assert_rel_error(self, jac[deriv]['value'], val, 1e-6) def test_reference(self): - class TmpComp(ExplicitComponent): + class TmpComp(om.ExplicitComponent): def initialize(self): self.A = np.ones((3, 3)) def setup(self): - self.add_output('y', shape=(3,)) - self.add_output('z', shape=(3,)) - self.add_input('x', shape=(3,), units='degF') + self.add_output('y', shape=(3, )) + self.add_output('z', shape=(3, )) + self.add_input('x', shape=(3, ), units='degF') self.declare_partials(of='*', wrt='*') @@ -415,9 +417,9 @@ def compute_partials(self, inputs, partials): partials['y', 'x'] = self.A partials['z', 'x'] = self.A - p = Problem() - model = p.model = Group() - indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*']) + p = om.Problem() + model = p.model + indep = model.add_subsystem('indep', om.IndepVarComp(), promotes=['*']) indep.add_output('x', val=100., shape=(3,), units='degK') @@ -437,23 +439,23 @@ class TestJacobianForDocs(unittest.TestCase): def test_const_jacobian(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, DirectSolver + import openmdao.api as om from openmdao.jacobians.tests.test_jacobian_features import SimpleCompConst - model = Group(assembled_jac_type='dense') - comp = IndepVarComp() + model = om.Group(assembled_jac_type='dense') + comp = om.IndepVarComp() for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)), ('y3', np.ones(2)), ('z', np.ones((2, 2)))): comp.add_output(name, val) model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z']) - problem = Problem(model=model) + problem = om.Problem(model=model) problem.set_solver_print(0) - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) model.add_subsystem('simple', SimpleCompConst(), promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g']) - problem.setup(check=False) + problem.setup() problem.run_model() totals = problem.compute_totals(['f', 'g'], ['x', 'y1', 'y2', 'y3', 'z']) @@ -472,14 +474,16 @@ def test_const_jacobian(self): def test_sparse_jacobian_in_place(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + import openmdao.api as om - class SparsePartialComp(ExplicitComponent): + class SparsePartialComp(om.ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) self.add_output('f', shape=(2,)) - self.declare_partials(of='f', wrt='x', rows=[0,1,1,1], cols=[0,1,2,3]) + self.declare_partials(of='f', wrt='x', + rows=[0, 1, 1, 1], + cols=[0, 1, 2, 3]) def compute_partials(self, inputs, partials): pd = partials['f', 'x'] @@ -497,8 +501,8 @@ def compute_partials(self, inputs, partials): pd[3] = 4 - model = Group() - comp = IndepVarComp() + model = om.Group() + comp = om.IndepVarComp() comp.add_output('x', np.ones(4)) model.add_subsystem('input', comp) @@ -506,8 +510,8 @@ def compute_partials(self, inputs, partials): model.connect('input.x', 'example.x') - problem = Problem(model=model) - problem.setup(check=False) + problem = om.Problem(model=model) + problem.setup() problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x']) @@ -516,21 +520,23 @@ def compute_partials(self, inputs, partials): def test_sparse_jacobian(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + import openmdao.api as om - class SparsePartialComp(ExplicitComponent): + class SparsePartialComp(om.ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) self.add_output('f', shape=(2,)) - self.declare_partials(of='f', wrt='x', rows=[0, 1, 1, 1], cols=[0, 1, 2, 3]) + self.declare_partials(of='f', wrt='x', + rows=[0, 1, 1, 1], + cols=[0, 1, 2, 3]) def compute_partials(self, inputs, partials): # Corresponds to the [(0,0), (1,1), (1,2), (1,3)] entries. partials['f', 'x'] = [1., 2., 3., 4.] - model = Group() - comp = IndepVarComp() + model = om.Group() + comp = om.IndepVarComp() comp.add_output('x', np.ones(4)) model.add_subsystem('input', comp) @@ -538,8 +544,8 @@ def compute_partials(self, inputs, partials): model.connect('input.x', 'example.x') - problem = Problem(model=model) - problem.setup(check=False) + problem = om.Problem(model=model) + problem.setup() problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x']) @@ -549,23 +555,25 @@ def test_sparse_jacobian_const(self): import numpy as np import scipy as sp - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + import openmdao.api as om - class SparsePartialComp(ExplicitComponent): + class SparsePartialComp(om.ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) self.add_input('y', shape=(2,)) self.add_output('f', shape=(2,)) - self.declare_partials(of='f', wrt='x', rows=[0,1,1,1], cols=[0,1,2,3], - val=[1. , 2., 3., 4.]) + self.declare_partials(of='f', wrt='x', + rows=[0, 1, 1, 1], + cols=[0, 1, 2, 3], + val=[1., 2., 3., 4.]) self.declare_partials(of='f', wrt='y', val=sp.sparse.eye(2, format='csc')) def compute_partials(self, inputs, partials): pass - model = Group() - comp = IndepVarComp() + model = om.Group() + comp = om.IndepVarComp() comp.add_output('x', np.ones(4)) comp.add_output('y', np.ones(2)) @@ -575,8 +583,8 @@ def compute_partials(self, inputs, partials): model.connect('input.x', 'example.x') model.connect('input.y', 'example.y') - problem = Problem(model=model) - problem.setup(check=False) + problem = om.Problem(model=model) + problem.setup() problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x', 'input.y']) @@ -586,9 +594,9 @@ def compute_partials(self, inputs, partials): def test_fd_glob(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + import openmdao.api as om - class FDPartialComp(ExplicitComponent): + class FDPartialComp(om.ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) self.add_input('y', shape=(2,)) @@ -607,8 +615,8 @@ def compute(self, inputs, outputs): f[0] = x[0] + y[0] f[1] = np.dot([0, 2, 3, 4], x) + y[1] - model = Group() - comp = IndepVarComp() + model = om.Group() + comp = om.IndepVarComp() comp.add_output('x', np.ones(4)) comp.add_output('y', np.ones(2)) @@ -618,8 +626,8 @@ def compute(self, inputs, outputs): model.connect('input.x', 'example.x') model.connect('input.y', 'example.y') - problem = Problem(model=model) - problem.setup(check=False) + problem = om.Problem(model=model) + problem.setup() problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x', 'input.y']) @@ -630,9 +638,9 @@ def compute(self, inputs, outputs): def test_fd_options(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent + import openmdao.api as om - class FDPartialComp(ExplicitComponent): + class FDPartialComp(om.ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) @@ -652,8 +660,8 @@ def compute(self, inputs, outputs): f[0] = x[0] + y[0] f[1] = np.dot([0, 2, 3, 4], x) + y[1] - model = Group() - comp = IndepVarComp() + model = om.Group() + comp = om.IndepVarComp() comp.add_output('x', np.ones(4)) comp.add_output('y', np.ones(2)) @@ -663,8 +671,8 @@ def compute(self, inputs, outputs): model.connect('input.x', 'example.x') model.connect('input.y', 'example.y') - problem = Problem(model=model) - problem.setup(check=False) + problem = om.Problem(model=model) + problem.setup() problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x', 'input.y']) diff --git a/openmdao/recorders/tests/test_distrib_sqlite_recorder.py b/openmdao/recorders/tests/test_distrib_sqlite_recorder.py index ddf9bef30f..e328f482b3 100644 --- a/openmdao/recorders/tests/test_distrib_sqlite_recorder.py +++ b/openmdao/recorders/tests/test_distrib_sqlite_recorder.py @@ -117,7 +117,6 @@ def tearDown(self): def test_distrib_record_system(self): prob = Problem() - prob.model = Group() try: prob.model.add_recorder(self.recorder) @@ -129,7 +128,6 @@ def test_distrib_record_system(self): def test_distrib_record_solver(self): prob = Problem() - prob.model = Group() try: prob.model.nonlinear_solver.add_recorder(self.recorder) except RuntimeError as err: @@ -141,7 +139,6 @@ def test_distrib_record_solver(self): def test_distrib_record_driver(self): size = 100 # how many items in the array prob = Problem() - prob.model = Group() prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size)), promotes=['x']) prob.model.add_subsystem('plus', DistributedAdder(size), promotes=['x', 'y']) @@ -156,7 +153,7 @@ def test_distrib_record_driver(self): prob.model.add_design_var('x') prob.model.add_objective('sum') - prob.setup(check=False) + prob.setup() prob['x'] = np.ones(size) diff --git a/openmdao/recorders/tests/test_sqlite_reader.py b/openmdao/recorders/tests/test_sqlite_reader.py index 8ca53668f9..d676f99c85 100644 --- a/openmdao/recorders/tests/test_sqlite_reader.py +++ b/openmdao/recorders/tests/test_sqlite_reader.py @@ -12,23 +12,18 @@ import numpy as np from six import iteritems, assertRaisesRegex -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, \ - NonlinearRunOnce, NonlinearBlockGS, LinearBlockGS, ScipyOptimizeDriver -from openmdao.recorders.sqlite_recorder import SqliteRecorder, format_version -from openmdao.recorders.case_reader import CaseReader +import openmdao.api as om +from openmdao.recorders.sqlite_recorder import format_version from openmdao.recorders.sqlite_reader import SqliteCaseReader from openmdao.core.tests.test_units import SpeedComp from openmdao.test_suite.components.expl_comp_array import TestExplCompArray +from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStates from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.sellar import SellarDerivativesGrouped, \ SellarDis1withDerivatives, SellarDis2withDerivatives, SellarProblem from openmdao.utils.assert_utils import assert_rel_error, assert_warning from openmdao.utils.general_utils import set_pyoptsparse_opt, determine_adder_scaler -from openmdao.solvers.linear.scipy_iter_solver import ScipyKrylov -from openmdao.solvers.nonlinear.newton import NewtonSolver -from openmdao.solvers.linesearch.backtracking import ArmijoGoldsteinLS -from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStates # check that pyoptsparse is installed OPT, OPTIMIZER = set_pyoptsparse_opt('SLSQP') @@ -63,7 +58,7 @@ def setUp(self): os.chdir(self.temp_dir) self.filename = os.path.join(self.temp_dir, "sqlite_test") - self.recorder = SqliteRecorder(self.filename, record_viewer_data=False) + self.recorder = om.SqliteRecorder(self.filename, record_viewer_data=False) def tearDown(self): os.chdir(self.orig_dir) @@ -82,7 +77,7 @@ def test_bad_filetype(self): tmp.close() with self.assertRaises(IOError) as cm: - CaseReader(filepath) + om.CaseReader(filepath) msg = 'File does not contain a valid sqlite database' self.assertTrue(str(cm.exception).startswith(msg)) @@ -90,7 +85,7 @@ def test_bad_filetype(self): def test_bad_filename(self): # Pass a nonexistent file. with self.assertRaises(IOError) as cm: - CaseReader('junk.sql') + om.CaseReader('junk.sql') self.assertTrue(str(cm.exception).startswith('File does not exist')) @@ -101,7 +96,7 @@ def test_format_version(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) self.assertEqual(cr._format_version, format_version, msg='format version not read correctly') @@ -113,7 +108,7 @@ def test_reader_instantiates(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) self.assertTrue(isinstance(cr, SqliteCaseReader), msg='CaseReader not returning the correct subclass.') @@ -134,7 +129,7 @@ def test_invalid_source(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # check that driver is our only source self.assertEqual(cr.list_sources(), ['driver']) @@ -164,7 +159,7 @@ def test_reading_driver_cases(self): """ Tests that the reader returns params correctly. """ prob = SellarProblem(SellarDerivativesGrouped) - driver = prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + driver = prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True @@ -177,7 +172,7 @@ def test_reading_driver_cases(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # check that we only have driver cases self.assertEqual(cr.list_sources(), ['driver']) @@ -243,7 +238,7 @@ def test_reading_system_cases(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # check that we only have the three system sources self.assertEqual(sorted(cr.list_sources()), ['root', 'root.d1', 'root.obj_cmp']) @@ -297,7 +292,7 @@ def test_reading_solver_cases(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # check that we only have the one solver source self.assertEqual(sorted(cr.list_sources()), ['root.nonlinear_solver']) @@ -324,27 +319,27 @@ def test_reading_solver_cases(self): 'rank0:Driver|0|root._solve_nonlinear|0|NonlinearBlockGS|%d' % i) def test_reading_metadata(self): - prob = Problem() + prob = om.Problem() model = prob.model # the Sellar problem but with units - model.add_subsystem('px', IndepVarComp('x', 1.0, units='m', lower=-1000, upper=1000), + model.add_subsystem('px', om.IndepVarComp('x', 1.0, units='m', lower=-1000, upper=1000), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) model.add_subsystem('obj_cmp', - ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), - x={'value': 0.0, 'units': 'm'}, - y1={'units': 'm'}, y2={'units': 'cm'}), + om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), + x={'value': 0.0, 'units': 'm'}, + y1={'units': 'm'}, y2={'units': 'cm'}), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS(iprint=0) - model.linear_solver = LinearBlockGS(iprint=0) + model.nonlinear_solver = om.NonlinearBlockGS(iprint=0) + model.linear_solver = om.LinearBlockGS(iprint=0) model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) model.add_design_var('x', lower=0.0, upper=10.0) @@ -358,7 +353,7 @@ def test_reading_metadata(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) self.assertEqual(cr._output2meta['x']['units'], 'm') self.assertEqual(cr._input2meta['obj_cmp.y1']['units'], 'm') @@ -380,19 +375,19 @@ def test_reading_metadata(self): self.assertEqual(cr._output2meta['y2']['lower'], 0.1) def test_reading_solver_metadata(self): - prob = SellarProblem(linear_solver=LinearBlockGS()) + prob = SellarProblem(linear_solver=om.LinearBlockGS()) prob.setup() prob.model.nonlinear_solver.add_recorder(self.recorder) d1 = prob.model.d1 # SellarDis1withDerivatives (an ExplicitComponent) - d1.nonlinear_solver = NonlinearBlockGS(maxiter=5) + d1.nonlinear_solver = om.NonlinearBlockGS(maxiter=5) d1.nonlinear_solver.add_recorder(self.recorder) prob.run_driver() prob.cleanup() - metadata = CaseReader(self.filename).solver_metadata + metadata = om.CaseReader(self.filename).solver_metadata self.assertEqual( sorted(metadata.keys()), @@ -404,7 +399,7 @@ def test_reading_solver_metadata(self): def test_reading_driver_recording_with_system_vars(self): prob = SellarProblem(SellarDerivativesGrouped) - driver = prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + driver = prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True @@ -417,7 +412,7 @@ def test_reading_driver_recording_with_system_vars(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # Test values from the last case driver_cases = cr.list_cases('driver') @@ -430,7 +425,7 @@ def test_reading_driver_recording_with_system_vars(self): @unittest.skipIf(OPT is None, "pyoptsparse is not installed") @unittest.skipIf(OPTIMIZER is None, "pyoptsparse is not providing SNOPT or SLSQP") def test_get_child_cases(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) driver = prob.driver = pyOptSparseDriver(optimizer='SLSQP', print_results=False) prob.driver.opt_settings['ACC'] = 1e-9 @@ -449,7 +444,7 @@ def test_get_child_cases(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # check driver cases expected_coords = [ @@ -550,8 +545,8 @@ def test_get_child_cases(self): self.assertEqual(count, 3) def test_get_child_cases_system(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) prob.setup() model = prob.model @@ -562,7 +557,7 @@ def test_get_child_cases_system(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) parent_coord = 'rank0:ScipyOptimize_SLSQP|2|root._solve_nonlinear|2' coord = parent_coord + '|NLRunOnce|0' @@ -594,8 +589,8 @@ def test_get_child_cases_system(self): self.assertEqual(i, len(expected_coords)) def test_list_cases_recurse(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=True) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=True) prob.driver.add_recorder(self.recorder) prob.setup() @@ -608,7 +603,7 @@ def test_list_cases_recurse(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # get total iteration count to check against global_iterations = len(cr._global_iterations) @@ -718,8 +713,8 @@ def test_list_cases_recurse(self): self.assertEqual(counter, root_counter) def test_list_cases_nested_model(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=True) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=True) prob.setup() model = prob.model @@ -731,7 +726,7 @@ def test_list_cases_nested_model(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # get total iteration count to check against global_iterations = len(cr._global_iterations) @@ -760,8 +755,8 @@ def test_list_cases_nested_model(self): self.assertEqual(num_cases, global_iterations) def test_list_cases_nested_no_source(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=True) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=True) prob.setup() model = prob.model @@ -772,7 +767,7 @@ def test_list_cases_nested_no_source(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # get total iteration count to check against global_iterations = len(cr._global_iterations) @@ -805,8 +800,8 @@ def test_list_cases_nested_no_source(self): self.assertEqual(str(cm.exception), expected_err) def test_get_cases_recurse(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=True) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=True) prob.driver.opt_settings['ACC'] = 1e-9 prob.driver.add_recorder(self.recorder) prob.setup() @@ -820,7 +815,7 @@ def test_get_cases_recurse(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # get total iteration count to check against global_iterations = len(cr._global_iterations) @@ -934,13 +929,13 @@ def test_list_outputs(self): prob.setup() d1 = prob.model.d1 # SellarDis1withDerivatives (an ExplicitComp) - d1.nonlinear_solver = NonlinearBlockGS(maxiter=5) + d1.nonlinear_solver = om.NonlinearBlockGS(maxiter=5) d1.add_recorder(self.recorder) prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # check the system case for 'd1' (there should be only one output, 'd1.y1') system_cases = cr.list_cases('root.d1') @@ -989,13 +984,13 @@ def test_list_inputs(self): prob.setup() d1 = prob.model.d1 # SellarDis1withDerivatives (an ExplicitComp) - d1.nonlinear_solver = NonlinearBlockGS(maxiter=5) + d1.nonlinear_solver = om.NonlinearBlockGS(maxiter=5) d1.add_recorder(self.recorder) prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) expected_inputs_case = { 'd1.z': {'value': [5., 2.]}, @@ -1028,7 +1023,7 @@ def test_get_vars(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) driver_cases = cr.list_cases('driver') driver_case = cr.get_case(driver_cases[0]) @@ -1068,7 +1063,7 @@ def test_simple_load_system_cases(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) system_cases = cr.list_cases('root') case = cr.get_case(system_cases[0]) @@ -1090,7 +1085,7 @@ def test_load_bad_system_case(self): prob.model.add_recorder(self.recorder) - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-9 driver.options['disp'] = False @@ -1103,7 +1098,7 @@ def test_load_bad_system_case(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) system_cases = cr.list_cases('root') case = cr.get_case(system_cases[0]) @@ -1131,7 +1126,7 @@ def test_subsystem_load_system_cases(self): prob.run_driver() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) system_cases = cr.list_cases('root.d2') case = cr.get_case(system_cases[0]) @@ -1149,15 +1144,15 @@ def test_subsystem_load_system_cases(self): _assert_model_matches_case(case, model.d2) def test_load_system_cases_with_units(self): - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('distance', val=1., units='m') comp.add_output('time', val=1., units='s') - prob = Problem() + prob = om.Problem() model = prob.model model.add_subsystem('c1', comp) model.add_subsystem('c2', SpeedComp()) - model.add_subsystem('c3', ExecComp('f=speed', speed={'units': 'm/s'}, f={'units': 'm/s'})) + model.add_subsystem('c3', om.ExecComp('f=speed', speed={'units': 'm/s'}, f={'units': 'm/s'})) model.connect('c1.distance', 'c2.distance') model.connect('c1.time', 'c2.time') model.connect('c2.speed', 'c3.speed') @@ -1167,7 +1162,7 @@ def test_load_system_cases_with_units(self): prob.setup() prob.run_model() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) system_cases = cr.list_cases('root') case = cr.get_case(system_cases[0]) @@ -1208,7 +1203,7 @@ def test_optimization_load_system_cases(self): prob.model.add_recorder(self.recorder) - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-9 driver.options['disp'] = False @@ -1224,7 +1219,7 @@ def test_optimization_load_system_cases(self): inputs_before = prob.model.list_inputs(values=True, units=True, out_stream=None) outputs_before = prob.model.list_outputs(values=True, units=True, out_stream=None) - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # get third case system_cases = cr.list_cases('root') @@ -1235,7 +1230,7 @@ def test_optimization_load_system_cases(self): # run the model again with a fresh model prob = SellarProblem(SellarDerivativesGrouped) - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-9 driver.options['disp'] = False @@ -1271,7 +1266,7 @@ def test_load_solver_cases(self): self.assertFalse(fail, 'Problem failed to converge') - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) solver_cases = cr.list_cases('root.nonlinear_solver') case = cr.get_case(solver_cases[0]) @@ -1289,13 +1284,13 @@ def test_load_solver_cases(self): _assert_model_matches_case(case, model) def test_load_driver_cases(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) @@ -1314,7 +1309,7 @@ def test_load_driver_cases(self): self.assertFalse(fail, 'Problem failed to converge') - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) driver_cases = cr.list_cases('driver') case = cr.get_case(driver_cases[0]) @@ -1333,8 +1328,8 @@ def test_load_driver_cases(self): def test_system_options_pickle_fail(self): # simple paraboloid model - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() ivc.add_output('x', 3.0) model.add_subsystem('subs', ivc) subs = model.subs @@ -1345,7 +1340,7 @@ def test_system_options_pickle_fail(self): subs.options.declare('options value to fail', (i for i in [])) subs.add_recorder(self.recorder) - prob = Problem(model) + prob = om.Problem(model) prob.setup() msg = "Trying to record options which cannot be pickled on system with name: subs. " \ @@ -1356,7 +1351,7 @@ def test_system_options_pickle_fail(self): prob.run_model() prob.cleanup() - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) subs_options = cr.system_metadata['subs']['component_options'] # no options should have been recorded for d1 @@ -1366,7 +1361,7 @@ def test_pre_load(self): prob = SellarProblem() prob.setup() - recorder = SqliteRecorder(self.filename) + recorder = om.SqliteRecorder(self.filename) prob.add_recorder(recorder) prob.driver.add_recorder(recorder) @@ -1379,7 +1374,7 @@ def test_pre_load(self): prob.cleanup() # without pre_load, we should get format_version and metadata but no cases - cr = CaseReader(self.filename, pre_load=False) + cr = om.CaseReader(self.filename, pre_load=False) num_driver_cases = len(cr.list_cases('driver', recurse=False)) num_system_cases = len(cr.list_cases('root', recurse=False)) @@ -1407,7 +1402,7 @@ def test_pre_load(self): self.assertEqual(len(cr._problem_cases._cases), 0) # with pre_load, we should get format_version, metadata and all cases - cr = CaseReader(self.filename, pre_load=True) + cr = om.CaseReader(self.filename, pre_load=True) num_driver_cases = len(cr.list_cases('driver', recurse=False)) num_system_cases = len(cr.list_cases('root', recurse=False)) @@ -1454,7 +1449,7 @@ def test_caching_cases(self): prob.record_iteration('c_2') prob.cleanup() - cr = CaseReader(self.filename, pre_load=False) + cr = om.CaseReader(self.filename, pre_load=False) self.assertEqual(len(cr._driver_cases._cases), 0) self.assertEqual(len(cr._system_cases._cases), 0) @@ -1493,9 +1488,9 @@ def test_caching_cases(self): def test_reading_driver_cases_with_indices(self): # note: size must be an even number SIZE = 10 - prob = Problem() + prob = om.Problem() - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['disp'] = False @@ -1503,7 +1498,7 @@ def test_reading_driver_cases_with_indices(self): driver.recording_options['includes'] = ['*'] model = prob.model - indeps = model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['*']) + indeps = model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*']) # the following were randomly generated using np.random.random(10)*2-1 to randomly # disperse them within a unit circle centered at the origin. @@ -1520,21 +1515,21 @@ def test_reading_driver_cases_with_indices(self): ])) indeps.add_output('r', .7) - model.add_subsystem('circle', ExecComp('area = pi * r**2')) + model.add_subsystem('circle', om.ExecComp('area = pi * r**2')) - model.add_subsystem('r_con', ExecComp('g = x**2 + y**2 - r**2', - g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) + model.add_subsystem('r_con', om.ExecComp('g = x**2 + y**2 - r**2', + g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))) thetas = np.linspace(0, np.pi/4, SIZE) - model.add_subsystem('theta_con', ExecComp('g=arctan(y/x) - theta', - g=np.ones(SIZE), x=np.ones(SIZE), - y=np.ones(SIZE), theta=thetas)) - model.add_subsystem('delta_theta_con', ExecComp('g = arctan(y/x)[::2]-arctan(y/x)[1::2]', - g=np.ones(SIZE//2), x=np.ones(SIZE), - y=np.ones(SIZE))) + model.add_subsystem('theta_con', om.ExecComp('g=arctan(y/x) - theta', + g=np.ones(SIZE), x=np.ones(SIZE), + y=np.ones(SIZE), theta=thetas)) + model.add_subsystem('delta_theta_con', om.ExecComp('g = arctan(y/x)[::2]-arctan(y/x)[1::2]', + g=np.ones(SIZE//2), x=np.ones(SIZE), + y=np.ones(SIZE))) - model.add_subsystem('l_conx', ExecComp('g=x-1', g=np.ones(SIZE), x=np.ones(SIZE))) + model.add_subsystem('l_conx', om.ExecComp('g=x-1', g=np.ones(SIZE), x=np.ones(SIZE))) model.connect('r', ('circle.r', 'r_con.r')) model.connect('x', ['r_con.x', 'theta_con.x', 'delta_theta_con.x']) @@ -1566,7 +1561,7 @@ def test_reading_driver_cases_with_indices(self): prob.cleanup() # get the case we recorded - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) case = cr.get_case(0) # check 'use_indices' option, default is to use indices @@ -1594,7 +1589,7 @@ def test_reading_driver_cases_with_indices(self): _assert_model_matches_case(case, model) def test_multidimensional_arrays(self): - prob = Problem() + prob = om.Problem() model = prob.model comp = TestExplCompArray(thickness=1.) # has 2D arrays as inputs and outputs @@ -1602,9 +1597,9 @@ def test_multidimensional_arrays(self): # just to add a connection, otherwise an exception is thrown in recording viewer data. # must be a bug model.add_subsystem('double_area', - ExecComp('double_area = 2 * areas', - areas=np.zeros((2, 2)), - double_area=np.zeros((2, 2))), + om.ExecComp('double_area = 2 * areas', + areas=np.zeros((2, 2)), + double_area=np.zeros((2, 2))), promotes=['*']) prob.driver.add_recorder(self.recorder) @@ -1622,7 +1617,7 @@ def test_multidimensional_arrays(self): model._outputs[name] += 1.0 # Now load in the case we recorded - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) driver_cases = cr.list_cases('driver') case = cr.get_case(driver_cases[0]) @@ -1633,17 +1628,17 @@ def test_multidimensional_arrays(self): def test_simple_paraboloid_scaled_desvars(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) prob.set_solver_print(level=0) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False @@ -1652,7 +1647,7 @@ def test_simple_paraboloid_scaled_desvars(self): prob.driver.recording_options['record_responses'] = True prob.driver.recording_options['record_objectives'] = True prob.driver.recording_options['record_constraints'] = True - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) ref = 5.0 @@ -1667,7 +1662,7 @@ def test_simple_paraboloid_scaled_desvars(self): prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # Test values from the last case driver_cases = cr.list_cases('driver') @@ -1686,10 +1681,10 @@ def test_simple_paraboloid_scaled_desvars(self): self.assertAlmostEqual((unscaled_y + adder) * scaler, scaled_y, places=12) def test_reading_all_case_types(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) prob.setup(mode='rev') - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) # # Add recorders @@ -1719,7 +1714,7 @@ def test_reading_all_case_types(self): pz.add_recorder(self.recorder) # mda solver - nl = prob.model.mda.nonlinear_solver = NonlinearBlockGS() + nl = prob.model.mda.nonlinear_solver = om.NonlinearBlockGS() nl.recording_options['record_metadata'] = True nl.recording_options['record_abs_error'] = True nl.recording_options['record_rel_error'] = True @@ -1740,7 +1735,7 @@ def test_reading_all_case_types(self): self.assertFalse(fail, 'Problem optimization failed.') - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) # # check sources @@ -1920,21 +1915,21 @@ def test_reading_all_case_types(self): self.assertTrue(case in all_driver_cases) def test_linesearch(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0)) + model.add_subsystem('px', om.IndepVarComp('x', 1.0)) model.add_subsystem('comp', ImplCompTwoStates()) model.connect('px.x', 'comp.x') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() model.nonlinear_solver.options['maxiter'] = 3 # model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['iprint'] = 2 - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - ls = model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['maxiter'] = 3 ls.options['alpha'] = 1.0 @@ -1944,7 +1939,7 @@ def test_linesearch(self): model.comp.add_recorder(self.recorder) model.add_recorder(self.recorder) - prob.setup(check=False) + prob.setup() prob['px.x'] = 2.0 prob['comp.y'] = 0.0 @@ -1966,7 +1961,7 @@ def test_linesearch(self): 'rank0:root._solve_nonlinear|0' ] - cr = CaseReader(self.filename) + cr = om.CaseReader(self.filename) for i, c in enumerate(cr.list_cases()): case = cr.get_case(c) @@ -2007,10 +2002,10 @@ def tearDown(self): def test_feature_list_cases(self): import numpy as np - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2020,16 +2015,16 @@ def test_feature_list_cases(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - driver = prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) - driver.add_recorder(SqliteRecorder('cases.sql')) + driver.add_recorder(om.SqliteRecorder('cases.sql')) prob.setup() prob.set_solver_print(0) prob.run_driver() prob.cleanup() - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') case_ids = cr.list_cases() @@ -2042,12 +2037,12 @@ def test_feature_list_cases(self): self.assertEqual(case, case) def test_feature_get_cases(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA import numpy as np - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2057,15 +2052,15 @@ def test_feature_get_cases(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - driver = prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) - driver.add_recorder(SqliteRecorder('cases.sql')) + driver = prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) + driver.add_recorder(om.SqliteRecorder('cases.sql')) prob.setup() prob.set_solver_print(0) prob.run_driver() prob.cleanup() - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') cases = cr.get_cases() @@ -2075,13 +2070,13 @@ def test_feature_get_cases(self): self.assertEqual(case, case) def test_feature_get_cases_nested(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA import numpy as np # define Sellar MDA problem - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2091,10 +2086,10 @@ def test_feature_get_cases_nested(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) # add recorder to the driver, model and solver - recorder = SqliteRecorder('cases.sql') + recorder = om.SqliteRecorder('cases.sql') prob.driver.add_recorder(recorder) model.add_recorder(recorder) @@ -2107,7 +2102,7 @@ def test_feature_get_cases_nested(self): prob.cleanup() # get the last driver case - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') driver_cases = cr.list_cases('driver') last_driver_case = driver_cases[-1] @@ -2124,13 +2119,13 @@ def test_feature_get_cases_nested(self): self.assertEqual(grandchild, grandchild) def test_feature_list_sources(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA import numpy as np # define Sellar MDA problem - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2140,10 +2135,10 @@ def test_feature_list_sources(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) # add recorder to the driver, model and solver - recorder = SqliteRecorder('cases.sql') + recorder = om.SqliteRecorder('cases.sql') prob.driver.add_recorder(recorder) model.add_recorder(recorder) @@ -2156,7 +2151,7 @@ def test_feature_list_sources(self): prob.cleanup() # examine cases to see what was recorded - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') self.assertEqual(sorted(cr.list_sources()), ['driver', 'root', 'root.nonlinear_solver']) @@ -2173,12 +2168,12 @@ def test_feature_list_sources(self): ('inputs:', ['x', 'y1', 'y2', 'z'], 'outputs:', ['con1', 'con2', 'obj', 'x', 'y1', 'y2', 'z'])) def test_feature_reading_derivatives(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA import numpy as np - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2188,17 +2183,17 @@ def test_feature_reading_derivatives(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - driver = prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) + driver = prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) driver.recording_options['record_derivatives'] = True - driver.add_recorder(SqliteRecorder('cases.sql')) + driver.add_recorder(om.SqliteRecorder('cases.sql')) prob.setup() prob.set_solver_print(0) prob.run_driver() prob.cleanup() - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') # Get derivatives associated with the last iteration. derivs = cr.get_case(-1).jacobian @@ -2213,19 +2208,17 @@ def test_feature_reading_derivatives(self): assert_rel_error(self, derivs['obj', 'z'], derivs['obj', 'z']) def test_feature_recording_option_precedence(self): - from openmdao.api import Problem, IndepVarComp, ExecComp, ScipyOptimizeDriver, \ - SqliteRecorder - from openmdao.recorders.case_reader import CaseReader + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) @@ -2233,7 +2226,7 @@ def test_feature_recording_option_precedence(self): model.add_constraint('c', lower=15.0) filename = "cases.sql" - recorder = SqliteRecorder(filename) + recorder = om.SqliteRecorder(filename) prob.driver.add_recorder(recorder) prob.driver.recording_options['record_desvars'] = True @@ -2246,13 +2239,13 @@ def test_feature_recording_option_precedence(self): prob.cleanup() # First case with record_desvars = True and includes = [] - cr = CaseReader(filename) + cr = om.CaseReader(filename) case = cr.get_case(-1) self.assertEqual(sorted(case.outputs.keys()), ['c', 'f_xy', 'x']) # Second case with record_desvars = False and includes = [] - recorder = SqliteRecorder(filename) + recorder = om.SqliteRecorder(filename) prob.driver.add_recorder(recorder) prob.driver.recording_options['record_desvars'] = False prob.driver.recording_options['includes'] = [] @@ -2261,13 +2254,13 @@ def test_feature_recording_option_precedence(self): prob.run_driver() prob.cleanup() - cr = CaseReader(filename) + cr = om.CaseReader(filename) case = cr.get_case(0) self.assertEqual(sorted(case.outputs.keys()), ['c', 'f_xy']) # Third case with record_desvars = True and includes = ['*'] - recorder = SqliteRecorder(filename) + recorder = om.SqliteRecorder(filename) prob.driver.add_recorder(recorder) prob.driver.recording_options['record_desvars'] = True prob.driver.recording_options['includes'] = ['*'] @@ -2276,13 +2269,13 @@ def test_feature_recording_option_precedence(self): prob.run_driver() prob.cleanup() - cr = CaseReader(filename) + cr = om.CaseReader(filename) case = cr.get_case(0) self.assertEqual(sorted(case.outputs.keys()), ['c', 'f_xy', 'x']) # Fourth case with record_desvars = False and includes = ['*'] - recorder = SqliteRecorder(filename) + recorder = om.SqliteRecorder(filename) prob.driver.add_recorder(recorder) prob.driver.recording_options['record_desvars'] = False prob.driver.recording_options['includes'] = ['*'] @@ -2291,18 +2284,18 @@ def test_feature_recording_option_precedence(self): prob.run_driver() prob.cleanup() - cr = CaseReader(filename) + cr = om.CaseReader(filename) case = cr.get_case(0) self.assertEqual(sorted(case.outputs.keys()), ['c', 'f_xy']) def test_feature_driver_options_with_values(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives import numpy as np - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2312,9 +2305,9 @@ def test_feature_driver_options_with_values(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - driver = prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) + driver = prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) - driver.add_recorder(SqliteRecorder("cases.sql")) + driver.add_recorder(om.SqliteRecorder("cases.sql")) driver.recording_options['includes'] = [] driver.recording_options['record_objectives'] = True @@ -2326,7 +2319,7 @@ def test_feature_driver_options_with_values(self): prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") driver_cases = cr.list_cases('driver') case = cr.get_case(driver_cases[0]) @@ -2367,9 +2360,9 @@ def tearDown(self): def test_dict_functionality(self): prob = SellarProblem(SellarDerivativesGrouped) - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") driver.add_recorder(recorder) driver.recording_options['includes'] = [] @@ -2382,7 +2375,7 @@ def test_dict_functionality(self): prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") driver_cases = cr.list_cases('driver') driver_case = cr.get_case(driver_cases[-1]) @@ -2507,7 +2500,7 @@ def test_database_v4(self): filename = os.path.join(self.legacy_dir, 'case_database_v4.sql') - cr = CaseReader(filename) + cr = om.CaseReader(filename) # # check sources @@ -2626,14 +2619,14 @@ def test_driver_v3(self): test in test_sqlite_recorder.py """ prob = SellarProblem(SellarDerivativesGrouped) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) prob.setup() prob.run_driver() prob.cleanup() filename = os.path.join(self.legacy_dir, 'case_driver_solver_system_03.sql') - cr = CaseReader(filename) + cr = om.CaseReader(filename) # list just the driver cases driver_cases = cr.list_cases('driver', recurse=False) @@ -2678,14 +2671,14 @@ def test_driver_v3(self): def test_driver_v2(self): """ Backwards compatibility version 2. """ prob = SellarProblem(SellarDerivativesGrouped) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) prob.setup() prob.run_driver() prob.cleanup() filename = os.path.join(self.legacy_dir, 'case_driver_solver_system_02.sql') - cr = CaseReader(filename) + cr = om.CaseReader(filename) # list just the driver cases driver_cases = cr.list_cases('driver', recurse=False) @@ -2731,7 +2724,7 @@ def test_solver_v2(self): """ Backwards compatibility version 2. """ filename = os.path.join(self.legacy_dir, 'case_driver_solver_system_02.sql') - cases = CaseReader(filename) + cases = om.CaseReader(filename) # list just the solver cases solver_cases = cases.list_cases('root.nonlinear_solver', recurse=False) @@ -2761,7 +2754,7 @@ def test_system_v2(self): """ Backwards compatibility version 2. """ filename = os.path.join(self.legacy_dir, 'case_driver_solver_system_02.sql') - cr = CaseReader(filename) + cr = om.CaseReader(filename) # list just the system cases system_cases = cr.list_cases('root', recurse=False) @@ -2797,14 +2790,14 @@ def test_system_v2(self): def test_driver_v1(self): """ Backwards compatibility oldest version. """ prob = SellarProblem(SellarDerivativesGrouped) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) prob.setup() prob.run_driver() prob.cleanup() filename = os.path.join(self.legacy_dir, 'case_driver_01.sql') - cr = CaseReader(filename) + cr = om.CaseReader(filename) # recorded data from driver only self.assertEqual(cr.list_sources(), ['driver']) @@ -2844,14 +2837,14 @@ def test_driver_v1(self): def test_driver_v1_pre_problem(self): """ Backwards compatibility oldest version. """ prob = SellarProblem(SellarDerivativesGrouped) - prob.driver = ScipyOptimizeDriver(tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(tol=1e-9, disp=False) prob.setup() prob.run_driver() prob.cleanup() filename = os.path.join(self.legacy_dir, 'case_driver_pre01.sql') - cr = CaseReader(filename) + cr = om.CaseReader(filename) # recorded data from driver only self.assertEqual(cr.list_sources(), ['driver']) diff --git a/openmdao/recorders/tests/test_sqlite_recorder.py b/openmdao/recorders/tests/test_sqlite_recorder.py index b9fb7d10cb..a557e4fc1f 100644 --- a/openmdao/recorders/tests/test_sqlite_recorder.py +++ b/openmdao/recorders/tests/test_sqlite_recorder.py @@ -9,11 +9,7 @@ from shutil import rmtree from tempfile import mkdtemp -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, SqliteRecorder, \ - ScipyOptimizeDriver, NonlinearRunOnce, NonlinearBlockGS, NonlinearBlockJac, NewtonSolver, \ - LinearRunOnce, LinearBlockGS, LinearBlockJac, DirectSolver, ScipyKrylov, PETScKrylov, \ - BoundsEnforceLS, ArmijoGoldsteinLS, CaseReader, AnalysisError - +import openmdao.api as om from openmdao.utils.general_utils import set_pyoptsparse_opt from openmdao.test_suite.components.ae_tests import AEComp @@ -37,7 +33,7 @@ from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver -class ParaboloidProblem(Problem): +class ParaboloidProblem(om.Problem): """ Paraboloid problem with Constraint. """ @@ -46,10 +42,10 @@ def __init__(self): super(ParaboloidProblem, self).__init__() model = self.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) @@ -65,7 +61,7 @@ def setUp(self): os.chdir(self.temp_dir) self.filename = os.path.join(self.temp_dir, "sqlite_test") - self.recorder = SqliteRecorder(self.filename, record_viewer_data=False) + self.recorder = om.SqliteRecorder(self.filename, record_viewer_data=False) self.eps = 1e-3 @@ -171,7 +167,7 @@ def test_only_constraints_recorded(self): def test_simple_driver_recording(self): prob = ParaboloidProblem() - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True driver.recording_options['record_objectives'] = True @@ -294,7 +290,7 @@ def test_simple_driver_recording_pyoptsparse(self): def test_simple_driver_recording_with_prefix(self): prob = ParaboloidProblem() - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True driver.recording_options['record_objectives'] = True @@ -352,7 +348,7 @@ def test_simple_driver_recording_with_prefix(self): def test_driver_everything_recorded_by_default(self): prob = ParaboloidProblem() - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) driver.add_recorder(self.recorder) driver.recording_options['includes'] = ['*'] @@ -384,7 +380,7 @@ def test_driver_everything_recorded_by_default(self): def test_driver_records_metadata(self): prob = SellarProblem() - recorder = SqliteRecorder(self.filename) + recorder = om.SqliteRecorder(self.filename) driver = prob.driver driver.recording_options['includes'] = ["p1.x"] @@ -447,9 +443,9 @@ def test_driver_records_metadata(self): assertViewerDataRecorded(self, expected_problem_metadata) def test_system_records_no_metadata(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.model.add_recorder(recorder) prob.model.recording_options['record_model_metadata'] = False prob.model.recording_options['record_metadata'] = False @@ -459,22 +455,22 @@ def test_system_records_no_metadata(self): prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") self.assertEqual(len(cr.system_metadata.keys()), 0) def test_system_record_model_metadata(self): # first check to see if recorded recursively, which is the default - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.model.add_recorder(recorder) prob.set_solver_print(level=0) prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # Quick check to see that keys and values were recorded for key in ['root', 'px', 'pz', 'd1', 'd2', 'obj_cmp', 'con_cmp1', 'con_cmp2']: self.assertTrue(key in cr.system_metadata.keys()) @@ -483,10 +479,10 @@ def test_system_record_model_metadata(self): self.assertEqual(value, 'csc') # quick check only. Too much to check exhaustively # second check to see if not recorded recursively, when option set to False - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.model.add_recorder(recorder) prob.model.recording_options['record_model_metadata'] = False @@ -494,23 +490,23 @@ def test_system_record_model_metadata(self): prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") self.assertEqual(list(cr.system_metadata.keys()), ['root']) self.assertEqual(cr.system_metadata['root']['component_options']['assembled_jac_type'], 'csc') def test_driver_record_model_metadata(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) prob.set_solver_print(level=0) prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # Quick check to see that keys and values were recorded for key in ['root', 'px', 'pz', 'd1', 'd2', 'obj_cmp', 'con_cmp1', 'con_cmp2']: self.assertTrue(key in cr.system_metadata.keys()) @@ -518,10 +514,10 @@ def test_driver_record_model_metadata(self): value = cr.system_metadata['root']['component_options']['assembled_jac_type'] self.assertEqual(value, 'csc') # quick check only. Too much to check exhaustively - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) prob.driver.recording_options['record_model_metadata'] = False @@ -529,13 +525,13 @@ def test_driver_record_model_metadata(self): prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") self.assertEqual(len(cr.system_metadata.keys()), 0) def test_without_n2_data(self): prob = SellarProblem() - recorder = SqliteRecorder(self.filename, record_viewer_data=False) + recorder = om.SqliteRecorder(self.filename, record_viewer_data=False) prob.driver.add_recorder(recorder) @@ -627,7 +623,7 @@ def test_record_system(self): def test_includes(self): prob = ParaboloidProblem() - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True @@ -669,7 +665,7 @@ def test_includes(self): def test_includes_post_setup(self): prob = ParaboloidProblem() - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) prob.setup() @@ -707,7 +703,7 @@ def test_includes_post_setup(self): assertDriverIterDataRecorded(self, expected_data, self.eps) def test_record_system_with_hierarchy(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) prob.setup(mode='rev') model = prob.model @@ -733,7 +729,7 @@ def test_record_system_with_hierarchy(self): d1.recording_options['record_metadata'] = True d1.add_recorder(self.recorder) - prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) t0, t1 = run_driver(prob) prob.cleanup() @@ -851,13 +847,13 @@ def test_record_line_search_armijo_goldstein(self): prob.setup() model = prob.model - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - nl = model.nonlinear_solver = NewtonSolver() + nl = model.nonlinear_solver = om.NewtonSolver() nl.options['solve_subsystems'] = True nl.options['max_sub_solves'] = 4 - ls = nl.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = nl.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['c'] = 100.0 # This is bogus, but it ensures that we get a few LS iterations. ls.add_recorder(self.recorder) @@ -897,13 +893,13 @@ def test_record_line_search_bounds_enforce(self): prob.setup() model = prob.model - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - nl = model.nonlinear_solver = NewtonSolver() + nl = model.nonlinear_solver = om.NewtonSolver() nl.options['solve_subsystems'] = True nl.options['max_sub_solves'] = 4 - ls = nl.linesearch = BoundsEnforceLS(bound_enforcement='vector') + ls = nl.linesearch = om.BoundsEnforceLS(bound_enforcement='vector') ls.add_recorder(self.recorder) t0, t1 = run_driver(prob) @@ -945,25 +941,26 @@ def test_record_pop_bug(self): model.connect('y1', 'ae.x') prob.setup() - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() - nl = model.nonlinear_solver = NewtonSolver() + nl = model.nonlinear_solver = om.NewtonSolver() nl.options['solve_subsystems'] = True nl.options['max_sub_solves'] = 4 - ls = nl.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = nl.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['c'] = 100.0 # This is bogus, but it ensures that we get a few LS iterations. model.add_recorder(self.recorder) try: t0, t1 = run_driver(prob) - except AnalysisError: + except om.AnalysisError: pass self.assertTrue(len(prob._recording_iter.stack) == 0) def test_record_solver_nonlinear_block_gs(self): - prob = SellarProblem(linear_solver=LinearBlockGS, nonlinear_solver=NonlinearBlockGS) + prob = SellarProblem(linear_solver=om.LinearBlockGS, + nonlinear_solver=om.NonlinearBlockGS) prob.setup() prob.model.nonlinear_solver.add_recorder(self.recorder) @@ -1003,7 +1000,7 @@ def test_record_solver_nonlinear_block_gs(self): assertSolverIterDataRecorded(self, expected_data, self.eps) def test_record_solver_nonlinear_block_jac(self): - prob = SellarProblem(linear_solver=LinearBlockGS, nonlinear_solver=NonlinearBlockJac) + prob = SellarProblem(linear_solver=om.LinearBlockGS, nonlinear_solver=om.NonlinearBlockJac) prob.setup() prob.model.nonlinear_solver.add_recorder(self.recorder) @@ -1034,7 +1031,7 @@ def test_record_solver_nonlinear_block_jac(self): assertSolverIterDataRecorded(self, expected_data, self.eps) def test_record_solver_nonlinear_newton(self): - prob = SellarProblem(linear_solver=LinearBlockGS, nonlinear_solver=NewtonSolver) + prob = SellarProblem(linear_solver=om.LinearBlockGS, nonlinear_solver=om.NewtonSolver) prob.setup() prob.model.nonlinear_solver.add_recorder(self.recorder) @@ -1065,7 +1062,7 @@ def test_record_solver_nonlinear_newton(self): assertSolverIterDataRecorded(self, expected_data, self.eps) def test_record_solver_nonlinear_nonlinear_run_once(self): - prob = SellarProblem(nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(nonlinear_solver=om.NonlinearRunOnce) prob.setup() prob.model.nonlinear_solver.add_recorder(self.recorder) @@ -1101,11 +1098,11 @@ def test_record_solver_linear(self): prob = SellarProblem() prob.setup() - nl = prob.model.nonlinear_solver = NewtonSolver() + nl = prob.model.nonlinear_solver = om.NewtonSolver() linear_solvers = [ - DirectSolver, ScipyKrylov, PETScKrylov, - LinearBlockGS, LinearRunOnce, LinearBlockJac + om.DirectSolver, om.ScipyKrylov, om.PETScKrylov, + om.LinearBlockGS, om.LinearRunOnce, om.LinearBlockJac ] for solver in linear_solvers: @@ -1125,10 +1122,10 @@ def test_record_solver_linear(self): def test_record_driver_system_solver(self): # Test what happens when all three types are recorded: Driver, System, and Solver - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) prob.setup(mode='rev') - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) # # Add recorders @@ -1150,7 +1147,7 @@ def test_record_driver_system_solver(self): pz.add_recorder(self.recorder) # Solver - nl = prob.model.mda.nonlinear_solver = NonlinearBlockGS() + nl = prob.model.mda.nonlinear_solver = om.NonlinearBlockGS() nl.recording_options['record_metadata'] = True nl.recording_options['record_abs_error'] = True nl.recording_options['record_rel_error'] = True @@ -1226,10 +1223,10 @@ def test_record_driver_system_solver(self): def test_global_counter(self): # The case recorder maintains a global counter across all recordings - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) prob.setup(mode='rev') - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) # Add recorders for Driver, System, Solver driver.add_recorder(self.recorder) @@ -1264,12 +1261,12 @@ def test_global_counter(self): def test_implicit_component(self): from openmdao.core.tests.test_impl_comp import QuadraticLinearize, QuadraticJacVec - indeps = IndepVarComp() + indeps = om.IndepVarComp() indeps.add_output('a', 1.0) indeps.add_output('b', 1.0) indeps.add_output('c', 1.0) - group = Group() + group = om.Group() group.add_subsystem('comp1', indeps) group.add_subsystem('comp2', QuadraticLinearize()) group.add_subsystem('comp3', QuadraticJacVec()) @@ -1280,7 +1277,7 @@ def test_implicit_component(self): group.connect('comp1.b', 'comp3.b') group.connect('comp1.c', 'comp3.c') - prob = Problem(model=group) + prob = om.Problem(model=group) prob.setup() prob['comp1.a'] = 1. @@ -1315,7 +1312,7 @@ def test_multidimensional_arrays(self): # component TestExplCompArray, put in a model and run it; its outputs are multi-d-arrays. from openmdao.test_suite.components.expl_comp_array import TestExplCompArray comp = TestExplCompArray(thickness=1.) - prob = Problem(comp).setup() + prob = om.Problem(comp).setup() prob['lengths'] = 3. prob['widths'] = 2. @@ -1356,7 +1353,7 @@ def test_multidimensional_arrays(self): def test_record_system_recursively(self): # Test adding recorders to all Systems using the recurse option to add_recorder - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) prob.setup(mode='rev') # Need to do recursive adding of recorders AFTER setup @@ -1394,7 +1391,7 @@ def test_record_system_recursively(self): ]) def test_record_system_with_prefix(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) prob.setup(mode='rev') prob.model.mda.nonlinear_solver.options['use_apply_nonlinear'] = True @@ -1442,9 +1439,9 @@ def test_record_system_with_prefix(self): ]) def test_driver_recording_with_system_vars(self): - prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=NonlinearRunOnce) + prob = SellarProblem(SellarDerivativesGrouped, nonlinear_solver=om.NonlinearRunOnce) - driver = prob.driver = ScipyOptimizeDriver(disp=False, tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(disp=False, tol=1e-9) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True driver.recording_options['record_objectives'] = True @@ -1511,7 +1508,7 @@ def test_recorder_file_already_exists_no_append(self): driver.recording_options['record_objectives'] = False driver.recording_options['record_constraints'] = False driver.recording_options['includes'] = [] - driver.add_recorder(SqliteRecorder(self.filename)) + driver.add_recorder(om.SqliteRecorder(self.filename)) prob.setup() t0, t1 = run_driver(prob) @@ -1539,12 +1536,12 @@ def assert_closed(self, recorder): driver = prob.driver system = prob.model.pz - solver = prob.model.nonlinear_solver.linesearch = BoundsEnforceLS() + solver = prob.model.nonlinear_solver.linesearch = om.BoundsEnforceLS() # create 3 different recorders - driver_recorder = SqliteRecorder('driver_cases.sql') - system_recorder = SqliteRecorder('system_cases.sql') - solver_recorder = SqliteRecorder('solver_cases.sql') + driver_recorder = om.SqliteRecorder('driver_cases.sql') + system_recorder = om.SqliteRecorder('system_cases.sql') + solver_recorder = om.SqliteRecorder('solver_cases.sql') # add recorders driver.add_recorder(driver_recorder) @@ -1578,9 +1575,9 @@ def assert_closed(self, recorder): self.assertFalse(solver._rec_mgr.has_recorders()) def test_problem_record_no_voi(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) - prob.add_recorder(SqliteRecorder("cases.sql")) + prob.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() @@ -1588,7 +1585,7 @@ def test_problem_record_no_voi(self): prob.record_iteration('final') prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") problem_cases = cr.list_cases('problem') self.assertEqual(len(problem_cases), 1) @@ -1609,7 +1606,7 @@ def test_problem_record_no_voi(self): {'con1', 'con2', 'obj', 'x', 'y1', 'y2', 'z'}) def test_problem_record_with_options(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -1619,7 +1616,7 @@ def test_problem_record_with_options(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - prob.add_recorder(SqliteRecorder("cases.sql")) + prob.add_recorder(om.SqliteRecorder("cases.sql")) prob.recording_options['record_objectives'] = False prob.recording_options['record_constraints'] = False @@ -1631,7 +1628,7 @@ def test_problem_record_with_options(self): prob.record_iteration('final') prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") problem_cases = cr.list_cases('problem') self.assertEqual(len(problem_cases), 1) @@ -1650,7 +1647,7 @@ def test_problem_record_with_options(self): self.assertEqual(set(final_case.outputs.keys()), {'y1', 'y2'}) def test_problem_record_options_includes(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -1660,7 +1657,7 @@ def test_problem_record_options_includes(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - prob.add_recorder(SqliteRecorder("cases.sql")) + prob.add_recorder(om.SqliteRecorder("cases.sql")) prob.recording_options['includes'] = [] @@ -1670,7 +1667,7 @@ def test_problem_record_options_includes(self): prob.record_iteration('final') prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") problem_cases = cr.list_cases('problem') self.assertEqual(len(problem_cases), 1) @@ -1690,22 +1687,22 @@ def test_problem_record_options_includes(self): {'con1', 'con2', 'obj', 'x', 'z'}) def test_simple_paraboloid_scaled_desvars(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = x - y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = x - y'), promotes=['*']) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=False) prob.driver.recording_options['record_desvars'] = True prob.driver.recording_options['record_responses'] = True prob.driver.recording_options['record_objectives'] = True prob.driver.recording_options['record_constraints'] = True - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) ref = 5.0 @@ -1721,7 +1718,7 @@ def test_simple_paraboloid_scaled_desvars(self): prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # Test values from one case, the last case driver_cases = cr.list_cases('driver') @@ -1762,24 +1759,23 @@ def tearDown(self): raise e def test_feature_simple_driver_recording(self): - from openmdao.api import Problem, IndepVarComp, ExecComp, \ - ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) - model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) + model.add_subsystem('p1', om.IndepVarComp('x', 50.0), promotes=['*']) + model.add_subsystem('p2', om.IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) - model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) + model.add_subsystem('con', om.ExecComp('c = - x + y'), promotes=['*']) model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-9 @@ -1790,33 +1786,33 @@ def test_feature_simple_driver_recording(self): case_recorder_filename = 'cases.sql' - recorder = SqliteRecorder(case_recorder_filename) + recorder = om.SqliteRecorder(case_recorder_filename) prob.driver.add_recorder(recorder) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader(case_recorder_filename) + cr = om.CaseReader(case_recorder_filename) case = cr.get_case('rank0:ScipyOptimize_SLSQP|4') assert_rel_error(self, case.outputs['x'], 7.16666667, 1e-6) assert_rel_error(self, case.outputs['y'], -7.83333333, 1e-6) def test_feature_problem_metadata(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(SellarDerivatives()) + prob = om.Problem(SellarDerivatives()) - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # access list of connections stored in metadata connections = sorted(cr.problem_metadata['connections_list'], key=lambda x: (x['tgt'], x['src'])) @@ -1843,11 +1839,10 @@ def test_feature_problem_metadata(self): ['con_cmp1', 'con_cmp2', 'd1', 'd2', 'obj_cmp', 'px', 'pz']) def test_feature_problem_metadata_with_driver_information(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader - from openmdao.api import DOEDriver, UniformGenerator + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(SellarDerivatives()) + prob = om.Problem(SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) @@ -1857,24 +1852,24 @@ def test_feature_problem_metadata_with_driver_information(self): model.add_constraint('con2', upper=0.0) # DOE - driver = prob.driver = DOEDriver(UniformGenerator()) - recorder = SqliteRecorder("cases.sql") + driver = prob.driver = om.DOEDriver(om.UniformGenerator()) + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) prob.setup() prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") metadata = cr.problem_metadata['driver'] self.assertEqual(set(metadata.keys()), {'name', 'type', 'options', 'opt_settings'}) self.assertEqual(metadata['name'], 'DOEDriver') self.assertEqual(metadata['type'], 'doe') - self.assertEqual(metadata['options'], {'debug_print': [], 'generator': 'UniformGenerator', - 'run_parallel': False, 'procs_per_model': 1}) + self.assertEqual(metadata['options'], {'debug_print': [], 'generator': 'UniformGenerator', + 'run_parallel': False, 'procs_per_model': 1}) # Optimization - driver = prob.driver = ScipyOptimizeDriver() - recorder = SqliteRecorder("cases.sql") + driver = prob.driver = om.ScipyOptimizeDriver() + recorder = om.SqliteRecorder("cases.sql") driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-3 driver.opt_settings['ACC'] = 1e-6 @@ -1883,40 +1878,40 @@ def test_feature_problem_metadata_with_driver_information(self): prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") metadata = cr.problem_metadata['driver'] self.assertEqual(set(metadata.keys()), {'name', 'type', 'options', 'opt_settings'}) self.assertEqual(metadata['name'], 'ScipyOptimizeDriver') self.assertEqual(metadata['type'], 'optimization') - self.assertEqual(metadata['options'], {"debug_print": [], "optimizer": "SLSQP", - "tol": 1e-03, "maxiter": 200, "disp": True, - "dynamic_simul_derivs": False, "dynamic_derivs_repeats": 3}) + self.assertEqual(metadata['options'], {"debug_print": [], "optimizer": "SLSQP", + "tol": 1e-03, "maxiter": 200, "disp": True, + "dynamic_simul_derivs": False, "dynamic_derivs_repeats": 3}) self.assertEqual(metadata['opt_settings'], {"ACC": 1e-06}) def test_feature_solver_metadata(self): - from openmdao.api import Problem, SqliteRecorder, CaseReader, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() # create recorder - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") # add recorder to the nonlinear solver for the model - prob.model.nonlinear_solver = NonlinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() prob.model.nonlinear_solver.add_recorder(recorder) # add recorder to the nonlinear solver for Component 'd1' d1 = prob.model.d1 - d1.nonlinear_solver = NonlinearBlockGS() + d1.nonlinear_solver = om.NonlinearBlockGS() d1.nonlinear_solver.options['maxiter'] = 5 d1.nonlinear_solver.add_recorder(recorder) prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") metadata = cr.solver_metadata @@ -1927,10 +1922,10 @@ def test_feature_solver_metadata(self): self.assertEqual(metadata['root.NonlinearBlockGS']['solver_options']['maxiter'], 10) def test_feature_system_metadata(self): - from openmdao.api import Problem, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) # also record the metadata for all systems in the model prob.driver.recording_options['record_model_metadata'] = True @@ -1945,14 +1940,14 @@ def test_feature_system_metadata(self): d1.recording_options['options_excludes'] = ['dynamic_derivs_repeats'] # create recorder and attach to driver and d1 - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) d1.add_recorder(recorder) prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # metadata for all the systems in the model metadata = cr.system_metadata @@ -1965,13 +1960,13 @@ def test_feature_system_metadata(self): self.assertEqual(metadata['d1']['component_options']['options value 1'], 1) def test_feature_system_options(self): - from openmdao.api import Problem, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") obj_cmp = prob.model.obj_cmp obj_cmp.add_recorder(recorder) @@ -1983,7 +1978,7 @@ def test_feature_system_options(self): prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") system_cases = cr.list_cases('root.obj_cmp') @@ -1994,12 +1989,12 @@ def test_feature_system_options(self): self.assertEqual(sorted(case.inputs.keys()), ['y1', 'y2', 'z']) def test_feature_driver_options(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives import numpy as np - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2009,13 +2004,13 @@ def test_feature_driver_options(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - driver = prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) + driver = prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) driver.recording_options['includes'] = [] driver.recording_options['record_objectives'] = True driver.recording_options['record_constraints'] = True driver.recording_options['record_desvars'] = True - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") driver.add_recorder(recorder) prob.setup() @@ -2023,7 +2018,7 @@ def test_feature_driver_options(self): prob.run_driver() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") driver_cases = cr.list_cases('driver') @@ -2039,13 +2034,13 @@ def test_feature_driver_options(self): assert_rel_error(self, constraints, case.get_constraints(), 1e-1) def test_feature_solver_options(self): - from openmdao.api import Problem, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") solver = prob.model.nonlinear_solver solver.add_recorder(recorder) @@ -2055,7 +2050,7 @@ def test_feature_solver_options(self): prob.run_model() prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") solver_cases = cr.list_cases('root.nonlinear_solver') @@ -2066,11 +2061,10 @@ def test_feature_solver_options(self): self.assertAlmostEqual(case.abs_err, 2.2545141) def test_feature_circuit_with_recorder(self): - from openmdao.api import Group, NewtonSolver, DirectSolver, Problem, IndepVarComp, \ - CaseReader, SqliteRecorder + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node - class Circuit(Group): + class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), @@ -2089,22 +2083,22 @@ def setup(self): self.connect('R2.I', 'n2.I_in:0') self.connect('D1.I', 'n2.I_out:0') - self.nonlinear_solver = NewtonSolver() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 20 - self.linear_solver = DirectSolver() + self.linear_solver = om.DirectSolver() - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') - recorder = SqliteRecorder("cases.sql") + recorder = om.SqliteRecorder("cases.sql") prob.driver.add_recorder(recorder) prob.driver.recording_options['includes'] = ['*'] prob.setup() @@ -2117,7 +2111,7 @@ def setup(self): prob.cleanup() # create the case reader - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # grab the data recorded in the first driver iteration driver_cases = cr.list_cases('driver') @@ -2130,12 +2124,12 @@ def test_feature_load_system_case_for_restart(self): ####################################################################### # Do the initial optimization run ####################################################################### - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives import numpy as np - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2145,7 +2139,7 @@ def test_feature_load_system_case_for_restart(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - recorder = SqliteRecorder('cases.sql') + recorder = om.SqliteRecorder('cases.sql') model.add_recorder(recorder) model.recording_options['record_inputs'] = True @@ -2154,7 +2148,7 @@ def test_feature_load_system_case_for_restart(self): model.recording_options['record_metadata'] = False model.recording_options['options_excludes'] = ['*'] - driver = prob.driver = ScipyOptimizeDriver() + driver = prob.driver = om.ScipyOptimizeDriver() driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-9 driver.options['disp'] = False @@ -2168,10 +2162,10 @@ def test_feature_load_system_case_for_restart(self): # To debug the problem, we can run the script again, but this time using # the last recorded case as a starting point. ####################################################################### - from openmdao.api import Problem, ScipyOptimizeDriver, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) @@ -2186,7 +2180,7 @@ def test_feature_load_system_case_for_restart(self): model.recording_options['record_metadata'] = False model.recording_options['options_excludes'] = ['*'] - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() driver = prob.driver driver.options['optimizer'] = 'SLSQP' driver.options['tol'] = 1e-9 @@ -2194,7 +2188,7 @@ def test_feature_load_system_case_for_restart(self): prob.setup() - cr = CaseReader('cases.sql') + cr = om.CaseReader('cases.sql') # Load the last case written last_case = cr.get_case(-1) @@ -2204,13 +2198,13 @@ def test_feature_load_system_case_for_restart(self): prob.cleanup() def test_feature_record_with_prefix(self): - from openmdao.api import Problem, SqliteRecorder, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) prob.setup() - recorder = SqliteRecorder("cases.sql", record_viewer_data=False) + recorder = om.SqliteRecorder("cases.sql", record_viewer_data=False) prob.model.add_recorder(recorder) prob.driver.add_recorder(recorder) @@ -2224,7 +2218,7 @@ def test_feature_record_with_prefix(self): prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # all cases recorded by the root system model_cases = cr.list_cases('root', recurse=False) @@ -2243,12 +2237,12 @@ def test_feature_record_with_prefix(self): ])) def test_feature_problem_record(self): - from openmdao.api import Problem, SqliteRecorder, ScipyOptimizeDriver, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives import numpy as np - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2258,9 +2252,9 @@ def test_feature_problem_record(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) - prob.add_recorder(SqliteRecorder("cases.sql")) + prob.add_recorder(om.SqliteRecorder("cases.sql")) prob.recording_options['includes'] = [] prob.recording_options['record_objectives'] = True @@ -2272,7 +2266,7 @@ def test_feature_problem_record(self): prob.record_iteration('final') prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # get list of cases recorded on problem problem_cases = cr.list_cases('problem') @@ -2295,14 +2289,14 @@ def test_feature_problem_record(self): assert_rel_error(self, constraints, case.get_constraints(), 1e-1) def test_scaling_multiple_calls(self): - from openmdao.api import Problem, SqliteRecorder, ScipyOptimizeDriver, CaseReader + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives import numpy as np scaler = 2. - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2312,9 +2306,9 @@ def test_scaling_multiple_calls(self): model.add_constraint('con1', upper=0.0, scaler=scaler) model.add_constraint('con2', upper=0.0, scaler=scaler) - prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) + prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9) - prob.add_recorder(SqliteRecorder("cases.sql")) + prob.add_recorder(om.SqliteRecorder("cases.sql")) prob.recording_options['includes'] = [] prob.recording_options['record_objectives'] = True @@ -2326,7 +2320,7 @@ def test_scaling_multiple_calls(self): prob.record_iteration('final') prob.cleanup() - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # get list of cases recorded on problem problem_cases = cr.list_cases('problem') @@ -2374,13 +2368,13 @@ def tearDown(self): raise e def record_cases(self): - from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA import numpy as np # create our Sellar problem - prob = Problem(model=SellarMDA()) + prob = om.Problem(model=SellarMDA()) model = prob.model model.add_design_var('z', lower=np.array([-10.0, 0.0]), @@ -2390,10 +2384,10 @@ def record_cases(self): model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) - prob.driver = ScipyOptimizeDriver(disp=False) + prob.driver = om.ScipyOptimizeDriver(disp=False) # create a case recorder - recorder = SqliteRecorder('cases.sql') + recorder = om.SqliteRecorder('cases.sql') # add the recorder to the driver so driver iterations will be recorded prob.driver.add_recorder(recorder) @@ -2413,10 +2407,10 @@ def record_cases(self): prob.cleanup() def test_read_cases(self): - from openmdao.api import CaseReader + import openmdao.api as om # open database of previously saved cases - cr = CaseReader("cases.sql") + cr = om.CaseReader("cases.sql") # get a list of cases that were recorded by the driver driver_cases = cr.list_cases('driver') diff --git a/openmdao/solvers/linear/tests/linear_test_base.py b/openmdao/solvers/linear/tests/linear_test_base.py index 32288fe9c3..4922428b49 100644 --- a/openmdao/solvers/linear/tests/linear_test_base.py +++ b/openmdao/solvers/linear/tests/linear_test_base.py @@ -32,7 +32,7 @@ def test_solve_linear_maxiter(self): group.linear_solver.options['maxiter'] = 2 p = Problem(group) - p.setup(check=False) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -58,7 +58,7 @@ def test_simple_matvec(self): # Tests derivatives on a simple comp that defines compute_jacvec. # Note, For DirectSolver, assemble_jac must be False for mat-vec. prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('x_param', IndepVarComp('length', 3.0), promotes=['length']) model.add_subsystem('mycomp', TestExplCompSimpleJacVec(), @@ -93,7 +93,7 @@ def test_simple_matvec_subbed(self): # Tests derivatives on a group that contains a simple comp that # defines compute_jacvec. prob = Problem() - model = prob.model = Group() + model = prob.model model.add_subsystem('x_param', IndepVarComp('length', 3.0), promotes=['length']) sub = model.add_subsystem('sub', Group(), @@ -131,7 +131,7 @@ def test_simple_matvec_subbed_like_multipoint(self): # defines compute_jacvec. For this one, the indepvarcomp is also # in the subsystem. prob = Problem() - model = prob.model = Group() + model = prob.model sub = model.add_subsystem('sub', Group(), promotes=['length', 'width', 'area']) sub.add_subsystem('x_param', IndepVarComp('length', 3.0), diff --git a/openmdao/solvers/linear/tests/test_direct_solver.py b/openmdao/solvers/linear/tests/test_direct_solver.py index cf32709d27..ba07ddde66 100644 --- a/openmdao/solvers/linear/tests/test_direct_solver.py +++ b/openmdao/solvers/linear/tests/test_direct_solver.py @@ -7,8 +7,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, DirectSolver, NewtonSolver, ExecComp, \ - NewtonSolver, BalanceComp, ExplicitComponent, ImplicitComponent +import openmdao.api as om from openmdao.solvers.linear.tests.linear_test_base import LinearSolverTests from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimpleJacVec from openmdao.test_suite.components.sellar import SellarDerivatives @@ -16,7 +15,7 @@ from openmdao.utils.assert_utils import assert_rel_error -class NanComp(ExplicitComponent): +class NanComp(om.ExplicitComponent): def setup(self): self.add_input('x', 1.0) self.add_output('y', 1.0) @@ -32,7 +31,7 @@ def compute_partials(self, inputs, partials): J['y', 'x'] = np.NaN -class SingularComp(ImplicitComponent): +class SingularComp(om.ImplicitComponent): def setup(self): self.add_input('x', 1.0) self.add_output('y', 1.0) @@ -46,7 +45,7 @@ def compute_partials(self, inputs, partials): J['y', 'y'] = 0.0 -class NanComp2(ExplicitComponent): +class NanComp2(om.ExplicitComponent): def setup(self): self.add_input('x', 1.0) self.add_output('y', 1.0) @@ -64,7 +63,7 @@ def compute_partials(self, inputs, partials): J['y', 'x'] = np.NaN J['y2', 'x'] = 2.0 -class DupPartialsComp(ExplicitComponent): +class DupPartialsComp(om.ExplicitComponent): def setup(self): self.add_input('c', np.zeros(19)) self.add_output('x', np.zeros(11)) @@ -82,12 +81,12 @@ def compute_partials(self, inputs, partials): class TestDirectSolver(LinearSolverTests.LinearSolverTestCase): - linear_solver_class = DirectSolver + linear_solver_class = om.DirectSolver # DirectSolver doesn't iterate. def test_solve_linear_maxiter(self): # Test that using options that should not exist in class cause an error - solver = DirectSolver() + solver = om.DirectSolver() msg = "\"Option '%s' cannot be set because it has not been declared.\"" @@ -100,15 +99,15 @@ def test_solve_linear_maxiter(self): def test_solve_on_subsystem(self): """solve an implicit system with DirectSolver attached to a subsystem""" - p = Problem() + p = om.Problem() model = p.model - dv = model.add_subsystem('des_vars', IndepVarComp()) + dv = model.add_subsystem('des_vars', om.IndepVarComp()) # just need a dummy variable so the sizes don't match between root and g1 dv.add_output('dummy', val=1.0, shape=10) - g1 = model.add_subsystem('g1', TestImplicitGroup(lnSolverClass=DirectSolver)) + g1 = model.add_subsystem('g1', TestImplicitGroup(lnSolverClass=om.DirectSolver)) - p.setup(check=False) + p.setup() g1.linear_solver.options['assemble_jac'] = False @@ -142,8 +141,9 @@ def test_solve_on_subsystem(self): def test_rev_mode_bug(self): - prob = Problem() - prob.model = SellarDerivatives(nonlinear_solver=NewtonSolver(), linear_solver=DirectSolver()) + prob = om.Problem() + prob.model = SellarDerivatives(nonlinear_solver=om.NewtonSolver(), + linear_solver=om.DirectSolver()) prob.setup(check=False, mode='rev') prob.set_solver_print(level=0) @@ -175,16 +175,16 @@ def test_rev_mode_bug(self): assert_rel_error(self, prob['y2'], 12.05848819, .00001) def test_multi_dim_src_indices(self): - prob = Problem() + prob = om.Problem() model = prob.model size = 5 - model.add_subsystem('indeps', IndepVarComp('x', np.arange(5).reshape((1,size,1)))) - model.add_subsystem('comp', ExecComp('y = x * 2.', x=np.zeros((size,)), y=np.zeros((size,)))) + model.add_subsystem('indeps', om.IndepVarComp('x', np.arange(5).reshape((1,size,1)))) + model.add_subsystem('comp', om.ExecComp('y = x * 2.', x=np.zeros((size,)), y=np.zeros((size,)))) src_indices = [[0, i, 0] for i in range(size)] model.connect('indeps.x', 'comp.x', src_indices=src_indices) - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() prob.setup() prob.run_model() @@ -192,18 +192,18 @@ def test_multi_dim_src_indices(self): np.testing.assert_almost_equal(J, np.eye(size) * 2.) def test_raise_error_on_singular(self): - prob = Problem() + prob = om.Problem() model = prob.model - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('dXdt:TAS', val=1.0) comp.add_output('accel_target', val=2.0) model.add_subsystem('des_vars', comp, promotes=['*']) - teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group()) - teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*']) + teg = model.add_subsystem('thrust_equilibrium_group', subsys=om.Group()) + teg.add_subsystem('dynamics', om.ExecComp('z = 2.0*thrust'), promotes=['*']) - thrust_bal = BalanceComp() + thrust_bal = om.BalanceComp() thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS', rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0) @@ -211,14 +211,14 @@ def test_raise_error_on_singular(self): promotes_inputs=['dXdt:TAS', 'accel_target'], promotes_outputs=['thrust']) - teg.linear_solver = DirectSolver(assemble_jac=False) + teg.linear_solver = om.DirectSolver(assemble_jac=False) - teg.nonlinear_solver = NewtonSolver() + teg.nonlinear_solver = om.NewtonSolver() teg.nonlinear_solver.options['solve_subsystems'] = True teg.nonlinear_solver.options['max_sub_solves'] = 1 teg.nonlinear_solver.options['atol'] = 1e-4 - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) with self.assertRaises(RuntimeError) as cm: @@ -229,34 +229,34 @@ def test_raise_error_on_singular(self): self.assertEqual(expected_msg, str(cm.exception)) def test_raise_error_on_dup_partials(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('des_vars', IndepVarComp('x', 1.0), promotes=['*']) + model.add_subsystem('des_vars', om.IndepVarComp('x', 1.0), promotes=['*']) model.add_subsystem('dupcomp', DupPartialsComp()) - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) with self.assertRaises(Exception) as cm: - prob.setup(check=False) + prob.setup() expected_msg = "dupcomp: declare_partials has been called with rows and cols that specify the following duplicate subjacobian entries: [(4, 11), (10, 2)]." self.assertEqual(expected_msg, str(cm.exception)) def test_raise_error_on_singular_with_densejac(self): - prob = Problem() + prob = om.Problem() model = prob.model - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('dXdt:TAS', val=1.0) comp.add_output('accel_target', val=2.0) model.add_subsystem('des_vars', comp, promotes=['*']) - teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group()) - teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*']) + teg = model.add_subsystem('thrust_equilibrium_group', subsys=om.Group()) + teg.add_subsystem('dynamics', om.ExecComp('z = 2.0*thrust'), promotes=['*']) - thrust_bal = BalanceComp() + thrust_bal = om.BalanceComp() thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS', rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0) @@ -264,15 +264,15 @@ def test_raise_error_on_singular_with_densejac(self): promotes_inputs=['dXdt:TAS', 'accel_target'], promotes_outputs=['thrust']) - teg.linear_solver = DirectSolver(assemble_jac=True) + teg.linear_solver = om.DirectSolver(assemble_jac=True) teg.options['assembled_jac_type'] = 'dense' - teg.nonlinear_solver = NewtonSolver() + teg.nonlinear_solver = om.NewtonSolver() teg.nonlinear_solver.options['solve_subsystems'] = True teg.nonlinear_solver.options['max_sub_solves'] = 1 teg.nonlinear_solver.options['atol'] = 1e-4 - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) with self.assertRaises(RuntimeError) as cm: @@ -283,18 +283,18 @@ def test_raise_error_on_singular_with_densejac(self): self.assertEqual(expected_msg, str(cm.exception)) def test_raise_error_on_singular_with_sparsejac(self): - prob = Problem() + prob = om.Problem() model = prob.model - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('dXdt:TAS', val=1.0) comp.add_output('accel_target', val=2.0) model.add_subsystem('des_vars', comp, promotes=['*']) - teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group()) - teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*']) + teg = model.add_subsystem('thrust_equilibrium_group', subsys=om.Group()) + teg.add_subsystem('dynamics', om.ExecComp('z = 2.0*thrust'), promotes=['*']) - thrust_bal = BalanceComp() + thrust_bal = om.BalanceComp() thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS', rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0) @@ -302,14 +302,14 @@ def test_raise_error_on_singular_with_sparsejac(self): promotes_inputs=['dXdt:TAS', 'accel_target'], promotes_outputs=['thrust']) - teg.linear_solver = DirectSolver(assemble_jac=True) + teg.linear_solver = om.DirectSolver(assemble_jac=True) - teg.nonlinear_solver = NewtonSolver() + teg.nonlinear_solver = om.NewtonSolver() teg.nonlinear_solver.options['solve_subsystems'] = True teg.nonlinear_solver.options['max_sub_solves'] = 1 teg.nonlinear_solver.options['atol'] = 1e-4 - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) with self.assertRaises(RuntimeError) as cm: @@ -320,18 +320,18 @@ def test_raise_error_on_singular_with_sparsejac(self): self.assertEqual(expected_msg, str(cm.exception)) def test_raise_no_error_on_singular(self): - prob = Problem() + prob = om.Problem() model = prob.model - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('dXdt:TAS', val=1.0) comp.add_output('accel_target', val=2.0) model.add_subsystem('des_vars', comp, promotes=['*']) - teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group()) - teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*']) + teg = model.add_subsystem('thrust_equilibrium_group', subsys=om.Group()) + teg.add_subsystem('dynamics', om.ExecComp('z = 2.0*thrust'), promotes=['*']) - thrust_bal = BalanceComp() + thrust_bal = om.BalanceComp() thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS', rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0) @@ -339,14 +339,14 @@ def test_raise_no_error_on_singular(self): promotes_inputs=['dXdt:TAS', 'accel_target'], promotes_outputs=['thrust']) - teg.linear_solver = DirectSolver(assemble_jac=False) + teg.linear_solver = om.DirectSolver(assemble_jac=False) - teg.nonlinear_solver = NewtonSolver() + teg.nonlinear_solver = om.NewtonSolver() teg.nonlinear_solver.options['solve_subsystems'] = True teg.nonlinear_solver.options['max_sub_solves'] = 1 teg.nonlinear_solver.options['atol'] = 1e-4 - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) teg.linear_solver.options['err_on_singular'] = False @@ -354,17 +354,17 @@ def test_raise_no_error_on_singular(self): def test_raise_error_on_nan(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0)) - model.add_subsystem('c1', ExecComp('y = 4.0*x')) - sub = model.add_subsystem('sub', Group()) + model.add_subsystem('p', om.IndepVarComp('x', 2.0)) + model.add_subsystem('c1', om.ExecComp('y = 4.0*x')) + sub = model.add_subsystem('sub', om.Group()) sub.add_subsystem('c2', NanComp()) - model.add_subsystem('c3', ExecComp('y = 4.0*x')) + model.add_subsystem('c3', om.ExecComp('y = 4.0*x')) model.add_subsystem('c4', NanComp2()) - model.add_subsystem('c5', ExecComp('y = 3.0*x')) - model.add_subsystem('c6', ExecComp('y = 2.0*x')) + model.add_subsystem('c5', om.ExecComp('y = 3.0*x')) + model.add_subsystem('c6', om.ExecComp('y = 2.0*x')) model.connect('p.x', 'c1.x') model.connect('c1.y', 'sub.c2.x') @@ -373,7 +373,7 @@ def test_raise_error_on_nan(self): model.connect('c4.y', 'c5.x') model.connect('c4.y2', 'c6.x') - model.linear_solver = DirectSolver(assemble_jac=False) + model.linear_solver = om.DirectSolver(assemble_jac=False) prob.setup() prob.run_model() @@ -387,17 +387,17 @@ def test_raise_error_on_nan(self): def test_raise_error_on_nan_sparse(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0)) - model.add_subsystem('c1', ExecComp('y = 4.0*x')) - sub = model.add_subsystem('sub', Group()) + model.add_subsystem('p', om.IndepVarComp('x', 2.0)) + model.add_subsystem('c1', om.ExecComp('y = 4.0*x')) + sub = model.add_subsystem('sub', om.Group()) sub.add_subsystem('c2', NanComp()) - model.add_subsystem('c3', ExecComp('y = 4.0*x')) + model.add_subsystem('c3', om.ExecComp('y = 4.0*x')) model.add_subsystem('c4', NanComp2()) - model.add_subsystem('c5', ExecComp('y = 3.0*x')) - model.add_subsystem('c6', ExecComp('y = 2.0*x')) + model.add_subsystem('c5', om.ExecComp('y = 3.0*x')) + model.add_subsystem('c6', om.ExecComp('y = 2.0*x')) model.connect('p.x', 'c1.x') model.connect('c1.y', 'sub.c2.x') @@ -406,7 +406,7 @@ def test_raise_error_on_nan_sparse(self): model.connect('c4.y', 'c5.x') model.connect('c4.y2', 'c6.x') - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) prob.setup() prob.run_model() @@ -420,17 +420,17 @@ def test_raise_error_on_nan_sparse(self): def test_raise_error_on_nan_dense(self): - prob = Problem(model=Group(assembled_jac_type='dense')) + prob = om.Problem(model=om.Group(assembled_jac_type='dense')) model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0)) - model.add_subsystem('c1', ExecComp('y = 4.0*x')) - sub = model.add_subsystem('sub', Group()) + model.add_subsystem('p', om.IndepVarComp('x', 2.0)) + model.add_subsystem('c1', om.ExecComp('y = 4.0*x')) + sub = model.add_subsystem('sub', om.Group()) sub.add_subsystem('c2', NanComp()) - model.add_subsystem('c3', ExecComp('y = 4.0*x')) + model.add_subsystem('c3', om.ExecComp('y = 4.0*x')) model.add_subsystem('c4', NanComp2()) - model.add_subsystem('c5', ExecComp('y = 3.0*x')) - model.add_subsystem('c6', ExecComp('y = 2.0*x')) + model.add_subsystem('c5', om.ExecComp('y = 3.0*x')) + model.add_subsystem('c6', om.ExecComp('y = 2.0*x')) model.connect('p.x', 'c1.x') model.connect('c1.y', 'sub.c2.x') @@ -439,7 +439,7 @@ def test_raise_error_on_nan_dense(self): model.connect('c4.y', 'c5.x') model.connect('c4.y2', 'c6.x') - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) prob.setup() prob.run_model() @@ -452,14 +452,14 @@ def test_raise_error_on_nan_dense(self): self.assertEqual(expected_msg, str(cm.exception)) def test_error_on_NaN_bug(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0*np.ones((2, 2)))) - model.add_subsystem('c1', ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c2', ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c3', ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c4', ExecComp('y = 2.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('p', om.IndepVarComp('x', 2.0*np.ones((2, 2)))) + model.add_subsystem('c1', om.ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c2', om.ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c3', om.ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c4', om.ExecComp('y = 2.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) model.add_subsystem('c5', NanComp()) model.connect('p.x', 'c1.x') @@ -468,7 +468,7 @@ def test_error_on_NaN_bug(self): model.connect('c3.y', 'c4.x') model.connect('c4.y', 'c5.x', src_indices=([0])) - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) prob.setup() prob.run_model() @@ -481,14 +481,14 @@ def test_error_on_NaN_bug(self): self.assertEqual(expected_msg, str(cm.exception)) def test_error_on_singular_with_sparsejac_bug(self): - prob = Problem(model=Group()) + prob = om.Problem() model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0*np.ones((2, 2)))) - model.add_subsystem('c1', ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c2', ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c3', ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c4', ExecComp('y = 2.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('p', om.IndepVarComp('x', 2.0*np.ones((2, 2)))) + model.add_subsystem('c1', om.ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c2', om.ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c3', om.ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c4', om.ExecComp('y = 2.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) model.add_subsystem('c5', SingularComp()) model.connect('p.x', 'c1.x') @@ -497,7 +497,7 @@ def test_error_on_singular_with_sparsejac_bug(self): model.connect('c3.y', 'c4.x') model.connect('c4.y', 'c5.x', src_indices=([0])) - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) prob.setup() prob.run_model() @@ -510,14 +510,14 @@ def test_error_on_singular_with_sparsejac_bug(self): self.assertEqual(expected_msg, str(cm.exception)) def test_error_on_singular_with_densejac_bug(self): - prob = Problem(model=Group()) + prob = om.Problem() model = prob.model - model.add_subsystem('p', IndepVarComp('x', 2.0*np.ones((2, 2)))) - model.add_subsystem('c1', ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c2', ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c3', ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) - model.add_subsystem('c4', ExecComp('y = 2.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('p', om.IndepVarComp('x', 2.0*np.ones((2, 2)))) + model.add_subsystem('c1', om.ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c2', om.ExecComp('y = 4.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c3', om.ExecComp('y = 3.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) + model.add_subsystem('c4', om.ExecComp('y = 2.0*x', x=np.zeros((2, 2)), y=np.zeros((2, 2)))) model.add_subsystem('c5', SingularComp()) model.connect('p.x', 'c1.x') @@ -526,7 +526,7 @@ def test_error_on_singular_with_densejac_bug(self): model.connect('c3.y', 'c4.x') model.connect('c4.y', 'c5.x', src_indices=([0])) - model.linear_solver = DirectSolver(assemble_jac=True) + model.linear_solver = om.DirectSolver(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -541,7 +541,7 @@ def test_error_on_singular_with_densejac_bug(self): def test_raise_error_on_underdetermined_csc(self): - class DCgenerator(ImplicitComponent): + class DCgenerator(om.ImplicitComponent): def setup(self): self.add_input('V_bus', val=1.0) @@ -563,7 +563,7 @@ def linearize(self, inputs, outputs, J): J['P_out', 'V_out'] = outputs['I_out'] J['P_out', 'I_out'] = inputs['V_out'] - class RectifierCalcs(ImplicitComponent): + class RectifierCalcs(om.ImplicitComponent): def setup(self): self.add_input('P_out', val=1.0) @@ -583,20 +583,20 @@ def apply_nonlinear(self, inputs, outputs, resids): resids['V_out'] = 1.0 - outputs['V_out'] resids['Q_in'] = outputs['P_in'] - outputs['Q_in'] - class Rectifier(Group): + class Rectifier(om.Group): def setup(self): self.add_subsystem('gen', DCgenerator(), promotes=[('V_bus', 'Vm_dc'), 'P_out']) self.add_subsystem('calcs', RectifierCalcs(), promotes=['P_out', ('V_out', 'Vm_dc')]) - self.nonlinear_solver = NewtonSolver() - self.linear_solver = DirectSolver() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.DirectSolver() - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('sub', Rectifier()) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) with self.assertRaises(RuntimeError) as cm: @@ -607,9 +607,9 @@ def setup(self): self.assertEqual(expected_msg, str(cm.exception)) def test_matvec_error_raised(self): - prob = Problem() - model = prob.model = Group() - model.add_subsystem('x_param', IndepVarComp('length', 3.0), + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param', om.IndepVarComp('length', 3.0), promotes=['length']) model.add_subsystem('mycomp', TestExplCompSimpleJacVec(), promotes=['length', 'width', 'area']) @@ -630,13 +630,13 @@ class TestDirectSolverFeature(unittest.TestCase): def test_specify_solver(self): - from openmdao.api import Problem, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivatives() - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() prob.setup() prob.run_model() diff --git a/openmdao/solvers/linear/tests/test_linear_block_gs.py b/openmdao/solvers/linear/tests/test_linear_block_gs.py index 08bc270951..3b02eb301d 100644 --- a/openmdao/solvers/linear/tests/test_linear_block_gs.py +++ b/openmdao/solvers/linear/tests/test_linear_block_gs.py @@ -5,17 +5,16 @@ import numpy as np +import openmdao.api as om from openmdao.solvers.linear.tests.linear_test_base import LinearSolverTests -from openmdao.utils.assert_utils import assert_rel_error -from openmdao.api import LinearBlockGS, Problem, Group, ImplicitComponent, IndepVarComp, \ - DirectSolver, NewtonSolver, ScipyKrylov, ExecComp, NonlinearBlockGS, BoundsEnforceLS from openmdao.test_suite.components.sellar import SellarImplicitDis1, SellarImplicitDis2, \ SellarDis1withDerivatives, SellarDis2withDerivatives from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimpleDense from openmdao.test_suite.components.sellar import SellarDerivatives +from openmdao.utils.assert_utils import assert_rel_error -class SimpleImp(ImplicitComponent): +class SimpleImp(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) self.add_output('x', val=0.) @@ -31,18 +30,18 @@ def linearize(self, inputs, outputs, jacobian): class TestBGSSolver(LinearSolverTests.LinearSolverTestCase): - linear_solver_class = LinearBlockGS + linear_solver_class = om.LinearBlockGS def test_globaljac_err(self): - prob = Problem() - model = prob.model = Group(assembled_jac_type='dense') - model.add_subsystem('x_param', IndepVarComp('length', 3.0), + prob = om.Problem() + model = prob.model = om.Group(assembled_jac_type='dense') + model.add_subsystem('x_param', om.IndepVarComp('length', 3.0), promotes=['length']) model.add_subsystem('mycomp', TestExplCompSimpleDense(), promotes=['length', 'width', 'area']) model.linear_solver = self.linear_solver_class(assemble_jac=True) - prob.setup(check=False) + prob.setup() with self.assertRaises(RuntimeError) as context: prob.run_model() @@ -54,14 +53,14 @@ def test_simple_implicit(self): # This verifies that we can perform lgs around an implicit comp and get the right answer # as long as we slot a non-lgs linear solver on that component. - prob = Problem() - model = prob.model = Group() - model.add_subsystem('p', IndepVarComp('a', 5.0)) + prob = om.Problem() + model = prob.model + model.add_subsystem('p', om.IndepVarComp('a', 5.0)) comp = model.add_subsystem('comp', SimpleImp()) model.connect('p.a', 'comp.a') model.linear_solver = self.linear_solver_class() - comp.linear_solver = DirectSolver() + comp.linear_solver = om.DirectSolver() prob.setup(check=False, mode='fwd') prob.run_model() @@ -70,20 +69,20 @@ def test_simple_implicit(self): self.assertEqual(deriv['comp.x', 'p.a'], -1.5) def test_implicit_cycle(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 1.0)) model.add_subsystem('d1', SellarImplicitDis1()) model.add_subsystem('d2', SellarImplicitDis2()) model.connect('d1.y1', 'd2.y1') model.connect('d2.y2', 'd1.y2') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() model.nonlinear_solver.options['maxiter'] = 5 model.linear_solver = self.linear_solver_class() - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -93,22 +92,22 @@ def test_implicit_cycle(self): self.assertLess(res, 2.0e-2) def test_implicit_cycle_precon(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 1.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 1.0)) model.add_subsystem('d1', SellarImplicitDis1()) model.add_subsystem('d2', SellarImplicitDis2()) model.connect('d1.y1', 'd2.y1') model.connect('d2.y2', 'd1.y2') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() model.nonlinear_solver.options['maxiter'] = 5 - model.nonlinear_solver.linesearch = BoundsEnforceLS() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver.linesearch = om.BoundsEnforceLS() + model.linear_solver = om.ScipyKrylov() model.linear_solver.precon = self.linear_solver_class() - prob.setup(check=False) + prob.setup() prob['d1.y1'] = 4.0 prob.set_solver_print() @@ -119,19 +118,19 @@ def test_implicit_cycle_precon(self): self.assertLess(res, 2.0e-2) def test_full_desvar_with_index_obj_relevance_bug(self): - prob = Problem() + prob = om.Problem() sub = prob.model.add_subsystem('sub', SellarDerivatives()) - prob.model.nonlinear_solver = NonlinearBlockGS() - prob.model.linear_solver = LinearBlockGS() - sub.nonlinear_solver = NonlinearBlockGS() - sub.linear_solver = LinearBlockGS() + prob.model.nonlinear_solver = om.NonlinearBlockGS() + prob.model.linear_solver = om.LinearBlockGS() + sub.nonlinear_solver = om.NonlinearBlockGS() + sub.linear_solver = om.LinearBlockGS() prob.model.add_design_var('sub.z', lower=-100, upper=100) prob.model.add_objective('sub.z', index=1) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() # We don't call run_driver() here because we don't # actually want the optimizer to run @@ -147,27 +146,27 @@ class TestBGSSolverFeature(unittest.TestCase): def test_specify_solver(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockGS, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = LinearBlockGS() - model.nonlinear_solver = NonlinearBlockGS() + model.linear_solver = om.LinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() prob.run_model() @@ -182,28 +181,28 @@ def test_specify_solver(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockGS, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() model.linear_solver.options['maxiter'] = 2 prob.setup() @@ -219,28 +218,28 @@ def test_feature_maxiter(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockGS, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() model.linear_solver.options['atol'] = 1.0e-3 prob.setup() @@ -256,28 +255,28 @@ def test_feature_atol(self): def test_feature_rtol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockGS, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() model.linear_solver.options['rtol'] = 1.0e-3 prob.setup() diff --git a/openmdao/solvers/linear/tests/test_linear_block_jac.py b/openmdao/solvers/linear/tests/test_linear_block_jac.py index 79d8d327d3..97fb9ef6bb 100644 --- a/openmdao/solvers/linear/tests/test_linear_block_jac.py +++ b/openmdao/solvers/linear/tests/test_linear_block_jac.py @@ -6,8 +6,7 @@ import numpy as np -from openmdao.api import Group, IndepVarComp, Problem, LinearBlockJac, \ - ExecComp, NonlinearBlockGS +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimpleDense @@ -16,18 +15,18 @@ class TestLinearBlockJacSolver(LinearSolverTests.LinearSolverTestCase): - linear_solver_class = LinearBlockJac + linear_solver_class = om.LinearBlockJac def test_globaljac_err(self): - prob = Problem() - model = prob.model = Group(assembled_jac_type='dense') - model.add_subsystem('x_param', IndepVarComp('length', 3.0), + prob = om.Problem() + model = prob.model = om.Group(assembled_jac_type='dense') + model.add_subsystem('x_param', om.IndepVarComp('length', 3.0), promotes=['length']) model.add_subsystem('mycomp', TestExplCompSimpleDense(), promotes=['length', 'width', 'area']) - model.linear_solver = LinearBlockJac(assemble_jac=True) - prob.setup(check=False) + model.linear_solver = om.LinearBlockJac(assemble_jac=True) + prob.setup() with self.assertRaises(RuntimeError) as context: prob.run_model() @@ -40,27 +39,27 @@ class TestBJacSolverFeature(unittest.TestCase): def test_specify_solver(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockJac, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() - model.linear_solver = LinearBlockJac() + model.nonlinear_solver = om.NonlinearBlockGS() + model.linear_solver = om.LinearBlockJac() prob.setup() prob.run_model() @@ -75,28 +74,28 @@ def test_specify_solver(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockJac, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = LinearBlockJac() + model.linear_solver = om.LinearBlockJac() model.linear_solver.options['maxiter'] = 5 prob.setup() @@ -112,28 +111,28 @@ def test_feature_maxiter(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockJac, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = LinearBlockJac() + model.linear_solver = om.LinearBlockJac() model.linear_solver.options['atol'] = 1.0e-3 prob.setup(mode='rev') @@ -149,28 +148,28 @@ def test_feature_atol(self): def test_feature_rtol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockJac, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = LinearBlockJac() + model.linear_solver = om.LinearBlockJac() model.linear_solver.options['rtol'] = 1.0e-3 prob.setup(mode='rev') diff --git a/openmdao/solvers/linear/tests/test_linear_runonce.py b/openmdao/solvers/linear/tests/test_linear_runonce.py index a403127850..997de818c1 100644 --- a/openmdao/solvers/linear/tests/test_linear_runonce.py +++ b/openmdao/solvers/linear/tests/test_linear_runonce.py @@ -2,24 +2,23 @@ import unittest -from openmdao.api import Problem, Group, IndepVarComp -from openmdao.utils.assert_utils import assert_rel_error -from openmdao.solvers.linear.linear_runonce import LinearRunOnce +import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.groups.parallel_groups import ConvergeDivergeGroups +from openmdao.utils.assert_utils import assert_rel_error class TestLinearRunOnceSolver(unittest.TestCase): def test_converge_diverge_groups(self): # Test derivatives for converge-diverge-groups topology. - prob = Problem() + prob = om.Problem() model = prob.model = ConvergeDivergeGroups() - model.linear_solver = LinearRunOnce() - model.g1.linear_solver = LinearRunOnce() - model.g1.g2.linear_solver = LinearRunOnce() - model.g3.linear_solver = LinearRunOnce() + model.linear_solver = om.LinearRunOnce() + model.g1.linear_solver = om.LinearRunOnce() + model.g1.g2.linear_solver = om.LinearRunOnce() + model.g3.linear_solver = om.LinearRunOnce() prob.set_solver_print(level=0) prob.setup(check=False, mode='fwd') @@ -42,7 +41,7 @@ def test_converge_diverge_groups(self): def test_undeclared_options(self): # Test that using options that should not exist in class cause an error - solver = LinearRunOnce() + solver = om.LinearRunOnce() msg = "\"Option '%s' cannot be set because it has not been declared.\"" @@ -54,17 +53,17 @@ def test_undeclared_options(self): def test_feature_solver(self): - from openmdao.api import Problem, Group, IndepVarComp, LinearRunOnce + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.linear_solver = LinearRunOnce() + model.linear_solver = om.LinearRunOnce() prob.setup(check=False, mode='fwd') diff --git a/openmdao/solvers/linear/tests/test_petsc_ksp.py b/openmdao/solvers/linear/tests/test_petsc_ksp.py index e74910a20a..c2d8776c0f 100644 --- a/openmdao/solvers/linear/tests/test_petsc_ksp.py +++ b/openmdao/solvers/linear/tests/test_petsc_ksp.py @@ -6,8 +6,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, PETScKrylov, LinearBlockGS, DirectSolver, \ - ExecComp, NewtonSolver, NonlinearBlockGS, PetscKSP +import openmdao.api as om from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimpleDense from openmdao.test_suite.components.misc_components import Comp4LinearCacheTest from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives @@ -28,8 +27,8 @@ class TestPETScKrylov(unittest.TestCase): def test_options(self): """Verify that the PETScKrylov specific options are declared.""" - group = Group() - group.linear_solver = PETScKrylov() + group = om.Group() + group.linear_solver = om.PETScKrylov() assert(group.linear_solver.options['ksp_type'] == 'fgmres') @@ -41,10 +40,10 @@ def test_solve_linear_ksp_default(self): msg = "PetscKSP is deprecated. Use PETScKrylov instead." with assert_warning(DeprecationWarning, msg): - group = TestImplicitGroup(lnSolverClass=PetscKSP) + group = TestImplicitGroup(lnSolverClass=om.PetscKSP) - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -71,11 +70,11 @@ def test_solve_linear_ksp_default(self): def test_solve_linear_ksp_gmres(self): """Solve implicit system with PETScKrylov using 'gmres' method.""" - group = TestImplicitGroup(lnSolverClass=PETScKrylov) + group = TestImplicitGroup(lnSolverClass=om.PETScKrylov) group.linear_solver.options['ksp_type'] = 'gmres' - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -102,11 +101,11 @@ def test_solve_linear_ksp_gmres(self): def test_solve_linear_ksp_maxiter(self): """Verify that PETScKrylov abides by the 'maxiter' option.""" - group = TestImplicitGroup(lnSolverClass=PETScKrylov) + group = TestImplicitGroup(lnSolverClass=om.PETScKrylov) group.linear_solver.options['maxiter'] = 2 - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -131,11 +130,11 @@ def test_solve_linear_ksp_maxiter(self): def test_solve_linear_ksp_precon(self): """Solve implicit system with PETScKrylov using a preconditioner.""" - group = TestImplicitGroup(lnSolverClass=PETScKrylov) - precon = group.linear_solver.precon = LinearBlockGS() + group = TestImplicitGroup(lnSolverClass=om.PETScKrylov) + precon = group.linear_solver.precon = om.LinearBlockGS() - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -164,8 +163,8 @@ def test_solve_linear_ksp_precon(self): self.assertTrue(precon._iter_count > 0) # test the direct solver and make sure KSP correctly recurses for _linearize - precon = group.linear_solver.precon = DirectSolver(assemble_jac=False) - p.setup(check=False) + precon = group.linear_solver.precon = om.DirectSolver(assemble_jac=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -193,13 +192,13 @@ def test_solve_linear_ksp_precon(self): def test_solve_linear_ksp_precon_left(self): """Solve implicit system with PETScKrylov using a preconditioner.""" - group = TestImplicitGroup(lnSolverClass=PETScKrylov) - precon = group.linear_solver.precon = DirectSolver(assemble_jac=False) + group = TestImplicitGroup(lnSolverClass=om.PETScKrylov) + precon = group.linear_solver.precon = om.DirectSolver(assemble_jac=False) group.linear_solver.options['precon_side'] = 'left' group.linear_solver.options['ksp_type'] = 'richardson' - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -226,11 +225,11 @@ def test_solve_linear_ksp_precon_left(self): assert_rel_error(self, output, group.expected_solution, 3e-15) # test the direct solver and make sure KSP correctly recurses for _linearize - precon = group.linear_solver.precon = DirectSolver(assemble_jac=False) + precon = group.linear_solver.precon = om.DirectSolver(assemble_jac=False) group.linear_solver.options['precon_side'] = 'left' group.linear_solver.options['ksp_type'] = 'richardson' - p.setup(check=False) + p.setup() # Conclude setup but don't run model. p.final_setup() @@ -257,14 +256,14 @@ def test_solve_linear_ksp_precon_left(self): def test_preconditioner_deprecation(self): - group = TestImplicitGroup(lnSolverClass=PETScKrylov) + group = TestImplicitGroup(lnSolverClass=om.PETScKrylov) msg = "The 'preconditioner' property provides backwards compatibility " \ "with OpenMDAO <= 1.x ; use 'precon' instead." # check deprecation on setter & getter with assert_warning(DeprecationWarning, msg): - precon = group.linear_solver.preconditioner = LinearBlockGS() + precon = group.linear_solver.preconditioner = om.LinearBlockGS() with assert_warning(DeprecationWarning, msg): pre = group.linear_solver.preconditioner @@ -272,16 +271,16 @@ def test_preconditioner_deprecation(self): def test_solve_on_subsystem(self): """solve an implicit system with KSP attached anywhere but the root""" - p = Problem() + p = om.Problem() model = p.model - dv = model.add_subsystem('des_vars', IndepVarComp()) + dv = model.add_subsystem('des_vars', om.IndepVarComp()) # just need a dummy variable so the sizes don't match between root and g1 dv.add_output('dummy', val=1.0, shape=10) - g1 = model.add_subsystem('g1', TestImplicitGroup(lnSolverClass=PETScKrylov)) + g1 = model.add_subsystem('g1', TestImplicitGroup(lnSolverClass=om.PETScKrylov)) - p.setup(check=False) + p.setup() p.set_solver_print(level=0) @@ -315,14 +314,14 @@ def test_linear_solution_cache(self): # Forward mode - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) model.add_subsystem('d1', Comp4LinearCacheTest(), promotes=['x', 'y']) - model.nonlinear_solver = NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.nonlinear_solver = om.NonlinearBlockGS() + model.linear_solver = om.PETScKrylov() model.add_design_var('x', cache_linear_solution=True) model.add_objective('y', cache_linear_solution=True) @@ -343,14 +342,14 @@ def test_linear_solution_cache(self): # Reverse mode - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) model.add_subsystem('d1', Comp4LinearCacheTest(), promotes=['x', 'y']) - model.nonlinear_solver = NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.nonlinear_solver = om.NonlinearBlockGS() + model.linear_solver = om.PETScKrylov() model.add_design_var('x', cache_linear_solution=True) model.add_objective('y', cache_linear_solution=True) @@ -371,24 +370,24 @@ def test_linear_solution_cache(self): def test_error_under_cs(self): """Verify that PETScKrylov abides by the 'maxiter' option.""" - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NewtonSolver() - model.linear_solver = PETScKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.PETScKrylov() model.approx_totals(method='cs') @@ -409,28 +408,28 @@ class TestPETScKrylovSolverFeature(unittest.TestCase): def test_specify_solver(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NonlinearBlockGS, PETScKrylov, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.linear_solver = om.PETScKrylov() prob.setup() prob.run_model() @@ -445,30 +444,29 @@ def test_specify_solver(self): def test_specify_ksp_type(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NonlinearBlockGS, PETScKrylov, \ - ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.linear_solver = om.PETScKrylov() model.linear_solver.options['ksp_type'] = 'gmres' prob.setup() @@ -484,28 +482,28 @@ def test_specify_ksp_type(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NonlinearBlockGS, PETScKrylov, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.linear_solver = om.PETScKrylov() model.linear_solver.options['maxiter'] = 3 prob.setup() @@ -521,28 +519,28 @@ def test_feature_maxiter(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NonlinearBlockGS, PETScKrylov, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.linear_solver = om.PETScKrylov() model.linear_solver.options['atol'] = 1.0e-20 prob.setup() @@ -558,28 +556,28 @@ def test_feature_atol(self): def test_feature_rtol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NonlinearBlockGS, PETScKrylov, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = PETScKrylov() + model.linear_solver = om.PETScKrylov() model.linear_solver.options['rtol'] = 1.0e-20 prob.setup() @@ -595,31 +593,30 @@ def test_feature_rtol(self): def test_specify_precon(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, LinearBlockGS, PETScKrylov, \ - NewtonSolver, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NewtonSolver() - model.linear_solver = PETScKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.PETScKrylov() - model.linear_solver.precon = LinearBlockGS() + model.linear_solver.precon = om.LinearBlockGS() model.linear_solver.precon.options['maxiter'] = 2 prob.setup() @@ -631,31 +628,30 @@ def test_specify_precon(self): def test_specify_precon_left(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, DirectSolver, PETScKrylov, \ - NewtonSolver, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NewtonSolver() - model.linear_solver = PETScKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.PETScKrylov() - model.linear_solver.precon = DirectSolver() + model.linear_solver.precon = om.DirectSolver() model.linear_solver.options['precon_side'] = 'left' model.linear_solver.options['ksp_type'] = 'richardson' diff --git a/openmdao/solvers/linear/tests/test_scipy_iter_solver.py b/openmdao/solvers/linear/tests/test_scipy_iter_solver.py index 68cb590048..689cc7fd6b 100644 --- a/openmdao/solvers/linear/tests/test_scipy_iter_solver.py +++ b/openmdao/solvers/linear/tests/test_scipy_iter_solver.py @@ -7,10 +7,7 @@ import numpy as np -from openmdao.api import Group, IndepVarComp, Problem, ExecComp, NonlinearBlockGS, BoundsEnforceLS -from openmdao.solvers.linear.linear_block_gs import LinearBlockGS -from openmdao.solvers.linear.scipy_iter_solver import ScipyKrylov, ScipyIterativeSolver -from openmdao.solvers.nonlinear.newton import NewtonSolver +import openmdao.api as om from openmdao.solvers.linear.tests.linear_test_base import LinearSolverTests from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimpleDense from openmdao.test_suite.components.misc_components import Comp4LinearCacheTest @@ -22,7 +19,7 @@ # use this to fake out the TestImplicitGroup so it'll use the solver we want. def krylov_factory(solver): def f(junk=None): - return ScipyKrylov(solver=solver) + return om.ScipyKrylov(solver=solver) return f @@ -34,7 +31,7 @@ class TestScipyKrylov(LinearSolverTests.LinearSolverTestCase): def test_options(self): """Verify that the SciPy solver specific options are declared.""" - group = Group() + group = om.Group() group.linear_solver = self.linear_solver_class() self.assertEqual(group.linear_solver.options['solver'], self.linear_solver_name) @@ -47,10 +44,10 @@ def test_solve_linear_scipy(self): msg = "ScipyIterativeSolver is deprecated. Use ScipyKrylov instead." with assert_warning(DeprecationWarning, msg): - group = TestImplicitGroup(lnSolverClass=lambda : ScipyIterativeSolver(solver=self.linear_solver_name)) + group = TestImplicitGroup(lnSolverClass=lambda : om.ScipyIterativeSolver(solver=self.linear_solver_name)) - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -78,8 +75,8 @@ def test_solve_linear_scipy_maxiter(self): group = TestImplicitGroup(lnSolverClass=self.linear_solver_class) group.linear_solver.options['maxiter'] = 2 - p = Problem(group) - p.setup(check=False) + p = om.Problem(group) + p.setup() p.set_solver_print(level=0) # Conclude setup but don't run model. @@ -104,16 +101,16 @@ def test_solve_linear_scipy_maxiter(self): def test_solve_on_subsystem(self): """solve an implicit system with GMRES attached to a subsystem""" - p = Problem() - model = p.model = Group() - dv = model.add_subsystem('des_vars', IndepVarComp()) + p = om.Problem() + model = p.model + dv = model.add_subsystem('des_vars', om.IndepVarComp()) # just need a dummy variable so the sizes don't match between root and g1 dv.add_output('dummy', val=1.0, shape=10) grp = TestImplicitGroup(lnSolverClass=self.linear_solver_class) g1 = model.add_subsystem('g1', grp) - p.setup(check=False) + p.setup() p.set_solver_print(level=0) @@ -150,7 +147,7 @@ def test_preconditioner_deprecation(self): # check deprecation on setter & getter with assert_warning(DeprecationWarning, msg): - group.linear_solver.preconditioner = LinearBlockGS() + group.linear_solver.preconditioner = om.LinearBlockGS() with assert_warning(DeprecationWarning, msg): group.linear_solver.preconditioner @@ -162,14 +159,14 @@ def test_linear_solution_cache(self): # Forward mode - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) model.add_subsystem('d1', Comp4LinearCacheTest(), promotes=['x', 'y']) - model.nonlinear_solver = NonlinearBlockGS() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NonlinearBlockGS() + model.linear_solver = om.ScipyKrylov() model.add_design_var('x', cache_linear_solution=True) model.add_objective('y', cache_linear_solution=True) @@ -188,14 +185,14 @@ def test_linear_solution_cache(self): # Reverse mode - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) model.add_subsystem('d1', Comp4LinearCacheTest(), promotes=['x', 'y']) - model.nonlinear_solver = NonlinearBlockGS() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NonlinearBlockGS() + model.linear_solver = om.ScipyKrylov() model.add_design_var('x', cache_linear_solution=True) model.add_objective('y', cache_linear_solution=True) @@ -218,18 +215,18 @@ class TestScipyKrylovFeature(unittest.TestCase): def test_feature_simple(self): """Tests feature for adding a Scipy GMRES solver and calculating the derivatives.""" - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.expl_comp_simple import TestExplCompSimpleDense # Tests derivatives on a simple comp that defines compute_jacvec. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('x_param', IndepVarComp('length', 3.0), + model.add_subsystem('x_param', om.IndepVarComp('length', 3.0), promotes=['length']) model.add_subsystem('mycomp', TestExplCompSimpleDense(), promotes=['length', 'width', 'area']) - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() prob.set_solver_print(level=0) prob.setup(check=False, mode='fwd') @@ -245,30 +242,29 @@ def test_feature_simple(self): def test_specify_solver(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, \ - NonlinearBlockGS, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() prob.setup() prob.run_model() @@ -283,28 +279,28 @@ def test_specify_solver(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, NonlinearBlockGS, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.linear_solver.options['maxiter'] = 3 prob.setup() @@ -320,28 +316,28 @@ def test_feature_maxiter(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, NonlinearBlockGS, ExecComp + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.linear_solver.options['atol'] = 1.0e-20 prob.setup() @@ -357,35 +353,33 @@ def test_feature_atol(self): def test_specify_precon(self): import numpy as np - from openmdao.api import Problem, Group, ScipyKrylov, NewtonSolver, LinearBlockGS, \ - DirectSolver, ExecComp, PETScKrylov - + import openmdao.api as om from openmdao.test_suite.components.quad_implicit import QuadraticComp - prob = Problem() + prob = om.Problem() model = prob.model - sub1 = model.add_subsystem('sub1', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) sub1.add_subsystem('q1', QuadraticComp()) - sub1.add_subsystem('z1', ExecComp('y = -6.0 + .01 * x')) - sub2 = model.add_subsystem('sub2', Group()) + sub1.add_subsystem('z1', om.ExecComp('y = -6.0 + .01 * x')) + sub2 = model.add_subsystem('sub2', om.Group()) sub2.add_subsystem('q2', QuadraticComp()) - sub2.add_subsystem('z2', ExecComp('y = -6.0 + .01 * x')) + sub2.add_subsystem('z2', om.ExecComp('y = -6.0 + .01 * x')) model.connect('sub1.q1.x', 'sub1.z1.x') model.connect('sub1.z1.y', 'sub2.q2.c') model.connect('sub2.q2.x', 'sub2.z2.x') model.connect('sub2.z2.y', 'sub1.q1.c') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() prob.setup() - model.sub1.linear_solver = DirectSolver() - model.sub2.linear_solver = DirectSolver() + model.sub1.linear_solver = om.DirectSolver() + model.sub2.linear_solver = om.DirectSolver() - model.linear_solver.precon = LinearBlockGS() + model.linear_solver.precon = om.LinearBlockGS() prob.set_solver_print(level=2) prob.run_model() diff --git a/openmdao/solvers/linear/tests/test_user_defined.py b/openmdao/solvers/linear/tests/test_user_defined.py index db0a2542bd..8126b9727f 100644 --- a/openmdao/solvers/linear/tests/test_user_defined.py +++ b/openmdao/solvers/linear/tests/test_user_defined.py @@ -6,10 +6,8 @@ import numpy as np -from openmdao.api import Group, Problem, ImplicitComponent, PETScKrylov, LinearRunOnce, \ - IndepVarComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -from openmdao.solvers.linear.user_defined import LinearUserDefined from openmdao.utils.array_utils import evenly_distrib_idxs try: @@ -18,7 +16,7 @@ PETScVector = None -class DistribStateImplicit(ImplicitComponent): +class DistribStateImplicit(om.ImplicitComponent): def setup(self): @@ -33,8 +31,8 @@ def setup(self): self.add_output('out_var', shape=1) self.local_size = sizes[rank] - self.linear_solver = PETScKrylov() - self.linear_solver.precon = LinearUserDefined(self.mysolve) + self.linear_solver = om.PETScKrylov() + self.linear_solver.precon = om.LinearUserDefined(self.mysolve) def solve_nonlinear(self, i, o): o['states'] = i['a'] @@ -121,16 +119,16 @@ def mysolve(self, d_outputs, d_residuals, mode): class TestUserDefinedSolver(unittest.TestCase): def test_method(self): - p = Problem() + p = om.Problem() - p.model.add_subsystem('des_vars', IndepVarComp('a', val=10., units='m'), promotes=['*']) + p.model.add_subsystem('des_vars', om.IndepVarComp('a', val=10., units='m'), promotes=['*']) p.model.add_subsystem('icomp', DistribStateImplicit(), promotes=['*']) model = p.model - model.linear_solver = PETScKrylov() - model.linear_solver.precon = LinearRunOnce() + model.linear_solver = om.PETScKrylov() + model.linear_solver.precon = om.LinearRunOnce() p.setup(mode='rev', check=False) p.run_model() @@ -147,7 +145,7 @@ def custom_method(d_outputs, d_residuals, mode): raise ValueError('This value should be unscaled.') - class ScaledComp(ImplicitComponent): + class ScaledComp(om.ImplicitComponent): def setup(self): @@ -157,12 +155,12 @@ def setup(self): self.add_output('out_var', val=20.0, ref=12.0) - p = Problem() - p.model.add_subsystem('des_vars', IndepVarComp('a', val=10., units='m'), promotes=['*']) + p = om.Problem() + p.model.add_subsystem('des_vars', om.IndepVarComp('a', val=10., units='m'), promotes=['*']) p.model.add_subsystem('icomp', ScaledComp(), promotes=['*']) model = p.model - model.linear_solver = LinearUserDefined(custom_method) + model.linear_solver = om.LinearUserDefined(custom_method) p.setup(mode='rev', check=False) p.run_model() @@ -170,20 +168,20 @@ def setup(self): def test_method_default(self): # Uses `solve_linear` by default - p = Problem() + p = om.Problem() - p.model.add_subsystem('des_vars', IndepVarComp('a', val=10., units='m'), promotes=['*']) + p.model.add_subsystem('des_vars', om.IndepVarComp('a', val=10., units='m'), promotes=['*']) p.model.add_subsystem('icomp', DistribStateImplicit(), promotes=['*']) model = p.model - model.linear_solver = PETScKrylov() - model.linear_solver.precon = LinearRunOnce() + model.linear_solver = om.PETScKrylov() + model.linear_solver.precon = om.LinearRunOnce() p.setup(mode='rev', check=False) - model.icomp.linear_solver.precon = LinearUserDefined() + model.icomp.linear_solver.precon = om.LinearUserDefined() p.run_model() jac = p.compute_totals(of=['out_var'], wrt=['a'], return_format='dict') @@ -193,10 +191,10 @@ def test_method_default(self): def test_feature(self): import numpy as np - from openmdao.api import Problem, ImplicitComponent, IndepVarComp, LinearRunOnce, PETScKrylov, PETScVector, LinearUserDefined + import openmdao.api as om from openmdao.utils.array_utils import evenly_distrib_idxs - class CustomSolveImplicit(ImplicitComponent): + class CustomSolveImplicit(om.ImplicitComponent): def setup(self): @@ -211,8 +209,8 @@ def setup(self): self.add_output('out_var', shape=1) self.local_size = sizes[rank] - self.linear_solver = PETScKrylov() - self.linear_solver.precon = LinearUserDefined(solve_function=self.mysolve) + self.linear_solver = om.PETScKrylov() + self.linear_solver.precon = om.LinearUserDefined(solve_function=self.mysolve) def solve_nonlinear(self, i, o): o['states'] = i['a'] @@ -289,16 +287,16 @@ def mysolve(self, d_outputs, d_residuals, mode): elif mode == 'rev': d_residuals.set_vec(d_outputs) - prob = Problem() + prob = om.Problem() - prob.model.add_subsystem('des_vars', IndepVarComp('a', val=10., units='m'), promotes=['*']) + prob.model.add_subsystem('des_vars', om.IndepVarComp('a', val=10., units='m'), promotes=['*']) prob.model.add_subsystem('icomp', CustomSolveImplicit(), promotes=['*']) model = prob.model - model.linear_solver = PETScKrylov() - model.linear_solver.precon = LinearRunOnce() + model.linear_solver = om.PETScKrylov() + model.linear_solver.precon = om.LinearRunOnce() prob.setup(mode='rev', check=False) prob.run_model() diff --git a/openmdao/solvers/linesearch/tests/test_backtracking.py b/openmdao/solvers/linesearch/tests/test_backtracking.py index f2071f44cd..5251195d0f 100644 --- a/openmdao/solvers/linesearch/tests/test_backtracking.py +++ b/openmdao/solvers/linesearch/tests/test_backtracking.py @@ -9,31 +9,26 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, DirectSolver, AnalysisError, \ - ExplicitComponent, ImplicitComponent -from openmdao.utils.assert_utils import assert_rel_error -from openmdao.solvers.linesearch.backtracking import ArmijoGoldsteinLS, BoundsEnforceLS -from openmdao.solvers.nonlinear.newton import NewtonSolver -from openmdao.solvers.linear.scipy_iter_solver import ScipyKrylov +import openmdao.api as om from openmdao.test_suite.components.double_sellar import DoubleSellar from openmdao.test_suite.components.implicit_newton_linesearch \ import ImplCompTwoStates, ImplCompTwoStatesArrays +from openmdao.utils.assert_utils import assert_rel_error class TestArmejoGoldsteinBounds(unittest.TestCase): def setUp(self): - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', 1.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 1.0)) top.model.add_subsystem('comp', ImplCompTwoStates()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - top.setup(check=False) + top.setup() self.top = top @@ -55,12 +50,12 @@ def test_nolinesearch(self): def test_linesearch_bounds_vector(self): top = self.top - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['maxiter'] = 10 ls.options['alpha'] = 1.0 # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bound: should go to the lower bound and stall top['px.x'] = 2.0 @@ -79,12 +74,12 @@ def test_linesearch_bounds_vector(self): def test_linesearch_bounds_wall(self): top = self.top - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='wall') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall') ls.options['maxiter'] = 10 ls.options['alpha'] = 10.0 # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bound: should go to the lower bound and stall top['px.x'] = 2.0 @@ -103,12 +98,12 @@ def test_linesearch_bounds_wall(self): def test_linesearch_bounds_scalar(self): top = self.top - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='scalar') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='scalar') ls.options['maxiter'] = 10 ls.options['alpha'] = 10.0 # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bound: should stop just short of the lower bound top['px.x'] = 2.0 @@ -125,7 +120,7 @@ def test_linesearch_bounds_scalar(self): self.assertTrue(2.4 <= top['comp.z'] <= 2.5) -class ParaboloidAE(ExplicitComponent): +class ParaboloidAE(om.ExplicitComponent): """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 This version raises an analysis error if x < 2.0 The AE in ParaboloidAE stands for AnalysisError.""" @@ -146,7 +141,7 @@ def compute(self, inputs, outputs): y = inputs['y'] if x < 1.75: - raise AnalysisError('Try Again.') + raise om.AnalysisError('Try Again.') outputs['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0 @@ -162,19 +157,18 @@ def compute_partials(self, inputs, partials): class TestAnalysisErrorExplicit(unittest.TestCase): def setUp(self): - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', 1.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 1.0)) top.model.add_subsystem('comp', ImplCompTwoStates()) top.model.add_subsystem('par', ParaboloidAE()) top.model.connect('px.x', 'comp.x') top.model.connect('comp.z', 'par.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 1 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['maxiter'] = 10 ls.options['alpha'] = 1.0 top.set_solver_print(level=0) @@ -185,7 +179,7 @@ def setUp(self): def test_retry(self): # Test the behavior with the switch turned on. top = self.top - top.setup(check=False) + top.setup() self.ls.options['retry_on_analysis_error'] = True # Test lower bound: should go as far as it can without going past 1.75 and triggering an @@ -201,19 +195,19 @@ def test_no_retry(self): self.ls.options['retry_on_analysis_error'] = False top = self.top - top.setup(check=False) + top.setup() top['px.x'] = 2.0 top['comp.y'] = 0.0 top['comp.z'] = 2.1 - with self.assertRaises(AnalysisError) as context: + with self.assertRaises(om.AnalysisError) as context: top.run_model() self.assertEqual(str(context.exception), 'Try Again.') -class ImplCompTwoStatesAE(ImplicitComponent): +class ImplCompTwoStatesAE(om.ImplicitComponent): def setup(self): self.add_input('x', 0.5) @@ -241,7 +235,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): self.counter += 1 if self.counter > 5 and self.counter < 11: - raise AnalysisError('catch me') + raise om.AnalysisError('catch me') def linearize(self, inputs, outputs, jac): """ @@ -268,31 +262,30 @@ class TestAnalysisErrorImplicit(unittest.TestCase): def test_deep_analysis_error_iprint(self): - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', 7.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 7.0)) - sub = top.model.add_subsystem('sub', Group()) + sub = top.model.add_subsystem('sub', om.Group()) sub.add_subsystem('comp', ImplCompTwoStatesAE()) top.model.connect('px.x', 'sub.comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 top.model.nonlinear_solver.options['solve_subsystems'] = True - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - sub.nonlinear_solver = NewtonSolver() + sub.nonlinear_solver = om.NewtonSolver() sub.nonlinear_solver.options['maxiter'] = 2 - sub.linear_solver = ScipyKrylov() + sub.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='wall') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall') ls.options['maxiter'] = 5 ls.options['alpha'] = 10.0 ls.options['retry_on_analysis_error'] = True ls.options['c'] = 10000.0 - top.setup(check=False) + top.setup() top.set_solver_print(level=2) stdout = sys.stdout @@ -318,31 +311,30 @@ def test_read_only_bug(self): # this tests for a bug in which guess_nonlinear failed due to the output # vector being left in a read only state after the AnalysisError - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', 7.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 7.0)) - sub = top.model.add_subsystem('sub', Group()) + sub = top.model.add_subsystem('sub', om.Group()) sub.add_subsystem('comp', ImplCompTwoStatesGuess()) top.model.connect('px.x', 'sub.comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 top.model.nonlinear_solver.options['solve_subsystems'] = True - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - sub.nonlinear_solver = NewtonSolver() + sub.nonlinear_solver = om.NewtonSolver() sub.nonlinear_solver.options['maxiter'] = 2 - sub.linear_solver = ScipyKrylov() + sub.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='wall') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall') ls.options['maxiter'] = 5 ls.options['alpha'] = 10.0 ls.options['retry_on_analysis_error'] = True ls.options['c'] = 10000.0 - top.setup(check=False) + top.setup() top.set_solver_print(level=2) stdout = sys.stdout @@ -368,18 +360,17 @@ def test_read_only_bug(self): class TestBoundsEnforceLSArrayBounds(unittest.TestCase): def setUp(self): - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() top.set_solver_print(level=0) - top.setup(check=False) + top.setup() self.top = top self.ub = np.array([2.6, 2.5, 2.65]) @@ -387,11 +378,11 @@ def setUp(self): def test_linesearch_vector_bound_enforcement(self): top = self.top - ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='vector') + ls = top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector') ls.options['print_bound_enforce'] = True # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -425,10 +416,10 @@ def test_linesearch_vector_bound_enforcement(self): def test_linesearch_wall_bound_enforcement_wall(self): top = self.top - top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='wall') + top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='wall') # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -449,10 +440,10 @@ def test_linesearch_wall_bound_enforcement_wall(self): def test_linesearch_wall_bound_enforcement_scalar(self): top = self.top - top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='scalar') + top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='scalar') # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bounds: should stop just short of the lower bound top['px.x'] = 2.0 @@ -473,7 +464,7 @@ def test_linesearch_wall_bound_enforcement_scalar(self): def test_error_handling(self): # Make sure the debug_print doesn't bomb out. - class Bad(ExplicitComponent): + class Bad(om.ExplicitComponent): def setup(self): self.add_input('x', val=0.0) @@ -501,21 +492,20 @@ def compute_partials(self, inputs, partials): partials['f_xy', 'x'] = 2.0*x - 6.0 + y partials['f_xy', 'y'] = 2.0*y + 8.0 + x - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', 1.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 1.0)) top.model.add_subsystem('comp', ImplCompTwoStates()) top.model.add_subsystem('par', Bad()) top.model.connect('px.x', 'comp.x') top.model.connect('comp.z', 'par.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 3 - top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='vector') + top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector') top.set_solver_print(level=0) - top.setup(check=False) + top.setup() # Make sure we don't raise an error when we reach the final debug print. top.run_model() @@ -526,25 +516,25 @@ def test_undeclared_options(self): # atol, rtol, maxiter, and err_on_maxiter are not used in BoundsEnforceLS with self.assertRaises(KeyError) as context: - BoundsEnforceLS(bound_enforcement='scalar', atol=1.0) + om.BoundsEnforceLS(bound_enforcement='scalar', atol=1.0) self.assertEqual(str(context.exception), "\"Option 'atol' cannot be set because it " "has not been declared.\"") with self.assertRaises(KeyError) as context: - BoundsEnforceLS(bound_enforcement='scalar', rtol=2.0) + om.BoundsEnforceLS(bound_enforcement='scalar', rtol=2.0) self.assertEqual(str(context.exception), "\"Option 'rtol' cannot be set because it " "has not been declared.\"") with self.assertRaises(KeyError) as context: - BoundsEnforceLS(bound_enforcement='scalar', maxiter=1) + om.BoundsEnforceLS(bound_enforcement='scalar', maxiter=1) self.assertEqual(str(context.exception), "\"Option 'maxiter' cannot be set because it " "has not been declared.\"") with self.assertRaises(KeyError) as context: - BoundsEnforceLS(bound_enforcement='scalar', err_on_maxiter=True) + om.BoundsEnforceLS(bound_enforcement='scalar', err_on_maxiter=True) self.assertEqual(str(context.exception), "\"Option 'err_on_maxiter' cannot be set because it " "has not been declared.\"") @@ -553,18 +543,17 @@ def test_undeclared_options(self): class TestArmijoGoldsteinLSArrayBounds(unittest.TestCase): def setUp(self): - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() top.set_solver_print(level=0) - top.setup(check=False) + top.setup() self.top = top self.ub = np.array([2.6, 2.5, 2.65]) @@ -572,11 +561,11 @@ def setUp(self): def test_linesearch_vector_bound_enforcement(self): top = self.top - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['c'] = .1 # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -597,10 +586,10 @@ def test_linesearch_vector_bound_enforcement(self): def test_linesearch_wall_bound_enforcement_wall(self): top = self.top - top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='wall') + top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall') # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -621,10 +610,10 @@ def test_linesearch_wall_bound_enforcement_wall(self): def test_linesearch_wall_bound_enforcement_scalar(self): top = self.top - top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='scalar') + top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='scalar') # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() # Test lower bounds: should stop just short of the lower bound top['px.x'] = 2.0 @@ -643,25 +632,25 @@ def test_linesearch_wall_bound_enforcement_scalar(self): self.assertTrue(2.4 <= top['comp.z'][ind] <= self.ub[ind]) def test_with_subsolves(self): - prob = Problem() + prob = om.Problem() model = prob.model = DoubleSellar() g1 = model.g1 - g1.nonlinear_solver = NewtonSolver() + g1.nonlinear_solver = om.NewtonSolver() g1.nonlinear_solver.options['rtol'] = 1.0e-5 - g1.linear_solver = DirectSolver() + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver() + g2.nonlinear_solver = om.NewtonSolver() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver() + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 4 - ls = model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') # This is pretty bogus, but it ensures that we get a few LS iterations. ls.options['c'] = 100.0 @@ -677,7 +666,7 @@ def test_with_subsolves(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) -class CompAtan(ImplicitComponent): +class CompAtan(om.ImplicitComponent): """ A simple implicit component with the following equation: @@ -716,14 +705,13 @@ def linearize(self, inputs, outputs, jacobian): class TestFeatureLineSearch(unittest.TestCase): def test_feature_specification(self): - from openmdao.api import Problem, IndepVarComp, NewtonSolver, BoundsEnforceLS - from openmdao.api import DirectSolver + import openmdao.api as om from openmdao.solvers.linesearch.tests.test_backtracking import CompAtan - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', -100.0)) + model.add_subsystem('px', om.IndepVarComp('x', -100.0)) model.add_subsystem('comp', CompAtan()) model.connect('px.x', 'comp.x') @@ -733,14 +721,14 @@ def test_feature_specification(self): # Initial value for the state: prob['comp.y'] = 12.0 - # You can change the NewtonSolver settings after setup is called - newton = prob.model.nonlinear_solver = NewtonSolver() - prob.model.linear_solver = DirectSolver() + # You can change the om.NewtonSolver settings after setup is called + newton = prob.model.nonlinear_solver = om.NewtonSolver() + prob.model.linear_solver = om.DirectSolver() newton.options['iprint'] = 2 newton.options['rtol'] = 1e-8 newton.options['solve_subsystems'] = True - newton.linesearch = BoundsEnforceLS() + newton.linesearch = om.BoundsEnforceLS() newton.linesearch.options['iprint'] = 2 prob.run_model() @@ -750,22 +738,21 @@ def test_feature_specification(self): def test_feature_boundsenforcels_basic(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - top.model.nonlinear_solver.linesearch = BoundsEnforceLS() + top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS() - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -780,22 +767,21 @@ def test_feature_boundsenforcels_basic(self): def test_feature_armijogoldsteinls_basic(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS() + top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS() - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -810,22 +796,21 @@ def test_feature_armijogoldsteinls_basic(self): def test_feature_boundscheck_basic(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - top.model.nonlinear_solver.linesearch = BoundsEnforceLS() + top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS() - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -840,23 +825,22 @@ def test_feature_boundscheck_basic(self): def test_feature_boundscheck_vector(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='vector') + ls = top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector') ls.options['bound_enforcement'] = 'vector' - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -871,23 +855,22 @@ def test_feature_boundscheck_vector(self): def test_feature_boundscheck_wall(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='wall') + ls = top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='wall') ls.options['bound_enforcement'] = 'wall' - top.setup(check=False) + top.setup() # Test upper bounds: should go to the upper bound and stall top['px.x'] = 0.5 @@ -902,23 +885,22 @@ def test_feature_boundscheck_wall(self): def test_feature_boundscheck_scalar(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='scalar') + ls = top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='scalar') ls.options['bound_enforcement'] = 'scalar' - top.setup(check=False) + top.setup() top.run_model() # Test lower bounds: should stop just short of the lower bound @@ -934,20 +916,19 @@ def test_feature_boundscheck_scalar(self): def test_feature_print_bound_enforce(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - newt = top.model.nonlinear_solver = NewtonSolver() + newt = top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = newt.linesearch = BoundsEnforceLS(bound_enforcement='vector') + ls = newt.linesearch = om.BoundsEnforceLS(bound_enforcement='vector') ls.options['print_bound_enforce'] = True top.set_solver_print(level=2) @@ -966,23 +947,22 @@ def test_feature_print_bound_enforce(self): def test_feature_armijo_boundscheck_vector(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='vector') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector') ls.options['bound_enforcement'] = 'vector' - top.setup(check=False) + top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 @@ -997,23 +977,22 @@ def test_feature_armijo_boundscheck_vector(self): def test_feature_armijo_boundscheck_wall(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='wall') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall') ls.options['bound_enforcement'] = 'wall' - top.setup(check=False) + top.setup() # Test upper bounds: should go to the upper bound and stall top['px.x'] = 0.5 @@ -1028,23 +1007,22 @@ def test_feature_armijo_boundscheck_wall(self): def test_feature_armijo_boundscheck_scalar(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(bound_enforcement='scalar') + ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='scalar') ls.options['bound_enforcement'] = 'scalar' - top.setup(check=False) + top.setup() top.run_model() # Test lower bounds: should stop just short of the lower bound @@ -1060,20 +1038,19 @@ def test_feature_armijo_boundscheck_scalar(self): def test_feature_armijo_print_bound_enforce(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS + import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays - top = Problem() - top.model = Group() - top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') - newt = top.model.nonlinear_solver = NewtonSolver() + newt = top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() - ls = newt.linesearch = ArmijoGoldsteinLS() + ls = newt.linesearch = om.ArmijoGoldsteinLS() ls.options['print_bound_enforce'] = True top.set_solver_print(level=2) diff --git a/openmdao/solvers/nonlinear/tests/test_broyden.py b/openmdao/solvers/nonlinear/tests/test_broyden.py index 7460dc5df9..1b2051ad3d 100644 --- a/openmdao/solvers/nonlinear/tests/test_broyden.py +++ b/openmdao/solvers/nonlinear/tests/test_broyden.py @@ -2,21 +2,18 @@ from __future__ import print_function from six import iteritems - import unittest import numpy as np -from openmdao.api import Problem, LinearRunOnce, ImplicitComponent, IndepVarComp, DirectSolver, \ - BoundsEnforceLS, LinearBlockGS, Group, ExecComp -from openmdao.solvers.nonlinear.broyden import BroydenSolver +import openmdao.api as om from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStates from openmdao.test_suite.components.sellar import SellarStateConnection, SellarDerivatives, \ SellarDis1withDerivatives, SellarDis2withDerivatives from openmdao.utils.assert_utils import assert_rel_error, assert_warning -class VectorEquation(ImplicitComponent): +class VectorEquation(om.ImplicitComponent): """Equation with 5 states in a single vector. Should converge to x=[0,0,0,0,0]""" def setup(self): @@ -32,7 +29,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): residuals['x'] = -d*x - c*x**3 -class MixedEquation(ImplicitComponent): +class MixedEquation(om.ImplicitComponent): """Equation with 5 states split between 3 vars. Should converge to x=[0,0,0,0,0]""" def setup(self): @@ -75,7 +72,7 @@ def linearize(self, inputs, outputs, jacobian): jacobian['x45', 'c'] = -3.0 * x45**2 -class SpedicatoHuang(ImplicitComponent): +class SpedicatoHuang(om.ImplicitComponent): cite = """ @article{spedicato_hwang, @@ -130,11 +127,11 @@ class TestBryoden(unittest.TestCase): def test_error_badname(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() model.nonlinear_solver.options['state_vars'] = ['junk'] @@ -147,11 +144,11 @@ def test_error_badname(self): def test_error_need_direct_solver(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() with self.assertRaises(ValueError) as context: prob.run_model() @@ -162,11 +159,11 @@ def test_error_need_direct_solver(self): def test_simple_sellar(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command'] model.nonlinear_solver.options['compute_jacobian'] = False @@ -179,11 +176,11 @@ def test_simple_sellar(self): def test_simple_sellar_cycle(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarDerivatives(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarDerivatives(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() model.nonlinear_solver.options['state_vars'] = ['y1'] model.nonlinear_solver.options['compute_jacobian'] = True @@ -198,12 +195,12 @@ def test_simple_sellar_cycle(self): def test_sellar_state_connection_fd_system(self): # Sellar model closes loop with state connection instead of a cycle. # This test is just fd. - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) prob.model.approx_totals(method='fd') - prob.setup(check=False) + prob.setup() model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command'] model.nonlinear_solver.options['compute_jacobian'] = False @@ -219,20 +216,20 @@ def test_sellar_state_connection_fd_system(self): def test_vector(self): # Testing Broyden on a 5 state single vector case. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('c', 0.01)) + model.add_subsystem('p1', om.IndepVarComp('c', 0.01)) model.add_subsystem('vec', VectorEquation()) model.connect('p1.c', 'vec.c') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['vec.x'] model.nonlinear_solver.options['maxiter'] = 15 model.nonlinear_solver.options['compute_jacobian'] = False - prob.setup(check=False) + prob.setup() prob.run_model() @@ -241,20 +238,20 @@ def test_vector(self): def test_mixed(self): # Testing Broyden on a 5 state case split among 3 vars. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('c', 0.01)) + model.add_subsystem('p1', om.IndepVarComp('c', 0.01)) model.add_subsystem('mixed', MixedEquation()) model.connect('p1.c', 'mixed.c') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['mixed.x12', 'mixed.x3', 'mixed.x45'] model.nonlinear_solver.options['maxiter'] = 15 model.nonlinear_solver.options['compute_jacobian'] = False - prob.setup(check=False) + prob.setup() prob.run_model() @@ -265,20 +262,20 @@ def test_mixed(self): def test_missing_state_warning(self): # Testing Broyden on a 5 state case split among 3 vars. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('c', 0.01)) + model.add_subsystem('p1', om.IndepVarComp('c', 0.01)) model.add_subsystem('mixed', MixedEquation()) model.connect('p1.c', 'mixed.c') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['mixed.x12'] model.nonlinear_solver.options['maxiter'] = 15 model.nonlinear_solver.options['compute_jacobian'] = False - prob.setup(check=False) + prob.setup() msg = "The following states are not covered by a solver, and may have been " \ "omitted from the BroydenSolver 'state_vars': mixed.x3, mixed.x45" @@ -287,20 +284,20 @@ def test_missing_state_warning(self): prob.run_model() # Try again with promoted names. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('c', 0.01)) + model.add_subsystem('p1', om.IndepVarComp('c', 0.01)) model.add_subsystem('mixed', MixedEquation(), promotes=['*']) model.connect('p1.c', 'c') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['x12'] model.nonlinear_solver.options['maxiter'] = 15 model.nonlinear_solver.options['compute_jacobian'] = False - prob.setup(check=False) + prob.setup() msg = "The following states are not covered by a solver, and may have been " \ "omitted from the BroydenSolver 'state_vars': x3, x45" @@ -311,20 +308,20 @@ def test_missing_state_warning(self): def test_mixed_promoted_vars(self): # Testing Broyden on a 5 state case split among 3 vars. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('c', 0.01)) + model.add_subsystem('p1', om.IndepVarComp('c', 0.01)) model.add_subsystem('mixed', MixedEquation(), promotes_outputs=['x12', 'x3', 'x45']) model.connect('p1.c', 'mixed.c') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['x12', 'x3', 'x45'] model.nonlinear_solver.options['maxiter'] = 15 model.nonlinear_solver.options['compute_jacobian'] = False - prob.setup(check=False) + prob.setup() prob.run_model() @@ -335,20 +332,20 @@ def test_mixed_promoted_vars(self): def test_mixed_jacobian(self): # Testing Broyden on a 5 state case split among 3 vars. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('c', 0.01)) + model.add_subsystem('p1', om.IndepVarComp('c', 0.01)) model.add_subsystem('mixed', MixedEquation()) model.connect('p1.c', 'mixed.c') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['mixed.x12', 'mixed.x3', 'mixed.x45'] model.nonlinear_solver.options['maxiter'] = 15 - model.nonlinear_solver.linear_solver = DirectSolver() + model.nonlinear_solver.linear_solver = om.DirectSolver() - prob.setup(check=False) + prob.setup() prob.run_model() @@ -363,14 +360,14 @@ def test_mixed_jacobian(self): def test_simple_sellar_jacobian(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command'] - model.nonlinear_solver.linear_solver = DirectSolver(assemble_jac=False) + model.nonlinear_solver.linear_solver = om.DirectSolver(assemble_jac=False) prob.run_model() @@ -384,13 +381,13 @@ def test_simple_sellar_jacobian(self): def test_simple_sellar_jacobian_assembled(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() - model.nonlinear_solver.linear_solver = DirectSolver(assemble_jac=True) + model.nonlinear_solver.linear_solver = om.DirectSolver(assemble_jac=True) prob.run_model() @@ -404,14 +401,14 @@ def test_simple_sellar_jacobian_assembled(self): def test_simple_sellar_jacobian_assembled_dense(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() model.options['assembled_jac_type'] = 'dense' - model.nonlinear_solver.linear_solver = DirectSolver(assemble_jac=True) + model.nonlinear_solver.linear_solver = om.DirectSolver(assemble_jac=True) prob.run_model() @@ -425,13 +422,13 @@ def test_simple_sellar_jacobian_assembled_dense(self): def test_simple_sellar_full(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() - model.nonlinear_solver.linear_solver = DirectSolver() + model.nonlinear_solver.linear_solver = om.DirectSolver() model.nonlinear_solver.options['compute_jacobian'] = False prob.run_model() @@ -446,13 +443,13 @@ def test_simple_sellar_full(self): def test_simple_sellar_full_jacobian(self): # Test top level Sellar (i.e., not grouped). - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) - prob.setup(check=False) + prob.setup() - model.nonlinear_solver.linear_solver = DirectSolver() + model.nonlinear_solver.linear_solver = om.DirectSolver() prob.run_model() @@ -466,22 +463,22 @@ def test_simple_sellar_full_jacobian(self): def test_jacobian_update_converge_limit(self): # This model needs jacobian updates to converge. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.array([0, 20.0]))) + model.add_subsystem('p1', om.IndepVarComp('x', np.array([0, 20.0]))) model.add_subsystem('comp', SpedicatoHuang()) model.connect('p1.x', 'comp.x') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['comp.y'] model.nonlinear_solver.options['maxiter'] = 20 model.nonlinear_solver.options['max_converge_failures'] = 1 model.nonlinear_solver.options['diverge_limit'] = np.inf - model.nonlinear_solver.linear_solver = DirectSolver() + model.nonlinear_solver.linear_solver = om.DirectSolver() - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=2) prob.run_model() @@ -491,21 +488,21 @@ def test_jacobian_update_converge_limit(self): def test_jacobian_update_diverge_limit(self): # This model needs jacobian updates to converge. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', np.array([0, 20.0]))) + model.add_subsystem('p1', om.IndepVarComp('x', np.array([0, 20.0]))) model.add_subsystem('comp', SpedicatoHuang()) model.connect('p1.x', 'comp.x') - model.nonlinear_solver = BroydenSolver() + model.nonlinear_solver = om.BroydenSolver() model.nonlinear_solver.options['state_vars'] = ['comp.y'] model.nonlinear_solver.options['maxiter'] = 20 model.nonlinear_solver.options['diverge_limit'] = 0.5 - model.nonlinear_solver.linear_solver = DirectSolver() + model.nonlinear_solver.linear_solver = om.DirectSolver() - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=2) prob.run_model() @@ -513,23 +510,23 @@ def test_jacobian_update_diverge_limit(self): assert_rel_error(self, prob['comp.y'], np.array([-36.26230985, 10.20857237, -54.17658612]), 1e-6) def test_backtracking(self): - top = Problem() - top.model.add_subsystem('px', IndepVarComp('x', 1.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 1.0)) top.model.add_subsystem('comp', ImplCompTwoStates()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = BroydenSolver() + top.model.nonlinear_solver = om.BroydenSolver() top.model.nonlinear_solver.options['maxiter'] = 25 top.model.nonlinear_solver.options['diverge_limit'] = 0.5 top.model.nonlinear_solver.options['state_vars'] = ['comp.y', 'comp.z'] - top.model.linear_solver = DirectSolver() + top.model.linear_solver = om.DirectSolver() - top.setup(check=False) - top.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='vector') + top.setup() + top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector') # Setup again because we assigned a new linesearch - top.setup(check=False) + top.setup() top.set_solver_print(level=2) # Test lower bound: should go to the lower bound and stall @@ -549,26 +546,28 @@ def test_backtracking(self): def test_cs_around_broyden(self): # Basic sellar test. - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('sub', Group(), promotes=['*']) + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), + promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), + promotes=['con2', 'y2']) - sub.nonlinear_solver = BroydenSolver() - sub.linear_solver = DirectSolver() - model.linear_solver = DirectSolver() + sub.nonlinear_solver = om.BroydenSolver() + sub.linear_solver = om.DirectSolver() + model.linear_solver = om.DirectSolver() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -589,26 +588,26 @@ def test_cs_around_broyden(self): def test_cs_around_broyden_compute_jac(self): # Basic sellar test. - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('sub', Group(), promotes=['*']) + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = BroydenSolver() - sub.linear_solver = DirectSolver(assemble_jac=False) - model.linear_solver = DirectSolver(assemble_jac=False) + sub.nonlinear_solver = om.BroydenSolver() + sub.linear_solver = om.DirectSolver(assemble_jac=False) + model.linear_solver = om.DirectSolver(assemble_jac=False) prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -631,26 +630,26 @@ def test_cs_around_broyden_compute_jac(self): def test_cs_around_broyden_compute_jac_dense(self): # Basic sellar test. - prob = Problem() + prob = om.Problem() model = prob.model - sub = model.add_subsystem('sub', Group(), promotes=['*']) + sub = model.add_subsystem('sub', om.Group(), promotes=['*']) - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - sub.nonlinear_solver = BroydenSolver() - sub.linear_solver = DirectSolver() - model.linear_solver = DirectSolver() + sub.nonlinear_solver = om.BroydenSolver() + sub.linear_solver = om.DirectSolver() + model.linear_solver = om.DirectSolver() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) @@ -674,12 +673,12 @@ def test_cs_around_broyden_compute_jac_dense(self): class TestBryodenFeature(unittest.TestCase): def test_sellar(self): - from openmdao.api import Problem, LinearRunOnce, IndepVarComp, BroydenSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarStateConnection - prob = Problem() - model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(), - linear_solver=LinearRunOnce()) + prob = om.Problem() + model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(), + linear_solver=om.LinearRunOnce()) prob.setup() @@ -693,15 +692,14 @@ def test_sellar(self): assert_rel_error(self, prob['state_eq.y2_command'], 12.05848819, .00001) def test_circuit(self): - from openmdao.api import Group, BroydenSolver, DirectSolver, Problem, IndepVarComp, LinearBlockGS - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -709,14 +707,14 @@ def test_circuit(self): p.setup() - # Replace existing solver with BroydenSolver - model.circuit.nonlinear_solver = BroydenSolver() + # Replace existing solver with om.BroydenSolver + model.circuit.nonlinear_solver = om.BroydenSolver() model.circuit.nonlinear_solver.options['maxiter'] = 20 # Specify states for Broyden to solve model.circuit.nonlinear_solver.options['state_vars'] = ['n1.V', 'n2.V'] - model.nonlinear_solver.linear_solver = LinearBlockGS() + model.nonlinear_solver.linear_solver = om.LinearBlockGS() # set some initial guesses p['circuit.n1.V'] = 10. @@ -732,15 +730,14 @@ def test_circuit(self): assert_rel_error(self, p['circuit.R1.I'] + p['circuit.D1.I'], .1, 1e-6) def test_circuit_options(self): - from openmdao.api import Group, BroydenSolver, DirectSolver, Problem, IndepVarComp - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -749,7 +746,7 @@ def test_circuit_options(self): p.setup() # Replace existing solver with BroydenSolver - model.circuit.nonlinear_solver = BroydenSolver() + model.circuit.nonlinear_solver = om.BroydenSolver() model.circuit.nonlinear_solver.options['maxiter'] = 20 model.circuit.nonlinear_solver.options['converge_limit'] = 0.1 model.circuit.nonlinear_solver.options['max_converge_failures'] = 1 @@ -771,15 +768,14 @@ def test_circuit_options(self): assert_rel_error(self, p['circuit.R1.I'] + p['circuit.D1.I'], .1, 1e-6) def test_circuit_full(self): - from openmdao.api import Group, BroydenSolver, DirectSolver, Problem, IndepVarComp - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -788,9 +784,9 @@ def test_circuit_full(self): p.setup() # Replace existing solver with BroydenSolver - model.circuit.nonlinear_solver = BroydenSolver() + model.circuit.nonlinear_solver = om.BroydenSolver() model.circuit.nonlinear_solver.options['maxiter'] = 20 - model.circuit.nonlinear_solver.linear_solver = DirectSolver() + model.circuit.nonlinear_solver.linear_solver = om.DirectSolver() # set some initial guesses p['circuit.n1.V'] = 10. @@ -805,5 +801,6 @@ def test_circuit_full(self): # sanity check: should sum to .1 Amps assert_rel_error(self, p['circuit.R1.I'] + p['circuit.D1.I'], .1, 1e-6) + if __name__ == "__main__": unittest.main() diff --git a/openmdao/solvers/nonlinear/tests/test_newton.py b/openmdao/solvers/nonlinear/tests/test_newton.py index 4dd668e39f..41e51483c3 100644 --- a/openmdao/solvers/nonlinear/tests/test_newton.py +++ b/openmdao/solvers/nonlinear/tests/test_newton.py @@ -4,11 +4,8 @@ import numpy as np -from openmdao.api import Group, Problem, IndepVarComp, LinearBlockGS, \ - NewtonSolver, ExecComp, ScipyKrylov, ImplicitComponent, \ - DirectSolver, AnalysisError +import openmdao.api as om from openmdao.core.tests.test_discrete import InternalDiscreteGroup -from openmdao.solvers.linesearch.backtracking import ArmijoGoldsteinLS from openmdao.test_suite.components.double_sellar import DoubleSellar, DoubleSellarImplicit, \ SubSellar from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStates @@ -22,14 +19,14 @@ class TestNewton(unittest.TestCase): def test_specify_newton_linear_solver_in_system(self): - my_newton = NewtonSolver() - my_newton.linear_solver = DirectSolver() + my_newton = om.NewtonSolver() + my_newton.linear_solver = om.DirectSolver() - prob = Problem(model=SellarDerivatives(nonlinear_solver=my_newton)) + prob = om.Problem(model=SellarDerivatives(nonlinear_solver=my_newton)) prob.setup() - self.assertIsInstance(prob.model.nonlinear_solver.linear_solver, DirectSolver) + self.assertIsInstance(prob.model.nonlinear_solver.linear_solver, om.DirectSolver) prob.run_model() @@ -40,12 +37,12 @@ def test_feature_newton_basic(self): """ Feature test for slotting a Newton solver and using it to solve Sellar. """ - from openmdao.api import Problem, NewtonSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem(model=SellarDerivatives(nonlinear_solver=NewtonSolver())) + prob = om.Problem(model=SellarDerivatives(nonlinear_solver=om.NewtonSolver())) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -54,9 +51,9 @@ def test_feature_newton_basic(self): def test_sellar_grouped(self): # Tests basic Newton solution on Sellar in a subgroup - prob = Problem(model=SellarDerivativesGrouped(nonlinear_solver=NewtonSolver())) + prob = om.Problem(model=SellarDerivativesGrouped(nonlinear_solver=om.NewtonSolver())) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -69,9 +66,9 @@ def test_sellar_grouped(self): def test_sellar(self): # Just tests Newton on Sellar with FD derivs. - prob = Problem(model=SellarNoDerivatives(nonlinear_solver=NewtonSolver())) + prob = om.Problem(model=SellarNoDerivatives(nonlinear_solver=om.NewtonSolver())) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -81,20 +78,20 @@ def test_sellar(self): self.assertLess(prob.model.nonlinear_solver._iter_count, 8) def test_line_search_deprecated(self): - top = Problem() - top.model.add_subsystem('px', IndepVarComp('x', 1.0)) + top = om.Problem() + top.model.add_subsystem('px', om.IndepVarComp('x', 1.0)) top.model.add_subsystem('comp', ImplCompTwoStates()) top.model.connect('px.x', 'comp.x') - top.model.nonlinear_solver = NewtonSolver() + top.model.nonlinear_solver = om.NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 - top.model.linear_solver = ScipyKrylov() + top.model.linear_solver = om.ScipyKrylov() msg = "The 'line_search' attribute provides backwards compatibility with OpenMDAO 1.x ; " \ "use 'linesearch' instead." with assert_warning(DeprecationWarning, msg): - top.model.nonlinear_solver.line_search = ArmijoGoldsteinLS(bound_enforcement='vector') + top.model.nonlinear_solver.line_search = om.ArmijoGoldsteinLS(bound_enforcement='vector') with assert_warning(DeprecationWarning, msg): ls = top.model.nonlinear_solver.line_search @@ -102,7 +99,7 @@ def test_line_search_deprecated(self): ls.options['maxiter'] = 10 ls.options['alpha'] = 1.0 - top.setup(check=False) + top.setup() # Test lower bound: should go to the lower bound and stall top['px.x'] = 2.0 @@ -123,10 +120,11 @@ def test_sellar_derivs(self): # Also, piggybacked testing that makes sure we only call apply_nonlinear # on the head component behind the cycle break. - prob = Problem() - prob.model = SellarDerivatives(nonlinear_solver=NewtonSolver(), linear_solver=LinearBlockGS()) + prob = om.Problem() + prob.model = SellarDerivatives(nonlinear_solver=om.NewtonSolver(), + linear_solver=om.LinearBlockGS()) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -146,9 +144,9 @@ def test_sellar_derivs(self): def test_sellar_derivs_with_Lin_GS(self): - prob = Problem(model=SellarDerivatives(nonlinear_solver=NewtonSolver())) + prob = om.Problem(model=SellarDerivatives(nonlinear_solver=om.NewtonSolver())) - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -161,10 +159,10 @@ def test_sellar_derivs_with_Lin_GS(self): def test_sellar_state_connection(self): # Sellar model closes loop with state connection instead of a cycle. - prob = Problem(model=SellarStateConnection(nonlinear_solver=NewtonSolver())) + prob = om.Problem(model=SellarStateConnection(nonlinear_solver=om.NewtonSolver())) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -176,11 +174,11 @@ def test_sellar_state_connection(self): def test_sellar_state_connection_fd_system(self): # Sellar model closes loop with state connection instead of a cycle. # This test is just fd. - prob = Problem(model=SellarStateConnection(nonlinear_solver=NewtonSolver())) + prob = om.Problem(model=SellarStateConnection(nonlinear_solver=om.NewtonSolver())) prob.model.approx_totals(method='fd') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -192,18 +190,18 @@ def test_sellar_state_connection_fd_system(self): def test_sellar_specify_linear_solver(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) proms = ['x', 'z', 'y1', 'state_eq.y2_actual', 'state_eq.y2_command', 'd1.y2', 'd2.y2'] - sub = model.add_subsystem('sub', Group(), promotes=proms) + sub = model.add_subsystem('sub', om.Group(), promotes=proms) - subgrp = sub.add_subsystem('state_eq_group', Group(), + subgrp = sub.add_subsystem('state_eq_group', om.Group(), promotes=['state_eq.y2_actual', 'state_eq.y2_command']) - subgrp.linear_solver = ScipyKrylov() + subgrp.linear_solver = om.ScipyKrylov() subgrp.add_subsystem('state_eq', StateConnection()) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1']) @@ -212,28 +210,28 @@ def test_sellar_specify_linear_solver(self): model.connect('state_eq.y2_command', 'd1.y2') model.connect('d2.y2', 'state_eq.y2_actual') - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['x', 'z', 'y1', 'obj']) model.connect('d2.y2', 'obj_cmp.y2') - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2']) model.connect('d2.y2', 'con_cmp2.y2') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() # Use bad settings for this one so that problem doesn't converge. # That way, we test that we are really using Newton's Lin Solver # instead. - model.linear_solver = ScipyKrylov() + model.linear_solver = om.ScipyKrylov() model.linear_solver.options['maxiter'] = 1 # The good solver - model.nonlinear_solver.linear_solver = ScipyKrylov() + model.nonlinear_solver.linear_solver = om.ScipyKrylov() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -246,18 +244,18 @@ def test_sellar_specify_linear_solver(self): def test_sellar_specify_linear_direct_solver(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) proms = ['x', 'z', 'y1', 'state_eq.y2_actual', 'state_eq.y2_command', 'd1.y2', 'd2.y2'] - sub = model.add_subsystem('sub', Group(), promotes=proms) + sub = model.add_subsystem('sub', om.Group(), promotes=proms) - subgrp = sub.add_subsystem('state_eq_group', Group(), + subgrp = sub.add_subsystem('state_eq_group', om.Group(), promotes=['state_eq.y2_actual', 'state_eq.y2_command']) - subgrp.linear_solver = ScipyKrylov() + subgrp.linear_solver = om.ScipyKrylov() subgrp.add_subsystem('state_eq', StateConnection()) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1']) @@ -266,28 +264,28 @@ def test_sellar_specify_linear_direct_solver(self): model.connect('state_eq.y2_command', 'd1.y2') model.connect('d2.y2', 'state_eq.y2_actual') - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['x', 'z', 'y1', 'obj']) model.connect('d2.y2', 'obj_cmp.y2') - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2']) model.connect('d2.y2', 'con_cmp2.y2') - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() # Use bad settings for this one so that problem doesn't converge. # That way, we test that we are really using Newton's Lin Solver # instead. - sub.linear_solver = ScipyKrylov() + sub.linear_solver = om.ScipyKrylov() sub.linear_solver.options['maxiter'] = 1 # The good solver - model.nonlinear_solver.linear_solver = DirectSolver() + model.nonlinear_solver.linear_solver = om.DirectSolver() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -298,23 +296,23 @@ def test_sellar_specify_linear_direct_solver(self): self.assertEqual(model.linear_solver._iter_count, 0) def test_solve_subsystems_basic(self): - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver() + g1.nonlinear_solver = om.NewtonSolver() g1.nonlinear_solver.options['rtol'] = 1.0e-5 - g1.linear_solver = DirectSolver(assemble_jac=True) + g1.linear_solver = om.DirectSolver(assemble_jac=True) g1.options['assembled_jac_type'] = 'dense' g2 = model.g2 - g2.nonlinear_solver = NewtonSolver() + g2.nonlinear_solver = om.NewtonSolver() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver(assemble_jac=True) + g2.linear_solver = om.DirectSolver(assemble_jac=True) g2.options['assembled_jac_type'] = 'dense' - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' model.nonlinear_solver.options['solve_subsystems'] = True @@ -328,21 +326,21 @@ def test_solve_subsystems_basic(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_basic_csc(self): - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) g1.options['assembled_jac_type'] = 'dense' - g1.linear_solver = DirectSolver(assemble_jac=True) + g1.linear_solver = om.DirectSolver(assemble_jac=True) g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver(assemble_jac=True) + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver(assemble_jac=True) g2.options['assembled_jac_type'] = 'dense' - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) prob.setup() prob.run_model() @@ -353,19 +351,19 @@ def test_solve_subsystems_basic_csc(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_basic_dense_jac(self): - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -377,19 +375,19 @@ def test_solve_subsystems_basic_dense_jac(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_basic_dense_jac_scaling(self): - prob = Problem(model=DoubleSellar(units=None, scaling=True)) + prob = om.Problem(model=DoubleSellar(units=None, scaling=True)) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -401,19 +399,19 @@ def test_solve_subsystems_basic_dense_jac_scaling(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_basic_dense_jac_units_scaling(self): - prob = Problem(model=DoubleSellar(units=True, scaling=True)) + prob = om.Problem(model=DoubleSellar(units=True, scaling=True)) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -425,19 +423,19 @@ def test_solve_subsystems_basic_dense_jac_units_scaling(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_assembled_jac_top(self): - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -449,19 +447,19 @@ def test_solve_subsystems_assembled_jac_top(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_assembled_jac_top_csc(self): - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) prob.setup() prob.run_model() @@ -472,19 +470,19 @@ def test_solve_subsystems_assembled_jac_top_csc(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_assembled_jac_top_implicit(self): - prob = Problem(model=DoubleSellarImplicit()) + prob = om.Problem(model=DoubleSellarImplicit()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -496,19 +494,19 @@ def test_solve_subsystems_assembled_jac_top_implicit(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_assembled_jac_top_implicit_scaling(self): - prob = Problem(model=DoubleSellarImplicit(scaling=True)) + prob = om.Problem(model=DoubleSellarImplicit(scaling=True)) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -520,19 +518,19 @@ def test_solve_subsystems_assembled_jac_top_implicit_scaling(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_assembled_jac_top_implicit_scaling_units(self): - prob = Problem(model=DoubleSellarImplicit(units=True, scaling=True)) + prob = om.Problem(model=DoubleSellarImplicit(units=True, scaling=True)) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver() + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver(solve_subsystems=True) - model.linear_solver = ScipyKrylov(assemble_jac=True) + model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) + model.linear_solver = om.ScipyKrylov(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' prob.setup() @@ -544,20 +542,20 @@ def test_solve_subsystems_assembled_jac_top_implicit_scaling_units(self): assert_rel_error(self, prob['g2.y2'], 0.80, .00001) def test_solve_subsystems_assembled_jac_subgroup(self): - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g1.linear_solver = DirectSolver(assemble_jac=True) + g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g1.linear_solver = om.DirectSolver(assemble_jac=True) model.options['assembled_jac_type'] = 'dense' g2 = model.g2 - g2.nonlinear_solver = NewtonSolver(rtol=1.0e-5) - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5) + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() prob.setup() prob.run_model() @@ -571,7 +569,7 @@ def test_solve_subsystems_internals(self): # Here we test that this feature is doing what it should do by counting the # number of calls in various places. - class CountNewton(NewtonSolver): + class CountNewton(om.NewtonSolver): """ This version of Newton also counts how many times it runs in total.""" def __init__(self, **kwargs): @@ -582,7 +580,7 @@ def _single_iteration(self): super(CountNewton, self)._single_iteration() self.total_count += 1 - class CountDS(DirectSolver): + class CountDS(om.DirectSolver): """ This version of Newton also counts how many times it linearizes""" def __init__(self, **kwargs): @@ -593,7 +591,7 @@ def _linearize(self): super(CountDS, self)._linearize() self.lin_count += 1 - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model # each SubSellar group converges itself @@ -605,11 +603,11 @@ def _linearize(self): g2 = model.g2 g2.nonlinear_solver = CountNewton() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver() + g2.linear_solver = om.DirectSolver() # Converge the outer loop with Gauss Seidel, with a looser tolerance. - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() # Enfore behavior: max_sub_solves = 0 means we run once during init @@ -626,7 +624,7 @@ def _linearize(self): self.assertEqual(g2.nonlinear_solver.total_count, 2) self.assertEqual(g1.linear_solver.lin_count, 2) - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model # each SubSellar group converges itself @@ -638,11 +636,11 @@ def _linearize(self): g2 = model.g2 g2.nonlinear_solver = CountNewton() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver() + g2.linear_solver = om.DirectSolver() # Converge the outer loop with Gauss Seidel, with a looser tolerance. - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() # Enforce Behavior: baseline @@ -659,7 +657,7 @@ def _linearize(self): self.assertEqual(g2.nonlinear_solver.total_count, 5) self.assertEqual(g1.linear_solver.lin_count, 5) - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model # each SubSellar group converges itself @@ -671,11 +669,11 @@ def _linearize(self): g2 = model.g2 g2.nonlinear_solver = CountNewton() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver() + g2.linear_solver = om.DirectSolver() # Converge the outer loop with Gauss Seidel, with a looser tolerance. - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() # Enfore behavior: max_sub_solves = 1 means we run during init and first iteration of iter_execute @@ -696,7 +694,7 @@ def test_maxiter_one(self): # Fix bug when maxiter was set to 1. # This bug caused linearize to run before apply in this case. - class ImpComp(ImplicitComponent): + class ImpComp(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) @@ -721,13 +719,13 @@ def linearize(self, inputs, outputs, jacobian): if not self.applied: raise RuntimeError("Bug! Linearize called before Apply!") - prob = Problem() + prob = om.Problem() root = prob.model - root.add_subsystem('p1', IndepVarComp('a', 1.0)) + root.add_subsystem('p1', om.IndepVarComp('a', 1.0)) root.add_subsystem('comp', ImpComp()) root.connect('p1.a', 'comp.a') - root.nonlinear_solver = NewtonSolver() + root.nonlinear_solver = om.NewtonSolver() root.nonlinear_solver.options['maxiter'] = 1 prob.set_solver_print(level=0) @@ -737,17 +735,18 @@ def linearize(self, inputs, outputs, jacobian): def test_err_on_maxiter(self): # Raise AnalysisError when it fails to converge - prob = Problem() - nlsolver = NewtonSolver() - prob.model = SellarDerivatives(nonlinear_solver=nlsolver, linear_solver=LinearBlockGS()) + prob = om.Problem() + nlsolver = om.NewtonSolver() + prob.model = SellarDerivatives(nonlinear_solver=nlsolver, + linear_solver=om.LinearBlockGS()) nlsolver.options['err_on_maxiter'] = True nlsolver.options['maxiter'] = 1 - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) - with self.assertRaises(AnalysisError) as context: + with self.assertRaises(om.AnalysisError) as context: prob.run_driver() msg = "Solver 'NL: Newton' on system '' failed to converge in 1 iterations." @@ -755,7 +754,7 @@ def test_err_on_maxiter(self): def test_relevancy_for_newton(self): - class TestImplCompSimple(ImplicitComponent): + class TestImplCompSimple(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) @@ -773,12 +772,12 @@ def linearize(self, inputs, outputs, jacobian): jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) model.add_subsystem('icomp', TestImplCompSimple()) - model.add_subsystem('ecomp', ExecComp('y = x*p', p=1.0)) + model.add_subsystem('ecomp', om.ExecComp('y = x*p', p=1.0)) model.connect('p1.x', 'ecomp.x') model.connect('icomp.x', 'ecomp.p') @@ -786,10 +785,10 @@ def linearize(self, inputs, outputs, jacobian): model.add_design_var('p1.x', 3.0) model.add_objective('ecomp.y') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() - prob.setup(check=False) + prob.setup() prob.run_model() @@ -802,28 +801,28 @@ class TestNewtonFeatures(unittest.TestCase): def test_feature_basic(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver() + model.nonlinear_solver = om.NewtonSolver() prob.setup() @@ -835,28 +834,28 @@ def test_feature_basic(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() - nlgbs = model.nonlinear_solver = NewtonSolver() + nlgbs = model.nonlinear_solver = om.NewtonSolver() nlgbs.options['maxiter'] = 2 prob.setup() @@ -869,28 +868,28 @@ def test_feature_maxiter(self): def test_feature_rtol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() - nlgbs = model.nonlinear_solver = NewtonSolver() + nlgbs = model.nonlinear_solver = om.NewtonSolver() nlgbs.options['rtol'] = 1e-3 prob.setup() @@ -903,28 +902,28 @@ def test_feature_rtol(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() - nlgbs = model.nonlinear_solver = NewtonSolver() + nlgbs = model.nonlinear_solver = om.NewtonSolver() nlgbs.options['atol'] = 1e-4 prob.setup() @@ -937,32 +936,31 @@ def test_feature_atol(self): def test_feature_linear_solver(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, \ - ExecComp, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() - nlgbs = model.nonlinear_solver = NewtonSolver() + nlgbs = model.nonlinear_solver = om.NewtonSolver() - nlgbs.linear_solver = DirectSolver() + nlgbs.linear_solver = om.DirectSolver() prob.setup() @@ -974,10 +972,10 @@ def test_feature_linear_solver(self): def test_feature_max_sub_solves(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp, DirectSolver, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.double_sellar import SubSellar - prob = Problem() + prob = om.Problem() model = prob.model model.add_subsystem('g1', SubSellar()) @@ -987,21 +985,21 @@ def test_feature_max_sub_solves(self): model.connect('g2.y2', 'g1.x') # Converge the outer loop with Gauss Seidel, with a looser tolerance. - model.nonlinear_solver = NewtonSolver() - model.linear_solver = DirectSolver() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.DirectSolver() g1 = model.g1 - g1.nonlinear_solver = NewtonSolver() + g1.nonlinear_solver = om.NewtonSolver() g1.nonlinear_solver.options['rtol'] = 1.0e-5 - g1.linear_solver = DirectSolver() + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver() + g2.nonlinear_solver = om.NewtonSolver() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver() + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 @@ -1012,29 +1010,28 @@ def test_feature_max_sub_solves(self): def test_feature_err_on_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, \ - ExecComp, AnalysisError, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() - nlgbs = model.nonlinear_solver = NewtonSolver() + nlgbs = model.nonlinear_solver = om.NewtonSolver() nlgbs.options['maxiter'] = 1 nlgbs.options['err_on_maxiter'] = True @@ -1042,28 +1039,28 @@ def test_feature_err_on_maxiter(self): try: prob.run_model() - except AnalysisError: + except om.AnalysisError: pass def test_solve_subsystems_basic(self): - from openmdao.api import Problem, NewtonSolver, DirectSolver, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.double_sellar import DoubleSellar - prob = Problem(model=DoubleSellar()) + prob = om.Problem(model=DoubleSellar()) model = prob.model g1 = model.g1 - g1.nonlinear_solver = NewtonSolver() + g1.nonlinear_solver = om.NewtonSolver() g1.nonlinear_solver.options['rtol'] = 1.0e-5 - g1.linear_solver = DirectSolver() + g1.linear_solver = om.DirectSolver() g2 = model.g2 - g2.nonlinear_solver = NewtonSolver() + g2.nonlinear_solver = om.NewtonSolver() g2.nonlinear_solver.options['rtol'] = 1.0e-5 - g2.linear_solver = DirectSolver() + g2.linear_solver = om.DirectSolver() - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True diff --git a/openmdao/solvers/nonlinear/tests/test_nonlinear_block_gs.py b/openmdao/solvers/nonlinear/tests/test_nonlinear_block_gs.py index 2143988663..353e5065a1 100644 --- a/openmdao/solvers/nonlinear/tests/test_nonlinear_block_gs.py +++ b/openmdao/solvers/nonlinear/tests/test_nonlinear_block_gs.py @@ -4,8 +4,7 @@ import numpy as np -from openmdao.api import Problem, NonlinearBlockGS, Group, ScipyKrylov, IndepVarComp, \ - ExecComp, AnalysisError +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.sellar import SellarDerivatives, \ @@ -17,26 +16,26 @@ class TestNLBGaussSeidel(unittest.TestCase): def test_feature_set_options(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() nlgbs.options['maxiter'] = 20 nlgbs.options['atol'] = 1e-6 @@ -52,26 +51,26 @@ def test_feature_set_options(self): def test_feature_basic(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() @@ -83,26 +82,26 @@ def test_feature_basic(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() nlgbs.options['maxiter'] = 2 prob.setup() @@ -115,26 +114,26 @@ def test_feature_maxiter(self): def test_feature_rtol(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives, SellarDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() nlgbs.options['rtol'] = 1e-3 prob.setup() @@ -147,26 +146,26 @@ def test_feature_rtol(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, IndepVarComp, ExecComp, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() nlgbs.options['atol'] = 1e-4 prob.setup() @@ -179,25 +178,25 @@ def test_feature_atol(self): def test_sellar(self): # Basic sellar test. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -212,26 +211,26 @@ def test_sellar(self): # With run_apply_linear, we execute the components more times. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() nlgbs.options['use_apply_nonlinear'] = True - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -247,32 +246,32 @@ def test_sellar(self): def test_sellar_analysis_error(self): # Tests Sellar behavior when AnalysisError is raised. - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - nlgbs = model.nonlinear_solver = NonlinearBlockGS() + nlgbs = model.nonlinear_solver = om.NonlinearBlockGS() nlgbs.options['maxiter'] = 2 nlgbs.options['err_on_maxiter'] = True - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) try: prob.run_model() - except AnalysisError as err: + except om.AnalysisError as err: self.assertEqual(str(err), "Solver 'NL: NLBGS' on system '' failed to converge in 2 iterations.") else: self.fail("expected AnalysisError") @@ -282,7 +281,7 @@ def test_sellar_group_nested(self): # solver couples them together through variable x. # This version has the indepvarcomps removed so we can connect them together. - class SellarModified(Group): + class SellarModified(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines with derivatives.""" @@ -292,12 +291,12 @@ def __init__(self): self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - self.nonlinear_solver = NonlinearBlockGS() - self.linear_solver = ScipyKrylov() + self.nonlinear_solver = om.NonlinearBlockGS() + self.linear_solver = om.ScipyKrylov() - prob = Problem() + prob = om.Problem() root = prob.model - root.nonlinear_solver = NonlinearBlockGS() + root.nonlinear_solver = om.NonlinearBlockGS() root.nonlinear_solver.options['maxiter'] = 20 root.add_subsystem('g1', SellarModified()) root.add_subsystem('g2', SellarModified()) @@ -305,7 +304,7 @@ def __init__(self): root.connect('g1.y2', 'g2.x') root.connect('g2.y2', 'g1.x') - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) prob.run_model() @@ -317,9 +316,9 @@ def __init__(self): def test_NLBGS_Aitken(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model - model.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() prob.setup() model.nonlinear_solver.options['use_aitken'] = True @@ -331,7 +330,7 @@ def test_NLBGS_Aitken(self): def test_NLBGS_Aitken_cs(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.approx_totals(method='cs', step=1e-10) @@ -352,7 +351,7 @@ def test_NLBGS_Aitken_cs(self): def test_NLBGS_cs(self): - prob = Problem(model=SellarDerivatives()) + prob = om.Problem(model=SellarDerivatives()) model = prob.model model.approx_totals(method='cs') @@ -381,16 +380,16 @@ def compute(self, inputs, outputs): super(ContrivedSellarDis1, self).compute(inputs, outputs) outputs['highly_nonlinear'] = 10*np.sin(10*inputs['y2']) - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', ContrivedSellarDis1(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2(), promotes=['z', 'y1', 'y2']) - nlbgs = model.nonlinear_solver = NonlinearBlockGS() + nlbgs = model.nonlinear_solver = om.NonlinearBlockGS() nlbgs.options['maxiter'] = 20 nlbgs.options['atol'] = 1e-6 diff --git a/openmdao/solvers/nonlinear/tests/test_nonlinear_block_jac.py b/openmdao/solvers/nonlinear/tests/test_nonlinear_block_jac.py index 5d29e9dc8c..229d033e97 100644 --- a/openmdao/solvers/nonlinear/tests/test_nonlinear_block_jac.py +++ b/openmdao/solvers/nonlinear/tests/test_nonlinear_block_jac.py @@ -4,9 +4,7 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, LinearBlockGS, ExplicitComponent, \ - AnalysisError, ParallelGroup, ExecComp -from openmdao.solvers.nonlinear.nonlinear_block_jac import NonlinearBlockJac +import openmdao.api as om from openmdao.test_suite.components.ae_tests import AEComp, AEDriver from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives from openmdao.utils.assert_utils import assert_rel_error @@ -23,27 +21,27 @@ class TestNLBlockJacobi(unittest.TestCase): def test_feature_basic(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockJac, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = LinearBlockGS() - model.nonlinear_solver = NonlinearBlockJac() + model.linear_solver = om.LinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockJac() prob.setup() @@ -55,28 +53,28 @@ def test_feature_basic(self): def test_feature_maxiter(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockJac, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() - nlgbs = model.nonlinear_solver = NonlinearBlockJac() + nlgbs = model.nonlinear_solver = om.NonlinearBlockJac() nlgbs.options['maxiter'] = 4 prob.setup() @@ -89,28 +87,28 @@ def test_feature_maxiter(self): def test_feature_rtol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockJac, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() - nlgbs = model.nonlinear_solver = NonlinearBlockJac() + nlgbs = model.nonlinear_solver = om.NonlinearBlockJac() nlgbs.options['rtol'] = 1e-3 prob.setup() @@ -123,28 +121,28 @@ def test_feature_rtol(self): def test_feature_atol(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockJac, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - model.linear_solver = LinearBlockGS() + model.linear_solver = om.LinearBlockGS() - nlgbs = model.nonlinear_solver = NonlinearBlockJac() + nlgbs = model.nonlinear_solver = om.NonlinearBlockJac() nlgbs.options['atol'] = 1e-2 prob.setup() @@ -162,18 +160,18 @@ class TestNonlinearBlockJacobiMPI(unittest.TestCase): @unittest.skipUnless(MPI, "MPI is not active.") def test_reraise_analylsis_error(self): - prob = Problem() - prob.model = model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.5)) - model.add_subsystem('p2', IndepVarComp('x', 3.0)) - sub = model.add_subsystem('sub', ParallelGroup()) + model.add_subsystem('p1', om.IndepVarComp('x', 0.5)) + model.add_subsystem('p2', om.IndepVarComp('x', 3.0)) + sub = model.add_subsystem('sub', om.ParallelGroup()) sub.add_subsystem('c1', AEComp()) sub.add_subsystem('c2', AEComp()) - sub.nonlinear_solver = NonlinearBlockJac() + sub.nonlinear_solver = om.NonlinearBlockJac() - model.add_subsystem('obj', ExecComp(['val = x1 + x2'])) + model.add_subsystem('obj', om.ExecComp(['val = x1 + x2'])) model.connect('p1.x', 'sub.c1.x') model.connect('p2.x', 'sub.c2.x') @@ -182,7 +180,7 @@ def test_reraise_analylsis_error(self): prob.driver = AEDriver() - prob.setup(check=False) + prob.setup() handled = prob.run_driver() self.assertTrue(handled) diff --git a/openmdao/solvers/nonlinear/tests/test_nonlinear_runonce.py b/openmdao/solvers/nonlinear/tests/test_nonlinear_runonce.py index 0ed985c5c6..7e54a0430a 100644 --- a/openmdao/solvers/nonlinear/tests/test_nonlinear_runonce.py +++ b/openmdao/solvers/nonlinear/tests/test_nonlinear_runonce.py @@ -2,9 +2,7 @@ import unittest -from openmdao.api import Problem, ScipyKrylov, IndepVarComp, Group, ExplicitComponent, \ - AnalysisError, ParallelGroup, ExecComp -from openmdao.solvers.nonlinear.nonlinear_runonce import NonlinearRunOnce +import openmdao.api as om from openmdao.test_suite.components.ae_tests import AEComp, AEDriver from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.groups.parallel_groups import ConvergeDivergeGroups @@ -21,15 +19,15 @@ class TestNonlinearRunOnceSolver(unittest.TestCase): def test_converge_diverge_groups(self): # Test derivatives for converge-diverge-groups topology. - prob = Problem() + prob = om.Problem() model = prob.model = ConvergeDivergeGroups() - model.linear_solver = ScipyKrylov() - model.nonlinear_solver = NonlinearRunOnce() + model.linear_solver = om.ScipyKrylov() + model.nonlinear_solver = om.NonlinearRunOnce() - model.g1.nonlinear_solver = NonlinearRunOnce() - model.g1.g2.nonlinear_solver = NonlinearRunOnce() - model.g3.nonlinear_solver = NonlinearRunOnce() + model.g1.nonlinear_solver = om.NonlinearRunOnce() + model.g1.g2.nonlinear_solver = om.NonlinearRunOnce() + model.g3.nonlinear_solver = om.NonlinearRunOnce() prob.set_solver_print(level=0) prob.setup(check=False, mode='fwd') @@ -40,7 +38,7 @@ def test_converge_diverge_groups(self): def test_undeclared_options(self): # Test that using options that should not exist in class cause an error - solver = NonlinearRunOnce() + solver = om.NonlinearRunOnce() msg = "\"Option '%s' cannot be set because it has not been declared.\"" @@ -51,17 +49,17 @@ def test_undeclared_options(self): self.assertEqual(str(context.exception), msg % option) def test_feature_solver(self): - from openmdao.api import Problem, Group, NonlinearRunOnce, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) - model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) + model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x']) + model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) - model.nonlinear_solver = NonlinearRunOnce() + model.nonlinear_solver = om.NonlinearRunOnce() prob.setup(check=False, mode='fwd') @@ -80,17 +78,17 @@ class TestNonlinearRunOnceSolverMPI(unittest.TestCase): @unittest.skipUnless(MPI, "MPI is not active.") def test_reraise_analylsis_error(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 0.5)) - model.add_subsystem('p2', IndepVarComp('x', 3.0)) - sub = model.add_subsystem('sub', ParallelGroup()) + model.add_subsystem('p1', om.IndepVarComp('x', 0.5)) + model.add_subsystem('p2', om.IndepVarComp('x', 3.0)) + sub = model.add_subsystem('sub', om.ParallelGroup()) sub.add_subsystem('c1', AEComp()) sub.add_subsystem('c2', AEComp()) - model.add_subsystem('obj', ExecComp(['val = x1 + x2'])) + model.add_subsystem('obj', om.ExecComp(['val = x1 + x2'])) model.connect('p1.x', 'sub.c1.x') model.connect('p2.x', 'sub.c2.x') @@ -99,7 +97,7 @@ def test_reraise_analylsis_error(self): prob.driver = AEDriver() - prob.setup(check=False) + prob.setup() handled = prob.run_driver() self.assertTrue(handled) diff --git a/openmdao/solvers/tests/test_solver_debug_print.py b/openmdao/solvers/tests/test_solver_debug_print.py index f6f6e00980..bfbaf6e8c5 100644 --- a/openmdao/solvers/tests/test_solver_debug_print.py +++ b/openmdao/solvers/tests/test_solver_debug_print.py @@ -15,14 +15,7 @@ import numpy as np -from openmdao.api import Problem, IndepVarComp, ExecComp, Group, BalanceComp, AnalysisError - -from openmdao.solvers.linear.direct import DirectSolver -from openmdao.solvers.nonlinear.broyden import BroydenSolver -from openmdao.solvers.nonlinear.newton import NewtonSolver -from openmdao.solvers.nonlinear.nonlinear_block_gs import NonlinearBlockGS -from openmdao.solvers.nonlinear.nonlinear_block_jac import NonlinearBlockJac - +import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit from openmdao.utils.assert_utils import assert_rel_error @@ -35,10 +28,10 @@ from openmdao.utils.assert_utils import SkipParameterized as parameterized nonlinear_solvers = [ - NonlinearBlockGS, - NonlinearBlockJac, - NewtonSolver, - BroydenSolver + om.NonlinearBlockGS, + om.NonlinearBlockJac, + om.NewtonSolver, + om.BroydenSolver ] @@ -98,11 +91,11 @@ def tearDown(self): [solver.__name__, solver] for solver in nonlinear_solvers ]) def test_solver_debug_print(self, name, solver): - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -158,15 +151,16 @@ def test_solver_debug_print(self, name, solver): def test_solver_debug_print_feature(self): from distutils.version import LooseVersion import numpy as np - from openmdao.api import Problem, IndepVarComp, NewtonSolver, AnalysisError + + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit from openmdao.utils.general_utils import printoptions - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -174,7 +168,7 @@ def test_solver_debug_print_feature(self): p.setup() - nl = model.circuit.nonlinear_solver = NewtonSolver() + nl = model.circuit.nonlinear_solver = om.NewtonSolver() nl.options['iprint'] = 2 nl.options['debug_print'] = True @@ -193,7 +187,7 @@ def test_solver_debug_print_feature(self): # run the model try: p.run_model() - except AnalysisError: + except om.AnalysisError: pass with open(self.filename, 'r') as f: @@ -222,18 +216,18 @@ def tearDown(self): pass def test_debug_after_raised_error(self): - prob = Problem() + prob = om.Problem() model = prob.model - comp = IndepVarComp() + comp = om.IndepVarComp() comp.add_output('dXdt:TAS', val=1.0) comp.add_output('accel_target', val=2.0) model.add_subsystem('des_vars', comp, promotes=['*']) - teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group()) - teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*']) + teg = model.add_subsystem('thrust_equilibrium_group', subsys=om.Group()) + teg.add_subsystem('dynamics', om.ExecComp('z = 2.0*thrust'), promotes=['*']) - thrust_bal = BalanceComp() + thrust_bal = om.BalanceComp() thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS', rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0) @@ -241,15 +235,15 @@ def test_debug_after_raised_error(self): promotes_inputs=['dXdt:TAS', 'accel_target'], promotes_outputs=['thrust']) - teg.linear_solver = DirectSolver() + teg.linear_solver = om.DirectSolver() - teg.nonlinear_solver = NewtonSolver() + teg.nonlinear_solver = om.NewtonSolver() teg.nonlinear_solver.options['solve_subsystems'] = True teg.nonlinear_solver.options['max_sub_solves'] = 1 teg.nonlinear_solver.options['atol'] = 1e-4 teg.nonlinear_solver.options['debug_print'] = True - prob.setup(check=False) + prob.setup() prob.set_solver_print(level=0) stdout = sys.stdout diff --git a/openmdao/solvers/tests/test_solver_features.py b/openmdao/solvers/tests/test_solver_features.py index 56ed8f63aa..c18ebf4d9a 100644 --- a/openmdao/solvers/tests/test_solver_features.py +++ b/openmdao/solvers/tests/test_solver_features.py @@ -2,12 +2,7 @@ import unittest -from openmdao.api import Problem -from openmdao.solvers.nonlinear.newton import NewtonSolver -from openmdao.solvers.nonlinear.nonlinear_block_gs import NonlinearBlockGS -from openmdao.solvers.linear.direct import DirectSolver -from openmdao.solvers.linear.scipy_iter_solver import ScipyKrylov -from openmdao.solvers.linear.linear_block_gs import LinearBlockGS +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error from openmdao.test_suite.components.sellar import SellarDerivatives @@ -17,19 +12,19 @@ class TestSolverFeatures(unittest.TestCase): def test_specify_solver(self): - from openmdao.api import Problem, NewtonSolver, ScipyKrylov, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() model = prob.model = SellarDerivatives() - model.nonlinear_solver = newton = NewtonSolver() + model.nonlinear_solver = newton = om.NewtonSolver() # using a different linear solver for Newton with a looser tolerance - newton.linear_solver = ScipyKrylov(atol=1e-4) + newton.linear_solver = om.ScipyKrylov(atol=1e-4) # used for analytic derivatives - model.linear_solver = DirectSolver() + model.linear_solver = om.DirectSolver() prob.setup() prob.run_model() @@ -38,25 +33,25 @@ def test_specify_solver(self): assert_rel_error(self, prob['y2'], 12.05848819, .00001) def test_specify_subgroup_solvers(self): - from openmdao.api import Problem, NewtonSolver, ScipyKrylov, DirectSolver, NonlinearBlockGS, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.double_sellar import DoubleSellar - prob = Problem() + prob = om.Problem() model = prob.model = DoubleSellar() # each SubSellar group converges itself g1 = model.g1 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = DirectSolver() # used for derivatives + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.DirectSolver() # used for derivatives g2 = model.g2 - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = DirectSolver() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.DirectSolver() # Converge the outer loop with Gauss Seidel, with a looser tolerance. - model.nonlinear_solver = NonlinearBlockGS(rtol=1.0e-5) - model.linear_solver = ScipyKrylov() - model.linear_solver.precon = LinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS(rtol=1.0e-5) + model.linear_solver = om.ScipyKrylov() + model.linear_solver.precon = om.LinearBlockGS() prob.setup() prob.run_model() diff --git a/openmdao/solvers/tests/test_solver_iprint.py b/openmdao/solvers/tests/test_solver_iprint.py index 28a9720150..9898ec426d 100644 --- a/openmdao/solvers/tests/test_solver_iprint.py +++ b/openmdao/solvers/tests/test_solver_iprint.py @@ -6,8 +6,7 @@ import numpy as np -from openmdao.api import Problem, NewtonSolver, ScipyKrylov, Group, PETScVector, \ - IndepVarComp, NonlinearBlockGS, NonlinearBlockJac, LinearBlockGS +import openmdao.api as om from openmdao.test_suite.components.double_sellar import SubSellar from openmdao.test_suite.components.sellar import SellarDerivatives @@ -18,16 +17,16 @@ class TestSolverPrint(unittest.TestCase): def test_feature_iprint_neg1(self): - from openmdao.api import Problem, NewtonSolver, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() prob.setup() - newton = prob.model.nonlinear_solver = NewtonSolver() - scipy = prob.model.linear_solver = ScipyKrylov() + newton = prob.model.nonlinear_solver = om.NewtonSolver() + scipy = prob.model.linear_solver = om.ScipyKrylov() newton.options['maxiter'] = 2 @@ -40,16 +39,16 @@ def test_feature_iprint_neg1(self): prob.run_model() def test_feature_iprint_0(self): - from openmdao.api import Problem, NewtonSolver, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() prob.setup() - newton = prob.model.nonlinear_solver = NewtonSolver() - scipy = prob.model.linear_solver = ScipyKrylov() + newton = prob.model.nonlinear_solver = om.NewtonSolver() + scipy = prob.model.linear_solver = om.ScipyKrylov() newton.options['maxiter'] = 1 @@ -62,16 +61,16 @@ def test_feature_iprint_0(self): prob.run_model() def test_feature_iprint_1(self): - from openmdao.api import Problem, NewtonSolver, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() prob.setup() - newton = prob.model.nonlinear_solver = NewtonSolver() - scipy = prob.model.linear_solver = ScipyKrylov() + newton = prob.model.nonlinear_solver = om.NewtonSolver() + scipy = prob.model.linear_solver = om.ScipyKrylov() newton.options['maxiter'] = 20 @@ -83,16 +82,16 @@ def test_feature_iprint_1(self): prob.run_model() def test_feature_iprint_2(self): - from openmdao.api import Problem, NewtonSolver, ScipyKrylov + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDerivatives - prob = Problem() + prob = om.Problem() prob.model = SellarDerivatives() prob.setup() - newton = prob.model.nonlinear_solver = NewtonSolver() - scipy = prob.model.linear_solver = ScipyKrylov() + newton = prob.model.nonlinear_solver = om.NewtonSolver() + scipy = prob.model.linear_solver = om.ScipyKrylov() newton.options['maxiter'] = 20 @@ -105,13 +104,13 @@ def test_feature_iprint_2(self): def test_hierarchy_iprint(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -119,35 +118,35 @@ def test_hierarchy_iprint(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = LinearBlockGS() + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.LinearBlockGS() - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = ScipyKrylov() - g2.linear_solver.precon = LinearBlockGS() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.ScipyKrylov() + g2.linear_solver.precon = om.LinearBlockGS() g2.linear_solver.precon.options['maxiter'] = 2 prob.set_solver_print(level=2) - prob.setup(check=False) + prob.setup() output = run_model(prob) # TODO: check output def test_hierarchy_iprint2(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -155,26 +154,26 @@ def test_hierarchy_iprint2(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NonlinearBlockGS() - g1.nonlinear_solver = NonlinearBlockGS() - g2.nonlinear_solver = NonlinearBlockGS() + model.nonlinear_solver = om.NonlinearBlockGS() + g1.nonlinear_solver = om.NonlinearBlockGS() + g2.nonlinear_solver = om.NonlinearBlockGS() prob.set_solver_print(level=2) - prob.setup(check=False) + prob.setup() output = run_model(prob) # TODO: check output def test_hierarchy_iprint3(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -182,15 +181,15 @@ def test_hierarchy_iprint3(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NonlinearBlockJac() - sub1.nonlinear_solver = NonlinearBlockJac() - sub2.nonlinear_solver = NonlinearBlockJac() - g1.nonlinear_solver = NonlinearBlockJac() - g2.nonlinear_solver = NonlinearBlockJac() + model.nonlinear_solver = om.NonlinearBlockJac() + sub1.nonlinear_solver = om.NonlinearBlockJac() + sub2.nonlinear_solver = om.NonlinearBlockJac() + g1.nonlinear_solver = om.NonlinearBlockJac() + g2.nonlinear_solver = om.NonlinearBlockJac() prob.set_solver_print(level=2) - prob.setup(check=False) + prob.setup() output = run_model(prob) # TODO: check output @@ -198,16 +197,16 @@ def test_hierarchy_iprint3(self): def test_feature_set_solver_print1(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.double_sellar import SubSellar - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -215,17 +214,17 @@ def test_feature_set_solver_print1(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = LinearBlockGS() + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.LinearBlockGS() - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = ScipyKrylov() - g2.linear_solver.precon = LinearBlockGS() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.ScipyKrylov() + g2.linear_solver.precon = om.LinearBlockGS() g2.linear_solver.precon.options['maxiter'] = 2 prob.set_solver_print(level=2) @@ -236,16 +235,16 @@ def test_feature_set_solver_print1(self): def test_feature_set_solver_print2(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.double_sellar import SubSellar - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -253,17 +252,17 @@ def test_feature_set_solver_print2(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = LinearBlockGS() + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.LinearBlockGS() - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = ScipyKrylov() - g2.linear_solver.precon = LinearBlockGS() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.ScipyKrylov() + g2.linear_solver.precon = om.LinearBlockGS() g2.linear_solver.precon.options['maxiter'] = 2 prob.set_solver_print(level=2) @@ -275,16 +274,16 @@ def test_feature_set_solver_print2(self): def test_feature_set_solver_print3(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, LinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.double_sellar import SubSellar - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -292,17 +291,17 @@ def test_feature_set_solver_print3(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = LinearBlockGS() + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.LinearBlockGS() - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = ScipyKrylov() - g2.linear_solver.precon = LinearBlockGS() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.ScipyKrylov() + g2.linear_solver.precon = om.LinearBlockGS() g2.linear_solver.precon.options['maxiter'] = 2 prob.set_solver_print(level=0) @@ -312,20 +311,20 @@ def test_feature_set_solver_print3(self): prob.run_model() -@unittest.skipUnless(PETScVector, "PETSc is required.") +@unittest.skipUnless(om.PETScVector, "PETSc is required.") class MPITests(unittest.TestCase): N_PROCS = 2 @unittest.skipUnless(MPI, "MPI is not active.") def test_hierarchy_iprint(self): - prob = Problem() + prob = om.Problem() model = prob.model - model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) - sub1 = model.add_subsystem('sub1', Group()) - sub2 = sub1.add_subsystem('sub2', Group()) + sub1 = model.add_subsystem('sub1', om.Group()) + sub2 = sub1.add_subsystem('sub2', om.Group()) g1 = sub2.add_subsystem('g1', SubSellar()) g2 = model.add_subsystem('g2', SubSellar()) @@ -333,22 +332,22 @@ def test_hierarchy_iprint(self): model.connect('sub1.sub2.g1.y2', 'g2.x') model.connect('g2.y2', 'sub1.sub2.g1.x') - model.nonlinear_solver = NewtonSolver() - model.linear_solver = ScipyKrylov() + model.nonlinear_solver = om.NewtonSolver() + model.linear_solver = om.ScipyKrylov() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 0 - g1.nonlinear_solver = NewtonSolver() - g1.linear_solver = LinearBlockGS() + g1.nonlinear_solver = om.NewtonSolver() + g1.linear_solver = om.LinearBlockGS() - g2.nonlinear_solver = NewtonSolver() - g2.linear_solver = ScipyKrylov() - g2.linear_solver.precon = LinearBlockGS() + g2.nonlinear_solver = om.NewtonSolver() + g2.linear_solver = om.ScipyKrylov() + g2.linear_solver.precon = om.LinearBlockGS() g2.linear_solver.precon.options['maxiter'] = 2 prob.set_solver_print(level=2) - prob.setup(check=False) + prob.setup() # Conclude setup but don't run model. prob.final_setup() diff --git a/openmdao/solvers/tests/test_solver_parametric_suite.py b/openmdao/solvers/tests/test_solver_parametric_suite.py index bc04ebefd2..d2e46cfcbb 100644 --- a/openmdao/solvers/tests/test_solver_parametric_suite.py +++ b/openmdao/solvers/tests/test_solver_parametric_suite.py @@ -55,7 +55,7 @@ def test_direct_solver_comp(self): prob.model.linear_solver = DirectSolver(assemble_jac=jac in ('csc','dense')) prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y'], [-1., 1.]) @@ -80,7 +80,7 @@ def test_direct_solver_group(self): """ prob = Problem(model=TestImplicitGroup(lnSolverClass=DirectSolver)) - prob.setup(check=False) + prob.setup() # Set this to False because we have matrix-free component(s). prob.model.linear_solver.options['assemble_jac'] = False diff --git a/openmdao/surrogate_models/tests/test_map.py b/openmdao/surrogate_models/tests/test_map.py index 47d4bef662..acf4824880 100644 --- a/openmdao/surrogate_models/tests/test_map.py +++ b/openmdao/surrogate_models/tests/test_map.py @@ -29,7 +29,7 @@ def test_comp_map(self): # add compressor map to problem p = Problem() p.model.add_subsystem('compmap', c) - p.setup(check=False) + p.setup() # train metamodel Nc = np.array([0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1]) diff --git a/openmdao/test_suite/components/ae_tests.py b/openmdao/test_suite/components/ae_tests.py index 984fe90c2b..9fa52dec58 100644 --- a/openmdao/test_suite/components/ae_tests.py +++ b/openmdao/test_suite/components/ae_tests.py @@ -2,11 +2,11 @@ Some classes that are used to test Analysis Errors on multiple processes. """ -from openmdao.api import ExplicitComponent, AnalysisError +import openmdao.api as om from openmdao.core.driver import Driver -class AEComp(ExplicitComponent): +class AEComp(om.ExplicitComponent): def setup(self): self.add_input('x', val=0.0) @@ -19,10 +19,11 @@ def compute(self, inputs, outputs): x = inputs['x'] if x > 2.0: - raise AnalysisError('Try again.') + raise om.AnalysisError('Try again.') outputs['y'] = x*x + 2.0 + class AEDriver(Driver): """ Handle an Analysis Error from below. @@ -34,7 +35,7 @@ def run(self): """ try: self._problem.model.run_solve_nonlinear() - except AnalysisError: + except om.AnalysisError: return True return False \ No newline at end of file diff --git a/openmdao/test_suite/components/array_comp.py b/openmdao/test_suite/components/array_comp.py index cfc347836c..ace654fbfb 100644 --- a/openmdao/test_suite/components/array_comp.py +++ b/openmdao/test_suite/components/array_comp.py @@ -1,7 +1,9 @@ import numpy as np -from openmdao.api import ExplicitComponent -class ArrayComp(ExplicitComponent): +import openmdao.api as om + + +class ArrayComp(om.ExplicitComponent): def setup(self): diff --git a/openmdao/test_suite/components/branin.py b/openmdao/test_suite/components/branin.py index 2ba38b70f9..5050078ed3 100644 --- a/openmdao/test_suite/components/branin.py +++ b/openmdao/test_suite/components/branin.py @@ -16,10 +16,10 @@ """ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class Branin(ExplicitComponent): +class Branin(om.ExplicitComponent): """ The Branin test problem. This version is the standard version and contains two continuous parameters. @@ -74,7 +74,7 @@ def compute_partials(self, inputs, partials): partials['f', 'x0'] = 2.0*a*(x1 - b*x0**2 + c*x0 - d)*(-2.*b*x0 + c) - e*(1.-f)*np.sin(x0) -class BraninDiscrete(ExplicitComponent): +class BraninDiscrete(om.ExplicitComponent): """ The Branin test problem. This version defines a Discrete Variable in OpenMDAO. diff --git a/openmdao/test_suite/components/double_sellar.py b/openmdao/test_suite/components/double_sellar.py index 4533946b2e..fc2334b91a 100644 --- a/openmdao/test_suite/components/double_sellar.py +++ b/openmdao/test_suite/components/double_sellar.py @@ -1,14 +1,12 @@ -from openmdao.core.group import Group -from openmdao.solvers.nonlinear.newton import NewtonSolver -from openmdao.solvers.linear.direct import DirectSolver +import openmdao.api as om + from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives from openmdao.test_suite.components.sellar import SellarImplicitDis1 - # TODO -- Need to convert these over to use `setup` after we have two setup # phases split up and have the ability to change driver settings -class SubSellar(Group): +class SubSellar(om.Group): def __init__(self, units=None, scaling=None, **kwargs): super(SubSellar, self).__init__(**kwargs) @@ -19,7 +17,7 @@ def __init__(self, units=None, scaling=None, **kwargs): promotes=['z', 'y1', 'y2']) -class DoubleSellar(Group): +class DoubleSellar(om.Group): def __init__(self, units=None, scaling=None, **kwargs): super(DoubleSellar, self).__init__(**kwargs) @@ -31,11 +29,11 @@ def __init__(self, units=None, scaling=None, **kwargs): self.connect('g2.y2', 'g1.x') # Converge the outer loop with Gauss Seidel, with a looser tolerance. - self.nonlinear_solver = NewtonSolver() - self.linear_solver = DirectSolver() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.DirectSolver() -class SubSellarImplicit(Group): +class SubSellarImplicit(om.Group): def __init__(self, units=None, scaling=None, **kwargs): super(SubSellarImplicit, self).__init__(**kwargs) @@ -46,7 +44,7 @@ def __init__(self, units=None, scaling=None, **kwargs): promotes=['z', 'y1', 'y2']) -class DoubleSellarImplicit(Group): +class DoubleSellarImplicit(om.Group): def __init__(self, units=None, scaling=None, **kwargs): super(DoubleSellarImplicit, self).__init__(**kwargs) @@ -58,5 +56,5 @@ def __init__(self, units=None, scaling=None, **kwargs): self.connect('g2.y2', 'g1.x') # Converge the outer loop with Gauss Seidel, with a looser tolerance. - self.nonlinear_solver = NewtonSolver() - self.linear_solver = DirectSolver() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.DirectSolver() diff --git a/openmdao/test_suite/components/expl_comp_array.py b/openmdao/test_suite/components/expl_comp_array.py index 2fa9cd30f3..0bd7e811d9 100644 --- a/openmdao/test_suite/components/expl_comp_array.py +++ b/openmdao/test_suite/components/expl_comp_array.py @@ -4,10 +4,10 @@ import numpy as np import scipy.sparse -from openmdao.api import ExplicitComponent +import openmdao.api as om -class TestExplCompArray(ExplicitComponent): +class TestExplCompArray(om.ExplicitComponent): def initialize(self): self.options.declare('thickness', default=1.) diff --git a/openmdao/test_suite/components/impl_comp_array.py b/openmdao/test_suite/components/impl_comp_array.py index 43c7ceaa16..db2b0ca74c 100644 --- a/openmdao/test_suite/components/impl_comp_array.py +++ b/openmdao/test_suite/components/impl_comp_array.py @@ -5,10 +5,10 @@ import numpy as np import scipy.sparse -from openmdao.api import ImplicitComponent +import openmdao.api as om -class TestImplCompArray(ImplicitComponent): +class TestImplCompArray(om.ImplicitComponent): def initialize(self): self.mtx = np.array([ diff --git a/openmdao/test_suite/components/impl_comp_simple.py b/openmdao/test_suite/components/impl_comp_simple.py index c109ed7ac8..f01596d815 100644 --- a/openmdao/test_suite/components/impl_comp_simple.py +++ b/openmdao/test_suite/components/impl_comp_simple.py @@ -5,10 +5,10 @@ import scipy.sparse import scipy.optimize -from openmdao.api import ImplicitComponent +import openmdao.api as om -class TestImplCompSimple(ImplicitComponent): +class TestImplCompSimple(om.ImplicitComponent): def setup(self): self.add_input('a', val=1.) diff --git a/openmdao/test_suite/components/implicit_newton_linesearch.py b/openmdao/test_suite/components/implicit_newton_linesearch.py index dfa0bd0a3d..6f5a510dcb 100644 --- a/openmdao/test_suite/components/implicit_newton_linesearch.py +++ b/openmdao/test_suite/components/implicit_newton_linesearch.py @@ -1,13 +1,13 @@ """Components used mainly for testing Newton and line searches.""" +from math import exp import numpy as np import unittest -from math import exp -from openmdao.api import ImplicitComponent +import openmdao.api as om -class ImplCompOneState(ImplicitComponent): +class ImplCompOneState(om.ImplicitComponent): """ A Simple Implicit Component @@ -44,7 +44,7 @@ def linearize(self, inputs, outputs, J): J[('y', 'y')] = y + 2.0 - 32.0*y*exp(-16.0*y*y) - 10.0*exp(-5.0*y) -class ImplCompTwoStates(ImplicitComponent): +class ImplCompTwoStates(om.ImplicitComponent): """ A Simple Implicit Component with an additional output equation. @@ -100,7 +100,7 @@ def linearize(self, inputs, outputs, jac): jac[('z', 'x')] = outputs['z'] -class ImplCompTwoStatesArrays(ImplicitComponent): +class ImplCompTwoStatesArrays(om.ImplicitComponent): """ A Simple Implicit Component with an additional output equation. diff --git a/openmdao/test_suite/components/matmultcomp.py b/openmdao/test_suite/components/matmultcomp.py index 59130ffdfa..caeb2bbeef 100644 --- a/openmdao/test_suite/components/matmultcomp.py +++ b/openmdao/test_suite/components/matmultcomp.py @@ -1,14 +1,15 @@ """ A simple component used for derivative testing. """ - from __future__ import division, print_function import time + import numpy as np -from openmdao.core.explicitcomponent import ExplicitComponent +import openmdao.api as om -class MatMultComp(ExplicitComponent): + +class MatMultComp(om.ExplicitComponent): def __init__(self, mat, approx_method='exact', sleep_time=0.1, **kwargs): super(MatMultComp, self).__init__(**kwargs) self.mat = mat @@ -30,7 +31,8 @@ def compute(self, inputs, outputs): if __name__ == '__main__': import sys - from openmdao.api import Problem, IndepVarComp + + import openmdao.api as om from openmdao.utils.mpi import MPI if len(sys.argv) > 1: @@ -52,9 +54,9 @@ def compute(self, inputs, outputs): print("mat shape:", mat.shape) - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('indep', IndepVarComp('x', val=np.ones(mat.shape[1]))) + model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(mat.shape[1]))) comp = model.add_subsystem('comp', MatMultComp(mat, approx_method='fd', num_par_fd=5)) model.connect('indep.x', 'comp.x') diff --git a/openmdao/test_suite/components/misc_components.py b/openmdao/test_suite/components/misc_components.py index ff4bf3b258..dc8ce5389f 100644 --- a/openmdao/test_suite/components/misc_components.py +++ b/openmdao/test_suite/components/misc_components.py @@ -9,10 +9,10 @@ import numpy as np -from openmdao.api import ImplicitComponent +import openmdao.api as om -class Comp4LinearCacheTest(ImplicitComponent): +class Comp4LinearCacheTest(om.ImplicitComponent): """ Component needed for testing cached linear solutions. diff --git a/openmdao/test_suite/components/options_feature_array.py b/openmdao/test_suite/components/options_feature_array.py index 08d8ed09e4..b309cee887 100644 --- a/openmdao/test_suite/components/options_feature_array.py +++ b/openmdao/test_suite/components/options_feature_array.py @@ -4,9 +4,10 @@ """ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class ArrayMultiplyComp(ExplicitComponent): + +class ArrayMultiplyComp(om.ExplicitComponent): def initialize(self): self.options.declare('array', types=np.ndarray) diff --git a/openmdao/test_suite/components/options_feature_function.py b/openmdao/test_suite/components/options_feature_function.py index accec16593..7718212944 100644 --- a/openmdao/test_suite/components/options_feature_function.py +++ b/openmdao/test_suite/components/options_feature_function.py @@ -5,9 +5,10 @@ from types import FunctionType -from openmdao.api import ExplicitComponent +import openmdao.api as om -class UnitaryFunctionComp(ExplicitComponent): + +class UnitaryFunctionComp(om.ExplicitComponent): def initialize(self): self.options.declare('func', types=FunctionType) diff --git a/openmdao/test_suite/components/options_feature_lincomb.py b/openmdao/test_suite/components/options_feature_lincomb.py index 86e5c592be..00214e9aec 100644 --- a/openmdao/test_suite/components/options_feature_lincomb.py +++ b/openmdao/test_suite/components/options_feature_lincomb.py @@ -4,9 +4,10 @@ """ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class LinearCombinationComp(ExplicitComponent): + +class LinearCombinationComp(om.ExplicitComponent): def initialize(self): self.options.declare('a', default=1., types=np.ScalarType) diff --git a/openmdao/test_suite/components/options_feature_vector.py b/openmdao/test_suite/components/options_feature_vector.py index 7daf704d61..6ab8726182 100644 --- a/openmdao/test_suite/components/options_feature_vector.py +++ b/openmdao/test_suite/components/options_feature_vector.py @@ -4,9 +4,10 @@ """ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class VectorDoublingComp(ExplicitComponent): + +class VectorDoublingComp(om.ExplicitComponent): def initialize(self): self.options.declare('size', types=int) diff --git a/openmdao/test_suite/components/paraboloid.py b/openmdao/test_suite/components/paraboloid.py index b799d99c42..6f437d2ad2 100644 --- a/openmdao/test_suite/components/paraboloid.py +++ b/openmdao/test_suite/components/paraboloid.py @@ -2,10 +2,11 @@ (x-3)^2 + xy + (y+4)^2 = 3 """ from __future__ import division, print_function -from openmdao.core.explicitcomponent import ExplicitComponent +import openmdao.api as om -class Paraboloid(ExplicitComponent): + +class Paraboloid(om.ExplicitComponent): """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3. """ @@ -41,10 +42,9 @@ def compute_partials(self, inputs, partials): if __name__ == "__main__": - from openmdao.api import Problem, Group, ScipyOptimizeDriver, ExecComp, IndepVarComp - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() ivc.add_output('x', 3.0) ivc.add_output('y', -4.0) model.add_subsystem('des_vars', ivc) @@ -53,8 +53,8 @@ def compute_partials(self, inputs, partials): model.connect('des_vars.x', 'parab_comp.x') model.connect('des_vars.y', 'parab_comp.y') - prob = Problem(model) - prob.driver = ScipyOptimizeDriver() # so 'openmdao cite' will report it for cite docs + prob = om.Problem(model) + prob.driver = om.ScipyOptimizeDriver() # so 'openmdao cite' will report it for cite docs prob.setup() prob.run_model() print(prob['parab_comp.f_xy']) diff --git a/openmdao/test_suite/components/paraboloid_feature.py b/openmdao/test_suite/components/paraboloid_feature.py index 4076fd7e0e..b6edf8633b 100644 --- a/openmdao/test_suite/components/paraboloid_feature.py +++ b/openmdao/test_suite/components/paraboloid_feature.py @@ -2,10 +2,11 @@ Demonstration of a model using the Paraboloid component. """ from __future__ import division, print_function -from openmdao.api import ExplicitComponent +import openmdao.api as om -class Paraboloid(ExplicitComponent): + +class Paraboloid(om.ExplicitComponent): """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3. """ @@ -32,12 +33,9 @@ def compute(self, inputs, outputs): if __name__ == "__main__": - from openmdao.core.problem import Problem - from openmdao.core.group import Group - from openmdao.core.indepvarcomp import IndepVarComp - model = Group() - ivc = IndepVarComp() + model = om.Group() + ivc = om.IndepVarComp() ivc.add_output('x', 3.0) ivc.add_output('y', -4.0) model.add_subsystem('des_vars', ivc) @@ -46,7 +44,7 @@ def compute(self, inputs, outputs): model.connect('des_vars.x', 'parab_comp.x') model.connect('des_vars.y', 'parab_comp.y') - prob = Problem(model) + prob = om.Problem(model) prob.setup() prob.run_model() print(prob['parab_comp.f_xy']) diff --git a/openmdao/test_suite/components/quad_implicit.py b/openmdao/test_suite/components/quad_implicit.py index 40d6f5144d..1479b7d373 100644 --- a/openmdao/test_suite/components/quad_implicit.py +++ b/openmdao/test_suite/components/quad_implicit.py @@ -1,6 +1,7 @@ -from openmdao.api import ImplicitComponent +import openmdao.api as om -class QuadraticComp(ImplicitComponent): + +class QuadraticComp(om.ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. diff --git a/openmdao/test_suite/components/sellar.py b/openmdao/test_suite/components/sellar.py index 04348c211f..5b26e7ded4 100644 --- a/openmdao/test_suite/components/sellar.py +++ b/openmdao/test_suite/components/sellar.py @@ -7,23 +7,14 @@ Optimization for Multidisciplinary System Design," Proceedings References 79 of the 34th AIAA Aerospace Sciences Meeting and Exhibit, Reno, NV, January 1996. """ +import inspect import numpy as np -import inspect - -from openmdao.components.exec_comp import ExecComp -from openmdao.core.indepvarcomp import IndepVarComp -from openmdao.core.explicitcomponent import ExplicitComponent -from openmdao.core.implicitcomponent import ImplicitComponent -from openmdao.core.group import Group -from openmdao.core.problem import Problem -from openmdao.solvers.nonlinear.nonlinear_block_gs import NonlinearBlockGS -from openmdao.solvers.linear.scipy_iter_solver import ScipyKrylov -from openmdao.solvers.nonlinear.newton import NewtonSolver +import openmdao.api as om -class SellarDis1(ExplicitComponent): +class SellarDis1(om.ExplicitComponent): """ Component containing Discipline 1 -- no derivatives version. """ @@ -108,7 +99,7 @@ def _do_declares(self): self.declare_partials(of='*', wrt='*', method='cs') -class SellarDis2(ExplicitComponent): +class SellarDis2(om.ExplicitComponent): """ Component containing Discipline 2 -- no derivatives version. """ @@ -199,19 +190,19 @@ def _do_declares(self): self.declare_partials(of='*', wrt='*', method='cs') -class SellarNoDerivatives(Group): +class SellarNoDerivatives(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines without derivatives. """ def initialize(self): - self.options.declare('nonlinear_solver', default=NonlinearBlockGS, + self.options.declare('nonlinear_solver', default=om.NonlinearBlockGS, desc='Nonlinear solver for Sellar MDA') self.options.declare('nl_atol', default=None, desc='User-specified atol for nonlinear solver.') self.options.declare('nl_maxiter', default=None, desc='Iteration limit for nonlinear solver.') - self.options.declare('linear_solver', default=ScipyKrylov, + self.options.declare('linear_solver', default=om.ScipyKrylov, desc='Linear solver') self.options.declare('ln_atol', default=None, desc='User-specified atol for linear solver.') @@ -219,19 +210,19 @@ def initialize(self): desc='Iteration limit for linear solver.') def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) - cycle = self.add_subsystem('cycle', Group(), promotes=['x', 'z', 'y1', 'y2']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['x', 'z', 'y1', 'y2']) cycle.add_subsystem('d1', SellarDis1(), promotes=['x', 'z', 'y1', 'y2']) cycle.add_subsystem('d2', SellarDis2(), promotes=['z', 'y1', 'y2']) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) nl = self.options['nonlinear_solver'] self.nonlinear_solver = nl() if inspect.isclass(nl) else nl @@ -249,19 +240,19 @@ def configure(self): self.cycle.linear_solver.options['maxiter'] = self.options['ln_maxiter'] -class SellarDerivatives(Group): +class SellarDerivatives(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines with derivatives. """ def initialize(self): - self.options.declare('nonlinear_solver', default=NonlinearBlockGS, + self.options.declare('nonlinear_solver', default=om.NonlinearBlockGS, desc='Nonlinear solver (class or instance) for Sellar MDA') self.options.declare('nl_atol', default=None, desc='User-specified atol for nonlinear solver.') self.options.declare('nl_maxiter', default=None, desc='Iteration limit for nonlinear solver.') - self.options.declare('linear_solver', default=ScipyKrylov, + self.options.declare('linear_solver', default=om.ScipyKrylov, desc='Linear solver (class or instance)') self.options.declare('ln_atol', default=None, desc='User-specified atol for linear solver.') @@ -269,19 +260,19 @@ def initialize(self): desc='Iteration limit for linear solver.') def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, - x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0, + x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0), promotes=['con2', 'y2']) nl = self.options['nonlinear_solver'] @@ -299,46 +290,46 @@ def setup(self): self.linear_solver.options['maxiter'] = self.options['ln_maxiter'] -class SellarDerivativesConnected(Group): +class SellarDerivativesConnected(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines with derivatives. """ def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0)) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) + self.add_subsystem('px', om.IndepVarComp('x', 1.0)) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0]))) self.add_subsystem('d1', SellarDis1withDerivatives()) self.add_subsystem('d2', SellarDis2withDerivatives()) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0)) + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0)) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1')) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0')) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1')) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0')) self.connect('px.x', ['d1.x', 'obj_cmp.x']) self.connect('pz.z', ['d1.z', 'd2.z', 'obj_cmp.z']) self.connect('d1.y1', ['d2.y1', 'obj_cmp.y1', 'con_cmp1.y1']) self.connect('d2.y2', ['d1.y2', 'obj_cmp.y2', 'con_cmp2.y2']) - self.nonlinear_solver = NonlinearBlockGS() - self.linear_solver = ScipyKrylov() + self.nonlinear_solver = om.NonlinearBlockGS() + self.linear_solver = om.ScipyKrylov() -class SellarDerivativesGrouped(Group): +class SellarDerivativesGrouped(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines with derivatives. """ def initialize(self): - self.options.declare('nonlinear_solver', default=NonlinearBlockGS, + self.options.declare('nonlinear_solver', default=om.NonlinearBlockGS, desc='Nonlinear solver (class or instance) for Sellar MDA') self.options.declare('nl_atol', default=None, desc='User-specified atol for nonlinear solver.') self.options.declare('nl_maxiter', default=None, desc='Iteration limit for nonlinear solver.') - self.options.declare('linear_solver', default=ScipyKrylov, + self.options.declare('linear_solver', default=om.ScipyKrylov, desc='Linear solver (class or instance)') self.options.declare('ln_atol', default=None, desc='User-specified atol for linear solver.') @@ -346,19 +337,19 @@ def initialize(self): desc='Iteration limit for linear solver.') def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) - self.mda = mda = self.add_subsystem('mda', Group(), promotes=['x', 'z', 'y1', 'y2']) + self.mda = mda = self.add_subsystem('mda', om.Group(), promotes=['x', 'z', 'y1', 'y2']) mda.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) mda.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) nl = self.options['nonlinear_solver'] self.nonlinear_solver = nl() if inspect.isclass(nl) else nl @@ -375,11 +366,11 @@ def setup(self): self.linear_solver.options['maxiter'] = self.options['ln_maxiter'] def configure(self): - self.mda.linear_solver = ScipyKrylov() - self.mda.nonlinear_solver = NonlinearBlockGS() + self.mda.linear_solver = om.ScipyKrylov() + self.mda.nonlinear_solver = om.NonlinearBlockGS() -class StateConnection(ImplicitComponent): +class StateConnection(om.ImplicitComponent): """ Define connection with an explicit equation. """ @@ -419,19 +410,19 @@ def linearize(self, inputs, outputs, J): J[('y2_command', 'y2_actual')] = 1.0 -class SellarStateConnection(Group): +class SellarStateConnection(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines with derivatives. """ def initialize(self): - self.options.declare('nonlinear_solver', default=NewtonSolver, + self.options.declare('nonlinear_solver', default=om.NewtonSolver, desc='Nonlinear solver (class or instance) for Sellar MDA') self.options.declare('nl_atol', default=None, desc='User-specified atol for nonlinear solver.') self.options.declare('nl_maxiter', default=None, desc='Iteration limit for nonlinear solver.') - self.options.declare('linear_solver', default=ScipyKrylov, + self.options.declare('linear_solver', default=om.ScipyKrylov, desc='Linear solver (class or instance)') self.options.declare('ln_atol', default=None, desc='User-specified atol for linear solver.') @@ -439,15 +430,15 @@ def initialize(self): desc='Iteration limit for linear solver.') def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) - sub = self.add_subsystem('sub', Group(), + sub = self.add_subsystem('sub', om.Group(), promotes=['x', 'z', 'y1', 'state_eq.y2_actual', 'state_eq.y2_command', 'd1.y2', 'd2.y2']) - subgrp = sub.add_subsystem('state_eq_group', Group(), + subgrp = sub.add_subsystem('state_eq_group', om.Group(), promotes=['state_eq.y2_actual', 'state_eq.y2_command']) subgrp.add_subsystem('state_eq', StateConnection()) @@ -457,13 +448,13 @@ def setup(self): self.connect('state_eq.y2_command', 'd1.y2') self.connect('d2.y2', 'state_eq.y2_actual') - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['x', 'z', 'y1', 'obj']) self.connect('d2.y2', 'obj_cmp.y2') - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2']) self.connect('d2.y2', 'con_cmp2.y2') nl = self.options['nonlinear_solver'] @@ -481,11 +472,11 @@ def setup(self): self.linear_solver.options['maxiter'] = self.options['ln_maxiter'] def configure(self): - self.sub.linear_solver = ScipyKrylov() - self.sub.state_eq_group.linear_solver = ScipyKrylov() + self.sub.linear_solver = om.ScipyKrylov() + self.sub.state_eq_group.linear_solver = om.ScipyKrylov() -class SellarImplicitDis1(ImplicitComponent): +class SellarImplicitDis1(om.ImplicitComponent): """ Component containing Discipline 1 -- no derivatives version. """ @@ -547,7 +538,7 @@ def linearize(self, inputs, outputs, J): J['y1', 'y1'] = 1.0 -class SellarImplicitDis2(ImplicitComponent): +class SellarImplicitDis2(om.ImplicitComponent): """ Component containing Discipline 2 -- implicit version. """ @@ -616,7 +607,7 @@ def linearize(self, inputs, outputs, J): J['y2', 'y2'] = 1.0 -class SellarProblem(Problem): +class SellarProblem(om.Problem): """ The Sellar problem with configurable model class. """ @@ -635,7 +626,7 @@ def __init__(self, model_class=SellarDerivatives, **kwargs): self.set_solver_print(0) -class SellarProblemWithArrays(Problem): +class SellarProblemWithArrays(om.Problem): """ The Sellar problem with ndarray variable options """ diff --git a/openmdao/test_suite/components/sellar_feature.py b/openmdao/test_suite/components/sellar_feature.py index 2843cb7345..7e02d2b365 100644 --- a/openmdao/test_suite/components/sellar_feature.py +++ b/openmdao/test_suite/components/sellar_feature.py @@ -7,15 +7,15 @@ Optimization for Multidisciplinary System Design," Proceedings References 79 of the 34th AIAA Aerospace Sciences Meeting and Exhibit, Reno, NV, January 1996. """ - import numpy as np -from openmdao.api import Group, ExplicitComponent, ExecComp, IndepVarComp, \ - NonlinearBlockGS, ScipyKrylov, DirectSolver, EQConstraintComp, NewtonSolver + +import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \ SellarDis2withDerivatives from openmdao.test_suite.components.double_sellar import SubSellar -class SellarDis1(ExplicitComponent): + +class SellarDis1(om.ExplicitComponent): """ Component containing Discipline 1 -- no derivatives version. """ @@ -50,7 +50,7 @@ def compute(self, inputs, outputs): outputs['y1'] = z1**2 + z2 + x1 - 0.2*y2 -class SellarDis2(ExplicitComponent): +class SellarDis2(om.ExplicitComponent): """ Component containing Discipline 2 -- no derivatives version. """ @@ -87,57 +87,61 @@ def compute(self, inputs, outputs): outputs['y2'] = y1**.5 + z1 + z2 -class SellarMDA(Group): +class SellarMDA(om.Group): """ Group containing the Sellar MDA. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group(), promotes=['*']) - cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], promotes_outputs=['y1']) - cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['*']) + cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], + promotes_outputs=['y1']) + cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], + promotes_outputs=['y2']) # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) -class SellarMDALinearSolver(Group): +class SellarMDALinearSolver(om.Group): """ Group containing the Sellar MDA. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group(), promotes=['*']) - d1 = cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], promotes_outputs=['y1']) - d2 = cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['*']) + d1 = cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], + promotes_outputs=['y1']) + d2 = cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], + promotes_outputs=['y2']) - cycle.nonlinear_solver = NonlinearBlockGS() - cycle.linear_solver = DirectSolver() + cycle.nonlinear_solver = om.NonlinearBlockGS() + cycle.linear_solver = om.DirectSolver() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) -class SellarDis1CS(ExplicitComponent): +class SellarDis1CS(om.ExplicitComponent): """ Component containing Discipline 1 -- no derivatives version. Uses Complex Step @@ -173,7 +177,7 @@ def compute(self, inputs, outputs): outputs['y1'] = z1**2 + z2 + x1 - 0.2*y2 -class SellarDis2CS(ExplicitComponent): +class SellarDis2CS(om.ExplicitComponent): """ Component containing Discipline 2 -- no derivatives version. Uses Complex Step @@ -211,37 +215,37 @@ def compute(self, inputs, outputs): outputs['y2'] = y1**.5 + z1 + z2 -class SellarNoDerivativesCS(Group): +class SellarNoDerivativesCS(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines without derivatives. """ def setup(self): - self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) - self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) + self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x']) + self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) - cycle = self.add_subsystem('cycle', Group(), promotes=['x', 'z', 'y1', 'y2']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['x', 'z', 'y1', 'y2']) d1 = cycle.add_subsystem('d1', SellarDis1CS(), promotes=['x', 'z', 'y1', 'y2']) d2 = cycle.add_subsystem('d2', SellarDis2CS(), promotes=['z', 'y1', 'y2']) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) - self.nonlinear_solver = NonlinearBlockGS() - self.linear_solver = ScipyKrylov() + self.nonlinear_solver = om.NonlinearBlockGS() + self.linear_solver = om.ScipyKrylov() -class SellarIDF(Group): +class SellarIDF(om.Group): """ Individual Design Feasible (IDF) architecture for the Sellar problem. """ def setup(self): # construct the Sellar model with `y1` and `y2` as independent variables - dv = IndepVarComp() + dv = om.IndepVarComp() dv.add_output('x', 5.) dv.add_output('y1', 5.) dv.add_output('y2', 5.) @@ -251,11 +255,11 @@ def setup(self): self.add_subsystem('d1', SellarDis1withDerivatives()) self.add_subsystem('d2', SellarDis2withDerivatives()) - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', x=0., z=np.array([0., 0.]))) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1')) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0')) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1')) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0')) self.connect('dv.x', ['d1.x', 'obj_cmp.x']) self.connect('dv.y1', ['d2.y1', 'obj_cmp.y1', 'con_cmp1.y1']) @@ -265,7 +269,7 @@ def setup(self): # rather than create a cycle by connecting d1.y1 to d2.y1 and d2.y2 to d1.y2 # we will constrain y1 and y2 to be equal for the two disciplines - equal = EQConstraintComp() + equal = om.EQConstraintComp() self.add_subsystem('equal', equal) equal.add_eq_output('y1', add_constraint=True) diff --git a/openmdao/test_suite/components/simple_comps.py b/openmdao/test_suite/components/simple_comps.py index f50f0904c6..1a518513e5 100644 --- a/openmdao/test_suite/components/simple_comps.py +++ b/openmdao/test_suite/components/simple_comps.py @@ -2,10 +2,10 @@ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class DoubleArrayComp(ExplicitComponent): +class DoubleArrayComp(om.ExplicitComponent): """ A fairly simple array component. """ @@ -51,7 +51,7 @@ def compute_partials(self, inputs, partials): partials[('y2', 'x2')] = self.JJ[2:4, 2:4] -class NonSquareArrayComp(ExplicitComponent): +class NonSquareArrayComp(om.ExplicitComponent): """ A fairly simple array component. """ @@ -97,7 +97,7 @@ def compute_partials(self, inputs, partials): partials[('y2', 'x2')] = self.JJ[3:4, 2:4] -class TestExplCompDeprecated(ExplicitComponent): +class TestExplCompDeprecated(om.ExplicitComponent): """ A component that adds variables in the __init__ function. """ diff --git a/openmdao/test_suite/components/three_bar_truss.py b/openmdao/test_suite/components/three_bar_truss.py index 233605e9ff..2094bbe28e 100644 --- a/openmdao/test_suite/components/three_bar_truss.py +++ b/openmdao/test_suite/components/three_bar_truss.py @@ -10,7 +10,7 @@ import numpy as np -from openmdao.core.explicitcomponent import ExplicitComponent +import openmdao.api as om def stress_calc(A, E): @@ -64,7 +64,7 @@ def stress_calc(A, E): return sigma -class ThreeBarTruss(ExplicitComponent): +class ThreeBarTruss(om.ExplicitComponent): """ 3 Bar truss problem with 3 continuous design variables and 3 discrete material choices. Material chosen as follows: @@ -156,7 +156,7 @@ def compute(self, inputs, outputs): outputs['stress'] = (np.abs(sigma)/sigma_y) -class ThreeBarTrussVector(ExplicitComponent): +class ThreeBarTrussVector(om.ExplicitComponent): """ 3 Bar truss problem with 3 continuous design variables and 3 discrete material choices. Material chosen as follows: diff --git a/openmdao/test_suite/components/unit_conv.py b/openmdao/test_suite/components/unit_conv.py index f5561cc3e7..93224a1679 100644 --- a/openmdao/test_suite/components/unit_conv.py +++ b/openmdao/test_suite/components/unit_conv.py @@ -2,10 +2,10 @@ import numpy as np -from openmdao.api import ExplicitComponent, Group, IndepVarComp +import openmdao.api as om -class SrcComp(ExplicitComponent): +class SrcComp(om.ExplicitComponent): """Source provides degrees Celsius.""" def setup(self): @@ -37,7 +37,7 @@ def compute_partials(self, inputs, partials): pass -class TgtCompF(ExplicitComponent): +class TgtCompF(om.ExplicitComponent): """Target expressed in degrees F.""" def setup(self): @@ -69,7 +69,7 @@ def compute_partials(self, inputs, partials): pass -class TgtCompC(ExplicitComponent): +class TgtCompC(om.ExplicitComponent): """Target expressed in degrees Celsius.""" def setup(self): @@ -101,7 +101,7 @@ def compute_partials(self, inputs, partials): pass -class TgtCompK(ExplicitComponent): +class TgtCompK(om.ExplicitComponent): """Target expressed in degrees Kelvin.""" def setup(self): @@ -133,7 +133,7 @@ def compute_partials(self, inputs, partials): pass -class TgtCompFMulti(ExplicitComponent): +class TgtCompFMulti(om.ExplicitComponent): """Contains some extra inputs that might trip things up.""" def setup(self): @@ -163,7 +163,7 @@ def compute_partials(self, inputs, J): J['x3_', 'x2_'] = 0.0 -class UnitConvGroup(Group): +class UnitConvGroup(om.Group): """Group containing a degC source that feeds into three targets with units degF, degC, and degK respectively. Good for testing unit conversion.""" @@ -171,7 +171,7 @@ class UnitConvGroup(Group): def __init__(self, **kwargs): super(UnitConvGroup, self).__init__(**kwargs) - self.add_subsystem('px1', IndepVarComp('x1', 100.0)) + self.add_subsystem('px1', om.IndepVarComp('x1', 100.0)) self.add_subsystem('src', SrcComp()) self.add_subsystem('tgtF', TgtCompF()) self.add_subsystem('tgtC', TgtCompC()) @@ -183,7 +183,7 @@ def __init__(self, **kwargs): self.connect('src.x2', 'tgtK.x2') -class UnitConvGroupImplicitConns(Group): +class UnitConvGroupImplicitConns(om.Group): """ Group containing a defF source that feeds into three targets with units degF, degC, and degK respectively. Good for testing unit conversion. @@ -194,7 +194,7 @@ class UnitConvGroupImplicitConns(Group): def __init__(self): super(UnitConvGroupImplicitConns, self).__init__() - self.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes_outputs=['x1']) + self.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes_outputs=['x1']) self.add_subsystem('src', SrcComp(), promotes_inputs=['x1'], promotes_outputs=['x2']) self.add_subsystem('tgtF', TgtCompF(), promotes_inputs=['x2']) self.add_subsystem('tgtC', TgtCompC(), promotes_inputs=['x2']) diff --git a/openmdao/test_suite/groups/cycle_group.py b/openmdao/test_suite/groups/cycle_group.py index 26e7d31c49..3e4006cfb9 100644 --- a/openmdao/test_suite/groups/cycle_group.py +++ b/openmdao/test_suite/groups/cycle_group.py @@ -28,12 +28,13 @@ from __future__ import print_function, division from six.moves import range + import numpy as np -from openmdao.api import IndepVarComp -from openmdao.test_suite.groups.parametric_group import ParametericTestGroup +import openmdao.api as om from openmdao.test_suite.components.cycle_comps import PSI, \ ExplicitCycleComp, ExplicitFirstComp, ExplicitLastComp +from openmdao.test_suite.groups.parametric_group import ParametericTestGroup class CycleGroup(ParametericTestGroup): @@ -118,8 +119,8 @@ def _generate_components(self, conn_type, first_class, middle_class, last_class, 'num_comp': self.options['num_comp'] } - self.add_subsystem('psi_comp', IndepVarComp('psi', PSI)) - indep_var_comp = self.add_subsystem('x0_comp', IndepVarComp()) + self.add_subsystem('psi_comp', om.IndepVarComp('psi', PSI)) + indep_var_comp = self.add_subsystem('x0_comp', om.IndepVarComp()) for i in range(num_var): indep_var_comp.add_output('x_{0}'.format(i), np.ones(var_shape)) diff --git a/openmdao/test_suite/groups/implicit_group.py b/openmdao/test_suite/groups/implicit_group.py index a1eed8feb1..6559ca2e32 100644 --- a/openmdao/test_suite/groups/implicit_group.py +++ b/openmdao/test_suite/groups/implicit_group.py @@ -2,11 +2,10 @@ from __future__ import division, print_function -from openmdao.api import Group, ImplicitComponent -from openmdao.api import LinearBlockGS, NonlinearBlockGS +import openmdao.api as om -class Comp(ImplicitComponent): +class Comp(om.ImplicitComponent): def setup(self): self.add_input('a') @@ -74,13 +73,13 @@ def solve_linear(self, d_outputs, d_residuals, mode): out_vec[var] = in_vec[var] -class TestImplicitGroup(Group): +class TestImplicitGroup(om.Group): """ A `Group` with two interconnected s. """ - def __init__(self, lnSolverClass=LinearBlockGS, - nlSolverClass=NonlinearBlockGS): + def __init__(self, lnSolverClass=om.LinearBlockGS, + nlSolverClass=om.NonlinearBlockGS): super(TestImplicitGroup, self).__init__() diff --git a/openmdao/test_suite/groups/parallel_groups.py b/openmdao/test_suite/groups/parallel_groups.py index 5870ca6050..ea5b489f77 100644 --- a/openmdao/test_suite/groups/parallel_groups.py +++ b/openmdao/test_suite/groups/parallel_groups.py @@ -2,13 +2,9 @@ from __future__ import division, print_function -from openmdao.core.group import Group -from openmdao.core.parallel_group import ParallelGroup -from openmdao.core.indepvarcomp import IndepVarComp -from openmdao.components.exec_comp import ExecComp +import openmdao.api as om - -class FanOut(Group): +class FanOut(om.Group): """ Topology where one comp broadcasts an output to two target components. @@ -17,17 +13,17 @@ class FanOut(Group): def __init__(self): super(FanOut, self).__init__() - self.add_subsystem('p', IndepVarComp('x', 1.0)) - self.add_subsystem('comp1', ExecComp(['y=3.0*x'])) - self.add_subsystem('comp2', ExecComp(['y=-2.0*x'])) - self.add_subsystem('comp3', ExecComp(['y=5.0*x'])) + self.add_subsystem('p', om.IndepVarComp('x', 1.0)) + self.add_subsystem('comp1', om.ExecComp(['y=3.0*x'])) + self.add_subsystem('comp2', om.ExecComp(['y=-2.0*x'])) + self.add_subsystem('comp3', om.ExecComp(['y=5.0*x'])) self.connect("p.x", "comp1.x") self.connect("comp1.y", "comp2.x") self.connect("comp1.y", "comp3.x") -class FanOutGrouped(Group): +class FanOutGrouped(om.Group): """ Topology where one component broadcasts an output to two target components. @@ -36,15 +32,15 @@ class FanOutGrouped(Group): def __init__(self): super(FanOutGrouped, self).__init__() - self.add_subsystem('iv', IndepVarComp('x', 1.0)) - self.add_subsystem('c1', ExecComp(['y=3.0*x'])) + self.add_subsystem('iv', om.IndepVarComp('x', 1.0)) + self.add_subsystem('c1', om.ExecComp(['y=3.0*x'])) - self.sub = self.add_subsystem('sub', ParallelGroup()) - self.sub.add_subsystem('c2', ExecComp(['y=-2.0*x'])) - self.sub.add_subsystem('c3', ExecComp(['y=5.0*x'])) + self.sub = self.add_subsystem('sub', om.ParallelGroup()) + self.sub.add_subsystem('c2', om.ExecComp(['y=-2.0*x'])) + self.sub.add_subsystem('c3', om.ExecComp(['y=5.0*x'])) - self.add_subsystem('c2', ExecComp(['y=x'])) - self.add_subsystem('c3', ExecComp(['y=x'])) + self.add_subsystem('c2', om.ExecComp(['y=x'])) + self.add_subsystem('c3', om.ExecComp(['y=x'])) self.connect('iv.x', 'c1.x') @@ -55,7 +51,7 @@ def __init__(self): self.connect('sub.c3.y', 'c3.x') -class FanIn(Group): +class FanIn(om.Group): """ Topology where two comps feed a single comp. """ @@ -63,11 +59,11 @@ class FanIn(Group): def __init__(self): super(FanIn, self).__init__() - self.add_subsystem('p1', IndepVarComp('x1', 1.0)) - self.add_subsystem('p2', IndepVarComp('x2', 1.0)) - self.add_subsystem('comp1', ExecComp(['y=-2.0*x'])) - self.add_subsystem('comp2', ExecComp(['y=5.0*x'])) - self.add_subsystem('comp3', ExecComp(['y=3.0*x1+7.0*x2'])) + self.add_subsystem('p1', om.IndepVarComp('x1', 1.0)) + self.add_subsystem('p2', om.IndepVarComp('x2', 1.0)) + self.add_subsystem('comp1', om.ExecComp(['y=-2.0*x'])) + self.add_subsystem('comp2', om.ExecComp(['y=5.0*x'])) + self.add_subsystem('comp3', om.ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("comp1.y", "comp3.x1") self.connect("comp2.y", "comp3.x2") @@ -75,7 +71,7 @@ def __init__(self): self.connect("p2.x2", "comp2.x") -class FanInGrouped(Group): +class FanInGrouped(om.Group): """ Topology where two components in a Group feed a single component outside of that Group. @@ -84,16 +80,16 @@ class FanInGrouped(Group): def __init__(self): super(FanInGrouped, self).__init__() - iv = self.add_subsystem('iv', IndepVarComp()) + iv = self.add_subsystem('iv', om.IndepVarComp()) iv.add_output('x1', 1.0) iv.add_output('x2', 1.0) iv.add_output('x3', 1.0) - self.sub = self.add_subsystem('sub', ParallelGroup()) - self.sub.add_subsystem('c1', ExecComp(['y=-2.0*x'])) - self.sub.add_subsystem('c2', ExecComp(['y=5.0*x'])) + self.sub = self.add_subsystem('sub', om.ParallelGroup()) + self.sub.add_subsystem('c1', om.ExecComp(['y=-2.0*x'])) + self.sub.add_subsystem('c2', om.ExecComp(['y=5.0*x'])) - self.add_subsystem('c3', ExecComp(['y=3.0*x1+7.0*x2'])) + self.add_subsystem('c3', om.ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("sub.c1.y", "c3.x1") self.connect("sub.c2.y", "c3.x2") @@ -101,7 +97,8 @@ def __init__(self): self.connect("iv.x1", "sub.c1.x") self.connect("iv.x2", "sub.c2.x") -class FanInGrouped2(Group): + +class FanInGrouped2(om.Group): """ Topology where two components in a Group feed a single component outside of that Group. This is slightly different than FanInGrouped @@ -113,14 +110,14 @@ class FanInGrouped2(Group): def __init__(self): super(FanInGrouped2, self).__init__() - p1 = self.add_subsystem('p1', IndepVarComp('x', 1.0)) - p2 = self.add_subsystem('p2', IndepVarComp('x', 1.0)) + p1 = self.add_subsystem('p1', om.IndepVarComp('x', 1.0)) + p2 = self.add_subsystem('p2', om.IndepVarComp('x', 1.0)) - self.sub = self.add_subsystem('sub', ParallelGroup()) - self.sub.add_subsystem('c1', ExecComp(['y=-2.0*x'])) - self.sub.add_subsystem('c2', ExecComp(['y=5.0*x'])) + self.sub = self.add_subsystem('sub', om.ParallelGroup()) + self.sub.add_subsystem('c1', om.ExecComp(['y=-2.0*x'])) + self.sub.add_subsystem('c2', om.ExecComp(['y=5.0*x'])) - self.add_subsystem('c3', ExecComp(['y=3.0*x1+7.0*x2'])) + self.add_subsystem('c3', om.ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("sub.c1.y", "c3.x1") self.connect("sub.c2.y", "c3.x2") @@ -129,7 +126,7 @@ def __init__(self): self.connect("p2.x", "sub.c2.x") -class DiamondFlat(Group): +class DiamondFlat(om.Group): """ Topology: one - two - one. @@ -138,20 +135,18 @@ class DiamondFlat(Group): def __init__(self): super(DiamondFlat, self).__init__() - self.add_subsystem('iv', IndepVarComp('x', 2.0)) + self.add_subsystem('iv', om.IndepVarComp('x', 2.0)) - self.add_subsystem('c1', ExecComp([ - 'y1 = 2.0*x1**2', - 'y2 = 3.0*x1' - ])) + self.add_subsystem('c1', om.ExecComp(['y1 = 2.0*x1**2', + 'y2 = 3.0*x1' + ])) - self.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) - self.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) + self.add_subsystem('c2', om.ExecComp('y1 = 0.5*x1')) + self.add_subsystem('c3', om.ExecComp('y1 = 3.5*x1')) - self.add_subsystem('c4', ExecComp([ - 'y1 = x1 + 2.0*x2', - 'y2 = 3.0*x1 - 5.0*x2' - ])) + self.add_subsystem('c4', om.ExecComp(['y1 = x1 + 2.0*x2', + 'y2 = 3.0*x1 - 5.0*x2' + ])) # make connections self.connect('iv.x', 'c1.x1') @@ -161,7 +156,7 @@ def __init__(self): self.connect('c3.y1', 'c4.x2') -class Diamond(Group): +class Diamond(om.Group): """ Topology: one - two - one. """ @@ -169,21 +164,19 @@ class Diamond(Group): def __init__(self): super(Diamond, self).__init__() - self.add_subsystem('iv', IndepVarComp('x', 2.0)) + self.add_subsystem('iv', om.IndepVarComp('x', 2.0)) - self.add_subsystem('c1', ExecComp([ - 'y1 = 2.0*x1**2', - 'y2 = 3.0*x1' - ])) + self.add_subsystem('c1', om.ExecComp(['y1 = 2.0*x1**2', + 'y2 = 3.0*x1' + ])) - sub = self.add_subsystem('sub', ParallelGroup()) - sub.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) - sub.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) + sub = self.add_subsystem('sub', om.ParallelGroup()) + sub.add_subsystem('c2', om.ExecComp('y1 = 0.5*x1')) + sub.add_subsystem('c3', om.ExecComp('y1 = 3.5*x1')) - self.add_subsystem('c4', ExecComp([ - 'y1 = x1 + 2.0*x2', - 'y2 = 3.0*x1 - 5.0*x2' - ])) + self.add_subsystem('c4', om.ExecComp(['y1 = x1 + 2.0*x2', + 'y2 = 3.0*x1 - 5.0*x2' + ])) # make connections self.connect('iv.x', 'c1.x1') @@ -195,7 +188,7 @@ def __init__(self): self.connect('sub.c3.y1', 'c4.x2') -class ConvergeDivergeFlat(Group): +class ConvergeDivergeFlat(om.Group): """ Topology one - two - one - two - one. This model was critical in testing parallel reverse scatters. This version is perfectly flat. @@ -204,24 +197,22 @@ class ConvergeDivergeFlat(Group): def __init__(self): super(ConvergeDivergeFlat, self).__init__() - self.add_subsystem('iv', IndepVarComp('x', 2.0)) + self.add_subsystem('iv', om.IndepVarComp('x', 2.0)) - self.add_subsystem('c1', ExecComp([ - 'y1 = 2.0*x1**2', - 'y2 = 3.0*x1' - ])) + self.add_subsystem('c1', om.ExecComp(['y1 = 2.0*x1**2', + 'y2 = 3.0*x1' + ])) - self.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) - self.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) + self.add_subsystem('c2', om.ExecComp('y1 = 0.5*x1')) + self.add_subsystem('c3', om.ExecComp('y1 = 3.5*x1')) - self.add_subsystem('c4', ExecComp([ - 'y1 = x1 + 2.0*x2', - 'y2 = 3.0*x1 - 5.0*x2' - ])) + self.add_subsystem('c4', om.ExecComp(['y1 = x1 + 2.0*x2', + 'y2 = 3.0*x1 - 5.0*x2' + ])) - self.add_subsystem('c5', ExecComp('y1 = 0.8*x1')) - self.add_subsystem('c6', ExecComp('y1 = 0.5*x1')) - self.add_subsystem('c7', ExecComp('y1 = x1 + 3.0*x2')) + self.add_subsystem('c5', om.ExecComp('y1 = 0.8*x1')) + self.add_subsystem('c6', om.ExecComp('y1 = 0.5*x1')) + self.add_subsystem('c7', om.ExecComp('y1 = x1 + 3.0*x2')) # make connections self.connect('iv.x', 'c1.x1') @@ -239,7 +230,7 @@ def __init__(self): self.connect('c6.y1', 'c7.x2') -class ConvergeDiverge(Group): +class ConvergeDiverge(om.Group): """ Topology: one - two - one - two - one. @@ -249,27 +240,25 @@ class ConvergeDiverge(Group): def __init__(self): super(ConvergeDiverge, self).__init__() - self.add_subsystem('iv', IndepVarComp('x', 2.0)) + self.add_subsystem('iv', om.IndepVarComp('x', 2.0)) - self.add_subsystem('c1', ExecComp([ - 'y1 = 2.0*x1**2', - 'y2 = 3.0*x1' - ])) + self.add_subsystem('c1', om.ExecComp(['y1 = 2.0*x1**2', + 'y2 = 3.0*x1' + ])) - g1 = self.add_subsystem('g1', ParallelGroup()) - g1.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) - g1.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) + g1 = self.add_subsystem('g1', om.ParallelGroup()) + g1.add_subsystem('c2', om.ExecComp('y1 = 0.5*x1')) + g1.add_subsystem('c3', om.ExecComp('y1 = 3.5*x1')) - self.add_subsystem('c4', ExecComp([ - 'y1 = x1 + 2.0*x2', - 'y2 = 3.0*x1 - 5.0*x2' - ])) + self.add_subsystem('c4', om.ExecComp(['y1 = x1 + 2.0*x2', + 'y2 = 3.0*x1 - 5.0*x2' + ])) - g2 = self.add_subsystem('g2', ParallelGroup()) - g2.add_subsystem('c5', ExecComp('y1 = 0.8*x1')) - g2.add_subsystem('c6', ExecComp('y1 = 0.5*x1')) + g2 = self.add_subsystem('g2', om.ParallelGroup()) + g2.add_subsystem('c5', om.ExecComp('y1 = 0.8*x1')) + g2.add_subsystem('c6', om.ExecComp('y1 = 0.5*x1')) - self.add_subsystem('c7', ExecComp('y1 = x1 + 3.0*x2')) + self.add_subsystem('c7', om.ExecComp('y1 = x1 + 3.0*x2')) # make connections self.connect('iv.x', 'c1.x1') @@ -287,7 +276,7 @@ def __init__(self): self.connect('g2.c6.y1', 'c7.x2') -class ConvergeDivergeGroups(Group): +class ConvergeDivergeGroups(om.Group): """ Topology: one - two - one - two - one. @@ -298,28 +287,26 @@ class ConvergeDivergeGroups(Group): def __init__(self): super(ConvergeDivergeGroups, self).__init__() - self.add_subsystem('iv', IndepVarComp('x', 2.0)) + self.add_subsystem('iv', om.IndepVarComp('x', 2.0)) - g1 = self.add_subsystem('g1', ParallelGroup()) - g1.add_subsystem('c1', ExecComp([ - 'y1 = 2.0*x1**2', - 'y2 = 3.0*x1' - ])) + g1 = self.add_subsystem('g1', om.ParallelGroup()) + g1.add_subsystem('c1', om.ExecComp(['y1 = 2.0*x1**2', + 'y2 = 3.0*x1' + ])) - g2 = g1.add_subsystem('g2', ParallelGroup()) - g2.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) - g2.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) + g2 = g1.add_subsystem('g2', om.ParallelGroup()) + g2.add_subsystem('c2', om.ExecComp('y1 = 0.5*x1')) + g2.add_subsystem('c3', om.ExecComp('y1 = 3.5*x1')) - g1.add_subsystem('c4', ExecComp([ - 'y1 = x1 + 2.0*x2', - 'y2 = 3.0*x1 - 5.0*x2' - ])) + g1.add_subsystem('c4', om.ExecComp(['y1 = x1 + 2.0*x2', + 'y2 = 3.0*x1 - 5.0*x2' + ])) - g3 = self.add_subsystem('g3', ParallelGroup()) - g3.add_subsystem('c5', ExecComp('y1 = 0.8*x1')) - g3.add_subsystem('c6', ExecComp('y1 = 0.5*x1')) + g3 = self.add_subsystem('g3', om.ParallelGroup()) + g3.add_subsystem('c5', om.ExecComp('y1 = 0.8*x1')) + g3.add_subsystem('c6', om.ExecComp('y1 = 0.5*x1')) - self.add_subsystem('c7', ExecComp('y1 = x1 + 3.0*x2')) + self.add_subsystem('c7', om.ExecComp('y1 = x1 + 3.0*x2')) # make connections self.connect('iv.x', 'g1.c1.x1') @@ -337,25 +324,25 @@ def __init__(self): self.connect('g3.c6.y1', 'c7.x2') -class FanInSubbedIDVC(Group): +class FanInSubbedIDVC(om.Group): """ Classic Fan In with indepvarcomps buried below the parallel group, and a summation component. """ def setup(self): - sub = self.add_subsystem('sub', ParallelGroup()) - sub1 = sub.add_subsystem('sub1', Group()) - sub2 = sub.add_subsystem('sub2', Group()) - - sub1.add_subsystem('p1', IndepVarComp('x', 3.0)) - sub2.add_subsystem('p2', IndepVarComp('x', 5.0)) - sub1.add_subsystem('c1', ExecComp(['y = 2.0*x'])) - sub2.add_subsystem('c2', ExecComp(['y = 4.0*x'])) + sub = self.add_subsystem('sub', om.ParallelGroup()) + sub1 = sub.add_subsystem('sub1', om.Group()) + sub2 = sub.add_subsystem('sub2', om.Group()) + + sub1.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + sub2.add_subsystem('p2', om.IndepVarComp('x', 5.0)) + sub1.add_subsystem('c1', om.ExecComp(['y = 2.0*x'])) + sub2.add_subsystem('c2', om.ExecComp(['y = 4.0*x'])) sub1.connect('p1.x', 'c1.x') sub2.connect('p2.x', 'c2.x') - self.add_subsystem('sum', ExecComp(['y = z1 + z2'])) + self.add_subsystem('sum',om. ExecComp(['y = z1 + z2'])) self.connect('sub.sub1.c1.y', 'sum.z1') self.connect('sub.sub2.c2.y', 'sum.z2') diff --git a/openmdao/test_suite/groups/sin_fitter.py b/openmdao/test_suite/groups/sin_fitter.py index 5d36fa29ed..2e1ceed3f7 100644 --- a/openmdao/test_suite/groups/sin_fitter.py +++ b/openmdao/test_suite/groups/sin_fitter.py @@ -3,11 +3,11 @@ """ from __future__ import print_function, division, absolute_import +from six.moves import range import numpy as np -from six.moves import range -from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent +import openmdao.api as om def lgl(n, tol=np.finfo(float).eps): @@ -155,7 +155,7 @@ def lagrange_matrices(x_disc, x_interp): return Li, Di -class LGLFit(ExplicitComponent): +class LGLFit(om.ExplicitComponent): """ Given values at discretization nodes, provide interpolated values at midpoint nodes and an approximation of arclength. @@ -187,7 +187,7 @@ def compute(self, inputs, outputs): outputs['yp_lgl'] = np.dot(self.D_lgl, inputs['y_lgl'])/np.pi -class DefectComp(ExplicitComponent): +class DefectComp(om.ExplicitComponent): def initialize(self): self.options.declare(name='num_nodes', types=int) @@ -207,7 +207,7 @@ def compute(self, inputs, outputs): outputs['defect'] = inputs['y_truth'] - inputs['y_approx'] -class ArcLengthFunction(ExplicitComponent): +class ArcLengthFunction(om.ExplicitComponent): def initialize(self): self.options.declare(name='num_nodes', types=int) @@ -229,7 +229,7 @@ def compute_partials(self, inputs, partials): partials['f_arclength', 'yp_lgl'] = inputs['yp_lgl'] / np.sqrt(1 + inputs['yp_lgl']**2) -class ArcLengthQuadrature(ExplicitComponent): +class ArcLengthQuadrature(om.ExplicitComponent): """ Computes the arclength of a polynomial segment whose values are given at the LGL nodes. """ @@ -262,7 +262,7 @@ def compute(self, inputs, outputs): outputs['arclength'] = outputs['arclength']*np.pi -class SineFitter(Group): +class SineFitter(om.Group): def setup(self): @@ -272,16 +272,15 @@ def setup(self): # Step 1: Make an indep var comp that provides the approximated values at the LGL nodes. - self.add_subsystem('y_lgl_ivc', IndepVarComp('y_lgl', val=np.zeros(n), desc='values at LGL nodes'), - promotes_outputs=['y_lgl']) + ivc = om.IndepVarComp('y_lgl', val=np.zeros(n), desc='values at LGL nodes') + self.add_subsystem('y_lgl_ivc', ivc, promotes_outputs=['y_lgl']) # Step 2: Make an indep var comp that provides the 'truth' values at the midpoint nodes. x_lgl, _ = lgl(n) x_lgl = x_lgl * np.pi # put x_lgl on [-pi, pi] x_mid = (x_lgl[1:] + x_lgl[:-1])/2.0 # midpoints on [-pi, pi] - self.add_subsystem('truth', IndepVarComp('y_mid', - val=np.sin(x_mid), - desc='truth values at midpoint nodes')) + self.add_subsystem('truth', om.IndepVarComp('y_mid', val=np.sin(x_mid), + desc='truth values at midpoint nodes')) # Step 3: Make a polynomial fitting component self.add_subsystem('lgl_fit', LGLFit(num_nodes=n)) diff --git a/openmdao/test_suite/scripts/beam_opt.py b/openmdao/test_suite/scripts/beam_opt.py index bcc9eac8dc..b24e88b956 100644 --- a/openmdao/test_suite/scripts/beam_opt.py +++ b/openmdao/test_suite/scripts/beam_opt.py @@ -1,7 +1,6 @@ import numpy as np -from openmdao.api import Problem, ScipyOptimizeDriver - +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.beam_group import BeamGroup if __name__ == '__main__': @@ -13,8 +12,8 @@ num_elements = 50 - prob = Problem(model=BeamGroup(E=E, L=L, b=b, volume=volume, num_elements=num_elements), - driver=ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=True)) + prob = om.Problem(model=BeamGroup(E=E, L=L, b=b, volume=volume, num_elements=num_elements), + driver=om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-9, disp=True)) prob.setup() prob.run_driver() diff --git a/openmdao/test_suite/scripts/circle_opt.py b/openmdao/test_suite/scripts/circle_opt.py index f4d967416a..beb680a3e1 100644 --- a/openmdao/test_suite/scripts/circle_opt.py +++ b/openmdao/test_suite/scripts/circle_opt.py @@ -16,7 +16,7 @@ def setup(self): indeps.add_output('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717, 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886])) indeps.add_output('y', np.array([ 0.52577864, 0.30894559, 0.8420792 , 0.35039912, -0.67290778, - -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582])) + -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582])) indeps.add_output('r', .7) self.add_subsystem('arctan_yox', om.ExecComp('g=arctan(y/x)', vectorize=True, @@ -68,8 +68,8 @@ def setup(self): if __name__ == '__main__': - p = om.Problem(model=CircleOpt(), driver=om.ScipyOptimizeDriver(optimizer='SLSQP', disp=False)) - p.setup(mode='fwd') - p.run_driver() + p = om.Problem(model=CircleOpt(), driver=om.ScipyOptimizeDriver(optimizer='SLSQP', disp=False)) + p.setup(mode='fwd') + p.run_driver() - print(p['circle.area'], np.pi) + print(p['circle.area'], np.pi) diff --git a/openmdao/test_suite/scripts/circuit.py b/openmdao/test_suite/scripts/circuit.py index 7760626182..f54c4044e3 100644 --- a/openmdao/test_suite/scripts/circuit.py +++ b/openmdao/test_suite/scripts/circuit.py @@ -1,8 +1,7 @@ -from openmdao.api import Group, NewtonSolver, DirectSolver, Problem, IndepVarComp - +import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node -class Circuit(Group): +class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')]) @@ -20,16 +19,16 @@ def setup(self): self.connect('R2.I', 'n2.I_in:0') self.connect('D1.I', 'n2.I_out:0') - self.nonlinear_solver = NewtonSolver() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 20 - self.linear_solver = DirectSolver() + self.linear_solver = om.DirectSolver() -p = Problem() +p = om.Problem() model = p.model -model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) -model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) +model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) +model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -39,7 +38,7 @@ def setup(self): model.add_design_var('source.I') model.add_objective('circuit.D1.I') -p.setup(check=False) +p.setup() # set some initial guesses p['circuit.n1.V'] = 10. diff --git a/openmdao/test_suite/scripts/circuit_analysis.py b/openmdao/test_suite/scripts/circuit_analysis.py index fd629a5798..ce4d4183ff 100644 --- a/openmdao/test_suite/scripts/circuit_analysis.py +++ b/openmdao/test_suite/scripts/circuit_analysis.py @@ -1,14 +1,13 @@ from __future__ import print_function, division, absolute_import -import numpy as np - import unittest -from openmdao.api import ExplicitComponent, ImplicitComponent, Group, NewtonSolver, DirectSolver +import numpy as np +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -class Resistor(ExplicitComponent): +class Resistor(om.ExplicitComponent): """Computes current across a resistor using Ohm's law.""" def initialize(self): @@ -27,7 +26,7 @@ def compute(self, inputs, outputs): outputs['I'] = deltaV / self.options['R'] -class Diode(ExplicitComponent): +class Diode(om.ExplicitComponent): """Computes current across a diode using the Shockley diode equation.""" def initialize(self): @@ -49,7 +48,7 @@ def compute(self, inputs, outputs): outputs['I'] = Is * (np.exp(deltaV / Vt) - 1) -class Node(ImplicitComponent): +class Node(om.ImplicitComponent): """Computes voltage residual across a node based on incoming and outgoing current.""" def initialize(self): @@ -80,7 +79,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): # note: This is defined twice in the file. Once so you can import it, and once inside a test that gets included in the docs. -class Circuit(Group): +class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')]) @@ -98,29 +97,29 @@ def setup(self): self.connect('R2.I', 'n2.I_in:0') self.connect('D1.I', 'n2.I_out:0') - self.nonlinear_solver = NewtonSolver() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 20 - self.linear_solver = DirectSolver() + self.linear_solver = om.DirectSolver() if __name__ == "__main__": - from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp, BalanceComp, ExecComp - from openmdao.api import NewtonSolver, DirectSolver, NonlinearRunOnce, LinearRunOnce + import openmdao.api as om - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) # replacing the fixed current source with a BalanceComp to represent a fixed Voltage source # model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) - model.add_subsystem('batt', IndepVarComp('V', 1.5, units='V')) - bal = model.add_subsystem('batt_balance', BalanceComp()) + model.add_subsystem('batt', om.IndepVarComp('V', 1.5, units='V')) + bal = model.add_subsystem('batt_balance', om.BalanceComp()) bal.add_balance('I', units='A', eq_units='V') model.add_subsystem('circuit', Circuit()) - model.add_subsystem('batt_deltaV', ExecComp('dV = V1 - V2', V1={'units':'V'}, V2={'units':'V'}, dV={'units':'V'})) + model.add_subsystem('batt_deltaV', om.ExecComp('dV = V1 - V2', V1={'units':'V'}, + V2={'units':'V'}, dV={'units':'V'})) # current into the circuit is now the output state from the batt_balance comp model.connect('batt_balance.I', 'circuit.I_in') @@ -139,16 +138,16 @@ def setup(self): # change the circuit solver to RunOnce because we're # going to converge at the top level of the model with newton instead - p.model.circuit.nonlinear_solver = NonlinearRunOnce() - p.model.circuit.linear_solver = LinearRunOnce() + p.model.circuit.nonlinear_solver = om.NonlinearRunOnce() + p.model.circuit.linear_solver = om.LinearRunOnce() # Put Newton at the top so it can also converge the new BalanceComp residual - newton = p.model.nonlinear_solver = NewtonSolver() - p.model.linear_solver = DirectSolver() + newton = p.model.nonlinear_solver = om.NewtonSolver() + p.model.linear_solver = om.DirectSolver() newton.options['iprint'] = 2 newton.options['maxiter'] = 20 newton.options['solve_subsystems'] = True - newton.linesearch = ArmijoGoldsteinLS() + newton.linesearch = om.ArmijoGoldsteinLS() newton.linesearch.options['maxiter'] = 10 newton.linesearch.options['iprint'] = 2 diff --git a/openmdao/test_suite/scripts/circuit_with_unconnected_input.py b/openmdao/test_suite/scripts/circuit_with_unconnected_input.py index bbb3eb826b..dc7fdafd4b 100644 --- a/openmdao/test_suite/scripts/circuit_with_unconnected_input.py +++ b/openmdao/test_suite/scripts/circuit_with_unconnected_input.py @@ -1,8 +1,8 @@ -from openmdao.api import Group, NewtonSolver, DirectSolver, Problem, IndepVarComp +import openmdao.api as om from openmdao.error_checking.check_config import check_config from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node -class Circuit(Group): +class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')]) @@ -21,16 +21,16 @@ def setup(self): # self.connect('D1.I', 'n2.I_out:0') # commented out so there is an unconnected input # example for docs for the N2 diagram - self.nonlinear_solver = NewtonSolver() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 20 - self.linear_solver = DirectSolver() + self.linear_solver = om.DirectSolver() -p = Problem() +p = om.Problem() model = p.model -model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) -model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) +model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) +model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') diff --git a/openmdao/test_suite/scripts/multipoint_beam_opt.py b/openmdao/test_suite/scripts/multipoint_beam_opt.py index d4ff9e9811..c4cdacd27b 100644 --- a/openmdao/test_suite/scripts/multipoint_beam_opt.py +++ b/openmdao/test_suite/scripts/multipoint_beam_opt.py @@ -2,7 +2,8 @@ from __future__ import print_function, division, absolute_import import numpy as np -from openmdao.api import Problem, ScipyOptimizeDriver + +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.beam_group import BeamGroup from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_group import MultipointBeamGroup @@ -23,11 +24,11 @@ num_elements = 50 num_load_cases = 2 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases)) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True diff --git a/openmdao/test_suite/scripts/sellar.py b/openmdao/test_suite/scripts/sellar.py index 01155149b2..fcbb657428 100644 --- a/openmdao/test_suite/scripts/sellar.py +++ b/openmdao/test_suite/scripts/sellar.py @@ -1,16 +1,17 @@ import numpy as np -from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockGS, ScipyOptimizeDriver + +import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1, SellarDis2 -class SellarMDAConnect(Group): +class SellarMDAConnect(om.Group): def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp()) + indeps = self.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group()) + cycle = self.add_subsystem('cycle', om.Group()) cycle.add_subsystem('d1', SellarDis1()) cycle.add_subsystem('d2', SellarDis2()) cycle.connect('d1.y1', 'd2.y1') @@ -21,13 +22,13 @@ def setup(self): #cycle.connect('d2.y2', 'd1.y2') # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0)) + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0)) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1')) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0')) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1')) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0')) self.connect('indeps.x', ['cycle.d1.x', 'obj_cmp.x']) self.connect('indeps.z', ['cycle.d1.z', 'cycle.d2.z', 'obj_cmp.z']) @@ -35,11 +36,11 @@ def setup(self): self.connect('cycle.d2.y2', ['obj_cmp.y2', 'con_cmp2.y2']) -prob = Problem() +prob = om.Problem() prob.model = SellarMDAConnect() -prob.driver = ScipyOptimizeDriver() +prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' # prob.driver.options['maxiter'] = 100 prob.driver.options['tol'] = 1e-8 diff --git a/openmdao/test_suite/test_examples/basic_opt_paraboloid.py b/openmdao/test_suite/test_examples/basic_opt_paraboloid.py index a1f0029ac0..dada62509b 100644 --- a/openmdao/test_suite/test_examples/basic_opt_paraboloid.py +++ b/openmdao/test_suite/test_examples/basic_opt_paraboloid.py @@ -3,22 +3,20 @@ import unittest from openmdao.utils.assert_utils import assert_rel_error - -from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp - from openmdao.test_suite.components.paraboloid import Paraboloid + class BasicOptParaboloid(unittest.TestCase): def test_unconstrainted(self): - from openmdao.api import Problem, ScipyOptimizeDriver, IndepVarComp + import openmdao.api as om # We'll use the component that was defined in the last tutorial from openmdao.test_suite.components.paraboloid import Paraboloid # build the model - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp()) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 3.0) indeps.add_output('y', -4.0) @@ -28,7 +26,7 @@ def test_unconstrainted(self): prob.model.connect('indeps.y', 'paraboloid.y') # setup the optimization - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.model.add_design_var('indeps.x', lower=-50, upper=50) @@ -47,27 +45,27 @@ def test_unconstrainted(self): def test_constrained(self): - from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp + import openmdao.api as om # We'll use the component that was defined in the last tutorial from openmdao.test_suite.components.paraboloid import Paraboloid # build the model - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp()) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 3.0) indeps.add_output('y', -4.0) prob.model.add_subsystem('parab', Paraboloid()) # define the component whose output will be constrained - prob.model.add_subsystem('const', ExecComp('g = x + y')) + prob.model.add_subsystem('const', om.ExecComp('g = x + y')) prob.model.connect('indeps.x', ['parab.x', 'const.x']) prob.model.connect('indeps.y', ['parab.y', 'const.y']) # setup the optimization - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'COBYLA' prob.model.add_design_var('indeps.x', lower=-50, upper=50) diff --git a/openmdao/test_suite/test_examples/beam_optimization/beam_group.py b/openmdao/test_suite/test_examples/beam_optimization/beam_group.py index c8c7257b78..3032b27d67 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/beam_group.py +++ b/openmdao/test_suite/test_examples/beam_optimization/beam_group.py @@ -1,7 +1,7 @@ from __future__ import division import numpy as np -from openmdao.api import Group, IndepVarComp +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.components.moment_comp import MomentOfInertiaComp from openmdao.test_suite.test_examples.beam_optimization.components.local_stiffness_matrix_comp import LocalStiffnessMatrixComp @@ -11,7 +11,7 @@ from openmdao.test_suite.test_examples.beam_optimization.components.volume_comp import VolumeComp -class BeamGroup(Group): +class BeamGroup(om.Group): def initialize(self): self.options.declare('E') @@ -31,7 +31,7 @@ def setup(self): force_vector = np.zeros(2 * num_nodes) force_vector[-2] = -1. - inputs_comp = IndepVarComp() + inputs_comp = om.IndepVarComp() inputs_comp.add_output('h', shape=num_elements) self.add_subsystem('inputs_comp', inputs_comp) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/compliance_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/compliance_comp.py index b3b28d2243..2d08fb3d45 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/compliance_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/compliance_comp.py @@ -3,10 +3,10 @@ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class ComplianceComp(ExplicitComponent): +class ComplianceComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) @@ -29,7 +29,7 @@ def compute(self, inputs, outputs): outputs['compliance'] = np.dot(force_vector, inputs['displacements']) -class MultiComplianceComp(ExplicitComponent): +class MultiComplianceComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/displacements_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/displacements_comp.py index d6a1b8bac3..1dd6cee299 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/displacements_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/displacements_comp.py @@ -3,10 +3,10 @@ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class DisplacementsComp(ExplicitComponent): +class DisplacementsComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) @@ -29,7 +29,7 @@ def compute(self, inputs, outputs): outputs['displacements'] = inputs['d'][:2 * num_nodes] -class MultiDisplacementsComp(ExplicitComponent): +class MultiDisplacementsComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/local_stiffness_matrix_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/local_stiffness_matrix_comp.py index 998d15c759..52d63d6398 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/local_stiffness_matrix_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/local_stiffness_matrix_comp.py @@ -1,9 +1,10 @@ from __future__ import division import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class LocalStiffnessMatrixComp(ExplicitComponent): + +class LocalStiffnessMatrixComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/moment_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/moment_comp.py index 8270800216..b3950a8ff4 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/moment_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/moment_comp.py @@ -1,9 +1,11 @@ from __future__ import division + import numpy as np -from openmdao.api import ExplicitComponent + +import openmdao.api as om -class MomentOfInertiaComp(ExplicitComponent): +class MomentOfInertiaComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/states_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/states_comp.py index 181e656a22..784439271e 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/states_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/states_comp.py @@ -5,10 +5,10 @@ from scipy.sparse import coo_matrix from scipy.sparse.linalg import splu -from openmdao.api import ImplicitComponent +import openmdao.api as om -class StatesComp(ImplicitComponent): +class StatesComp(om.ImplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) @@ -120,7 +120,7 @@ def assemble_CSC_K(self, inputs): return coo_matrix((data, (rows, cols)), shape=(n_K, n_K)).tocsc() -class MultiStatesComp(ImplicitComponent): +class MultiStatesComp(om.ImplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/stress_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/stress_comp.py index 846f8887d7..e95a14c745 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/stress_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/stress_comp.py @@ -10,10 +10,10 @@ import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class MultiStressComp(ExplicitComponent): +class MultiStressComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/components/volume_comp.py b/openmdao/test_suite/test_examples/beam_optimization/components/volume_comp.py index d8ff827ef3..c3f3d4a7be 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/components/volume_comp.py +++ b/openmdao/test_suite/test_examples/beam_optimization/components/volume_comp.py @@ -1,9 +1,10 @@ from __future__ import division import numpy as np -from openmdao.api import ExplicitComponent +import openmdao.api as om -class VolumeComp(ExplicitComponent): + +class VolumeComp(om.ExplicitComponent): def initialize(self): self.options.declare('num_elements', types=int) diff --git a/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_group.py b/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_group.py index 14cfd51bb1..c44fab79ef 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_group.py +++ b/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_group.py @@ -8,8 +8,7 @@ import numpy as np -from openmdao.api import Group, IndepVarComp, ParallelGroup, ExecComp -from openmdao.components.bsplines_comp import BsplinesComp +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.components.compliance_comp import MultiComplianceComp from openmdao.test_suite.test_examples.beam_optimization.components.displacements_comp import MultiDisplacementsComp @@ -51,7 +50,7 @@ def divide_cases(ncases, nprocs): return data -class MultipointBeamGroup(Group): +class MultipointBeamGroup(om.Group): def initialize(self): self.options.declare('E') @@ -72,12 +71,12 @@ def setup(self): num_cp = self.options['num_cp'] num_load_cases = self.options['num_load_cases'] - inputs_comp = IndepVarComp() + inputs_comp = om.IndepVarComp() inputs_comp.add_output('h_cp', shape=num_cp) self.add_subsystem('inputs_comp', inputs_comp) - comp = BsplinesComp(num_control_points=num_cp, num_points=num_elements, in_name='h_cp', - out_name='h') + comp = om.BsplinesComp(num_control_points=num_cp, num_points=num_elements, + in_name='h_cp', out_name='h') self.add_subsystem('interp', comp) I_comp = MomentOfInertiaComp(num_elements=num_elements, b=b) @@ -87,7 +86,7 @@ def setup(self): self.add_subsystem('local_stiffness_matrix_comp', comp) # Parallel Subsystem for load cases. - par = self.add_subsystem('parallel', ParallelGroup()) + par = self.add_subsystem('parallel', om.ParallelGroup()) # Determine how to split cases up over the available procs. nprocs = self.comm.size @@ -98,7 +97,7 @@ def setup(self): num_rhs = len(this_proc) name = 'sub_%d' % j - sub = par.add_subsystem(name, Group()) + sub = par.add_subsystem(name, om.Group()) # Load is a sinusoidal distributed force of varying spatial frequency. force_vector = np.zeros((2 * num_nodes, num_rhs)) @@ -139,7 +138,7 @@ def setup(self): comp = VolumeComp(num_elements=num_elements, b=b, L=L) self.add_subsystem('volume_comp', comp) - comp = ExecComp(['obj = ' + ' + '.join(['compliance_%d' % i for i in range(num_load_cases)])]) + comp = om.ExecComp(['obj = ' + ' + '.join(['compliance_%d' % i for i in range(num_load_cases)])]) self.add_subsystem('obj_sum', comp) for j, src in enumerate(obj_srcs): diff --git a/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_stress.py b/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_stress.py index 42869d0e93..35854523f9 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_stress.py +++ b/openmdao/test_suite/test_examples/beam_optimization/multipoint_beam_stress.py @@ -9,9 +9,7 @@ import numpy as np -from openmdao.api import Group, IndepVarComp, ParallelGroup, ExecComp -from openmdao.components.bsplines_comp import BsplinesComp -from openmdao.components.ks_comp import KSComp +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.components.displacements_comp import MultiDisplacementsComp from openmdao.test_suite.test_examples.beam_optimization.components.local_stiffness_matrix_comp import LocalStiffnessMatrixComp @@ -53,7 +51,7 @@ def divide_cases(ncases, nprocs): return data -class MultipointBeamGroup(Group): +class MultipointBeamGroup(om.Group): """ System setup for minimization of volume (i.e., mass) subject to KS aggregated bending stress constraints. """ @@ -81,12 +79,12 @@ def setup(self): num_load_cases = self.options['num_load_cases'] parallel_derivs = self.options['parallel_derivs'] - inputs_comp = IndepVarComp() + inputs_comp = om.IndepVarComp() inputs_comp.add_output('h_cp', shape=num_cp) self.add_subsystem('inputs_comp', inputs_comp) - comp = BsplinesComp(num_control_points=num_cp, num_points=num_elements, in_name='h_cp', - out_name='h') + comp = om.BsplinesComp(num_control_points=num_cp, num_points=num_elements, in_name='h_cp', + out_name='h') self.add_subsystem('interp', comp) I_comp = MomentOfInertiaComp(num_elements=num_elements, b=b) @@ -96,7 +94,7 @@ def setup(self): self.add_subsystem('local_stiffness_matrix_comp', comp) # Parallel Subsystem for load cases. - par = self.add_subsystem('parallel', ParallelGroup()) + par = self.add_subsystem('parallel', om.ParallelGroup()) # Determine how to split cases up over the available procs. nprocs = self.comm.size @@ -106,7 +104,7 @@ def setup(self): num_rhs = len(this_proc) name = 'sub_%d' % j - sub = par.add_subsystem(name, Group()) + sub = par.add_subsystem(name, om.Group()) # Load is a sinusoidal distributed force of varying spatial frequency. force_vector = np.zeros((2 * num_nodes, num_rhs)) @@ -142,7 +140,7 @@ def setup(self): 'displacements_comp.displacements_%d' % k, 'stress_comp.displacements_%d' % k) - comp = KSComp(width=num_elements) + comp = om.KSComp(width=num_elements) comp.options['upper'] = max_bending sub.add_subsystem('KS_%d' % k, comp) diff --git a/openmdao/test_suite/test_examples/beam_optimization/test_beam_optimization.py b/openmdao/test_suite/test_examples/beam_optimization/test_beam_optimization.py index 66afad4117..ed5fd1861b 100644 --- a/openmdao/test_suite/test_examples/beam_optimization/test_beam_optimization.py +++ b/openmdao/test_suite/test_examples/beam_optimization/test_beam_optimization.py @@ -4,7 +4,7 @@ from openmdao.utils.assert_utils import assert_rel_error -from openmdao.api import Problem, ScipyOptimizeDriver +import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.beam_group import BeamGroup from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_group import MultipointBeamGroup @@ -19,8 +19,7 @@ class TestCase(unittest.TestCase): def test(self): import numpy as np - from openmdao.api import Problem, ScipyOptimizeDriver - + import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.beam_group import BeamGroup E = 1. @@ -30,9 +29,9 @@ def test(self): num_elements = 50 - prob = Problem(model=BeamGroup(E=E, L=L, b=b, volume=volume, num_elements=num_elements)) + prob = om.Problem(model=BeamGroup(E=E, L=L, b=b, volume=volume, num_elements=num_elements)) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True @@ -55,8 +54,7 @@ def test(self): def test_multipoint(self): import numpy as np - from openmdao.api import Problem, ScipyOptimizeDriver - + import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_group import MultipointBeamGroup E = 1. @@ -68,11 +66,13 @@ def test_multipoint(self): num_elements = 50 num_load_cases = 2 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + model = MultipointBeamGroup(E=E, L=L, b=b, volume=volume, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases) - prob.driver = ScipyOptimizeDriver() + prob = om.Problem(model=model) + + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True @@ -95,8 +95,7 @@ def test_multipoint(self): def test_multipoint_stress(self): import numpy as np - from openmdao.api import Problem, ScipyOptimizeDriver - + import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_stress import MultipointBeamGroup E = 1. @@ -109,11 +108,13 @@ def test_multipoint_stress(self): num_elements = 25 num_load_cases = 2 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, max_bending = max_bending, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + model = MultipointBeamGroup(E=E, L=L, b=b, volume=volume, max_bending = max_bending, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases) - prob.driver = ScipyOptimizeDriver() + prob = om.Problem(model=model) + + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True @@ -138,8 +139,7 @@ class TestParallelGroups(unittest.TestCase): def test_multipoint(self): import numpy as np - from openmdao.api import Problem, ScipyOptimizeDriver - + import openmdao.api as om from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_group import MultipointBeamGroup E = 1. @@ -151,11 +151,13 @@ def test_multipoint(self): num_elements = 50 num_load_cases = 2 - prob = Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, - num_elements=num_elements, num_cp=num_cp, - num_load_cases=num_load_cases)) + model = MultipointBeamGroup(E=E, L=L, b=b, volume=volume, + num_elements=num_elements, num_cp=num_cp, + num_load_cases=num_load_cases) + + prob = om.Problem(model=model) - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True diff --git a/openmdao/test_suite/test_examples/test_betz_limit.py b/openmdao/test_suite/test_examples/test_betz_limit.py index af11897602..37ebeb6480 100644 --- a/openmdao/test_suite/test_examples/test_betz_limit.py +++ b/openmdao/test_suite/test_examples/test_betz_limit.py @@ -5,12 +5,12 @@ import scipy +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -from openmdao.api import Problem, ScipyOptimizeDriver, IndepVarComp, ExplicitComponent # duplicate definition here so it can be included in docs by itself -class ActuatorDisc(ExplicitComponent): +class ActuatorDisc(om.ExplicitComponent): """Simple wind turbine model based on actuator disc theory""" def setup(self): @@ -90,14 +90,15 @@ def compute_partials(self, inputs, J): J['power', 'rho'] = 2.0 * a_times_area * Vu ** 3 * (one_minus_a)**2 J['power', 'Vu'] = 6.0 * Area * Vu**2 * a * rho * one_minus_a**2 + class TestBetzLimit(unittest.TestCase): def test_betz(self): from distutils.version import LooseVersion import scipy - from openmdao.api import Problem, ScipyOptimizeDriver, IndepVarComp, ExplicitComponent + import openmdao.api as om - class ActuatorDisc(ExplicitComponent): + class ActuatorDisc(om.ExplicitComponent): """Simple wind turbine model based on actuator disc theory""" def setup(self): @@ -180,8 +181,8 @@ def compute_partials(self, inputs, J): # build the model - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('a', .5) indeps.add_output('Area', 10.0, units='m**2') indeps.add_output('rho', 1.225, units='kg/m**3') @@ -191,7 +192,7 @@ def compute_partials(self, inputs, J): promotes_inputs=['a', 'Area', 'rho', 'Vu']) # setup the optimization - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('a', lower=0., upper=1.) @@ -213,16 +214,15 @@ def compute_partials(self, inputs, J): raise unittest.SkipTest(msg) def test_betz_derivatives(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.test_examples.test_betz_limit import ActuatorDisc - prob = Problem() + prob = om.Problem() prob.model.add_subsystem('a_disk', ActuatorDisc()) prob.setup() - prob.check_partials(compact_print=True) diff --git a/openmdao/test_suite/test_examples/test_circuit_analysis.py b/openmdao/test_suite/test_examples/test_circuit_analysis.py index 357d2ec4cd..bee1cb4700 100644 --- a/openmdao/test_suite/test_examples/test_circuit_analysis.py +++ b/openmdao/test_suite/test_examples/test_circuit_analysis.py @@ -3,7 +3,7 @@ import unittest -from openmdao.api import ExplicitComponent, ImplicitComponent, Group, NewtonSolver, DirectSolver +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error @@ -11,11 +11,10 @@ class TestCircuit(unittest.TestCase): def test_circuit_plain_newton_assembled(self): - from openmdao.api import Group, NewtonSolver, DirectSolver, Problem, IndepVarComp - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node - class Circuit(Group): + class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')]) @@ -33,20 +32,20 @@ def setup(self): self.connect('R2.I', 'n2.I_in:0') self.connect('D1.I', 'n2.I_out:0') - self.nonlinear_solver = NewtonSolver() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 20 ################################################################## # Assemble at the group level. Default assembled jac type is 'csc' ################################################################## self.options['assembled_jac_type'] = 'csc' - self.linear_solver = DirectSolver(assemble_jac=True) + self.linear_solver = om.DirectSolver(assemble_jac=True) - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -71,11 +70,10 @@ def setup(self): def test_circuit_plain_newton(self): - from openmdao.api import Group, NewtonSolver, DirectSolver, Problem, IndepVarComp - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node - class Circuit(Group): + class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')]) @@ -93,16 +91,16 @@ def setup(self): self.connect('R2.I', 'n2.I_in:0') self.connect('D1.I', 'n2.I_out:0') - self.nonlinear_solver = NewtonSolver() + self.nonlinear_solver = om.NewtonSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 20 - self.linear_solver = DirectSolver() + self.linear_solver = om.DirectSolver() - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -127,15 +125,14 @@ def setup(self): def test_circuit_plain_newton_many_iter(self): - from openmdao.api import Problem, IndepVarComp - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -160,15 +157,14 @@ def test_circuit_plain_newton_many_iter(self): assert_rel_error(self, p['circuit.R1.I'] + p['circuit.D1.I'], 0.09987447, 1e-6) def test_circuit_advanced_newton(self): - from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') @@ -181,7 +177,7 @@ def test_circuit_advanced_newton(self): newton.options['iprint'] = 2 newton.options['maxiter'] = 10 newton.options['solve_subsystems'] = True - newton.linesearch = ArmijoGoldsteinLS() + newton.linesearch = om.ArmijoGoldsteinLS() newton.linesearch.options['maxiter'] = 10 newton.linesearch.options['iprint'] = 2 @@ -201,24 +197,23 @@ def test_circuit_advanced_newton(self): assert_rel_error(self, p['circuit.R1.I'] + p['circuit.D1.I'], .1, 1e-6) def test_circuit_voltage_source(self): - from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp, BalanceComp, ExecComp - from openmdao.api import NewtonSolver, DirectSolver, NonlinearRunOnce, LinearRunOnce - + import openmdao.api as om from openmdao.test_suite.scripts.circuit_analysis import Circuit - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) # replacing the fixed current source with a BalanceComp to represent a fixed Voltage source - # model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) - model.add_subsystem('batt', IndepVarComp('V', 1.5, units='V')) - bal = model.add_subsystem('batt_balance', BalanceComp()) + # model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('batt', om.IndepVarComp('V', 1.5, units='V')) + bal = model.add_subsystem('batt_balance', om.BalanceComp()) bal.add_balance('I', units='A', eq_units='V') model.add_subsystem('circuit', Circuit()) - model.add_subsystem('batt_deltaV', ExecComp('dV = V1 - V2', V1={'units':'V'}, V2={'units':'V'}, dV={'units':'V'})) + model.add_subsystem('batt_deltaV', om.ExecComp('dV = V1 - V2', V1={'units':'V'}, + V2={'units':'V'}, dV={'units':'V'})) # current into the circuit is now the output state from the batt_balance comp model.connect('batt_balance.I', 'circuit.I_in') @@ -237,16 +232,16 @@ def test_circuit_voltage_source(self): # change the circuit solver to RunOnce because we're # going to converge at the top level of the model with newton instead - p.model.circuit.nonlinear_solver = NonlinearRunOnce() - p.model.circuit.linear_solver = LinearRunOnce() + p.model.circuit.nonlinear_solver = om.NonlinearRunOnce() + p.model.circuit.linear_solver = om.LinearRunOnce() # Put Newton at the top so it can also converge the new BalanceComp residual - newton = p.model.nonlinear_solver = NewtonSolver() - p.model.linear_solver = DirectSolver() + newton = p.model.nonlinear_solver = om.NewtonSolver() + p.model.linear_solver = om.DirectSolver() newton.options['iprint'] = 2 newton.options['maxiter'] = 20 newton.options['solve_subsystems'] = True - newton.linesearch = ArmijoGoldsteinLS() + newton.linesearch = om.ArmijoGoldsteinLS() newton.linesearch.options['maxiter'] = 10 newton.linesearch.options['iprint'] = 2 diff --git a/openmdao/test_suite/test_examples/test_circuit_analysis_derivs.py b/openmdao/test_suite/test_examples/test_circuit_analysis_derivs.py index cd6fedf462..429452128d 100644 --- a/openmdao/test_suite/test_examples/test_circuit_analysis_derivs.py +++ b/openmdao/test_suite/test_examples/test_circuit_analysis_derivs.py @@ -1,11 +1,9 @@ import unittest -from openmdao.utils.assert_utils import assert_rel_error - import numpy as np -from openmdao.api import ExplicitComponent, ImplicitComponent, NewtonSolver, DirectSolver, ArmijoGoldsteinLS -from openmdao.api import IndepVarComp, Problem, Group +import openmdao.api as om +from openmdao.utils.assert_utils import assert_rel_error class TestNonlinearCircuit(unittest.TestCase): @@ -13,10 +11,9 @@ class TestNonlinearCircuit(unittest.TestCase): def test_nonlinear_circuit_analysis(self): import numpy as np - from openmdao.api import ExplicitComponent, ImplicitComponent, NewtonSolver, DirectSolver, ArmijoGoldsteinLS - from openmdao.api import IndepVarComp, Problem, Group + import openmdao.api as om - class Resistor(ExplicitComponent): + class Resistor(om.ExplicitComponent): """Computes current across a resistor using Ohm's law.""" def initialize(self): @@ -36,7 +33,7 @@ def compute(self, inputs, outputs): deltaV = inputs['V_in'] - inputs['V_out'] outputs['I'] = deltaV / self.options['R'] - class Diode(ExplicitComponent): + class Diode(om.ExplicitComponent): """Computes current across a diode using the Shockley diode equation.""" def initialize(self): @@ -67,7 +64,7 @@ def compute_partials(self, inputs, J): J['I', 'V_in'] = I/Vt J['I', 'V_out'] = -I/Vt - class Node(ImplicitComponent): + class Node(om.ImplicitComponent): """Computes voltage residual across a node based on incoming and outgoing current.""" def initialize(self): @@ -97,7 +94,7 @@ def apply_nonlinear(self, inputs, outputs, residuals): for i_conn in range(self.options['n_out']): residuals['V'] -= inputs['I_out:{}'.format(i_conn)] - class Circuit(Group): + class Circuit(om.Group): def setup(self): self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')]) @@ -115,22 +112,22 @@ def setup(self): self.connect('R2.I', 'n2.I_in:0') self.connect('D1.I', 'n2.I_out:0') - self.nonlinear_solver = NewtonSolver() - self.linear_solver = DirectSolver() + self.nonlinear_solver = om.NewtonSolver() + self.linear_solver = om.DirectSolver() self.nonlinear_solver.options['iprint'] = 2 self.nonlinear_solver.options['maxiter'] = 10 self.nonlinear_solver.options['solve_subsystems'] = True - self.nonlinear_solver.linesearch = ArmijoGoldsteinLS() + self.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS() self.nonlinear_solver.linesearch.options['maxiter'] = 10 self.nonlinear_solver.linesearch.options['iprint'] = 2 - p = Problem() + p = om.Problem() model = p.model - model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) - model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) + model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V')) + model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') diff --git a/openmdao/test_suite/test_examples/test_hohmann_transfer.py b/openmdao/test_suite/test_examples/test_hohmann_transfer.py index 1d3c3a8136..1b5bbdcad7 100644 --- a/openmdao/test_suite/test_examples/test_hohmann_transfer.py +++ b/openmdao/test_suite/test_examples/test_hohmann_transfer.py @@ -3,15 +3,14 @@ Low Earth Orbit (LEO) to Geostationary Orbit (GEO) """ from __future__ import print_function, division, absolute_import - import unittest import numpy as np -from openmdao.api import Problem, Group, ExplicitComponent, IndepVarComp, \ - ExecComp, ScipyOptimizeDriver + +import openmdao.api as om -class VCircComp(ExplicitComponent): +class VCircComp(om.ExplicitComponent): """ Computes the circular orbit velocity given a radius and gravitational parameter. @@ -54,7 +53,7 @@ def compute_partials(self, inputs, partials): partials['vcirc', 'r'] = -0.5 * mu / (vcirc * r ** 2) -class DeltaVComp(ExplicitComponent): +class DeltaVComp(om.ExplicitComponent): """ Compute the delta-V performed given the magnitude of two velocities and the angle between them. @@ -95,7 +94,7 @@ def compute_partials(self, inputs, partials): partials['delta_v', 'dinc'] = 0.5 / delta_v * (2 * v1 * v2 * np.sin(dinc)) -class TransferOrbitComp(ExplicitComponent): +class TransferOrbitComp(om.ExplicitComponent): def initialize(self): pass @@ -131,14 +130,14 @@ def compute(self, inputs, outputs): class TestHohmannTransfer(unittest.TestCase): def test_dv_at_apogee(self): - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ScipyOptimizeDriver + import openmdao.api as om from openmdao.test_suite.test_examples.test_hohmann_transfer import VCircComp, TransferOrbitComp, DeltaVComp - prob = Problem(model=Group()) + prob = om.Problem() model = prob.model - ivc = model.add_subsystem('ivc', IndepVarComp(), promotes_outputs=['*']) + ivc = model.add_subsystem('ivc', om.IndepVarComp(), promotes_outputs=['*']) ivc.add_output('mu', val=0.0, units='km**3/s**2') ivc.add_output('r1', val=0.0, units='km') ivc.add_output('r2', val=0.0, units='km') @@ -168,26 +167,26 @@ def test_dv_at_apogee(self): model.connect('dinc2', 'dv2.dinc') model.add_subsystem('dv_total', - subsys=ExecComp('delta_v=dv1+dv2', - delta_v={'units': 'km/s'}, - dv1={'units': 'km/s'}, - dv2={'units': 'km/s'}), + subsys=om.ExecComp('delta_v=dv1+dv2', + delta_v={'units': 'km/s'}, + dv1={'units': 'km/s'}, + dv2={'units': 'km/s'}), promotes=['delta_v']) model.connect('dv1.delta_v', 'dv_total.dv1') model.connect('dv2.delta_v', 'dv_total.dv2') model.add_subsystem('dinc_total', - subsys=ExecComp('dinc=dinc1+dinc2', - dinc={'units': 'deg'}, - dinc1={'units': 'deg'}, - dinc2={'units': 'deg'}), + subsys=om.ExecComp('dinc=dinc1+dinc2', + dinc={'units': 'deg'}, + dinc1={'units': 'deg'}, + dinc2={'units': 'deg'}), promotes=['dinc']) model.connect('dinc1', 'dinc_total.dinc1') model.connect('dinc2', 'dinc_total.dinc2') - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() model.add_design_var('dinc1', lower=0, upper=28.5) model.add_design_var('dinc2', lower=0, upper=28.5) diff --git a/openmdao/test_suite/test_examples/test_keplers_equation.py b/openmdao/test_suite/test_examples/test_keplers_equation.py index 19f842f7b2..21dacafe88 100644 --- a/openmdao/test_suite/test_examples/test_keplers_equation.py +++ b/openmdao/test_suite/test_examples/test_keplers_equation.py @@ -5,8 +5,8 @@ import numpy as np from numpy.testing import assert_almost_equal -from openmdao.api import Problem, Group, IndepVarComp, BalanceComp, \ - ExecComp, DirectSolver, NewtonSolver +import openmdao.api as om + class TestKeplersEquation(unittest.TestCase): @@ -14,12 +14,11 @@ def test_result(self): import numpy as np from numpy.testing import assert_almost_equal - from openmdao.api import Problem, Group, IndepVarComp, BalanceComp, \ - ExecComp, DirectSolver, NewtonSolver + import openmdao.api as om - prob = Problem() + prob = om.Problem() - ivc = IndepVarComp() + ivc = om.IndepVarComp() ivc.add_output(name='M', val=0.0, @@ -31,7 +30,7 @@ def test_result(self): units=None, desc='orbit eccentricity') - bal = BalanceComp() + bal = om.BalanceComp() bal.add_balance(name='E', val=0.0, units='rad', eq_units='rad', rhs_name='M') @@ -42,10 +41,10 @@ def guess_function(inputs, outputs, residuals): bal.options['guess_func'] = guess_function # ExecComp used to compute the LHS of Kepler's equation. - lhs_comp = ExecComp('lhs=E - ecc * sin(E)', - lhs={'value': 0.0, 'units': 'rad'}, - E={'value': 0.0, 'units': 'rad'}, - ecc={'value': 0.0}) + lhs_comp = om.ExecComp('lhs=E - ecc * sin(E)', + lhs={'value': 0.0, 'units': 'rad'}, + E={'value': 0.0, 'units': 'rad'}, + ecc={'value': 0.0}) prob.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['M', 'ecc']) @@ -61,8 +60,8 @@ def guess_function(inputs, outputs, residuals): prob.model.connect('lhs_comp.lhs', 'balance.lhs:E') # Set up solvers - prob.model.linear_solver = DirectSolver() - prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) + prob.model.linear_solver = om.DirectSolver() + prob.model.nonlinear_solver = om.NewtonSolver(maxiter=100, iprint=0) prob.setup() diff --git a/openmdao/test_suite/test_examples/test_sellar_mda_promote_connect.py b/openmdao/test_suite/test_examples/test_sellar_mda_promote_connect.py index c3f0c9b972..7e6d588a29 100644 --- a/openmdao/test_suite/test_examples/test_sellar_mda_promote_connect.py +++ b/openmdao/test_suite/test_examples/test_sellar_mda_promote_connect.py @@ -1,48 +1,51 @@ from __future__ import print_function, division import unittest + import numpy as np -from openmdao.api import Group, IndepVarComp, ExecComp, NonlinearBlockGS +import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1, SellarDis2 - from openmdao.utils.assert_utils import assert_rel_error - class TestSellarMDAPromoteConnect(unittest.TestCase): def test_sellar_mda_promote(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockGS + + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1, SellarDis2 - class SellarMDA(Group): + class SellarMDA(om.Group): """ Group containing the Sellar MDA. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group(), promotes=['*']) - cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], promotes_outputs=['y1']) - cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], promotes_outputs=['y2']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['*']) + cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'], + promotes_outputs=['y1']) + cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'], + promotes_outputs=['y2']) # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver =om. NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0), + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0), promotes=['x', 'z', 'y1', 'y2', 'obj']) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), + promotes=['con1', 'y1']) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), + promotes=['con2', 'y2']) - prob = Problem() - + prob = om.Problem() prob.model = SellarMDA() prob.setup() @@ -58,41 +61,41 @@ def setup(self): def test_sellar_mda_connect(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockGS + + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1, SellarDis2 - class SellarMDAConnect(Group): + class SellarMDAConnect(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines without derivatives. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp()) + indeps = self.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group()) + cycle = self.add_subsystem('cycle', om.Group()) cycle.add_subsystem('d1', SellarDis1()) cycle.add_subsystem('d2', SellarDis2()) cycle.connect('d1.y1', 'd2.y1') cycle.connect('d2.y2', 'd1.y2') # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0)) + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0)) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1')) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0')) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1')) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0')) self.connect('indeps.x', ['cycle.d1.x', 'obj_cmp.x']) self.connect('indeps.z', ['cycle.d1.z', 'cycle.d2.z', 'obj_cmp.z']) self.connect('cycle.d1.y1', ['obj_cmp.y1', 'con_cmp1.y1']) self.connect('cycle.d2.y2', ['obj_cmp.y2', 'con_cmp2.y2']) - prob = Problem() - + prob = om.Problem() prob.model = SellarMDAConnect() prob.setup() @@ -109,33 +112,33 @@ def setup(self): def test_sellar_mda_promote_connect(self): import numpy as np - from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NonlinearBlockGS + import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1, SellarDis2 - class SellarMDAPromoteConnect(Group): + class SellarMDAPromoteConnect(om.Group): """ Group containing the Sellar MDA. This version uses the disciplines without derivatives. """ def setup(self): - indeps = self.add_subsystem('indeps', IndepVarComp(), promotes=['*']) + indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*']) indeps.add_output('x', 1.0) indeps.add_output('z', np.array([5.0, 2.0])) - cycle = self.add_subsystem('cycle', Group(), promotes=['*']) + cycle = self.add_subsystem('cycle', om.Group(), promotes=['*']) cycle.add_subsystem('d1', SellarDis1()) cycle.add_subsystem('d2', SellarDis2()) cycle.connect('d1.y1', 'd2.y1') cycle.connect('d2.y2', 'd1.y2') # Nonlinear Block Gauss Seidel is a gradient free solver - cycle.nonlinear_solver = NonlinearBlockGS() + cycle.nonlinear_solver = om.NonlinearBlockGS() - self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', - z=np.array([0.0, 0.0]), x=0.0)) + self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', + z=np.array([0.0, 0.0]), x=0.0)) - self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1')) - self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0')) + self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1')) + self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0')) self.connect('x', ['d1.x', 'obj_cmp.x']) self.connect('z', ['d1.z', 'd2.z', 'obj_cmp.z']) @@ -143,8 +146,7 @@ def setup(self): self.connect('d2.y2', ['con_cmp2.y2', 'obj_cmp.y2']) - prob = Problem() - + prob = om.Problem() prob.model = SellarMDAPromoteConnect() prob.setup() diff --git a/openmdao/test_suite/test_examples/test_sellar_opt.py b/openmdao/test_suite/test_examples/test_sellar_opt.py index 306796e954..5107c2d1ac 100644 --- a/openmdao/test_suite/test_examples/test_sellar_opt.py +++ b/openmdao/test_suite/test_examples/test_sellar_opt.py @@ -2,21 +2,20 @@ import unittest +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error -from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp, DirectSolver - class TestSellarOpt(unittest.TestCase): def test_sellar_opt(self): - from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp, DirectSolver + import openmdao.api as om from openmdao.test_suite.components.sellar_feature import SellarMDA - prob = Problem() + prob = om.Problem() prob.model = SellarMDA() - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' # prob.driver.options['maxiter'] = 100 prob.driver.options['tol'] = 1e-8 diff --git a/openmdao/test_suite/test_examples/test_tldr_paraboloid_b.py b/openmdao/test_suite/test_examples/test_tldr_paraboloid_b.py index e4f638b576..6e1d12d260 100644 --- a/openmdao/test_suite/test_examples/test_tldr_paraboloid_b.py +++ b/openmdao/test_suite/test_examples/test_tldr_paraboloid_b.py @@ -8,21 +8,21 @@ class TestParaboloidTLDR(unittest.TestCase): def test_tldr(self): - from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp + import openmdao.api as om # build the model - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp()) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 3.0) indeps.add_output('y', -4.0) - prob.model.add_subsystem('paraboloid', ExecComp('f = (x-3)**2 + x*y + (y+4)**2 - 3')) + prob.model.add_subsystem('paraboloid', om.ExecComp('f = (x-3)**2 + x*y + (y+4)**2 - 3')) prob.model.connect('indeps.x', 'paraboloid.x') prob.model.connect('indeps.y', 'paraboloid.y') # setup the optimization - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('indeps.x', lower=-50, upper=50) diff --git a/openmdao/test_suite/test_examples/tldr_paraboloid.py b/openmdao/test_suite/test_examples/tldr_paraboloid.py index 49367f8033..c1ee40040a 100644 --- a/openmdao/test_suite/test_examples/tldr_paraboloid.py +++ b/openmdao/test_suite/test_examples/tldr_paraboloid.py @@ -8,21 +8,21 @@ class TestParaboloidTLDR(unittest.TestCase): def test_tldr(self): - from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp + import openmdao.api as om # build the model - prob = Problem() - indeps = prob.model.add_subsystem('indeps', IndepVarComp()) + prob = om.Problem() + indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('x', 3.0) indeps.add_output('y', -4.0) - prob.model.add_subsystem('paraboloid', ExecComp('f = (x-3)**2 + x*y + (y+4)**2 - 3')) + prob.model.add_subsystem('paraboloid', om.ExecComp('f = (x-3)**2 + x*y + (y+4)**2 - 3')) prob.model.connect('indeps.x', 'paraboloid.x') prob.model.connect('indeps.y', 'paraboloid.y') # setup the optimization - prob.driver = ScipyOptimizeDriver() + prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('indeps.x', lower=-50, upper=50) diff --git a/openmdao/test_suite/tests/test_feature_sellar.py b/openmdao/test_suite/tests/test_feature_sellar.py index f888538c9f..b31476a368 100644 --- a/openmdao/test_suite/tests/test_feature_sellar.py +++ b/openmdao/test_suite/tests/test_feature_sellar.py @@ -2,18 +2,18 @@ import unittest -from openmdao.api import Problem +import openmdao.api as om +from openmdao.test_suite.components.sellar_feature import SellarMDA, SellarMDALinearSolver from openmdao.utils.assert_utils import assert_rel_error -from openmdao.test_suite.components.sellar_feature import SellarMDA, SellarMDALinearSolver, IndepVarComp class TestSellarFeature(unittest.TestCase): def test_sellar(self): - prob = Problem() + prob = om.Problem() prob.model = SellarMDA() - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) @@ -25,10 +25,10 @@ def test_sellar(self): def test_sellar_linear_solver(self): - prob = Problem() + prob = om.Problem() prob.model = SellarMDALinearSolver() - prob.setup(check=False) + prob.setup() prob.model.cycle.nonlinear_solver.options['use_apply_nonlinear'] = True prob.run_model() @@ -47,5 +47,6 @@ def test_sellar_linear_solver(self): assert_rel_error(self, jac['con2', 'x'][0], 0.09692762, 1e-4) assert_rel_error(self, jac['con2', 'z'][0], [1.94989079, 1.0775421], 1e-4) + if __name__ == "__main__": unittest.main() diff --git a/openmdao/test_suite/tests/test_paraboloid_feature.py b/openmdao/test_suite/tests/test_paraboloid_feature.py index 6edcc3d211..29c8e04150 100644 --- a/openmdao/test_suite/tests/test_paraboloid_feature.py +++ b/openmdao/test_suite/tests/test_paraboloid_feature.py @@ -2,7 +2,7 @@ import unittest -from openmdao.api import Problem, Group, IndepVarComp +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error from openmdao.test_suite.components.paraboloid_feature import Paraboloid @@ -11,17 +11,17 @@ class TestSellarFeature(unittest.TestCase): def test_paraboloid_feature(self): - prob = Problem() - model = prob.model = Group() + prob = om.Problem() + model = prob.model - model.add_subsystem('p1', IndepVarComp('x', 3.0)) - model.add_subsystem('p2', IndepVarComp('y', -4.0)) + model.add_subsystem('p1', om.IndepVarComp('x', 3.0)) + model.add_subsystem('p2', om.IndepVarComp('y', -4.0)) model.add_subsystem('comp', Paraboloid()) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') - prob.setup(check=False) + prob.setup() prob.run_model() assert_rel_error(self, prob['comp.f_xy'], -15.0) diff --git a/openmdao/test_suite/tests/test_quad_implicit.py b/openmdao/test_suite/tests/test_quad_implicit.py index e4a5e53153..d985984bc3 100644 --- a/openmdao/test_suite/tests/test_quad_implicit.py +++ b/openmdao/test_suite/tests/test_quad_implicit.py @@ -2,21 +2,20 @@ import numpy as np -from openmdao.api import Problem +import openmdao.api as om from openmdao.test_suite.components.quad_implicit import QuadraticComp - class TestQuadImplicit(unittest.TestCase): def test_check_partials_for_docs(self): - from openmdao.api import Problem + import openmdao.api as om from openmdao.test_suite.components.quad_implicit import QuadraticComp - p = Problem() + p = om.Problem() p.model.add_subsystem('quad', QuadraticComp()) @@ -25,7 +24,7 @@ def test_check_partials_for_docs(self): p.check_partials(compact_print=True) def test_check_partials(self): - p = Problem() + p = om.Problem() p.model.add_subsystem('quad', QuadraticComp()) diff --git a/openmdao/utils/code_utils.py b/openmdao/utils/code_utils.py index 063afb0b15..efd845e4fc 100644 --- a/openmdao/utils/code_utils.py +++ b/openmdao/utils/code_utils.py @@ -241,5 +241,6 @@ def _calltree_exec(options): if __name__ == '__main__': - from openmdao.api import LinearBlockGS - get_nested_calls(LinearBlockGS, 'solve') + import openmdao.api as om + + get_nested_calls(om.LinearBlockGS, 'solve') diff --git a/openmdao/utils/tests/test_assert_utils.py b/openmdao/utils/tests/test_assert_utils.py index 099d3efdad..d5870a8402 100644 --- a/openmdao/utils/tests/test_assert_utils.py +++ b/openmdao/utils/tests/test_assert_utils.py @@ -39,7 +39,7 @@ def compute_partials(self, inputs, partials): prob.model = MyComp() prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -71,7 +71,7 @@ def compute_partials(self, inputs, partials): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -124,7 +124,7 @@ def compute_partials(self, inputs, partials): prob.set_solver_print(level=0) - prob.setup(check=False) + prob.setup() prob.run_model() data = prob.check_partials(out_stream=None) @@ -141,7 +141,7 @@ def test_assert_no_approx_partials_exception_expected(self): prob = Problem() prob.model = SellarNoDerivativesCS() - prob.setup(check=False) + prob.setup() try: assert_no_approx_partials(prob.model, include_self=True, recurse=True) @@ -163,7 +163,7 @@ def test_assert_no_approx_partials_exception_not_expected(self): prob = Problem() prob.model = DoubleSellar() - prob.setup(check=False) + prob.setup() assert_no_approx_partials(prob.model, include_self=True, recurse=True) @@ -172,7 +172,7 @@ def test_assert_no_dict_jacobians_exception_expected(self): prob = Problem() prob.model = SellarNoDerivativesCS() - prob.setup(check=False) + prob.setup() prob.model.cycle._jacobian = DictionaryJacobian(prob.model.cycle) try: @@ -199,6 +199,6 @@ def test_assert_no_dict_jacobians_exception_not_expected(self): prob = Problem(model) prob.model.linear_solver = DirectSolver(assemble_jac=True) - prob.setup(check=False) + prob.setup() assert_no_dict_jacobians(prob.model, include_self=True, recurse=True) diff --git a/openmdao/utils/tests/test_find_citations.py b/openmdao/utils/tests/test_find_citations.py index ccc79977f2..5915865909 100644 --- a/openmdao/utils/tests/test_find_citations.py +++ b/openmdao/utils/tests/test_find_citations.py @@ -17,7 +17,6 @@ def setUp(self): p = Problem() - p.model = Group() p.model.cite = "foobar model" p.model.nonlinear_solver.cite = "foobar nonlinear_solver" p.model.linear_solver.cite = "foobar linear_solver" @@ -139,8 +138,6 @@ def setUp(self): p = Problem() - p.model = Group() - p.model.cite = "foobar model" p.model.nonlinear_solver.cite = "foobar nonlinear_solver" p.model.linear_solver.cite = "foobar linear_solver" diff --git a/openmdao/utils/tests/test_options_dictionary_feature.py b/openmdao/utils/tests/test_options_dictionary_feature.py index 6ce6c389e3..0e2b7b45d2 100644 --- a/openmdao/utils/tests/test_options_dictionary_feature.py +++ b/openmdao/utils/tests/test_options_dictionary_feature.py @@ -1,18 +1,20 @@ -from openmdao.api import ExplicitComponent import unittest from six import PY3, assertRegex + import numpy as np + +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error class TestOptionsDictionaryFeature(unittest.TestCase): def test_simple(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp - prob = Problem() - prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) + prob = om.Problem() + prob.model.add_subsystem('inputs', om.IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp(size=3)) # 'size' is an option prob.model.connect('inputs.x', 'double.x') @@ -24,11 +26,11 @@ def test_simple(self): assert_rel_error(self, prob['double.y'], [2., 4., 6.]) def test_simple_fail(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp - prob = Problem() - prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) + prob = om.Problem() + prob.model.add_subsystem('inputs', om.IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) # 'size' not specified prob.model.connect('inputs.x', 'double.x') @@ -38,11 +40,11 @@ def test_simple_fail(self): self.assertEqual(str(err), "Option 'size' is required but has not been set.") def test_with_default(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.options_feature_lincomb import LinearCombinationComp - prob = Problem() - prob.model.add_subsystem('inputs', IndepVarComp('x')) + prob = om.Problem() + prob.model.add_subsystem('inputs', om.IndepVarComp('x')) prob.model.add_subsystem('linear', LinearCombinationComp(a=2.)) # 'b' not specified prob.model.connect('inputs.x', 'linear.x') @@ -56,11 +58,11 @@ def test_with_default(self): def test_simple_array(self): import numpy as np - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.options_feature_array import ArrayMultiplyComp - prob = Problem() - prob.model.add_subsystem('inputs', IndepVarComp('x', 1.)) + prob = om.Problem() + prob.model.add_subsystem('inputs', om.IndepVarComp('x', 1.)) prob.model.add_subsystem('a_comp', ArrayMultiplyComp(array=np.array([1, 2, 3]))) prob.model.connect('inputs.x', 'a_comp.x') @@ -73,14 +75,14 @@ def test_simple_array(self): assert_rel_error(self, prob['a_comp.y'], [5., 10., 15.]) def test_simple_function(self): - from openmdao.api import Problem, IndepVarComp + import openmdao.api as om from openmdao.test_suite.components.options_feature_function import UnitaryFunctionComp def my_func(x): return x*2 - prob = Problem() - prob.model.add_subsystem('inputs', IndepVarComp('x', 1.)) + prob = om.Problem() + prob.model.add_subsystem('inputs', om.IndepVarComp('x', 1.)) prob.model.add_subsystem('f_comp', UnitaryFunctionComp(func=my_func)) prob.model.connect('inputs.x', 'f_comp.x') diff --git a/openmdao/utils/tests/test_visualization.py b/openmdao/utils/tests/test_visualization.py index cd400388ab..98d7da770a 100644 --- a/openmdao/utils/tests/test_visualization.py +++ b/openmdao/utils/tests/test_visualization.py @@ -9,7 +9,7 @@ except ImportError: matplotlib = None -from openmdao.api import Problem, IndepVarComp, ExplicitComponent, Group, partial_deriv_plot +import openmdao.api as om from openmdao.utils.assert_utils import assert_rel_error @unittest.skipUnless(matplotlib, "Matplotlib is required.") @@ -20,7 +20,7 @@ def setUp(self): def test_partial_deriv_plot(self): - class ArrayComp2D(ExplicitComponent): + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component with an intentional error in compute_partials. """ @@ -50,15 +50,15 @@ def compute_partials(self, inputs, partials): error[1][2] = - 2.0 * err partials[('y1', 'x1')] = self.JJ + error - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), promotes=['x1']) + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) prob.setup(check=False, mode='fwd') check_partials_data = prob.check_partials(out_stream=None) # plot with defaults - fig, ax = partial_deriv_plot('y1', 'x1', check_partials_data, title="Defaults") + fig, ax = om.partial_deriv_plot('y1', 'x1', check_partials_data, title="Defaults") # Instead of seeing if the images created by matplotlib match what we expect, which # is a fragile thing to do in testing, check a data structure inside matplotlib's # objects. We will assume matplotlib draws the correct thing. @@ -82,8 +82,8 @@ def compute_partials(self, inputs, partials): assert_rel_error(self, expected_array, actual_array, 1e-8) # plot with specified jac_method - fig, ax = partial_deriv_plot('y1', 'x1', check_partials_data, jac_method = "J_rev", - title="specified jac_method") + fig, ax = om.partial_deriv_plot('y1', 'x1', check_partials_data, jac_method = "J_rev", + title="specified jac_method") expected_array = np.array([[1., 0., 0., 1.], [0., 1., 0., 0.], [1., 0., 1., 0.], @@ -104,8 +104,8 @@ def compute_partials(self, inputs, partials): assert_rel_error(self, expected_array, actual_array, 1e-8) # plot in non-binary mode - fig, ax = partial_deriv_plot('y1', 'x1', check_partials_data, binary = False, - title="non-binary") + fig, ax = om.partial_deriv_plot('y1', 'x1', check_partials_data, binary = False, + title="non-binary") expected_array = np.array([[ 1. , 0. , 0. , 7. ], [ 0. , 2.5, 0. , 0. ], [-1. , 0. , 8. , 0. ], @@ -127,10 +127,10 @@ def compute_partials(self, inputs, partials): # plot with different tol values # Not obvious how to test this other than image matching - partial_deriv_plot('y1', 'x1', check_partials_data, tol=1e-5, - title="tol greater than err") - partial_deriv_plot('y1', 'x1', check_partials_data, tol=1e-10, - title="tol less than err") + om.partial_deriv_plot('y1', 'x1', check_partials_data, tol=1e-5, + title="tol greater than err") + om.partial_deriv_plot('y1', 'x1', check_partials_data, tol=1e-10, + title="tol less than err") @unittest.skipUnless(matplotlib, "Matplotlib is required.") @@ -141,8 +141,9 @@ def setUp(self): def test_partial_deriv_plot(self): import numpy as np - from openmdao.api import ExplicitComponent, Problem, Group, IndepVarComp - class ArrayComp2D(ExplicitComponent): + import openmdao.api as om + + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component with an intentional error in compute_partials. """ @@ -174,20 +175,21 @@ def compute_partials(self, inputs, partials): error[1][2] = - 2.0 * err partials[('y1', 'x1')] = self.JJ + error - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), promotes=['x1']) + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) prob.setup(check=False, mode='fwd') check_partials_data = prob.check_partials(out_stream=None) # plot with defaults - partial_deriv_plot('y1', 'x1', check_partials_data) + om.partial_deriv_plot('y1', 'x1', check_partials_data) def test_partial_deriv_non_binary_plot(self): import numpy as np - from openmdao.api import ExplicitComponent, Problem, Group, IndepVarComp - class ArrayComp2D(ExplicitComponent): + import openmdao.api as om + + class ArrayComp2D(om.ExplicitComponent): """ A fairly simple array component with an intentional error in compute_partials. """ @@ -219,15 +221,15 @@ def compute_partials(self, inputs, partials): error[1][2] = - 2.0 * err partials[('y1', 'x1')] = self.JJ + error - prob = Problem() - prob.model = model = Group() - model.add_subsystem('x_param1', IndepVarComp('x1', np.ones((4))), promotes=['x1']) + prob = om.Problem() + model = prob.model + model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))), promotes=['x1']) model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1']) prob.setup(check=False, mode='fwd') check_partials_data = prob.check_partials(out_stream=None) # plot in non-binary mode - partial_deriv_plot('y1', 'x1', check_partials_data, binary = False) + om.partial_deriv_plot('y1', 'x1', check_partials_data, binary = False) if __name__ == "__main__":