Пример #1
0
def test_get_string_vector():
    """ Test the function 'get_string_vector'"""

    tixi = cpsf.open_tixi(CPACS_IN_PATH)
    xpath = '/cpacs/toolspecific/CEASIOMpy/testVector'

    # Add a new vector
    string_vector = ['aaa', 'zzz']
    cpsf.add_string_vector(tixi, xpath, string_vector)

    # Get a string vector
    string_vector_get = cpsf.get_string_vector(tixi, xpath)

    assert string_vector_get == string_vector

    # Raise an error when the XPath is wrong
    wrong_xpath = '/cpacs/toolspecific/CEASIOMpy/testVectorWrong'
    with pytest.raises(ValueError):
        vector = cpsf.get_string_vector(tixi, wrong_xpath)

    # Raise an error when no value at XPath
    no_value_xpath = '/cpacs/toolspecific/CEASIOMpy'
    with pytest.raises(ValueError):
        vector = cpsf.get_string_vector(tixi, no_value_xpath)
Пример #2
0
def add_skin_friction(cpacs_path, cpacs_out_path):
    """ Function to add the skin frinction drag coeffienct to aerodynamic coefficients

    Function 'add_skin_friction' add the skin friction drag 'cd0' to  the
    SU2 and pyTornado aeroMap, if their UID is not geven, it will add skin
    friction to all aeroMap. For each aeroMap it creates a new aeroMap where
    the skin friction drag coeffienct is added with the correct projcetions.

    Args:
        cpacs_path (str):  Path to CPACS file
        cpacs_out_path (str): Path to CPACS output file
    """

    tixi = cpsf.open_tixi(cpacs_path)
    tigl = cpsf.open_tigl(tixi)

    wing_area_max, wing_span_max = get_largest_wing_dim(tixi, tigl)

    analyses_xpath = '/cpacs/toolspecific/CEASIOMpy/geometry/analysis'

    # Requiered input data from CPACS
    wetted_area = cpsf.get_value(tixi, analyses_xpath + '/wettedArea')

    # Wing area/span, default values will be calated if no value found in the CPACS file
    wing_area_xpath = analyses_xpath + '/wingArea'
    wing_area = cpsf.get_value_or_default(tixi, wing_area_xpath, wing_area_max)
    wing_span_xpath = analyses_xpath + '/wingSpan'
    wing_span = cpsf.get_value_or_default(tixi, wing_span_xpath, wing_span_max)

    aeromap_uid_list = []

    # Try to get aeroMapToCalculate
    aeroMap_to_clculate_xpath = SF_XPATH + '/aeroMapToCalculate'
    if tixi.checkElement(aeroMap_to_clculate_xpath):
        aeromap_uid_list = cpsf.get_string_vector(tixi,
                                                  aeroMap_to_clculate_xpath)
    else:
        aeromap_uid_list = []

    # If no aeroMap in aeroMapToCalculate, get all existing aeroMap
    if len(aeromap_uid_list) == 0:
        try:
            aeromap_uid_list = apmf.get_aeromap_uid_list(tixi)
        except:
            raise ValueError(
                'No aeroMap has been found in this CPACS file, skin friction cannot be added!'
            )

    # Get unique aeroMap list
    aeromap_uid_list = list(set(aeromap_uid_list))
    new_aeromap_uid_list = []

    # Add skin friction to all listed aeroMap
    for aeromap_uid in aeromap_uid_list:

        log.info('adding skin friction coefficients to: ' + aeromap_uid)

        # Get orignial aeroPerformanceMap
        AeroCoef = apmf.get_aeromap(tixi, aeromap_uid)
        AeroCoef.complete_with_zeros()

        # Create new aeroCoefficient object to store coef with added skin friction
        AeroCoefSF = apmf.AeroCoefficient()
        AeroCoefSF.alt = AeroCoef.alt
        AeroCoefSF.mach = AeroCoef.mach
        AeroCoefSF.aoa = AeroCoef.aoa
        AeroCoefSF.aos = AeroCoef.aos

        # Iterate over all cases
        case_count = AeroCoef.get_count()
        for case in range(case_count):

            # Get parameters for this case
            alt = AeroCoef.alt[case]
            mach = AeroCoef.mach[case]
            aoa = AeroCoef.aoa[case]
            aos = AeroCoef.aos[case]

            # Calculate Cd0 for this case
            cd0 = estimate_skin_friction_coef(wetted_area,wing_area,wing_span, \
                                              mach,alt)

            # Projection of cd0 on cl, cd and cs axis
            #TODO: Should Cd0 be projected or not???
            aoa_rad = math.radians(aoa)
            aos_rad = math.radians(aos)
            cd0_cl = cd0 * math.sin(aoa_rad)
            cd0_cd = cd0 * math.cos(aoa_rad) * math.cos(aos_rad)
            cd0_cs = cd0 * math.sin(aos_rad)

            # Update aerodynamic coefficients
            cl = AeroCoef.cl[case] + cd0_cl
            cd = AeroCoef.cd[case] + cd0_cd
            cs = AeroCoef.cs[case] + cd0_cs

            # Shoud we change something? e.i. if a force is not apply at aero center...?
            if len(AeroCoef.cml):
                cml = AeroCoef.cml[case]
            else:
                cml = 0.0  # Shoud be change, just to test pyTornado
            if len(AeroCoef.cmd):
                cmd = AeroCoef.cmd[case]
            else:
                cmd = 0.0
            if len(AeroCoef.cms):
                cms = AeroCoef.cms[case]
            else:
                cms = 0.0

            # Add new coefficients into the aeroCoefficient object
            AeroCoefSF.add_coefficients(cl, cd, cs, cml, cmd, cms)

        # Create new aeroMap UID
        aeromap_sf_uid = aeromap_uid + '_SkinFriction'
        new_aeromap_uid_list.append(aeromap_sf_uid)

        # Create new description
        description_xpath = tixi.uIDGetXPath(aeromap_uid) + '/description'
        sf_description = cpsf.get_value(
            tixi,
            description_xpath) + ' Skin friction has been add to this AeroMap.'
        apmf.create_empty_aeromap(tixi, aeromap_sf_uid, sf_description)

        # Save aeroCoefficient object Coef in the CPACS file
        apmf.save_parameters(tixi, aeromap_sf_uid, AeroCoefSF)
        apmf.save_coefficients(tixi, aeromap_sf_uid, AeroCoefSF)

    # Get aeroMap list to plot
    plot_xpath = '/cpacs/toolspecific/CEASIOMpy/aerodynamics/plotAeroCoefficient'
    aeromap_to_plot_xpath = plot_xpath + '/aeroMapToPlot'

    if tixi.checkElement(aeromap_to_plot_xpath):
        aeromap_uid_list = cpsf.get_string_vector(tixi, aeromap_to_plot_xpath)
        new_aeromap_to_plot = aeromap_uid_list + new_aeromap_uid_list
        new_aeromap_to_plot = list(set(new_aeromap_to_plot))
        cpsf.add_string_vector(tixi, aeromap_to_plot_xpath,
                               new_aeromap_to_plot)
    else:
        cpsf.create_branch(tixi, aeromap_to_plot_xpath)
        cpsf.add_string_vector(tixi, aeromap_to_plot_xpath,
                               new_aeromap_uid_list)

    log.info('AeroMap "' + aeromap_uid + '" has been added to the CPACS file')

    cpsf.close_tixi(tixi, cpacs_out_path)
Пример #3
0
def plot_aero_coef(cpacs_path, cpacs_out_path):
    """Plot Aero coefficients from the chosen aeroMap in the CPACS file

    Function 'plot_aero_coef' can plot one or several aeromap from the CPACS
    file according to some user option, these option will be shown in the the
    SettingGUI or default values will be used.

    Args:
        cpacs_path (str): Path to CPACS file
        cpacs_out_path (str):Path to CPACS output file
    """

    # Open TIXI handle
    tixi = cpsf.open_tixi(cpacs_path)
    aircraft_name = cpsf.aircraft_name(tixi)

    # Get aeroMap list to plot
    aeromap_to_plot_xpath = PLOT_XPATH + '/aeroMapToPlot'
    aeromap_uid_list = []

    # Option to select aeromap manualy
    manual_selct = cpsf.get_value_or_default(tixi,
                                             PLOT_XPATH + '/manualSelection',
                                             False)
    if manual_selct:
        aeromap_uid_list = call_select_aeromap(tixi)
        cpsf.create_branch(tixi, aeromap_to_plot_xpath)
        cpsf.add_string_vector(tixi, aeromap_to_plot_xpath, aeromap_uid_list)

    else:
        try:
            aeromap_uid_list = cpsf.get_string_vector(tixi,
                                                      aeromap_to_plot_xpath)
        except:
            # If aeroMapToPlot is not define, select manualy anyway
            aeromap_uid_list = call_select_aeromap(tixi)
            cpsf.create_branch(tixi, aeromap_to_plot_xpath)
            cpsf.add_string_vector(tixi, aeromap_to_plot_xpath,
                                   aeromap_uid_list)

    # Create DataFrame from aeromap(s)
    aeromap_df_list = []
    for aeromap_uid in aeromap_uid_list:
        aeromap_df = apmf.get_datafram_aeromap(tixi, aeromap_uid)
        aeromap_df['uid'] = aeromap_uid
        aeromap_df_list.append(aeromap_df)

    aeromap = pd.concat(aeromap_df_list, ignore_index=True)

    if len(aeromap_uid_list) > 1:
        uid_crit = None
    else:
        uid_crit = aeromap_uid_list[0]

    # Default options
    title = aircraft_name
    criterion = pd.Series([True] * len(aeromap.index))
    groupby_list = ['uid', 'mach', 'alt', 'aos']

    # Get criterion from CPACS
    crit_xpath = PLOT_XPATH + '/criterion'
    alt_crit = cpsf.get_value_or_default(tixi, crit_xpath + '/alt', 'None')
    mach_crit = cpsf.get_value_or_default(tixi, crit_xpath + '/mach', 'None')
    aos_crit = cpsf.get_value_or_default(tixi, crit_xpath + '/aos', 'None')

    cpsf.close_tixi(tixi, cpacs_out_path)

    # Modify criterion and title according to user option
    if len(aeromap['alt'].unique()) == 1:
        title += ' - Alt = ' + str(aeromap['alt'].loc[0])
        groupby_list.remove('alt')
    elif alt_crit not in NONE_LIST:
        criterion = criterion & (aeromap.alt == alt_crit)
        title += ' - Alt = ' + str(alt_crit)
        groupby_list.remove('alt')

    if len(aeromap['mach'].unique()) == 1:
        title += ' - Mach = ' + str(aeromap['mach'].loc[0])
        groupby_list.remove('mach')
    elif mach_crit not in NONE_LIST:
        criterion = criterion & (aeromap.mach == mach_crit)
        title += ' - Mach = ' + str(mach_crit)
        groupby_list.remove('mach')

    if len(aeromap['aos'].unique()) == 1:
        title += ' - AoS = ' + str(aeromap['aos'].loc[0])
        groupby_list.remove('aos')
    elif aos_crit not in NONE_LIST:
        criterion = criterion & (aeromap.aos == aos_crit)
        title += ' - AoS = ' + str(aos_crit)
        groupby_list.remove('aos')

    if uid_crit is not None and len(groupby_list) > 1:
        criterion = criterion & (aeromap.uid == uid_crit)
        title += ' - ' + uid_crit
        groupby_list.remove('uid')

    # Plot settings
    fig, axs = plt.subplots(2, 3)
    fig.suptitle(title, fontsize=14)
    fig.set_figheight(8)
    fig.set_figwidth(15)
    fig.subplots_adjust(left=0.06)
    axs[0, 1].axhline(y=0.0, color='k', linestyle='-')  # Line at Cm=0

    # Plot aerodynamic coerfficients
    for value, grp in aeromap.loc[criterion].groupby(groupby_list):

        legend = write_legend(groupby_list, value)

        axs[0, 0].plot(grp['aoa'], grp['cl'], 'x-', label=legend)
        axs[1, 0].plot(grp['aoa'], grp['cd'], 'x-')
        axs[0, 1].plot(grp['aoa'], grp['cms'], 'x-')
        axs[1, 1].plot(grp['aoa'], grp['cl'] / grp['cd'], 'x-')
        axs[0, 2].plot(grp['cd'], grp['cl'], 'x-')
        axs[1, 2].plot(grp['cl'], grp['cl'] / grp['cd'], 'x-')

    # Set subplot options
    subplot_options(axs[0, 0], 'CL', 'AoA')
    subplot_options(axs[1, 0], 'CD', 'AoA')
    subplot_options(axs[0, 1], 'Cm', 'AoA')
    subplot_options(axs[1, 1], 'CL/CD', 'AoA')
    subplot_options(axs[0, 2], 'CL', 'CD')
    subplot_options(axs[1, 2], 'CL/CD', 'CL')

    fig.legend(loc='upper right')
    plt.show()
Пример #4
0
    def __init__(self, tabs, tixi, module_name):
        """Tab class

        Note:
            A tab will only be created if the module actually has
            any settings which are to be shown

        Args:
            tabs (TODO): TODO
            tixi (handle): Tixi handle
            module_name (str): String of the module name for which a tab is to be created
        """

        self.var_dict = {}
        self.group_dict = {}

        self.module_name = module_name
        self.tabs = tabs
        self.tixi = tixi
        self.tab = tk.Frame(tabs, borderwidth=1)
        tabs.add(self.tab, text=module_name)

        # Get GUI dict from specs
        specs = mif.get_specs_for_module(module_name)

        self.gui_dict = specs.cpacs_inout.get_gui_dict()

        #canvas has replaced self.tab in the following lines
        space_label = tk.Label(self.tab, text=' ')
        space_label.grid(column=0, row=0)

        row_pos = 1

        for key, (name, def_value, dtype, unit, xpath, description, group) in self.gui_dict.items():
            # Create a LabelFrame for new groupe
            if group:
                if not group in self.group_dict:
                    self.labelframe = tk.LabelFrame(self.tab, text=group)
                    self.labelframe.grid(column=0, row=row_pos, columnspan=3,sticky= tk.W, padx=5, pady=5)
                    self.group_dict[group] = self.labelframe
                parent = self.group_dict[group]
            else:  # if not a group, use tab as parent
                parent = self.tab

            # Name label for variable
            if (name is not '__AEROMAP_SELECTION' and name is not '__AEROMAP_CHECHBOX'):
                self.name_label = tk.Label(parent, text= name)
                self.name_label.grid(column=0, row=row_pos, sticky= tk.W, padx=5, pady=5)

            # Type and Value
            if dtype is bool:
                self.var_dict[key] = tk.BooleanVar()
                value = cpsf.get_value_or_default(self.tixi,xpath,def_value)
                self.var_dict[key].set(value)
                bool_entry = tk.Checkbutton(parent, text='', variable=self.var_dict[key])
                bool_entry.grid(column=1, row=row_pos, padx=5, pady=5)

            elif dtype is int:
                value = cpsf.get_value_or_default(self.tixi, xpath, def_value)
                self.var_dict[key] = tk.IntVar()
                self.var_dict[key].set(int(value))
                value_entry = tk.Entry(parent, bd=2, textvariable=self.var_dict[key])
                value_entry.grid(column=1, row=row_pos, padx=5, pady=5)

            elif dtype is float:
                value = cpsf.get_value_or_default(self.tixi, xpath, def_value)
                self.var_dict[key] = tk.DoubleVar()
                self.var_dict[key].set(value)
                value_entry = tk.Entry(parent, bd=2, textvariable=self.var_dict[key])
                value_entry.grid(column=1, row=row_pos, padx=5, pady=5)

            elif dtype is 'pathtype':

                value = cpsf.get_value_or_default(self.tixi,xpath,def_value)
                self.var_dict[key] = tk.StringVar()
                self.var_dict[key].set(value)
                value_entry = tk.Entry(parent, textvariable=self.var_dict[key])
                value_entry.grid(column=1, row=row_pos, padx=5, pady=5)

                self.key = key
                self.browse_button = tk.Button(parent, text="Browse", command=self._browse_file)
                self.browse_button.grid(column=2, row=row_pos, padx=5, pady=5)


            elif dtype is list:
                if name == '__AEROMAP_SELECTION':

                    # Get the list of all AeroMaps
                    self.aeromap_uid_list = apm.get_aeromap_uid_list(self.tixi)

                    # Try to get the pre-selected AeroMap from the xpath
                    try:
                        selected_aeromap = cpsf.get_value(self.tixi,xpath)
                        selected_aeromap_index = self.aeromap_uid_list.index(selected_aeromap)
                    except:
                        selected_aeromap = ''
                        selected_aeromap_index = 0

                    self.labelframe = tk.LabelFrame(parent, text='Choose an AeroMap')
                    self.labelframe.grid(column=0, row=row_pos, columnspan=3, sticky=tk.W, padx=5, pady=5)

                    # The Combobox is directly use as the varaible
                    self.var_dict[key] = ttk.Combobox(self.labelframe, values=self.aeromap_uid_list)
                    self.var_dict[key].current(selected_aeromap_index)
                    self.var_dict[key].grid(column=1, row=row_pos, padx=5, pady=5)


                elif name == '__AEROMAP_CHECHBOX':

                    # Just to find back the name when data are saved
                    self.var_dict[key] = None
                    # __AEROMAP_CHECHBOX is a bit different, data are saved in their own dictionary
                    self.aeromap_var_dict = {}

                    # Get the list of all AeroMaps
                    self.aeromap_uid_list = apm.get_aeromap_uid_list(self.tixi)
                    self.labelframe = tk.LabelFrame(parent, text='Selecte AeroMap(s)')
                    self.labelframe.grid(column=0, row=row_pos, columnspan=3, sticky=tk.W, padx=5, pady=5)

                    # Try to get pre-selected AeroMaps from the xpath
                    try:
                        selected_aeromap = cpsf.get_string_vector(self.tixi,xpath)
                    except:
                        selected_aeromap = ''

                    # Create one checkbox for each AeroMap
                    for aeromap in self.aeromap_uid_list:
                        self.aeromap_var_dict[aeromap] = tk.BooleanVar()

                        #if aeromap in selected_aeromap:
                        # For now, set all to True
                        self.aeromap_var_dict[aeromap].set(True)

                        aeromap_entry = tk.Checkbutton(self.labelframe,text=aeromap,variable=self.aeromap_var_dict[aeromap])
                        aeromap_entry.pack()#side=tk.TOP, anchor='w')

                else: # Other kind of list (not aeroMap)

                    # 'def_value' will be the list of possibilies in this case

                    # Try to get the pre-selected AeroMap from the xpath
                    try: # TODO Should be retested...
                        selected_value = cpsf.get_value(self.tixi,xpath)
                        selected_value_index = def_value.index(selected_value)
                    except:
                        selected_value = ''
                        selected_value_index = 0

                    # The Combobox is directly use as the varaible
                    self.var_dict[key] = ttk.Combobox(parent, values=def_value)
                    self.var_dict[key].current(selected_value_index)
                    self.var_dict[key].grid(column=1, row=row_pos, padx=5, pady=5)

            else:
                value = cpsf.get_value_or_default(self.tixi,xpath,def_value)
                self.var_dict[key] = tk.StringVar()
                self.var_dict[key].set(value)
                value_entry = tk.Entry(parent, textvariable=self.var_dict[key])
                value_entry.grid(column=1, row=row_pos, padx=5, pady=5)

            # Units
            if unit and unit != '1':
                unit_label = tk.Label(parent, text=pretty_unit(unit))
                unit_label.grid(column=2, row=row_pos, padx=5, pady=5)

            row_pos += 1
Пример #5
0
def generate_su2_config(cpacs_path, cpacs_out_path, wkdir):
    """Function to create SU2 confif file.

    Function 'generate_su2_config' reads data in the CPACS file and generate
    configuration files for one or multible flight conditions (alt,mach,aoa,aos)

    Source:
        * SU2 config template: https://github.com/su2code/SU2/blob/master/config_template.cfg

    Args:
        cpacs_path (str): Path to CPACS file
        cpacs_out_path (str):Path to CPACS output file
        wkdir (str): Path to the working directory

    """

    # Get value from CPACS
    tixi = cpsf.open_tixi(cpacs_path)
    tigl = cpsf.open_tigl(tixi)

    # Get SU2 mesh path
    su2_mesh_xpath = '/cpacs/toolspecific/CEASIOMpy/filesPath/su2Mesh'
    su2_mesh_path = cpsf.get_value(tixi,su2_mesh_xpath)

    # Get reference values
    ref_xpath = '/cpacs/vehicles/aircraft/model/reference'
    ref_len = cpsf.get_value(tixi,ref_xpath + '/length')
    ref_area = cpsf.get_value(tixi,ref_xpath + '/area')
    ref_ori_moment_x = cpsf.get_value_or_default(tixi,ref_xpath+'/point/x',0.0)
    ref_ori_moment_y = cpsf.get_value_or_default(tixi,ref_xpath+'/point/y',0.0)
    ref_ori_moment_z = cpsf.get_value_or_default(tixi,ref_xpath+'/point/z',0.0)

    # Get SU2 settings
    settings_xpath = SU2_XPATH + '/settings'
    max_iter_xpath = settings_xpath + '/maxIter'
    max_iter = cpsf.get_value_or_default(tixi, max_iter_xpath,200)
    cfl_nb_xpath = settings_xpath + '/cflNumber'
    cfl_nb = cpsf.get_value_or_default(tixi, cfl_nb_xpath,1.0)
    mg_level_xpath =  settings_xpath + '/multigridLevel'
    mg_level = cpsf.get_value_or_default(tixi, mg_level_xpath,3)

    # Mesh Marker
    bc_wall_xpath = SU2_XPATH + '/boundaryConditions/wall'
    bc_wall_list = su2f.get_mesh_marker(su2_mesh_path)
    cpsf.create_branch(tixi, bc_wall_xpath)
    bc_wall_str = ';'.join(bc_wall_list)
    tixi.updateTextElement(bc_wall_xpath,bc_wall_str)

    # Fixed CL parameters
    fixed_cl_xpath = SU2_XPATH + '/fixedCL'
    fixed_cl = cpsf.get_value_or_default(tixi, fixed_cl_xpath,'NO')
    target_cl_xpath = SU2_XPATH + '/targetCL'
    target_cl = cpsf.get_value_or_default(tixi, target_cl_xpath,1.0)

    if fixed_cl == 'NO':
        active_aeroMap_xpath = SU2_XPATH + '/aeroMapUID'
        aeromap_uid = cpsf.get_value(tixi,active_aeroMap_xpath)

        log.info('Configuration file for ""' + aeromap_uid + '"" calculation will be created.')

        # Get parameters of the aeroMap (alt,ma,aoa,aos)
        Param = apmf.get_aeromap(tixi,aeromap_uid)
        param_count = Param.get_count()

        if param_count >= 1:
            alt_list = Param.alt
            mach_list =  Param.mach
            aoa_list = Param.aoa
            aos_list = Param.aos
        else:
            raise ValueError('No parametre have been found in the aeroMap!')

    else: # if fixed_cl == 'YES':
        log.info('Configuration file for fixed CL calculation will be created.')

        range_xpath = '/cpacs/toolspecific/CEASIOMpy/ranges'

        # Parameters fixed CL calulation
        param_count = 1

        # These parameters will not be used
        aoa_list = [0.0]
        aos_list = [0.0]

        cruise_mach_xpath= range_xpath + '/cruiseMach'
        mach = cpsf.get_value_or_default(tixi,cruise_mach_xpath,0.78)
        mach_list = [mach]
        cruise_alt_xpath= range_xpath + '/cruiseAltitude'
        alt = cpsf.get_value_or_default(tixi,cruise_alt_xpath,12000)
        alt_list = [alt]

        aeromap_uid = 'aeroMap_fixedCL_SU2'
        description = 'AeroMap created for SU2 fixed CL value of: ' + str(target_cl)
        apmf.create_empty_aeromap(tixi, aeromap_uid, description)
        Parameters = apmf.AeroCoefficient()
        Parameters.alt = alt_list
        Parameters.mach = mach_list
        Parameters.aoa = aoa_list
        Parameters.aos = aos_list
        apmf.save_parameters(tixi,aeromap_uid,Parameters)
        tixi.updateTextElement(SU2_XPATH+ '/aeroMapUID',aeromap_uid)


    # Get and modify the default configuration file
    cfg = su2f.read_config(DEFAULT_CONFIG_PATH)

    # General parmeters
    cfg['REF_LENGTH'] = ref_len
    cfg['REF_AREA'] = ref_area

    cfg['REF_ORIGIN_MOMENT_X'] = ref_ori_moment_x
    cfg['REF_ORIGIN_MOMENT_Y'] = ref_ori_moment_y
    cfg['REF_ORIGIN_MOMENT_Z'] = ref_ori_moment_z


    # Settings
    cfg['INNER_ITER'] = int(max_iter)
    cfg['CFL_NUMBER'] = cfl_nb
    cfg['MGLEVEL'] = int(mg_level)

    # Fixed CL mode (AOA will not be taken into account)
    cfg['FIXED_CL_MODE'] = fixed_cl
    cfg['TARGET_CL'] = target_cl
    cfg['DCL_DALPHA'] = '0.1'
    cfg['UPDATE_AOA_ITER_LIMIT'] = '50'
    cfg['ITER_DCL_DALPHA'] = '80'
    # TODO: correct value for the 3 previous parameters ??

    # Mesh Marker
    bc_wall_str = '(' + ','.join(bc_wall_list) + ')'
    cfg['MARKER_EULER'] = bc_wall_str
    cfg['MARKER_FAR'] = ' (Farfield)' # TODO: maybe make that a variable
    cfg['MARKER_SYM'] = ' (0)'       # TODO: maybe make that a variable?
    cfg['MARKER_PLOTTING'] = bc_wall_str
    cfg['MARKER_MONITORING'] = bc_wall_str
    cfg['MARKER_MOVING'] = '( NONE )'  # TODO: when do we need to define MARKER_MOVING?
    cfg['DV_MARKER'] = bc_wall_str

    # Parameters which will vary for the different cases (alt,mach,aoa,aos)
    for case_nb in range(param_count):

        cfg['MESH_FILENAME'] = su2_mesh_path

        alt = alt_list[case_nb]
        mach = mach_list[case_nb]
        aoa = aoa_list[case_nb]
        aos = aos_list[case_nb]

        Atm = get_atmosphere(alt)
        pressure = Atm.pres
        temp = Atm.temp

        cfg['MACH_NUMBER'] = mach
        cfg['AOA'] = aoa
        cfg['SIDESLIP_ANGLE'] = aos
        cfg['FREESTREAM_PRESSURE'] = pressure
        cfg['FREESTREAM_TEMPERATURE'] = temp

        cfg['ROTATION_RATE'] = '0.0 0.0 0.0'

        config_file_name = 'ConfigCFD.cfg'


        case_dir_name = ''.join(['Case',str(case_nb).zfill(2),
                                 '_alt',str(alt),
                                 '_mach',str(round(mach,2)),
                                 '_aoa',str(round(aoa,1)),
                                 '_aos',str(round(aos,1))])

        case_dir_path = os.path.join(wkdir,case_dir_name)
        if not os.path.isdir(case_dir_path):
            os.mkdir(case_dir_path)

        config_output_path = os.path.join(wkdir,case_dir_name,config_file_name)

        su2f.write_config(config_output_path,cfg)


        # Damping derivatives
        damping_der_xpath = SU2_XPATH + '/options/clalculateDampingDerivatives'
        damping_der = cpsf.get_value_or_default(tixi,damping_der_xpath,False)

        if damping_der:

            rotation_rate_xpath = SU2_XPATH + '/options/rotationRate'
            rotation_rate = cpsf.get_value_or_default(tixi,rotation_rate_xpath,1.0)

            cfg['GRID_MOVEMENT'] = 'ROTATING_FRAME'

            cfg['ROTATION_RATE'] = str(rotation_rate) + ' 0.0 0.0'
            os.mkdir(os.path.join(wkdir,case_dir_name+'_dp'))
            config_output_path = os.path.join(wkdir,case_dir_name+'_dp',config_file_name)
            su2f.write_config(config_output_path,cfg)

            cfg['ROTATION_RATE'] = '0.0 ' + str(rotation_rate) + ' 0.0'
            os.mkdir(os.path.join(wkdir,case_dir_name+'_dq'))
            config_output_path = os.path.join(wkdir,case_dir_name+'_dq',config_file_name)
            su2f.write_config(config_output_path,cfg)

            cfg['ROTATION_RATE'] = '0.0 0.0 ' + str(rotation_rate)
            os.mkdir(os.path.join(wkdir,case_dir_name+'_dr'))
            config_output_path = os.path.join(wkdir,case_dir_name+'_dr',config_file_name)
            su2f.write_config(config_output_path,cfg)

            log.info('Damping derivatives cases directory has been created.')



        # Control surfaces deflections
        control_surf_xpath = SU2_XPATH + '/options/clalculateCotrolSurfacesDeflections'
        control_surf = cpsf.get_value_or_default(tixi,control_surf_xpath,False)

        if control_surf:

            # Get deformed mesh list
            su2_def_mesh_xpath = SU2_XPATH + '/availableDeformedMesh'
            if tixi.checkElement(su2_def_mesh_xpath):
                su2_def_mesh_list = cpsf.get_string_vector(tixi,su2_def_mesh_xpath)
            else:
                log.warning('No SU2 deformed mesh has been found!')
                su2_def_mesh_list = []

            for su2_def_mesh in su2_def_mesh_list:

                mesh_path = os.path.join(wkdir,'MESH',su2_def_mesh)

                config_dir_path = os.path.join(wkdir,case_dir_name+'_'+su2_def_mesh.split('.')[0])
                os.mkdir(config_dir_path)
                cfg['MESH_FILENAME'] = mesh_path

                config_file_name = 'ConfigCFD.cfg'
                config_output_path = os.path.join(wkdir,config_dir_path,config_file_name)
                su2f.write_config(config_output_path,cfg)


    # TODO: change that, but if it is save in tooloutput it will be erease by results...
    cpsf.close_tixi(tixi,cpacs_path)
Пример #6
0
def test_static_stability_analysis():
    """Test function 'staticStabilityAnalysis' """

    MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
    cpacs_path = os.path.join(MODULE_DIR,'ToolInput','CPACSTestStability.xml')
    cpacs_out_path = os.path.join(MODULE_DIR,'ToolOutput', 'CPACSTestStability.xml')
    csv_path = MODULE_DIR + '/ToolInput/csvtest.csv'

    tixi = cpsf.open_tixi(cpacs_path)
    # Get Aeromap UID list
    # uid_list = apmf.get_aeromap_uid_list(tixi)
    # aeromap_uid = uid_list[0]
    # # Import aeromap from the CSV to the xml
    # apmf.aeromap_from_csv(tixi, aeromap_uid, csv_path)
    # cpsf.close_tixi(tixi, cpacs_out_path)

    # Make the static stability analysis, on the modified xml file
    static_stability_analysis(cpacs_path, cpacs_out_path)

    # Assert that all error messages are present
    #log_path = os.path.join(LIB_DIR,'StabilityStatic','staticstability.log')
    # graph_cruising = False
    # errors = ''
    # #Open  log file
    # with open(log_path, "r") as f :
    #     # For each line in the log file
    #     for line in f :
    #         # if the info insureing that the graph of cruising aoa VS mach has been generated.
    #         if 'graph : cruising aoa vs mach genrated' in line :
    #             graph_cruising = True
    #         # if 'warning' or 'error ' is in line
    #         if  'ERROR' in line :
    #             # check if error type (altitude) is in line
    #             errors += line
    # TODO: remove, not good to test with the logfile
    # Assert that all error type happend only once.
    #assert graph_cruising == True

    tixi = cpsf.open_tixi(cpacs_out_path)
    static_xpath = '/cpacs/toolspecific/CEASIOMpy/stability/static'
    long_static_stable = cpsf.get_value(tixi, static_xpath+'/results/longitudinalStaticStable')
    lat_static_stable = cpsf.get_value(tixi, static_xpath+'/results/lateralStaticStable')
    dir_static_stable = cpsf.get_value(tixi, static_xpath+'/results/directionnalStaticStable')

    assert long_static_stable
    assert lat_static_stable
    assert not dir_static_stable

    trim_longi_alt = cpsf.get_value(tixi, static_xpath+'/trimConditions/longitudinal/altitude')
    trim_longi_mach = cpsf.get_value(tixi, static_xpath+'/trimConditions/longitudinal/machNumber')
    trim_longi_aoa = cpsf.get_value(tixi, static_xpath+'/trimConditions/longitudinal/angleOfAttack')
    trim_longi_aos = cpsf.get_value(tixi, static_xpath+'/trimConditions/longitudinal/angleOfSideslip')

    assert trim_longi_alt == 1400
    assert trim_longi_mach == 0.6
    assert trim_longi_aoa == 3.25803
    assert trim_longi_aos == 0

    trim_dir_alt = cpsf.get_string_vector(tixi, static_xpath+'/trimConditions/directional/altitude')
    trim_dir_mach = cpsf.get_string_vector(tixi, static_xpath+'/trimConditions/directional/machNumber')
    trim_dir_aoa = cpsf.get_string_vector(tixi, static_xpath+'/trimConditions/directional/angleOfAttack')
    trim_dir_aos = cpsf.get_string_vector(tixi, static_xpath+'/trimConditions/directional/angleOfSideslip')

    assert trim_dir_alt == ['2400','2500','2600','2700']
    assert trim_dir_mach == ['0.6','0.5','0.5','0.5']
    assert trim_dir_aoa == ['1','2','4','2.5']
    assert trim_dir_aos == ['0','0','0','0']

    cpsf.close_tixi(tixi, cpacs_out_path)
Пример #7
0
def plot_aero_coef(cpacs_path, cpacs_out_path):
    """Function to plot available aerodynamic coefficients from aeroMap.

    Function 'plot_aero_coef' plot aerodynamic coefficients (CL,CD,Cm) of the
    aeroMap selected in the CPACS file or if not define, ask the user to select
    them.

    Args:
        cpacs_path (str): Path to CPACS file
        cpacs_out_path (str):Path to CPACS output file

    """

    # Open TIXI handle
    tixi = cpsf.open_tixi(cpacs_path)

    # Prepare subplots
    figure_1 = plt.figure(figsize=(9, 9))
    subplot1 = figure_1.add_subplot(221)
    subplot2 = figure_1.add_subplot(222)
    subplot3 = figure_1.add_subplot(223)
    subplot4 = figure_1.add_subplot(224)

    LINE_STYLE = ['bo-', 'ro-', 'go-', 'co-', 'mo-', 'ko-', 'yo-']

    # Get aeroMap list to plot
    aeromap_to_plot_xpath = PLOT_XPATH + '/aeroMapToPlot'
    aeromap_uid_list = []
    try:
        aeromap_uid_list = cpsf.get_string_vector(tixi, aeromap_to_plot_xpath)
    except:
        # If aeroMapToPlot is not define, open GUI to select which ones shoud be
        aeromap_uid_list = call_select_aeromap(tixi)
        cpsf.create_branch(tixi, aeromap_to_plot_xpath)
        cpsf.add_string_vector(tixi, aeromap_to_plot_xpath, aeromap_uid_list)

    for i, aeromap_uid in enumerate(aeromap_uid_list):

        log.info('"' + aeromap_uid + '" will be added to the plot.')

        # Get aeroMap to plot and replace missing results with zeros
        AeroCoef = apmf.get_aeromap(tixi, aeromap_uid)
        AeroCoef.complete_with_zeros()
        AeroCoef.print_coef_list()

        # Subplot1
        x1 = AeroCoef.aoa
        y1 = AeroCoef.cl
        subplot1.plot(x1, y1, LINE_STYLE[i])

        # Subplot2
        x2 = AeroCoef.aoa
        y2 = AeroCoef.cms
        subplot2.plot(x2, y2, LINE_STYLE[i])

        # Subplot3
        x3 = AeroCoef.aoa
        y3 = AeroCoef.cd
        subplot3.plot(x3, y3, LINE_STYLE[i])

        # Subplot4
        x4 = AeroCoef.aoa
        if any(AeroCoef.cd) == 0.0:
            cl_cd = [0] * len(AeroCoef.aoa)
        else:
            cl_cd = res = [cl / cd for cl, cd in zip(AeroCoef.cl, AeroCoef.cd)]
        y4 = cl_cd
        subplot4.plot(x4, y4, LINE_STYLE[i])

    # Labels
    subplot1.set_xlabel('Angle of attack')
    subplot1.set_ylabel('Lift coefficient')
    subplot2.set_xlabel('Angle of attack')
    subplot2.set_ylabel('Moment coefficient')
    subplot3.set_xlabel('Angle of attack')
    subplot3.set_ylabel('Drag coefficient')
    subplot4.set_xlabel('Angle of attack')
    subplot4.set_ylabel('Efficiency CL/CD')

    # Legend
    figure_1.legend(aeromap_uid_list)

    # Grid
    subplot1.grid()
    subplot2.grid()
    subplot3.grid()
    subplot4.grid()

    cpsf.close_tixi(tixi, cpacs_out_path)

    plt.show()
def dynamic_stability_analysis(cpacs_path, cpacs_out_path):
    """Function to analyse a full Aeromap

    Function 'dynamic_stability_analysis' analyses longitudinal dynamic
    stability and directionnal dynamic.

    Args:
        cpacs_path (str): Path to CPACS file
        cpacs_out_path (str):Path to CPACS output file
        plot (boolean): Choise to plot graph or not

    Returns:  (#TODO put that in the documentation)
        *   Adrvertisements certifying if the aircraft is stable or Not
        *   In case of longitudinal dynamic UNstability or unvalid test on data:
                -	Plot cms VS aoa for constant Alt, Mach and different aos
                -	Plot cms VS aoa for const alt and aos and different mach
                -	plot cms VS aoa for constant mach, AOS and different altitudes
        *  In case of directionnal dynamic UNstability or unvalid test on data:
                -	Pcot cml VS aos for constant Alt, Mach and different aoa
                -	Plot cml VS aos for const alt and aoa and different mach
                -	plot cml VS aos for constant mach, AOA and different altitudes
        *  Plot one graph of  cruising angles of attack for different mach and altitudes

    Make the following tests:
        *   Check the CPACS path
        *   For longitudinal dynamic stability analysis:
                -   If there is more than one angle of attack for a given altitude, mach, aos
                -   If cml values are only zeros for a given altitude, mach, aos
                -   If there one aoa value which is repeated for a given altitude, mach, aos
        *   For directionnal dynamic stability analysis:
                -   If there is more than one angle of sideslip for a given altitude, mach, aoa
                -   If cms values are only zeros for a given altitude, mach, aoa
                -   If there one aos value which is repeated for a given altitude, mach, aoa
    """

    # XPATH definition
    aeromap_uid_xpath = DYNAMIC_ANALYSIS_XPATH + '/aeroMapUid'
    aircraft_class_xpath = DYNAMIC_ANALYSIS_XPATH + '/class'  # Classes 1 2 3 4 small, heavy ...
    aircraft_cathegory_xpath = DYNAMIC_ANALYSIS_XPATH + '/category'  # flight phase A B C
    selected_mass_config_xpath = DYNAMIC_ANALYSIS_XPATH + '/massConfiguration'
    longi_analysis_xpath = DYNAMIC_ANALYSIS_XPATH + '/instabilityModes/longitudinal'
    direc_analysis_xpath = DYNAMIC_ANALYSIS_XPATH + '/instabilityModes/lateralDirectional'
    show_plot_xpath = DYNAMIC_ANALYSIS_XPATH + '/showPlots'
    save_plot_xpath = DYNAMIC_ANALYSIS_XPATH + '/savePlots'

    model_xpath = '/cpacs/vehicles/aircraft/model'
    ref_area_xpath = model_xpath + '/reference/area'
    ref_length_xpath = model_xpath + '/reference/length'
    flight_qualities_case_xpath = model_xpath + '/analyses/flyingQualities/fqCase'
    masses_location_xpath = model_xpath + '/analyses/massBreakdown/designMasses'
    # aircraft_class_xpath = flight_qualities_case_xpath + '/class' # Classes 1 2 3 4 small, heavy ...
    # aircraft_cathegory_xpath = flight_qualities_case_xpath + '/cathegory' # flight phase A B C

    # Ask user flight path angles : gamma_e
    thrust_available = None  # Thrust data are not available
    flight_path_angle_deg = [
        0
    ]  # [-15,-10,-5,0,5,10,15] # The user should have the choice to select them !!!!!!!!!!!!!!!!!!!!
    flight_path_angle = [
        angle * (np.pi / 180) for angle in flight_path_angle_deg
    ]  # flight_path_angle in [rad]

    tixi = cpsf.open_tixi(cpacs_path)
    # Get aeromap uid
    aeromap_uid = cpsf.get_value(tixi, aeromap_uid_xpath)
    log.info('The following aeroMap will be analysed: ' + aeromap_uid)

    # Mass configuration: (Maximum landing mass, Maximum ramp mass (the maximum weight authorised for the ground handling), Take off mass, Zero Fuel mass)
    mass_config = cpsf.get_value(tixi, selected_mass_config_xpath)
    log.info('The aircraft mass configuration used for analysis is: ' +
             mass_config)

    # Analyses to do : longitudinal / Lateral-Directional
    longitudinal_analysis = cpsf.get_value(tixi, longi_analysis_xpath)
    lateral_directional_analysis = False
    # lateral_directional_analysis = cpsf.get_value(tixi, direc_analysis_xpath )
    # Plots configuration with Setting GUI
    show_plots = cpsf.get_value_or_default(tixi, show_plot_xpath, False)
    save_plots = cpsf.get_value_or_default(tixi, save_plot_xpath, False)

    mass_config_xpath = masses_location_xpath + '/' + mass_config
    if tixi.checkElement(mass_config_xpath):
        mass_xpath = mass_config_xpath + '/mass'
        I_xx_xpath = mass_config_xpath + '/massInertia/Jxx'
        I_yy_xpath = mass_config_xpath + '/massInertia/Jyy'
        I_zz_xpath = mass_config_xpath + '/massInertia/Jzz'
        I_xz_xpath = mass_config_xpath + '/massInertia/Jxz'
    else:
        raise ValueError(
            'The mass configuration : {} is not defined in the CPACS file !!!'.
            format(mass_config))

    s = cpsf.get_value(
        tixi, ref_area_xpath
    )  # Wing area : s  for non-dimonsionalisation of aero data.
    mac = cpsf.get_value(
        tixi, ref_length_xpath
    )  # ref length for non dimensionalisation, Mean aerodynamic chord: mac,
    # TODO: check that
    b = s / mac

    # TODO: find a way to get that
    xh = 10  # distance Aircaft cg-ac_horizontal-tail-plane.

    m = cpsf.get_value(tixi, mass_xpath)  # aircraft mass dimensional
    I_xx = cpsf.get_value(tixi, I_xx_xpath)  # X inertia dimensional
    I_yy = cpsf.get_value(tixi, I_yy_xpath)  # Y inertia dimensional
    I_zz = cpsf.get_value(tixi, I_zz_xpath)  # Z inertia dimensional
    I_xz = cpsf.get_value(tixi, I_xz_xpath)  # XZ inertia dimensional

    aircraft_class = cpsf.get_value(
        tixi, aircraft_class_xpath)  # aircraft class 1 2 3 4
    flight_phase = cpsf.get_string_vector(
        tixi, aircraft_cathegory_xpath)[0]  # Flight phase A B C

    Coeffs = apmf.get_aeromap(
        tixi, aeromap_uid
    )  # Warning: Empty uID found! This might lead to unknown errors!

    alt_list = Coeffs.alt
    mach_list = Coeffs.mach
    aoa_list = Coeffs.aoa
    aos_list = Coeffs.aos
    cl_list = Coeffs.cl
    cd_list = Coeffs.cd
    cs_list = Coeffs.cs
    cml_list = Coeffs.cml
    cms_list = Coeffs.cms
    cmd_list = Coeffs.cmd
    dcsdrstar_list = Coeffs.dcsdrstar
    dcsdpstar_list = Coeffs.dcsdpstar
    dcldqstar_list = Coeffs.dcldqstar
    dcmsdqstar_list = Coeffs.dcmsdqstar
    dcddqstar_list = Coeffs.dcddqstar
    dcmldqstar_list = Coeffs.dcmldqstar
    dcmddpstar_list = Coeffs.dcmddpstar
    dcmldpstar_list = Coeffs.dcmldpstar
    dcmldrstar_list = Coeffs.dcmldrstar
    dcmddrstar_list = Coeffs.dcmddrstar

    # All different vallues with only one occurence
    alt_unic = get_unic(alt_list)
    mach_unic = get_unic(mach_list)
    aos_unic = get_unic(aos_list)
    aoa_unic = get_unic(aoa_list)

    # TODO get from CPACS
    incrementalMap = False

    for alt in alt_unic:
        idx_alt = [i for i in range(len(alt_list)) if alt_list[i] == alt]
        Atm = get_atmosphere(alt)
        g = Atm.grav
        a = Atm.sos
        rho = Atm.dens

        for mach in mach_unic:
            print('Mach : ', mach)
            idx_mach = [
                i for i in range(len(mach_list)) if mach_list[i] == mach
            ]
            u0, m_adim, i_xx, i_yy, i_zz, i_xz = adimensionalise(
                a, mach, rho, s, b, mac, m, I_xx, I_yy, I_zz,
                I_xz)  # u0 is V0 in Cook

            # Hyp: trim condition when: ( beta = 0 and dCm/dalpha = 0)  OR  ( aos=0 and dcms/daoa = 0 )
            if 0 not in aos_unic:
                log.warning(
                    'The aircraft can not be trimmed (requiring symetric flight condition) as beta never equal to 0 for Alt = {}, mach = {}'
                    .format(alt, mach))
            else:
                idx_aos = [i for i in range(len(aos_list)) if aos_list[i] == 0]
                find_index = get_index(idx_alt, idx_mach, idx_aos)
                # If there is only one data at (alt, mach, aos) then dont make stability anlysis
                if len(find_index) <= 1:
                    log.warning(
                        'Not enough data at : Alt = {} , mach = {}, aos = 0, can not perform stability analysis'
                        .format(alt, mach))
                # If there is at leat 2 data at (alt, mach, aos) then, make stability anlysis
                else:
                    # Calculate trim conditions
                    cms = []
                    aoa = []
                    cl = []
                    for index in find_index:
                        cms.append(cms_list[index])
                        aoa.append(aoa_list[index] * np.pi / 180)
                        cl.append(cl_list[index])

                    cl_required = (m * g) / (0.5 * rho * u0**2 * s)
                    (trim_aoa, idx_trim_before, idx_trim_after,
                     ratio) = trim_condition(
                         alt,
                         mach,
                         cl_required,
                         cl,
                         aoa,
                     )

                    if trim_aoa:
                        trim_aoa_deg = trim_aoa * 180 / np.pi
                        trim_cms = interpolation(cms, idx_trim_before,
                                                 idx_trim_after, ratio)
                        pitch_moment_derivative_rad = (
                            cms[idx_trim_after] - cms[idx_trim_before]) / (
                                aoa[idx_trim_after] - aoa[idx_trim_before])
                        pitch_moment_derivative_deg = pitch_moment_derivative_rad / (
                            180 / np.pi)
                        # Find incremental cms
                        if incrementalMap:
                            for index, mach_number in enumerate(mach_unic, 0):
                                if mach_number == mach:
                                    mach_index = index
                            dcms_before = dcms_list[mach_index * len(aoa_unic)
                                                    + idx_trim_before]
                            dcms_after = dcms_list[mach_index * len(aoa_unic) +
                                                   idx_trim_after]
                            dcms = dcms_before + ratio * (dcms_after -
                                                          dcms_before)
                            trim_elevator = -trim_cms / dcms  # Trim elevator deflection in [°]
                        else:
                            dcms = None
                            trim_elevator = None

                    else:
                        trim_aoa_deg = None
                        trim_cms = None
                        pitch_moment_derivative_deg = None
                        dcms = None
                        trim_elevator = None

                    # Longitudinal dynamic stability,
                    # Stability analysis
                    if longitudinal_analysis and trim_cms:
                        cl = []
                        cd = []
                        dcldqstar = []
                        dcddqstar = []
                        dcmsdqstar = []
                        for index in find_index:
                            cl.append(cl_list[index])
                            cd.append(cd_list[index])
                            dcldqstar.append(dcldqstar_list[index])
                            dcddqstar.append(dcddqstar_list[index])
                            dcmsdqstar.append(dcmsdqstar_list[index])

                        # Trimm variables
                        cd0 = interpolation(cd, idx_trim_before,
                                            idx_trim_after,
                                            ratio)  # Dragg coeff at trim
                        cl0 = interpolation(cl, idx_trim_before,
                                            idx_trim_after,
                                            ratio)  # Lift coeff at trim
                        cl_dividedby_cd_trim = cl0 / cd0  #  cl/cd ratio at trim, at trim aoa

                        # Lift & drag coefficient derivative with respect to AOA at trimm
                        cl_alpha0 = (cl[idx_trim_after] - cl[idx_trim_before]
                                     ) / (aoa[idx_trim_after] -
                                          aoa[idx_trim_before])
                        cd_alpha0 = (cd[idx_trim_after] - cd[idx_trim_before]
                                     ) / (aoa[idx_trim_after] -
                                          aoa[idx_trim_before])
                        print(idx_trim_before, idx_trim_after, ratio)

                        dcddqstar0 = interpolation(dcddqstar, idx_trim_before,
                                                   idx_trim_after,
                                                   ratio)  # x_q
                        dcldqstar0 = interpolation(dcldqstar, idx_trim_before,
                                                   idx_trim_after,
                                                   ratio)  # z_q
                        dcmsdqstar0 = interpolation(dcmsdqstar,
                                                    idx_trim_before,
                                                    idx_trim_after,
                                                    ratio)  # m_q
                        cm_alpha0 = trim_cms

                        # Speed derivatives if there is at least 2 distinct mach values
                        if len(mach_unic) >= 2:
                            dcddm0 = speed_derivative_at_trim(
                                cd_list, mach, mach_list, mach_unic, idx_alt,
                                aoa_list, aos_list, idx_trim_before,
                                idx_trim_after, ratio)

                            if dcddm0 == None:
                                dcddm0 = 0
                                log.warning(
                                    'Not enough data to determine dcddm or (Cd_mach) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: dcddm = 0'
                                    .format(alt, mach, round(trim_aoa_deg, 2)))
                            dcldm0 = speed_derivative_at_trim(
                                cl_list, mach, mach_list, mach_unic, idx_alt,
                                aoa_list, aos_list, idx_trim_before,
                                idx_trim_after, ratio)
                            if dcldm0 == None:
                                dcldm0 = 0
                                log.warning(
                                    'Not enough data to determine dcldm (Cl_mach) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: dcldm = 0'
                                    .format(alt, mach, round(trim_aoa_deg, 2)))
                        else:
                            dcddm0 = 0
                            dcldm0 = 0
                            log.warning(
                                'Not enough data to determine dcddm (Cd_mach) and dcldm (Cl_mach) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: dcddm = dcldm = 0'
                                .format(alt, mach, round(trim_aoa_deg, 2)))

                        # Controls Derivatives to be found in the CPACS (To be calculated)
                        dcddeta0 = 0
                        dcldeta0 = 0
                        dcmsdeta0 = 0
                        dcddtau0 = 0
                        dcldtau0 = 0
                        dcmsdtau0 = 0

                        # Traduction Ceasiom -> Theory
                        Ue = u0 * np.cos(
                            trim_aoa
                        )  # *np.cos(aos) as aos = 0 at trim, cos(aos)=1
                        We = u0 * np.sin(
                            trim_aoa
                        )  # *np.cos(aos) as aos = 0 at trim, cos(aos)=1

                        # Dimentionless State Space variables,
                        # In generalised body axes coordinates ,
                        # simplifications: Ue=V0, We=0, sin(Theta_e)=0 cos(Theta_e)=0
                        if thrust_available:  #   If power data
                            X_u = -(2 * cd0 + mach * dcddm0) + 1 / (
                                0.5 * rho * s * a ^ 2
                            ) * dtaudm0  # dtaudm dimensional Thrust derivative at trim conditions, P340 Michael V. Cook
                        else:  #   Glider Mode
                            X_u = -(2 * cd0 + mach * dcddm0)

                        Z_u = -(2 * cl0 + mach * dcldm0)
                        M_u = 0  # Negligible for subsonic conditions  or better with P289 Yechout (cm_u+2cm0)

                        X_w = (cl0 - cd_alpha0)
                        Z_w = -(cl_alpha0 + cd0)
                        M_w = cm_alpha0

                        X_q = dcddqstar0  # Normally almost = 0
                        Z_q = dcldqstar0
                        M_q = -dcmsdqstar0

                        X_dotw = 0  # Negligible
                        Z_dotw = 1 / 3 * M_q / u0 / (
                            xh / mac
                        )  # Thumb rule : M_alpha_dot = 1/3 Mq , ( not true for 747 :caughey P83,M_alpha_dot = 1/6Mq )
                        M_dotw = 1 / 3 * M_q / u0  # Thumb rule : M_alpha_dot = 1/3 Mq

                        # Controls:
                        X_eta = dcddeta0  # To be found from the cpacs file, and defined by the user!
                        Z_eta = dcldeta0  # To be found from the cpacs file, and defined by the user!
                        M_eta = dcmsdeta0  # To be found from the cpacs file, and defined by the user!

                        X_tau = dcddtau0  # To be found from the cpacs file, and defined by the user!
                        Z_tau = dcldtau0  # To be found from the cpacs file, and defined by the user!
                        M_tau = dcmsdtau0  # To be found from the cpacs file, and defined by the user!
                        # -----------------  Traduction Ceasiom -> Theory   END -----------------------------------

                        # Sign check  (Ref: Thomas Yechout Book, P304)
                        check_sign_longi(cd_alpha0, M_w, cl_alpha0, M_dotw,
                                         Z_dotw, M_q, Z_q, M_eta, Z_eta)

                    # Laterl-Directional
                    if lateral_directional_analysis:
                        cml = []  # N
                        cmd = []  # L
                        aos = []
                        aoa = []  # For Ue We
                        cs = []  # For y_v
                        dcsdpstar = []  # y_p
                        dcmddpstar = []  # l_p
                        dcmldpstar = []  # n_p
                        dcsdrstar = []  # y_r
                        dcmldrstar = []  # n_r
                        dcmddrstar = []  # l_r

                        for index in find_index:
                            cml.append(cml_list[index])  # N , N_v
                            cmd.append(cmd_list[index])  # L ,  L_v
                            aos.append(aos_list[index] * np.pi / 180)
                            aoa.append(aoa_list[index])  # For Ue We
                            cs.append(cs_list[index])
                            dcsdpstar.append(dcsdpstar_list[index])  # y_p
                            dcmddpstar.append(dcmddpstar_list[index])  # l_p
                            dcmldpstar.append(dcmldpstar_list[index])  # n_p
                            dcsdrstar.append(dcsdrstar_list[index])  # y_r
                            dcmldrstar.append(dcmldrstar_list[index])  # n_r
                            dcmddrstar.append(dcmddrstar_list[index])  # l_r

                        #Trimm condition calculation
                        # speed derivatives :  y_v / l_v / n_v  /  Must be devided by speed given that the hyp v=Beta*U
                        if len(aos_unic) >= 2:
                            print('Mach : ', mach, '   and idx_mach : ',
                                  idx_mach)
                            cs_beta0 = speed_derivative_at_trim_lat(
                                cs_list, aos_list, aos_unic, idx_alt, idx_mach,
                                aoa_list, idx_trim_before, idx_trim_after,
                                ratio)  # y_v
                            if cs_beta0 == None:
                                cs_beta0 = 0
                                log.warning(
                                    'Not enough data to determine cs_beta (Y_v) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: cs_beta = 0'
                                    .format(alt, mach, round(trim_aoa_deg, 2)))
                            cmd_beta0 = speed_derivative_at_trim_lat(
                                cmd_list, aos_list, aos_unic, idx_alt,
                                idx_mach, aoa_list, idx_trim_before,
                                idx_trim_after, ratio)  # l_v
                            if cmd_beta0 == None:
                                cmd_beta0 = 0
                                log.warning(
                                    'Not enough data to determine cmd_beta (L_v) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: cmd_beta = 0'
                                    .format(alt, mach, round(trim_aoa_deg, 2)))
                            cml_beta0 = speed_derivative_at_trim_lat(
                                cml_list, aos_list, aos_unic, idx_alt,
                                idx_mach, aoa_list, idx_trim_before,
                                idx_trim_after, ratio)  # n_v
                            if cml_beta0 == None:
                                cml_beta0 = 0
                                log.warning(
                                    'Not enough data to determine cml_beta (N_v) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: cml_beta = 0'
                                    .format(alt, mach, round(trim_aoa_deg, 2)))
                        else:
                            cs_beta0 = 0
                            cmd_beta0 = 0
                            cml_beta0 = 0
                            log.warning(
                                'Not enough data to determine cs_beta (Y_v), cmd_beta (L_v) and cml_beta (N_v) at trim condition at Alt = {}, mach = {}, aoa = {}, aos = 0. Assumption: cs_beta = cmd_beta = cml_beta = 0'
                                .format(alt, mach, round(trim_aoa_deg, 2)))

                        dcsdpstar0 = interpolation(dcsdpstar, idx_trim_before,
                                                   idx_trim_after,
                                                   ratio)  # y_p
                        dcmddpstar0 = interpolation(dcmddpstar,
                                                    idx_trim_before,
                                                    idx_trim_after,
                                                    ratio)  # l_p
                        dcmldpstar0 = interpolation(dcmldpstar,
                                                    idx_trim_before,
                                                    idx_trim_after,
                                                    ratio)  # n_p

                        dcsdrstar0 = interpolation(dcsdrstar, idx_trim_before,
                                                   idx_trim_after,
                                                   ratio)  # y_r
                        dcmldrstar0 = interpolation(dcmldrstar,
                                                    idx_trim_before,
                                                    idx_trim_after,
                                                    ratio)  # n_r
                        dcmddrstar0 = interpolation(dcmddrstar,
                                                    idx_trim_before,
                                                    idx_trim_after,
                                                    ratio)  # l_r

                        # TODO: calculate that and find in the cpacs
                        dcsdxi0 = 0
                        dcmddxi0 = 0
                        dcmldxi0 = 0
                        dcsdzeta0 = 0
                        dcmddzeta0 = 0
                        dcmldzeta0 = 0

                        # Traduction Ceasiom -> Theory
                        Y_v = cs_beta0
                        L_v = cmd_beta0
                        N_v = cml_beta0

                        Y_p = -dcsdpstar0 * mac / b
                        L_p = -dcmddpstar0 * mac / b
                        N_p = dcmldpstar0 * mac / b

                        Y_r = dcsdrstar0 * mac / b
                        N_r = -dcmldrstar0 * mac / b  # mac/b :Because coefficients in ceasiom are nondimensionalised by the mac instead of the span
                        L_r = dcmddrstar0 * mac / b

                        # Controls:
                        # Ailerons
                        Y_xi = dcsdxi0  # To be found from the cpacs file, and defined by the user!
                        L_xi = dcmddxi0  # To be found from the cpacs file, and defined by the user!
                        N_xi = dcmldxi0  # To be found from the cpacs file, and defined by the user!
                        # Rudder
                        Y_zeta = dcsdzeta0  # To be found from the cpacs file, and defined by the user!
                        L_zeta = dcmddzeta0  # To be found from the cpacs file, and defined by the user!
                        N_zeta = dcmldzeta0  # To be found from the cpacs file, and defined by the user!

                        Ue = u0 * np.cos(
                            trim_aoa
                        )  # *np.cos(aos) as aos = 0 at trim, cos(aos)=1
                        We = u0 * np.sin(
                            trim_aoa
                        )  # *np.cos(aos) as aos = 0 at trim, cos(aos)=1

                        # Sign check  (Ref: Thomas Yechout Book, P304)
                        check_sign_lat(Y_v, L_v, N_v, Y_p, L_p, Y_r, L_r, N_r,
                                       L_xi, Y_zeta, L_zeta, N_zeta)

                    if trim_aoa:
                        for angles in flight_path_angle:
                            theta_e = angles + trim_aoa

                            if longitudinal_analysis:
                                (A_longi, B_longi, x_u,z_u,m_u,x_w,z_w,m_w, x_q,z_q,m_q,x_theta,z_theta,m_theta,x_eta,z_eta,m_eta, x_tau,z_tau,m_tau)\
                                                                    = concise_derivative_longi(X_u,Z_u,M_u,X_w,Z_w,M_w,\
                                                                    X_q,Z_q,M_q,X_dotw,Z_dotw,M_dotw,X_eta,Z_eta,M_eta,\
                                                                    X_tau,Z_tau,M_tau, g, theta_e, u0,We,Ue,mac,m_adim,i_yy)

                                C_longi = np.identity(4)
                                D_longi = np.zeros((4, 2))
                                # Identify longitudinal roots
                                if longi_root_identification(
                                        A_longi
                                )[0] == None:  # If longitudinal root not complex conjugate raise warning and plot roots
                                    eg_value_longi = longi_root_identification(
                                        A_longi)[1]
                                    log.warning(
                                        'Longi : charcateristic equation  roots are not complex conjugate : {}'
                                        .format(eg_value_longi))
                                    legend = [
                                        'Root1', 'Root2', 'Root3', 'Root4'
                                    ]
                                    plot_title = 'S-plane longitudinal characteristic equation roots at (Alt = {}, Mach= {}, trimed at aoa = {}°)'.format(
                                        alt, mach, trim_aoa)
                                    plot_splane(eg_value_longi, plot_title,
                                                legend, show_plots, save_plots)
                                else:  # Longitudinal roots are complex conjugate
                                    (sp1, sp2, ph1, ph2, eg_value_longi , eg_vector_longi, eg_vector_longi_magnitude)\
                                            = longi_root_identification(A_longi)
                                    legend = ['sp1', 'sp2', 'ph1', 'ph2']
                                    plot_title = 'S-plane longitudinal characteristic equation roots at (Alt = {}, Mach= {}, trimed at aoa = {}°)'.format(
                                        alt, mach, trim_aoa)
                                    plot_splane(eg_value_longi, plot_title,
                                                legend, show_plots, save_plots)

                                    # Modes parameters : damping ratio, frequence, CAP, time tou double amplitude
                                    Z_w_dimensional = Z_w * (
                                        0.5 * rho * s * u0**2
                                    )  # Z_w* (0.5*rho*s*u0**2)  is the dimensional form of Z_w,   Z_w = -(cl_alpha0 + cd0) P312 Yechout
                                    z_alpha = Z_w_dimensional * u0 / m  # alpha = w/u0 hence,   z_alpha =  Z_w_dimensional * u0      [Newton/rad/Kg :   m/s^2 /rad]
                                    load_factor = -z_alpha / g  #  number of g's/rad (1g/rad 2g/rad  3g/rad)
                                    (sp_freq, sp_damp, sp_cap, ph_freq, ph_damp, ph_t2)\
                                            =  longi_mode_characteristic(sp1,sp2,ph1,ph2,load_factor)

                                    # Rating
                                    sp_damp_rate = short_period_damping_rating(
                                        aircraft_class, sp_damp)
                                    sp_freq_rate = short_period_frequency_rating(
                                        flight_phase, aircraft_class, sp_freq,
                                        load_factor)
                                    # Plot SP freq vs Load factor
                                    legend = 'Alt = {}, Mach= {}, trim aoa = {}°'.format(
                                        alt, mach, trim_aoa)
                                    if flight_phase == 'A':
                                        plot_sp_level_a([load_factor],
                                                        [sp_freq], legend,
                                                        show_plots, save_plots)
                                    elif flight_phase == 'B':
                                        plot_sp_level_b(
                                            x_axis, y_axis, legend, show_plots,
                                            save_plots)
                                    else:
                                        plot_sp_level_c(
                                            x_axis, y_axis, legend, show_plots,
                                            save_plots)
                                    sp_cap_rate = cap_rating(
                                        flight_phase, sp_cap, sp_damp)
                                    ph_rate = phugoid_rating(ph_damp, ph_t2)
                                    # Raise warning if unstable mode in the log file
                                    if sp_damp_rate == None:
                                        log.warning(
                                            'ShortPeriod UNstable at Alt = {}, Mach = {} , due to DampRatio = {} '
                                            .format(alt, mach,
                                                    round(sp_damp, 4)))
                                    if sp_freq_rate == None:
                                        log.warning(
                                            'ShortPeriod UNstable at Alt = {}, Mach = {} , due to UnDampedFreq = {} rad/s '
                                            .format(alt, mach,
                                                    round(sp_freq, 4)))
                                    if sp_cap_rate == None:
                                        log.warning(
                                            'ShortPeriod UNstable at Alt = {}, Mach = {} , with CAP evaluation, DampRatio = {} , CAP = {} '
                                            .format(alt, mach,
                                                    round(sp_damp, 4),
                                                    round(sp_cap, 4)))
                                    if ph_rate == None:
                                        log.warning(
                                            'Phugoid UNstable at Alt = {}, Mach = {} , DampRatio = {} , UnDampedFreq = {} rad/s'
                                            .format(alt, mach,
                                                    round(ph_damp, 4),
                                                    round(ph_freq, 4)))

                                    # TODO
                                    # Compute numerator TF for (Alt, mach, flight_path_angle, aoa_trim, aos=0

                            if lateral_directional_analysis:
                                (A_direc, B_direc,y_v,l_v,n_v,y_p,y_phi,y_psi,l_p,l_phi,l_psi,n_p,y_r,l_r,n_r,n_phi,n_psi, y_xi,l_xi,n_xi, y_zeta,l_zeta,n_zeta)\
                                    = concise_derivative_lat(Y_v,L_v,N_v,Y_p,L_p,N_p,Y_r,L_r,N_r,\
                                                                            Y_xi,L_xi,N_xi, Y_zeta,L_zeta,N_zeta,\
                                                                            g, b, theta_e, u0,We,Ue,m_adim,i_xx,i_zz,i_xz )

                                C_direc = np.identity(5)
                                D_direc = np.zeros((5, 2))

                                if direc_root_identification(
                                        A_direc
                                )[0] == None:  # Lateral-directional roots are correctly identified
                                    eg_value_direc = direc_root_identification(
                                        A_direc)[1]
                                    print(
                                        'Lat-Dir : charcateristic equation  roots are not complex conjugate : {}'
                                        .format(eg_value_direc))
                                    legend = [
                                        'Root1', 'Root2', 'Root3', 'Root4'
                                    ]
                                    plot_title = 'S-plane lateral characteristic equation roots at (Alt = {}, Mach= {}, trimed at aoa = {}°)'.format(
                                        alt, mach, trim_aoa)
                                    plot_splane(eg_value_direc, plot_title,
                                                legend, show_plots, save_plots)
                                else:  # Lateral-directional roots are correctly identified
                                    (roll, spiral, dr1, dr2, eg_value_direc, eg_vector_direc, eg_vector_direc_magnitude)\
                                        = direc_root_identification(A_direc)
                                    legend = ['roll', 'spiral', 'dr1', 'dr2']
                                    plot_title = 'S-plane lateralcharacteristic equation roots at (Alt = {}, Mach= {}, trimed at aoa = {}°)'.format(
                                        alt, mach, trim_aoa)
                                    plot_splane(eg_value_direc, plot_title,
                                                legend, show_plots, save_plots)
                                    (roll_timecst, spiral_timecst, spiral_t2,
                                     dr_freq, dr_damp,
                                     dr_damp_freq) = direc_mode_characteristic(
                                         roll, spiral, dr1, dr2)

                                    # Rating
                                    roll_rate = roll_rating(
                                        flight_phase, aircraft_class,
                                        roll_timecst)
                                    spiral_rate = spiral_rating(
                                        flight_phase, spiral_timecst,
                                        spiral_t2)
                                    dr_rate = dutch_roll_rating(
                                        flight_phase, aircraft_class, dr_damp,
                                        dr_freq, dr_damp_freq)

                                    # Raise warning in the log file if unstable mode
                                    if roll_rate == None:
                                        log.warning(
                                            'Roll mode UNstable at Alt = {}, Mach = {} , due to roll root = {}, roll time contatant = {} s'
                                            .format(alt, mach,
                                                    round(roll_root, 4),
                                                    round(roll_timecst, 4)))
                                    if spiral_rate == None:
                                        log.warning(
                                            'Spiral mode UNstable at Alt = {}, Mach = {} , spiral root = {}, time_double_ampl = {}'
                                            .format(alt, mach,
                                                    round(spiral_root, 4),
                                                    round(spiral_t2, 4)))
                                    if dr_rate == None:
                                        log.warning(
                                            'Dutch Roll UNstable at Alt = {}, Mach = {} , Damping Ratio = {} , frequency = {} rad/s '
                                            .format(alt, mach,
                                                    round(dr_damp, 4),
                                                    round(dr_freq, 4)))