Esempio n. 1
0
def run_mesh_deformation(tixi, wkdir):
    """Function to run all the configuration files with SU2_DEF.

    Function 'run_mesh_deformation' will check in all config file directory and run
    SU2_DEF for each config file in order.

    Args:
        tixi (handles): TIXI Handle
        wkdir (str): Path to the working directory

    """

    log.info('All mesh deromation will be preformed.')

    mesh_dir = os.path.join(wkdir, 'MESH')
    if not os.path.exists(mesh_dir):
        raise OSError('The MESH directory : ' + mesh_dir + 'does not exit!')
    os.chdir(mesh_dir)

    su2_def_mesh_list = []

    ted_dir_list = [dir for dir in os.listdir(mesh_dir) if '_TED_' in dir]

    # Iterate in all TED directory
    for dir in sorted(ted_dir_list):
        ted_dir = os.path.join(mesh_dir, dir)
        os.chdir(ted_dir)

        cfg_file_list = [
            file for file in os.listdir(ted_dir) if 'Config' in file
        ]

        # Run all the config file in the directory with SU2_DEF, in alphabetical
        # order to respect the order of execution (DEF,ROT_,ROT_sym)
        for cfg_file in sorted(cfg_file_list):

            if os.path.isfile(cfg_file):
                su2f.run_soft('SU2_DEF', cfg_file, ted_dir)
            else:
                raise ValueError("Not correct configuration file to run!")

        tmp_su2_mesh_list = [
            file for file in os.listdir(ted_dir) if '.su2' in file
        ]

        # Copy in the completly deform mesh in the MESH directory
        for su2_mesh in tmp_su2_mesh_list:
            if not su2_mesh.startswith('_'):
                shutil.copyfile(su2_mesh, os.path.join('..', su2_mesh))
                log.info(su2_mesh + ' mesh has been copied in the MESH dir.')
                su2_def_mesh_list.append(su2_mesh)

            # Remove all SU2 mesh from the config folder (to save space)
            os.remove(su2_mesh)
            log.info(su2_mesh + ' mesh has been deleted from the temp mesh.')

    # Add the list of available SU2 deformed mesh in the CPACS file
    su2_def_mesh_xpath = SU2_XPATH + '/availableDeformedMesh'
    cpsf.add_string_vector(tixi, su2_def_mesh_xpath, su2_def_mesh_list)
Esempio n. 2
0
def test_add_sting_vector():
    """ Test the function 'add_sting_vector'"""

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

    # Add a new vector
    string_vector = ['aaa', 'bbb', 'ccc']
    cpsf.add_string_vector(tixi, xpath, string_vector)
    added_sting_vector_str = tixi.getTextElement(xpath)
    added_sting_vector = added_sting_vector_str.split(';')
    added_sting_vector = [str(elem) for elem in added_sting_vector]

    assert added_sting_vector == string_vector

    # Update a vector
    string_vector = ['abc', '123', 'test-01']
    cpsf.add_string_vector(tixi, xpath, string_vector)
    added_sting_vector_str = tixi.getTextElement(xpath)
    added_sting_vector = added_sting_vector_str.split(';')
    added_sting_vector = [str(elem) for elem in added_sting_vector]

    assert added_sting_vector == string_vector
Esempio n. 3
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)
Esempio n. 4
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)
Esempio n. 5
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()
Esempio n. 6
0
def aeromap_case_gen(modules):
    """
    Generate a CSV file containing a dataset generated with aeromap parameters
    only.

    Args:
        modules (lst) : list of modules to execute.

    Returns:
        file (str) : Path to CSV file.

    """
    file = MODULE_DIR + '/Aeromap_generated.csv'
    infile = mi.get_toolinput_file_path('PredictiveTool')
    outfile = mi.get_tooloutput_file_path('PredictiveTool')

    tixi = cpsf.open_tixi(infile)

    # Inputs
    alt = [0, 0]
    mach = [0.5, 0.5]
    aoa = [-10, 10]
    aos = [0, 0]
    nt = 100
    bounds = np.array([alt, mach, aoa, aos])
    # Sort criterion : ‘center’, ‘maximin’, ‘centermaximin’, ‘correlation’
    crit = 'corr'

    # Generate sample points, LHS or FullFactorial
    sampling = smp.LHS(xlimits=bounds, criterion=crit)
    xd = sampling(nt)
    xd = xd.transpose()
    # Delete the other aeromaps... maybe conserve them ?
    for uid in apmf.get_aeromap_uid_list(tixi):
        apmf.delete_aeromap(tixi, uid)

    # Create new aeromap
    aeromap_uid = 'DoE_Aeromap'
    am_xpath = tls.get_aeromap_path(modules)
    apmf.create_empty_aeromap(tixi, aeromap_uid)
    cpsf.add_string_vector(tixi, am_xpath + '/aeroMapUID', [aeromap_uid])

    # Add parameters to aeromap
    Param = apmf.AeroCoefficient()
    for i in range(0, xd.shape[1]):
        Param.add_param_point(xd[0][i], xd[1][i], xd[2][i], xd[3][i])
    apmf.save_parameters(tixi, aeromap_uid, Param)
    cpsf.close_tixi(tixi, infile)

    wkf.run_subworkflow(modules, cpacs_path_in=infile, cpacs_path_out=outfile)

    # Get Aerocoefficient
    tixi = cpsf.open_tixi(outfile)
    am_xpath = tls.get_aeromap_path(modules)
    aeromap_uid = cpsf.get_value(tixi, am_xpath + '/aeroMapUID')
    AeroCoefficient = apmf.get_aeromap(tixi, aeromap_uid)
    cpsf.close_tixi(tixi, outfile)

    dct = AeroCoefficient.to_dict()

    # Write to CSV
    df = pd.DataFrame(dct)
    df = df.transpose()
    var_type = [
        'obj' if i in objectives else
        'des' if i in ['alt', 'mach', 'aoa', 'aos'] else 'const'
        for i in df.index
    ]
    df.insert(0, 'type', var_type)
    df.to_csv(file, index=True)
    return file
Esempio n. 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()