Ejemplo n.º 1
0
    def test_beam_tutorial_viewmodel_using_data_from_sqlite_case_recorder_file(self):

        top = Problem()
        top.root = BeamTutorial()

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'
        top.driver.options['tol'] = 1.0e-8
        top.driver.options['maxiter'] = 10000 #maximum number of solver iterations
        top.driver.options['disp'] = False

        #room length and width bounds
        top.driver.add_desvar('ivc_rlength.room_length', lower=5.0*12.0, upper=50.0*12.0) #domain: 1in <= length <= 50ft
        top.driver.add_desvar('ivc_rwidth.room_width', lower=5.0*12.0, upper=30.0*12.0) #domain: 1in <= width <= 30ft

        top.driver.add_objective('d_neg_area.neg_room_area') #minimize negative area (or maximize area)

        top.driver.add_constraint('d_len_minus_wid.length_minus_width', lower=0.0) #room_length >= room_width
        top.driver.add_constraint('d_deflection.deflection', lower=720.0) #deflection >= 720
        top.driver.add_constraint('d_bending.bending_stress_ratio', upper=0.5) #bending < 0.5
        top.driver.add_constraint('d_shear.shear_stress_ratio', upper=1.0/3.0) #shear < 1/3

        tempdir = mkdtemp()
        case_recorder_filename = "tmp.sql"
        filename = os.path.join(tempdir, case_recorder_filename)
        recorder = SqliteRecorder(filename)
        top.driver.add_recorder(recorder)

        top.setup(check=False)

        top.run()
        view_model(filename, show_browser=False)

        self.assertTrue(os.path.isfile('partition_tree_n2.html'))
        os.remove('partition_tree_n2.html')
Ejemplo n.º 2
0
    def store_model_view(self, open_in_browser=False):
        # type: (bool) -> None
        """Implementation of the view_model() function for storage and (optionally) viewing in the browser.

        Parameters
        ----------
            open_in_browser : bool
                Setting whether to attempt to automatically open the model view in the browser.
        """
        if self._setup_status == 0:
            self.setup()
        view_model(self, outfile=self.model_view_path, show_browser=open_in_browser)
Ejemplo n.º 3
0
    def test_viewmodel_using_bogus_recorder_file_type(self):

        tempdir = mkdtemp()
        case_recorder_filename = "tmp.bogus"
        filename = os.path.join(tempdir, case_recorder_filename)
        # Just make an empty file
        open(filename, 'a').close()

        try:
            view_model(filename, show_browser=False)
        except Exception as err:
            self.assertEqual(str(err),
                "The given filename is not one of the supported file formats: sqlite or hdf5")
Ejemplo n.º 4
0
def run_problem(prob):

    prob.driver.options['debug_print'] = ['desvars', 'nl_cons', 'objs']

    # prob.model.approx_totals(method='fd')

    # Set up the problem
    prob.setup()

    from openmdao.api import view_model
    view_model(prob, show_browser=False)

    prob.run_driver()
Ejemplo n.º 5
0
    def run(self):
        """
        Method to actually run analysis or optimization. Also saves history in
        a .db file and creates an N2 diagram to view the problem hierarchy.
        """

        # Have more verbose output about optimization convergence
        if self.prob_dict['print_level']:
            self.prob.print_all_convergence()

        # Save an N2 diagram for the problem
        if self.prob_dict['record_db']:
            view_model(self.prob, outfile=self.prob_dict['prob_name']+".html", show_browser=False)

        # If `optimize` == True in prob_dict, perform optimization. Otherwise,
        # simply pass the problem since analysis has already been run.
        if not self.prob_dict['optimize']:
            # Run a single analysis loop. This shouldn't actually be
            # necessary, but sometimes the .db file is not complete unless we do this.
            self.prob.run_once()
        else:
            # Perform optimization
            self.prob.run()

        # If the problem type is aero or aerostruct, we can compute the static margin.
        # This is a naive tempoerary implementation that currently finite differences
        # over the entire model to obtain the static margin.
        if self.prob_dict['compute_static_margin'] and 'aero' in self.prob_dict['type']:

            # Turn off problem recording (so nothing for these computations
            # appears in the .db file) and get the current CL and CM.
            self.prob.driver.recorders._recorders = []
            CL = self.prob['wing_perf.CL']
            CM = self.prob['CM'][1]
            step = 1e-5

            # Perturb alpha and run an analysis loop to obtain the new CL and CM.
            self.prob['alpha'] += step
            self.prob.run_once()
            CL_new = self.prob['wing_perf.CL']
            CM_new = self.prob['CM'][1]

            # Un-perturb alpha and run a single analysis loop to get the problem
            # back to where it was before we finite differenced.
            self.prob['alpha'] -= step
            self.prob.run_once()

            # Compute, print, and save the static margin in metadata.
            static_margin = -(CM_new - CM) / (CL_new - CL)
            print("Static margin is:", static_margin)
            self.prob.root.add_metadata('static_margin', static_margin)
Ejemplo n.º 6
0
    def test_viewmodel_using_bogus_recorder_file_type(self):

        tempdir = mkdtemp()
        case_recorder_filename = "tmp.bogus"
        filename = os.path.join(tempdir, case_recorder_filename)
        # Just make an empty file
        open(filename, 'a').close()

        try:
            view_model(filename, show_browser=False)
        except Exception as err:
            self.assertEqual(
                str(err),
                "The given filename is not one of the supported file formats: sqlite or hdf5"
            )
Ejemplo n.º 7
0
    def test_beam_tutorial_viewmodel_using_data_from_hdf5_case_recorder_file(self):

        SKIP = False
        try:
            from openmdao.recorders.hdf5_recorder import HDF5Recorder
            import h5py
        except ImportError:
            # Necessary for the file to parse
            from openmdao.recorders.base_recorder import BaseRecorder
            HDF5Recorder = BaseRecorder
            SKIP = True

        if SKIP:
            raise unittest.SkipTest("Could not import HDF5Recorder. Is h5py installed?")

        top = Problem()
        top.root = BeamTutorial()

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'
        top.driver.options['tol'] = 1.0e-8
        top.driver.options['maxiter'] = 10000 #maximum number of solver iterations
        top.driver.options['disp'] = False

        #room length and width bounds
        top.driver.add_desvar('ivc_rlength.room_length', lower=5.0*12.0, upper=50.0*12.0) #domain: 1in <= length <= 50ft
        top.driver.add_desvar('ivc_rwidth.room_width', lower=5.0*12.0, upper=30.0*12.0) #domain: 1in <= width <= 30ft

        top.driver.add_objective('d_neg_area.neg_room_area') #minimize negative area (or maximize area)

        top.driver.add_constraint('d_len_minus_wid.length_minus_width', lower=0.0) #room_length >= room_width
        top.driver.add_constraint('d_deflection.deflection', lower=720.0) #deflection >= 720
        top.driver.add_constraint('d_bending.bending_stress_ratio', upper=0.5) #bending < 0.5
        top.driver.add_constraint('d_shear.shear_stress_ratio', upper=1.0/3.0) #shear < 1/3

        tempdir = mkdtemp()
        case_recorder_filename = "tmp.hdf5"
        filename = os.path.join(tempdir, case_recorder_filename)
        recorder = HDF5Recorder(filename)
        top.driver.add_recorder(recorder)

        top.setup(check=False)

        top.run()
        view_model(filename, show_browser=False)

        self.assertTrue(os.path.isfile('partition_tree_n2.html'))
        os.remove('partition_tree_n2.html')
Ejemplo n.º 8
0
    def test_beam_tutorial_viewmodel_using_data_from_sqlite_case_recorder_file(
            self):

        top = Problem()
        top.root = BeamTutorial()

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'
        top.driver.options['tol'] = 1.0e-8
        top.driver.options[
            'maxiter'] = 10000  #maximum number of solver iterations
        top.driver.options['disp'] = False

        #room length and width bounds
        top.driver.add_desvar('ivc_rlength.room_length',
                              lower=5.0 * 12.0,
                              upper=50.0 *
                              12.0)  #domain: 1in <= length <= 50ft
        top.driver.add_desvar('ivc_rwidth.room_width',
                              lower=5.0 * 12.0,
                              upper=30.0 * 12.0)  #domain: 1in <= width <= 30ft

        top.driver.add_objective('d_neg_area.neg_room_area'
                                 )  #minimize negative area (or maximize area)

        top.driver.add_constraint('d_len_minus_wid.length_minus_width',
                                  lower=0.0)  #room_length >= room_width
        top.driver.add_constraint('d_deflection.deflection',
                                  lower=720.0)  #deflection >= 720
        top.driver.add_constraint('d_bending.bending_stress_ratio',
                                  upper=0.5)  #bending < 0.5
        top.driver.add_constraint('d_shear.shear_stress_ratio',
                                  upper=1.0 / 3.0)  #shear < 1/3

        tempdir = mkdtemp()
        case_recorder_filename = "tmp.sql"
        filename = os.path.join(tempdir, case_recorder_filename)
        recorder = SqliteRecorder(filename)
        top.driver.add_recorder(recorder)

        top.setup(check=False)

        top.run()
        view_model(filename, show_browser=False)

        self.assertTrue(os.path.isfile('partition_tree_n2.html'))
        os.remove('partition_tree_n2.html')
Ejemplo n.º 9
0
    def run(self):
        """
        Method to actually run analysis or optimization. Also saves history in
        a .db file and creates an N2 diagram to view the problem hierarchy.
        """

        # Uncomment this to use finite differences over the entire model
        # self.prob.root.deriv_options['type'] = 'cs'

        # Record optimization history to a database
        # Data saved here can be examined using `plot_all.py`
        recorder = SqliteRecorder(self.prob_dict['prob_name'] + ".db")
        recorder.options['record_params'] = True
        recorder.options['record_derivs'] = True
        self.prob.driver.add_recorder(recorder)

        # Profile (time) the problem
        # profile.setup(self.prob)
        # profile.start()

        # Set up the problem
        self.prob.setup()

        # Uncomment this line to have more verbose output about convergence
        # self.prob.print_all_convergence()

        # Save an N2 diagram for the problem
        view_model(self.prob,
                   outfile=self.prob_dict['prob_name'] + ".html",
                   show_browser=False)

        # Run a single analysis loop to populate uninitialized values
        self.prob.run_once()

        # If `optimize` == True in prob_dict, perform optimization. Otherwise,
        # simply pass the problem since analysis has already been run.
        if not self.prob_dict['optimize']:  # run analysis once
            pass
        else:  # perform optimization
            self.prob.run()
Ejemplo n.º 10
0
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.
"""

from openmdao.api import Problem, Group, ExecComp, IndepVarComp, view_model, ImplicitComponent

p = Problem()
dvs = p.model.add_subsystem('design_vars', IndepVarComp(), promotes=['*'])
dvs.add_output('x_aero')
dvs.add_output('x_struct')
aerostruct = p.model.add_subsystem('aerostruct_cycle', 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']),
    promotes=['*'])
aerostruct.add_subsystem('struct',
                         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.setup()

view_model(p,
           outfile='aerostruct_n2.html',
           embeddable=True,
           draw_potential_connections=False,
           show_browser=False)
Ejemplo n.º 11
0
Archivo: MDAO.py Proyecto: DexQJ/PIE
prob.driver = ScipyOptimizeDriver()
prob.driver.options['optimizer'] = 'SLSQP'  #'L-BFGS-B'#
prob.driver.options['maxiter'] = 200
prob.driver.options['tol'] = 1e-5
prob.driver.options['debug_print'] = [
    'desvars', 'ln_cons', 'nl_cons', 'objs', 'totals'
]
prob.driver.options['disp'] = True
prob.set_solver_print(level=1)
prob.setup()

# Ask OpenMDAO to finite-difference across the model to compute the gradients for the optimizer
prob.model.approx_totals()
prob.run_driver()

view_model(prob, outfile="mdao2.html", show_browser=False)

# generate as file for OpenVSP
generate_geometry = False  # True#

# view values calculations
view_values = False  #  True #

# plot the trajectory
plot_trajectory = False  # True #
MDA_value = False

# visualize output values
if plot_trajectory == True:
    #result_vizualization.view_traj_values(test)
    result_vizualization.plot_trajectory(MDA_value)
Ejemplo n.º 12
0
        cycle.add_subsystem('mass_group',mass_group() , promotes_inputs=['*'], promotes_outputs=['*'])
        cycle.add_subsystem('trajectory',trajectory() , promotes_inputs=['*'], promotes_outputs=['*'])

        # Linear and non-linear Solvers for MDA
        cycle.nonlinear_solver =    NonlinearBlockGS(maxiter =100) #NewtonSolver(maxiter =100)# 
        cycle.nonlinear_solver.options['rtol'] = 10**-6
        cycle.nonlinear_solver.options['atol'] = 10**-6
        cycle.linear_solver = DirectSolver()# LinearBlockGS(maxiter =100) #ScipyKrylov()
        self.linear_solver = DirectSolver()# LinearBlockGS(maxiter =100) #ScipyKrylov()
        
        
# test of the MDA
test = Problem()
test.model = LAST_MDA()
test.set_solver_print(level=2)
test.setup()
test.run_model()
view_model(test, outfile="mda2.html", show_browser=False)   # N² diagramm


# generate as file for OpenVSP
view_values =             True # False #
plot_trajectory =              True # False #
MDA_value = True

# visualize output values
if plot_trajectory == True:
    result_vizualization.plot_trajectory(MDA_value)
if view_values == True:
    result_vizualization.view_values(test)
Ejemplo n.º 13
0
    def create_mda(self):
        return Mda(self.scalers)

    @staticmethod
    def create_performance(self):
        return Performance(self.scalers)

    @staticmethod
    def create_constraints(self):
        return Constraints(self.scalers)


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-n",
                      "--no-n2",
                      action="store_false",
                      dest='n2_view',
                      default=True,
                      help="display N2 openmdao viewer")
    (options, args) = parser.parse_args()

    problem = Problem()
    problem.model = SsbjMda()

    problem.setup()
    problem.final_setup()

    if options.n2_view:
        view_model(problem)
Ejemplo n.º 14
0
model.connect('A_sa', 'solar.A_sa')
model.connect('G_sc', 'solar.G_sc')
model.connect('eta_sa', 'solar.eta_sa')
model.connect('Z_sa', 'solar.Z_sa')

model.connect('T_0', 'massvel.T_0')
model.connect('v_e', 'massvel.v_e')
model.connect('battery.T_th', 'massvel.T_th')

#Setting Solvers
# model.nonlinear_solver = NewtonSolver(maxiter = 30, iprint = 2, rtol = 1e-10)
# model.linear_solver = DirectSolver()

#Set-up and Run
p.setup()
p.run_model()
print(p[f'massvel.istep_{N-1}.DV_tot_e'])
print(p['propul.DV_tot'])
view_model(p)

#Plotting
Re = [
    (p['init_cond.R_0'] - 6378000) * 10**-3,
]
for i in range(N):
    Re.append((p[f'istep_{i}.Re'] - 6378000) * 10**-3)
time = np.arange(N + 1) * timestep
plt.plot(time, Re)
plt.show()
Ejemplo n.º 15
0
"""
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

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', om.Group(), promotes=['*'])
#note the equations don't matter... just need a simple way to get inputs and outputs there
aerostruct.add_subsystem('aero',
                         om.ExecComp(['w = u+x_aero', 'Cl=u+x_aero', 'Cd = u + x_aero']),
                         promotes=['*'])
aerostruct.add_subsystem('struct', om.ExecComp(['u = w+x_struct', 'mass=x_struct']),
                         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()

om.view_model(p, outfile='aerostruct_n2.html', embeddable=True, show_browser=False)




Ejemplo n.º 16
0
    # derivatives used for optimization.
    prob.root.deriv_options['type'] = 'fd'

    # Record the optimization history in `spatialbeam.db`. You can view
    # this by running `python plot_all.py s` or `python OptView.py s`.
    recorder = SqliteRecorder('spatialbeam.db')
    recorder.options['record_params'] = True
    recorder.options['record_derivs'] = True
    prob.driver.add_recorder(recorder)

    # Have OpenMDAO set up the problem that we have constructed.
    prob.setup()

    # Create an html output file showing the problem formulation and data
    # passing with an interactive chart. Open this in any web browser.
    view_model(prob, outfile="prob1.html", show_browser=False)

    # Start timing and perform the optimization.
    st = time.time()
    prob.run()
    print("\nrun time: {} secs".format(time.time() - st))
    print('                         tip')
    print('thickness distribution:', prob['thickness'], "\n")

    # Uncomment the following line to check the partial derivatives of each
    # component and view their accuracy.
    # prob.check_partial_derivatives(compact_print=True)

elif 'prob2' in input_arg or 'prob3' in input_arg:

    # Set problem type. Any option not set here will be set in the method
Ejemplo n.º 17
0
    root.connect('load_factor.n', 'structures_h.n')
    root.connect('s_coord.node_coord', 'inter_h.node_coord')
    root.connect('s_coord_all.node_coord_all', 'structures_h.node_coord_all')

    #Multifidelity explicit connections

    root.connect('structures.u', 'mult_filter.ul')

    #Recorder Lo-Fi
    recorder_l = SqliteRecorder('mda_l.sqlite3')
    recorder_l.options['record_metadata'] = False
    #Recorder Hi-Fi
    recorder_h = SqliteRecorder('mda_h.sqlite3')
    recorder_h.options['record_metadata'] = False
    # recorder.options['includes'] =
    top.root.mda_group_l.nl_solver.add_recorder(recorder_l)
    top.root.mda_group_h.nl_solver.add_recorder(recorder_h)

    #Define solver type
    root.ln_solver = ScipyGMRES()

    tic = timeit.default_timer()
    top.setup()
    toc = timeit.default_timer()
    print("Set up time = " + str(toc - tic))  #elapsed time in seconds
    view_model(top, show_browser=False)
    tic = timeit.default_timer()
    top.run()
    toc = timeit.default_timer()
    print("Run time = " + str(toc - tic))  #elapsed time in seconds
Ejemplo n.º 18
0
        
        # sub-components         
        self.add_subsystem('dof', i, promotes=['*'])   
        self.add_subsystem('pc', PowerCurve(), promotes_inputs=['*'])
        
        
        


if __name__ == "__main__":
    start = time()
    
    # workflow setup
    prob = Problem(PowerCurveTest())
    prob.setup()
    view_model(prob, outfile='N2/power_curve.html')
    
    # define inputs
    prob['dof.design_tsr'] = 7.0
    prob['dof.cut_in_speed'] = 3.0
    prob['dof.cut_out_speed'] = 25.0
    prob['dof.swept_area'] = 12445.26
    prob['dof.machine_rating'] = 5000.0
    prob['dof.drive_train_efficiency'] = 0.95
    prob['dof.rotor_cp'] = 0.467403
    prob['dof.rotor_ct'] = 0.7410045
    
     
    prob.run_model()
    
    # print outputs 
Ejemplo n.º 19
0
def main(maxiter):

    # select which problem to solve
    obj_flag = 1
    print(locals())
    print("solving %s problem" % objectives[obj_flag])

    ########################################################
    ################# 		FEA 		####################
    ########################################################
    # NB: only Q4 elements + integer-spaced mesh are assumed
    nelx = 160
    nely = 80

    length_x = 160.
    length_y = 80.

    ls2fe_x = length_x / float(nelx)
    ls2fe_y = length_y / float(nely)

    num_nodes_x = nelx + 1
    num_nodes_y = nely + 1

    nELEM = nelx * nely
    nNODE = num_nodes_x * num_nodes_y

    # NB: nodes for plotting (quickfix...)
    nodes = get_mesh(num_nodes_x, num_nodes_y, nelx, nely)

    # Declare FEA object (OpenLSTO_FEA) ======================
    fea_solver = py_FEA(lx=length_x,
                        ly=length_y,
                        nelx=nelx,
                        nely=nely,
                        element_order=2)
    [node, elem, elem_dof] = fea_solver.get_mesh()

    # validate the mesh
    if nELEM != elem.shape[0]:
        error("error found in the element")
    if nNODE != node.shape[0]:
        error("error found in the node")

    nDOF_t = nNODE * 1  # each node has one temperature DOF
    nDOF_e = nNODE * 2  # each node has two displacement DOFs

    # constitutive properties =================================
    E = 1.
    nu = 0.3
    f = -1  # dead load
    K_cond = 0.1  # thermal conductivity
    alpha = 1e-5  # thermal expansion coefficient

    fea_solver.set_material(E=E, nu=nu, rho=1.0)

    # Boundary Conditions =====================================
    if 1:
        coord_e = np.array([[0., 0.], [length_x, 0.]])
        tol_e = np.array([[1e-3, 1e3], [1e-3, 1e+3]])
        fea_solver.set_boundary(coord=coord_e, tol=tol_e)

        BCid_e = fea_solver.get_boundary()
        nDOF_e_wLag = nDOF_e + len(BCid_e)  # elasticity DOF

        coord = np.array([length_x * 0.5, 0.0])  # length_y])
        tol = np.array([0.1, 1e-3])
        GF_e_ = fea_solver.set_force(coord=coord, tol=tol, direction=1, f=-f)
        GF_e = np.zeros(nDOF_e_wLag)
        GF_e[:nDOF_e] = GF_e_
    else:  # cantilever bending
        coord_e = np.array([[0, 0]])
        tol_e = np.array([[1e-3, 1e10]])
        fea_solver.set_boundary(coord=coord_e, tol=tol_e)
        BCid_e = fea_solver.get_boundary()
        nDOF_e_wLag = nDOF_e + len(BCid_e)  # elasticity DOF

        coord = np.array([length_x, length_y / 2])
        tol = np.array([0.1, 0.1])
        GF_e_ = fea_solver.set_force(coord=coord, tol=tol, direction=1, f=-1.0)
        GF_e = np.zeros(nDOF_e_wLag)
        GF_e[:nDOF_e] = GF_e_

    xlo = np.array(range(0, nNODE, num_nodes_x))
    xhi = np.array(range(nelx, nNODE, num_nodes_x))
    # xfix = np.array([num_nodes_x*(nely/2-1), num_nodes_x*nely/2,
    # num_nodes_x*(nely/2-1) + nelx, num_nodes_x*nely/2 + nelx])
    xfix = np.append(xlo, xhi)
    yfix = np.array(range(num_nodes_x * nely + 70, nNODE - 70))
    # yloid = np.array(range(70, 91))
    # fixID_d = np.append(xfix, yfix)
    #fixID_d = np.unique(fixID_d)
    #fixID = np.append(fixID_d, arange(70, 91))
    # BCid_t = np.array(np.append(xfix, arange(70,91)), dtype=int)
    BCid_t = np.array(np.append(yfix, arange(70, 91)), dtype=int)
    nDOF_t_wLag = nDOF_t + len(BCid_t)  # temperature DOF (zero temp)

    GF_t = np.zeros(nDOF_t_wLag)  # FORCE_HEAT (NB: Q matrix)
    for ee in range(nELEM):  # between element 70 to 91
        GF_t[elem[ee]] += 10.  # heat generation
    GF_t[BCid_t] = 0.0
    GF_t /= np.sum(GF_t)
    #GF_t[nDOF_t:nDOF_t+len(fixID_d)+1] = 100.
    # GF_t[:] = 0.0

    ########################################################
    ################# 		LSM 		####################
    ########################################################
    movelimit = 0.5

    # Declare Level-set object
    lsm_solver = py_LSM(nelx=nelx, nely=nely, moveLimit=movelimit)

    if ((nelx == 160) and (nely == 80)):  # 160 x 80 case
        hole = array(
            [[16, 14, 5], [48, 14, 5], [80, 14, 5], [112, 14, 5], [144, 14, 5],
             [32, 27, 5], [64, 27, 5], [96, 27, 5], [128, 27, 5], [16, 40, 5],
             [48, 40, 5], [80, 40, 5], [112, 40, 5], [144, 40, 5], [32, 53, 5],
             [64, 53, 5], [96, 53, 5], [128, 53, 5], [16, 66, 5], [48, 66, 5],
             [80, 66, 5], [112, 66, 5], [144, 66, 5]],
            dtype=float)

        # NB: level set value at the corners should not be 0.0
        hole = append(
            hole,
            [[0., 0., 0.1], [0., 80., 0.1], [160., 0., 0.1], [160., 80., 0.1]],
            axis=0)

        lsm_solver.add_holes(locx=list(hole[:, 0]),
                             locy=list(hole[:, 1]),
                             radius=list(hole[:, 2]))

    elif ((nelx == 80) and (nely == 40)):
        hole = np.array(
            [[8, 7, 2.5], [24, 7, 2.5], [40, 7, 2.5], [56, 7, 2.5],
             [72, 7, 2.5], [16, 13.5, 2.5], [32, 13.5, 2.5], [48, 13.5, 2.5],
             [64, 13.5, 2.5], [8, 20, 2.5], [24, 20, 2.5], [40, 20, 2.5],
             [56, 20, 2.5], [72, 20, 2.5], [16, 26.5, 2.5], [32, 26.5, 2.5],
             [48, 26.5, 2.5], [64, 26.5, 2.5], [8, 33, 2.5], [24, 33, 2.5],
             [40, 33, 2.5], [56, 33, 2.5], [72, 33, 2.5]],
            dtype=np.float)

        # NB: level set value at the corners should not be 0.0
        hole = append(
            hole,
            [[0., 0., 0.1], [0., 40., 0.1], [80., 0., 0.1], [80., 40., 0.1]],
            axis=0)

        lsm_solver.add_holes(locx=list(hole[:, 0]),
                             locy=list(hole[:, 1]),
                             radius=list(hole[:, 2]))

    else:
        lsm_solver.add_holes([], [], [])

    lsm_solver.set_levelset()

    for i_HJ in range(maxiter):
        (bpts_xy, areafraction, seglength) = lsm_solver.discretise()

        ########################################################
        ############### 		OpenMDAO 		################
        ########################################################

        # Declare Group
        if (objectives[obj_flag] == "compliance"):
            model = ComplianceGroup(fea_solver=fea_solver,
                                    lsm_solver=lsm_solver,
                                    nelx=nelx,
                                    nely=nely,
                                    force=GF_e,
                                    movelimit=movelimit,
                                    BCid=BCid_e)
        elif (objectives[obj_flag] == "stress"):
            # TODO: sensitivity has not been verified yet
            model = StressGroup(fea_solver=fea_solver,
                                lsm_solver=lsm_solver,
                                nelx=nelx,
                                nely=nely,
                                force=GF_e,
                                movelimit=movelimit,
                                pval=5.0,
                                E=E,
                                nu=nu)
        elif (objectives[obj_flag] == "conduction"):
            model = ConductionGroup(fea_solver=fea_solver,
                                    lsm_solver=lsm_solver,
                                    nelx=nelx,
                                    nely=nely,
                                    force=GF_t,
                                    movelimit=movelimit,
                                    K_cond=K_cond,
                                    BCid=BCid_t)
        elif (objectives[obj_flag] == "coupled_heat"):
            model = HeatCouplingGroup(
                fea_solver=fea_solver,
                lsm_solver=lsm_solver,
                nelx=nelx,
                nely=nely,
                force_e=GF_e,
                force_t=GF_t,
                movelimit=movelimit,
                K_cond=K_cond,
                BCid_e=BCid_e,
                BCid_t=BCid_t,
                E=E,
                nu=nu,
                alpha=alpha,
                w=0.9
            )  # if w = 0.0, thermoelastic + conduction, if w = 1.0, conduction only

        # One Problem per one OpenMDAO object
        prob = Problem(model)

        # optimize ...
        prob.driver = pyOptSparseDriver()
        prob.driver.options['optimizer'] = 'IPOPT'
        prob.driver.opt_settings['linear_solver'] = 'ma27'
        prob.setup(check=False)
        if i_HJ == 0:
            view_model(prob)
        prob.run_model()

        # Total derivative using MAUD =====================
        total = prob.compute_totals()
        if (objectives[obj_flag] == "compliance"):
            ff = total['compliance_comp.compliance', 'inputs_comp.Vn'][0]
            gg = total['weight_comp.weight', 'inputs_comp.Vn'][0]
        elif (objectives[obj_flag] == "stress"):
            ff = total['pnorm_comp.pnorm', 'inputs_comp.Vn'][0]
            gg = total['weight_comp.weight', 'inputs_comp.Vn'][0]
        elif (objectives[obj_flag] == "conduction"):
            ff = total['compliance_comp.compliance', 'inputs_comp.Vn'][0]
            gg = total['weight_comp.weight', 'inputs_comp.Vn'][0]
        elif (objectives[obj_flag] == "coupled_heat"):
            ff = total['objective_comp.y', 'inputs_comp.Vn'][0]
            gg = total['weight_comp.weight', 'inputs_comp.Vn'][0]

        nBpts = int(bpts_xy.shape[0])
        # # WIP checking sensitivity 10/23
        Sf = -ff[:nBpts]  # equal to M2DO-perturbation
        Cf = np.multiply(Sf, seglength)
        #np.savetxt('/home/hayoung/Desktop/a',Sf)
        #exit()

        Sg = -gg[:nBpts]
        Cg = np.multiply(Sf, seglength)
        # ## WIP

        # previous ver.
        # Cf = -ff[:nBpts]
        # Cg = -gg[:nBpts]

        # Sf = np.divide(Cf, seglength)
        # Sg = np.divide(Cg, seglength)

        # bracketing Sf and Sg
        Sg[Sg < -1.5] = -1.5
        Sg[Sg > 0.5] = 0.5
        # Sg[:] = -1.0
        Cg = np.multiply(Sg, seglength)

        ########################################################
        ############## 		suboptimize 		################
        ########################################################
        if 1:
            suboptim = Solvers(bpts_xy=bpts_xy,
                               Sf=Sf,
                               Sg=Sg,
                               Cf=Cf,
                               Cg=Cg,
                               length_x=length_x,
                               length_y=length_y,
                               areafraction=areafraction,
                               movelimit=movelimit)
            # suboptimization
            if 1:  # simplex
                Bpt_Vel = suboptim.simplex(isprint=False)
            else:  # bisection..
                Bpt_Vel = suboptim.bisection(isprint=False)
            timestep = 1.0
            np.savetxt('a.txt', Bpt_Vel)

        elif 1:  # works when Sf <- Sf / length is used (which means Cf <- actual Sf)
            bpts_sens = np.zeros((nBpts, 2))
            # issue: scaling problem
            #
            bpts_sens[:, 0] = Sf
            bpts_sens[:, 1] = Sg

            lsm_solver.set_BptsSens(bpts_sens)
            scales = lsm_solver.get_scale_factors()
            (lb2, ub2) = lsm_solver.get_Lambda_Limits()
            constraint_distance = (0.4 * nelx * nely) - areafraction.sum()

            model = LSM2D_slpGroup(lsm_solver=lsm_solver,
                                   num_bpts=nBpts,
                                   ub=ub2,
                                   lb=lb2,
                                   Sf=bpts_sens[:, 0],
                                   Sg=bpts_sens[:, 1],
                                   constraintDistance=constraint_distance,
                                   movelimit=movelimit)

            subprob = Problem(model)
            subprob.setup()

            subprob.driver = ScipyOptimizeDriver()
            subprob.driver.options['optimizer'] = 'SLSQP'
            subprob.driver.options['disp'] = True
            subprob.driver.options['tol'] = 1e-10

            subprob.run_driver()
            lambdas = subprob['inputs_comp.lambdas']
            displacements_ = subprob['displacement_comp.displacements']

            # displacements_[displacements_ > movelimit] = movelimit
            # displacements_[displacements_ < -movelimit] = -movelimit
            timestep = abs(lambdas[0] * scales[0])

            Bpt_Vel = displacements_ / timestep
            np.savetxt('a.txt', Bpt_Vel)
            # print(timestep)
            del subprob

        else:  # branch: perturb-suboptim
            bpts_sens = np.zeros((nBpts, 2))
            # issue: scaling problem
            #
            bpts_sens[:, 0] = Sf
            bpts_sens[:, 1] = Sg

            lsm_solver.set_BptsSens(bpts_sens)
            scales = lsm_solver.get_scale_factors()
            (lb2, ub2) = lsm_solver.get_Lambda_Limits()

            constraint_distance = (0.4 * nelx * nely) - areafraction.sum()
            constraintDistance = np.array([constraint_distance])
            scaled_constraintDist = lsm_solver.compute_scaledConstraintDistance(
                constraintDistance)

            def objF_nocallback(x):
                displacement = lsm_solver.compute_displacement(x)
                displacement_np = np.asarray(displacement)
                return lsm_solver.compute_delF(displacement_np)

            def conF_nocallback(x):
                displacement = lsm_solver.compute_displacement(x)
                displacement_np = np.asarray(displacement)
                return lsm_solver.compute_delG(displacement_np,
                                               scaled_constraintDist, 1)

            cons = ({'type': 'eq', 'fun': lambda x: conF_nocallback(x)})
            res = sp_optim.minimize(objF_nocallback,
                                    np.zeros(2),
                                    method='SLSQP',
                                    options={'disp': True},
                                    bounds=((lb2[0], ub2[0]), (lb2[1],
                                                               ub2[1])),
                                    constraints=cons)

            lambdas = res.x
            displacements_ = lsm_solver.compute_unscaledDisplacement(lambdas)
            displacements_[displacements_ > movelimit] = movelimit
            displacements_[displacements_ < -movelimit] = -movelimit
            timestep = 1.0  #abs(lambdas[0]*scales[0])
            Bpt_Vel = displacements_ / timestep
            # scaling
            # Bpt_Vel = Bpt_Vel#/np.max(np.abs(Bpt_Vel))

        lsm_solver.advect(Bpt_Vel, timestep)
        lsm_solver.reinitialise()

        print('loop %d is finished' % i_HJ)
        area = areafraction.sum() / (nelx * nely)
        try:
            u = prob['temp_comp.disp']
            compliance = np.dot(u, GF_t[:nNODE])
        except:
            u = prob['disp_comp.disp']
            # compliance = np.dot(u, GF_e[:nDOF_e])
            pass

        if 1:  # quickplot
            plt.figure(1)
            plt.clf()
            plt.scatter(bpts_xy[:, 0], bpts_xy[:, 1], 10)
            plt.axis("equal")
            plt.savefig(saveFolder + "figs/bpts_%d.png" % i_HJ)
            if obj_flag == 3 or obj_flag == 2:
                plt.figure(2)
                plt.clf()
                [xx, yy] = np.meshgrid(range(0, 161), range(0, 81))
                plt.contourf(xx, yy, np.reshape(u, [81, 161]))
                plt.colorbar()
                plt.axis("equal")
                plt.scatter(bpts_xy[:, 0], bpts_xy[:, 1], 5)
                plt.savefig(saveFolder + "figs/temp_%d.png" % i_HJ)

        # print([compliance[0], area])
        if (objectives[obj_flag] == "compliance"):
            compliance = prob['compliance_comp.compliance']
            print(compliance, area)

            fid = open(saveFolder + "log.txt", "a+")
            fid.write(str(compliance) + ", " + str(area) + "\n")
            fid.close()
        elif (objectives[obj_flag] == "stress"):
            print(prob['pnorm_comp.pnorm'][0], area)

            fid = open(saveFolder + "log.txt", "a+")
            fid.write(
                str(prob['pnorm_comp.pnorm'][0]) + ", " + str(area) + "\n")
            fid.close()
        elif (objectives[obj_flag] == "coupled_heat"):
            obj1 = prob['objective_comp.x1'][0]
            obj2 = prob['objective_comp.x2'][0]
            obj = prob['objective_comp.y'][0]

            print([obj1, obj2, obj, area])
            fid = open(saveFolder + "log.txt", "a+")
            fid.write(
                str(obj1) + ", " + str(obj2) + ", " + str(obj) + ", " +
                str(area) + "\n")
            fid.close()

        # Saving Phi
        phi = lsm_solver.get_phi()

        if i_HJ == 0:
            raw = {}
            raw['mesh'] = nodes
            raw['nodes'] = nodes
            raw['elem'] = elem
            raw['GF_e'] = GF_e
            raw['GF_t'] = GF_t
            raw['BCid_e'] = BCid_e
            raw['BCid_t'] = BCid_t
            raw['E'] = E
            raw['nu'] = nu
            raw['f'] = f
            raw['K_cond'] = K_cond
            raw['alpha'] = alpha
            raw['nelx'] = nelx
            raw['nely'] = nely
            raw['length_x'] = length_x
            raw['length_y'] = length_y
            raw['coord_e'] = coord_e
            raw['tol_e'] = tol_e
            filename = saveFolder + 'const.pkl'
            with open(filename, 'wb') as f:
                pickle.dump(raw, f)

        raw = {}
        raw['phi'] = phi
        if obj_flag == 3:
            raw['T'] = prob['temp_comp.disp']
        filename = saveFolder + 'phi%03i.pkl' % i_HJ
        with open(filename, 'wb') as f:
            pickle.dump(raw, f)

        del model
        del prob

        mem = virtual_memory()
        print(str(mem.available / 1024. / 1024. / 1024.) + "GB")
        if mem.available / 1024. / 1024. / 1024. < 3.0:
            print("memory explodes at iteration %3i " % i_HJ)
            return ()
Ejemplo n.º 20
0
# Create the aero point group for this flight condition and add it to the model
aero_group = AeroPoint(surfaces=[surface], rotational=True)
point_name = 'flight_condition_0'
prob.model.add_subsystem(point_name,
                         aero_group,
                         promotes_inputs=[
                             'v', 'alpha', 'beta', 'omega', 'Mach_number',
                             're', 'rho', 'cg'
                         ])

# Connect the mesh from the geometry component to the analysis point
prob.model.connect(name + '.mesh', point_name + '.' + name + '.def_mesh')

# Perform the connections with the modified names within the
# 'aero_states' group.
prob.model.connect(name + '.mesh',
                   point_name + '.aero_states.' + name + '_def_mesh')

# Set up the problem
prob.setup()

# Create a n^2 diagram for user to view model connections
om.view_model(prob)

# Run analysis
prob.run_model()

print('CL', prob['flight_condition_0.wing_perf.CL'][0])
print('CD', prob['flight_condition_0.wing_perf.CD'][0])
Ejemplo n.º 21
0
    def minimize(
            self,  # type: CharDB
            objective,  # type: str
            define=None,  # type: List[Tuple[str, int]]
            cons=None,  # type: Dict[str, Dict[str, float]]
            vector_params=None,  # type: Set[str]
            debug=False,  # type: bool
            **kwargs  # type: **kwargs
    ):
        # type: (...) -> Dict[str, Union[np.ndarray, float]]
        """Find operating point that minimizes the given objective.

        Parameters
        ----------
        objective : str
            the objective to minimize.  Must be a scalar.
        define : List[Tuple[str, int]]
            list of expressions to define new variables.  Each
            element of the list is a tuple of string and integer.  The string
            contains a python assignment that computes the variable from
            existing ones, and the integer indicates the variable shape.

            Note that define can also be used to enforce relationships between
            existing variables.  Using transistor as an example, defining
            'vgs = vds' will force the vgs of vds of the transistor to be
            equal.
        cons : Dict[str, Dict[str, float]]
            a dictionary from variable name to constraints of that variable.
            see OpenMDAO documentations for details on constraints.
        vector_params : Set[str]
            set of input variables that are vector instead of scalar.  An input
            variable is a vector if it can change across simulation environments.
        debug : bool
            True to enable debugging messages.  Defaults to False.
        **kwargs :
            known parameter values.

        Returns
        -------
        results : Dict[str, Union[np.ndarray, float]]
            the results dictionary.
        """
        cons = cons or {}
        fidx_list = self._get_function_index(**kwargs)
        builder = GroupBuilder()

        params_ranges = dict(
            zip(self._cont_params,
                ((vec[0], vec[-1]) for vec in self._cont_values)))
        # add functions
        fun_name_iter = itertools.chain(iter(self._data.keys()),
                                        self.derived_parameters())
        for name in fun_name_iter:
            fun_list = []
            for idx, env in enumerate(self.env_list):
                fidx_list[0] = idx
                fun_list.append(self._get_function_helper(name, fidx_list))

            builder.add_fun(name,
                            fun_list,
                            self._cont_params,
                            params_ranges,
                            vector_params=vector_params)

        # add expressions
        for expr, ndim in define:
            builder.add_expr(expr, ndim)

        # update input bounds from constraints
        input_set = builder.get_inputs()
        var_list = builder.get_variables()

        for name in input_set:
            if name in cons:
                setup = cons[name]
                if 'equals' in setup:
                    eq_val = setup['equals']
                    builder.set_input_limit(name, equals=eq_val)
                else:
                    vmin = vmax = None
                    if 'lower' in setup:
                        vmin = setup['lower']
                    if 'upper' in setup:
                        vmax = setup['upper']
                    builder.set_input_limit(name, lower=vmin, upper=vmax)

        # build the group and make the problem
        grp, input_bounds = builder.build()

        top = omdao.Problem()
        top.root = grp

        opt_package = self.get_config('opt_package')  # type: str
        opt_settings = self.get_config('opt_settings')

        if opt_package == 'scipy':
            driver = top.driver = omdao.ScipyOptimizer()
            print_opt_name = 'disp'
        elif opt_package == 'pyoptsparse':
            driver = top.driver = omdao.pyOptSparseDriver()
            print_opt_name = 'print_results'
        else:
            raise ValueError('Unknown optimization package: %s' % opt_package)

        driver.options['optimizer'] = self.get_config('opt_method')
        driver.options[print_opt_name] = debug
        driver.opt_settings.update(opt_settings)

        # add constraints
        constants = {}
        for name, setup in cons.items():
            if name not in input_bounds:
                # add constraint
                driver.add_constraint(name, **setup)

        # add inputs
        for name in input_set:
            eq_val, lower, upper, ndim = input_bounds[name]
            val = kwargs.get(name, self[name])  # type: float
            if val is None:
                val = eq_val
            comp_name = 'comp__%s' % name
            if val is not None:
                val = np.atleast_1d(np.ones(ndim) * val)
                constants[name] = val
                top.root.add(comp_name,
                             omdao.IndepVarComp(name, val=val),
                             promotes=[name])
            else:
                avg = (lower + upper) / 2.0
                span = upper - lower
                val = np.atleast_1d(np.ones(ndim) * avg)
                top.root.add(comp_name,
                             omdao.IndepVarComp(name, val=val),
                             promotes=[name])
                driver.add_desvar(name,
                                  lower=lower,
                                  upper=upper,
                                  adder=-avg,
                                  scaler=1.0 / span)
                # driver.add_desvar(name, lower=lower, upper=upper)

        # add objective and setup
        driver.add_objective(objective)
        top.setup(check=debug)

        # somehow html file is not viewable.
        if debug:
            omdao.view_model(top, outfile='CharDB_debug.html')

        # set constants
        for name, val in constants.items():
            top[name] = val

        top.run()

        results = {
            var: kwargs.get(var, self[var])
            for var in self._discrete_params
        }
        for var in var_list:
            results[var] = top[var]

        return results
Ejemplo n.º 22
0
    def test_beam_tutorial_viewmodel_using_data_from_hdf5_case_recorder_file(
            self):

        SKIP = False
        try:
            from openmdao.recorders.hdf5_recorder import HDF5Recorder
            import h5py
        except ImportError:
            # Necessary for the file to parse
            from openmdao.recorders.base_recorder import BaseRecorder
            HDF5Recorder = BaseRecorder
            SKIP = True

        if SKIP:
            raise unittest.SkipTest(
                "Could not import HDF5Recorder. Is h5py installed?")

        top = Problem()
        top.root = BeamTutorial()

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'
        top.driver.options['tol'] = 1.0e-8
        top.driver.options[
            'maxiter'] = 10000  #maximum number of solver iterations
        top.driver.options['disp'] = False

        #room length and width bounds
        top.driver.add_desvar('ivc_rlength.room_length',
                              lower=5.0 * 12.0,
                              upper=50.0 *
                              12.0)  #domain: 1in <= length <= 50ft
        top.driver.add_desvar('ivc_rwidth.room_width',
                              lower=5.0 * 12.0,
                              upper=30.0 * 12.0)  #domain: 1in <= width <= 30ft

        top.driver.add_objective('d_neg_area.neg_room_area'
                                 )  #minimize negative area (or maximize area)

        top.driver.add_constraint('d_len_minus_wid.length_minus_width',
                                  lower=0.0)  #room_length >= room_width
        top.driver.add_constraint('d_deflection.deflection',
                                  lower=720.0)  #deflection >= 720
        top.driver.add_constraint('d_bending.bending_stress_ratio',
                                  upper=0.5)  #bending < 0.5
        top.driver.add_constraint('d_shear.shear_stress_ratio',
                                  upper=1.0 / 3.0)  #shear < 1/3

        tempdir = mkdtemp()
        case_recorder_filename = "tmp.hdf5"
        filename = os.path.join(tempdir, case_recorder_filename)
        recorder = HDF5Recorder(filename)
        top.driver.add_recorder(recorder)

        top.setup(check=False)

        top.run()
        view_model(filename, show_browser=False)

        self.assertTrue(os.path.isfile('partition_tree_n2.html'))
        os.remove('partition_tree_n2.html')
    recorder.options['record_metadata'] = False
    recorder.options['includes'] = ['CDi', 'con_l_u', 'con_s', 't', 'a', 'chords', 'sweep', 'b', 'alpha', 'theta', 'tc', 'CD0', 'CDw', 'D', 'FB', 'con_area', 'con_h_1', 'con_h_2', 'con_h_3']
    
    top.driver.add_recorder(recorder)

    #Define solver type
    root.ln_solver = ScipyGMRES()

    start1 = time.time() #timer for set-up and re-order
    top.setup()
    order = root.list_auto_order() #This is to ensure that the mda_l group is executed always before the mda_h group
    a, b = order[0].index('mda_group_h'), order[0].index('mda_group_l')
    order[0].insert(a, order[0].pop(b))
    root.set_order(order[0])
    end1 = time.time()
    view_model(top, show_browser=False) #generates an N2 diagram to visualize connections

    #Setting initial values for design variables
    top['t'] = t_0
    top['chords'] = chords_0
    top['sweep'] = sweep_0
    top['b'] = b_0
    top['alpha'] = alpha_0
    top['theta'] = theta_0
    top['tc'] = tc_0

    start2 = time.time()
    top.run()
    end2 = time.time()
    top.cleanup()  # this closes all recorders
    print("Set up time = " + str(end1 - start1))
Ejemplo n.º 24
0
    probl.model.add_subsystem('trajectory',
                              trajectory(),
                              promotes_inputs=['*'],
                              promotes_outputs=['*'])

    probl.model.nonlinear_solver = NewtonSolver()
    probl.model.linear_solver = DirectSolver()
    #probl.model.linear_solver = ScipyKrylov()
    probl.model.nonlinear_solver.options['maxiter'] = 10**3
    probl.model.nonlinear_solver.options['rtol'] = 10**-6
    probl.set_solver_print(level=1)

    probl.setup()

    probl.run_model()
    view_model(probl, outfile="trajectoryn2.html", show_browser=False)
    test = probl
    print('\n')
    print('final altitude (km) =', test['alt_f'][0])
    print('final speed (m/s)=', test['v_f'][0])
    print('final  fi= ', test['fi_f'][0])
    print('final long= ', test['l_f'][0])
    print("\n")
    print("m_dot1:", test['m_dot1'][0])
    #    print("m_dot2:", test['m_dot2'][0])

    print("Thrust 1 :", test['ft1'][0])
    print('nx_max ', test['nx_max'][0])
    print('alf_max ', test['alf_max'][0])

#"""
Ejemplo n.º 25
0
        0.0, 152.8413, 692.3132, 1231.7851, 1771.257, 2077.937, 2385.88,
        2693.823, 3167.965, 3613.9953, 4060.0257, 4506.056, 4882.4425,
        5258.829, 5635.2155, 6011.602, 5169.536, 4327.47, 3485.404, 2222.305
    ]
    span_fy = [
        -3.5, -103.8047, 162.8256, 429.456, 696.0863, 702.4778, 701.8906,
        701.3033, 720.8832, 725.5557, 730.2281, 734.9006, 732.7446, 730.5885,
        728.4325, 726.2764, 558.9978, 391.7192, 224.4406, -26.4774
    ]

    start = time()

    # workflow setup
    prob = Problem(RotorMechanicsTest())
    prob.setup()
    view_model(prob, outfile='N2/rotor_structure.html')

    # define inputs
    prob['dof.shaft_angle'] = shaft_angle
    prob['dof.span_r'] = span_r
    prob['dof.span_dr'] = span_dr
    prob['dof.span_chord'] = span_chord
    prob['dof.span_thickness'] = span_thickness
    prob['dof.span_mass'] = span_mass
    prob['dof.span_flap_stiff'] = span_flap_stiff
    prob['dof.span_edge_stiff'] = span_edge_stiff
    prob['dof.span_fx'] = span_fx
    prob['dof.span_fy'] = span_fy

    prob.run_model()
Ejemplo n.º 26
0
    def test(self):
    
        start = time()
        
        # workflow setup
        prob = Problem(self)
        prob.setup()
        view_model(prob, outfile='N2/rna.html')
        
        # define inputs 
        prob['in_design_tsr'] = 1.0
        prob['in_tf'] = 1.0
        prob['in_chord_coefficients'] = np.ones(degree_bezier)
        prob['in_twist_coefficients'] = np.ones(degree_bezier)
        
        prob.run_model()
        
        print 'span_r = ' + beautify(prob['rna.span_r'])
        print 'span_dr = ' + beautify(prob['rna.span_dr'])
        print 'span_chord = ' + beautify(prob['rna.span_chord'])
        print 'span_twist = ' + beautify(prob['rna.span_twist'])
        print 'pitch = ' + beautify(prob['rna.pitch'])
        print 'rotor_cp = ' + str(prob['rna.rotor_cp'])
        print 'rotor_ct = ' + str(prob['rna.rotor_ct'])
        print 'rated_wind_speed = ' + beautify(prob['rna.rated_wind_speed'])
        print 'wind_bin = ' + beautify(prob['rna.wind_bin'])
        print 'power_bin = ' + beautify(prob['rna.power_bin'])
        print 'span_stress_max = ' + str(max(prob['rna.span_stress_max']))
        print 'tip_deflection = ' + beautify(prob['rna.tip_deflection'])
        print 'rotor_mass = ' + beautify(prob['rna.rotor_mass'])
        print 'hub_system_mass = ' + beautify(prob['rna.hub_system_mass'])
        print 'nacelle_mass = ' + beautify(prob['rna.nacelle_mass'])
        print 'gb_mass = ' + beautify(prob['rna.gearbox_mass'])
        print 'rna_mass = ' + str(prob['rna.rotor_mass'][0] + prob['rna.hub_system_mass'][0] + prob['rna.nacelle_mass'][0])
        print 'rna_cost = ' + beautify(prob['rna.cost_rna_total'])

        print 'root_force = ' + beautify(prob['rna.rotor_force'])
        print 'root_moment = ' + beautify(prob['rna.rotor_moment'])
        print 'rotor_mass = ' + beautify(prob['rna.rotor_mass'])
        print 'hub_mass = ' + beautify(prob['rna.hub_mass'])
        print 'pitch_system_mass = ' + beautify(prob['rna.pitch_system_mass'])
        print 'spinner_mass = ' + beautify(prob['rna.spinner_mass'])
        print 'low_speed_shaft_mass = ' + beautify(prob['rna.low_speed_shaft_mass'])
        print 'main_bearing_mass = ' + beautify(prob['rna.main_bearing_mass'])
        print 'gearbox_mass = ' + beautify(prob['rna.gearbox_mass'])
        print 'generator_mass = ' + beautify(prob['rna.generator_mass'])
        print 'high_speed_side_mass = ' + beautify(prob['rna.high_speed_side_mass'])
        print 'vs_electronics_mass = ' + beautify(prob['rna.vs_electronics_mass'])
        print 'yaw_system_mass = ' + beautify(prob['rna.yaw_system_mass'])
        print 'mainframe_mass = ' + beautify(prob['rna.mainframe_mass'])
        print 'electrical_mass = ' + beautify(prob['rna.electrical_mass'])
        print 'hvac_mass = ' + beautify(prob['rna.hvac_mass'])
        print 'cover_mass = ' + beautify(prob['rna.cover_mass'])
        print 'controls_mass = ' + beautify(prob['rna.controls_mass'])
        
        
        print 'Done in ' + str(time() - start) + ' seconds'
        
        # plots
        font = {'family' : 'Tahoma', 'size' : 15}
        plt.rc('font', **font)
        fig = plt.figure()
        
        x1 = fig.add_subplot(121)
        x1.set_title('Chord distribution')
        x1.set_xlabel('r [m]')
        x1.set_ylabel('Chord [m]')
        x1.plot(prob['rna.span_r'], prob['rna.span_chord'])
        
        x2 = fig.add_subplot(122)
        x2.set_title('Twist distribution')
        x2.set_xlabel('r [m]')
        x2.set_ylabel('Twist [deg]')
        x2.plot(prob['rna.span_r'], prob['rna.span_twist'])
        
        plt.show()
Ejemplo n.º 27
0
prob.model.connect("ivc.Cla_t", "Aerodynamics.cla_tail.Cla_t")
prob.model.connect("ivc.S_t", "Aerodynamics.cla_tail.S_t")
prob.model.connect("ivc.d_fuse_t", "Aerodynamics.cla_tail.d_fuse_t")
prob.model.connect("ivc.b_t", "Aerodynamics.cla_tail.b_t")
prob.model.connect("ivc.b", "Aerodynamics.wing_param.b")
prob.model.connect("ivc.taper", "Aerodynamics.wing_param.taper")
prob.model.connect("ivc.croot", "Aerodynamics.wing_param.croot")
prob.model.connect("ivc.W_0", "Weights.W_lg.W_0")
prob.model.connect("ivc.S_t", "Weights.W_tail.S_t")
prob.model.connect("ivc.S", "Weights.W_wing.S")
prob.model.connect("ivc.AR", "Weights.W_wing.AR")
prob.model.connect("ivc.q", "Weights.W_wing.q")
prob.model.connect("ivc.taper", "Weights.W_wing.taper")
prob.model.connect("ivc.thickness_ratio", "Weights.W_wing.thickness_ratio")
prob.model.connect("ivc.n", "Weights.W_wing.n")
prob.model.connect("ivc.W_0", "Weights.W_wing.W_0")
prob.model.connect("ivc.W_0", "Weights.W_wing_control.W_0")
# replace all "ivc.W_0" with "Weights.GrossWeightComp.W_0"

group.nonlinear_solver = NonlinearBlockGS(iprint=2, maxiter=30)

prob.setup()
prob.run_model()
#print(prob['cla_wing.CLa'])
#prob.check_partials(compact_print=True)

# TO RUN: 'python run.py'
# TO VISUALIZE: 'openmdao view_model run.py'

view_model(prob)
Ejemplo n.º 28
0
"""
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.
"""

from openmdao.api import Problem, Group, ExecComp, IndepVarComp, view_model, ImplicitComponent

p = Problem()
dvs = p.model.add_subsystem('design_vars', IndepVarComp(), promotes=['*'])
dvs.add_output('x_aero')
dvs.add_output('x_struct')
aerostruct = p.model.add_subsystem('aerostruct_cycle', 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']),
                         promotes=['*'])
aerostruct.add_subsystem('struct', 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.setup()

view_model(p, outfile='aerostruct_n2.html', embeddable=True, show_browser=False)