Ejemplo n.º 1
0
    def random_var(self, is_random, *args):
        """Generate a list of objects as random attributes.

        This function creates a list of objects with random values for selected
        attributes from ross.Material.

        Parameters
        ----------
        is_random : list
            List of the object attributes to become stochastic.
        *args : dict
            Dictionary instanciating the ross.Material class.
            The attributes that are supposed to be stochastic should be
            set as lists of random variables.

        Returns
        -------
        f_list : generator
            Generator of random objects.
        """
        args_dict = args[0]
        new_args = []
        for i in range(len(args_dict[is_random[0]])):
            arg = []
            for key, value in args_dict.items():
                if key in is_random:
                    arg.append(value[i])
                else:
                    arg.append(value)
            new_args.append(arg)
        f_list = (Material(*arg) for arg in new_args)

        return f_list
Ejemplo n.º 2
0
def load_shaft_from_xltrc(file, sheet_name='Model'):
    """Load shaft from xltrc.

    This method will construct a shaft loading the geometry
    and materials from a xltrc file.

    Parameters
    ----------
    file : str
        File path name.
    sheet_name : str
        Shaft sheet name. Default is 'Model'.

    Returns
    -------
    shaft : list
        List with the shaft elements.

    Examples
    --------
    """
    df = pd.read_excel(file, sheet_name=sheet_name)

    geometry = pd.DataFrame(df.iloc[19:])
    geometry = geometry.rename(columns=df.loc[18])
    geometry = geometry.dropna(thresh=3)

    material = df.iloc[3:13, 9:15]
    material = material.rename(columns=df.iloc[0])
    material = material.dropna(axis=0, how='all')

    # change to SI units
    if df.iloc[1, 1] == 'inches':
        for dim in ['length', 'od_Left', 'id_Left', 'od_Right', 'id_Right']:
            geometry[dim] = geometry[dim] * 0.0254

        geometry['axial'] = geometry['axial'] * 4.44822161

        for prop in ['Elastic Modulus E', 'Shear Modulus G']:
            material[prop] = material[prop] * 6894.757

        material['Density   r'] = material['Density   r'] * 27679.904

    colors = [
        '#636363', '#969696', '#bdbdbd', '#d9d9d9', '#636363', '#969696',
        '#bdbdbd', '#d9d9d9'
    ]
    materials = {}
    for i, mat in material.iterrows():
        materials[mat.Material] = Material(name=f'Material{mat["Material"]}',
                                           rho=mat['Density   r'],
                                           E=mat['Elastic Modulus E'],
                                           G_s=mat['Shear Modulus G'],
                                           color=colors[mat['Material']])

    return (geometry, materials)
    shaft = [
        ShaftElement(el.length,
                     el.id_Left,
                     el.od_Left,
                     materials[el.matnum],
                     n=el.elemnum - 1) for i, el in geometry.iterrows()
    ]

    return shaft
Ejemplo n.º 3
0
def read_table_file(file, element, sheet_name=0, n=0, sheet_type="Model"):
    """Instantiate one or more element objects using inputs from an Excel table.
    Parameters
    ----------
    file: str
        Path to the file containing the shaft parameters.
    element: str
        Specify the type of element to be instantiated: bearing, shaft or disk.
    sheet_name: int or str, optional
        Position of the sheet in the file (starting from 0) or its name. If none is passed, it is
        assumed to be the first sheet in the file.
    n: int
        Exclusive for bearing elements, since this parameter is given outside the table file.
    sheet_type: str
        Exclusive for shaft elements, as they have a Model table in which more information can be passed,
        such as the material parameters.
    Returns
    -------
    A dictionary of parameters.
    Examples
    --------
    >>> import os
    >>> file_path = os.path.dirname(os.path.realpath(__file__)) + '/tests/data/shaft_si.xls'
    >>> read_table_file(file_path, "shaft", sheet_type="Model", sheet_name="Model") # doctest: +ELLIPSIS
    {'L': [0.03...
    """
    df = pd.read_excel(file, header=None, sheet_name=sheet_name)

    # Assign specific values to variables
    parameter_columns = {}
    optional_parameter_columns = {}
    header_key_word = ""
    default_dictionary = {}
    parameters = {}
    if element == "bearing":
        header_key_word = "kxx"
        parameter_columns["kxx"] = ["kxx"]
        parameter_columns["cxx"] = ["cxx"]
        optional_parameter_columns["kyy"] = ["kyy"]
        optional_parameter_columns["kxy"] = ["kxy"]
        optional_parameter_columns["kyx"] = ["kyx"]
        optional_parameter_columns["cyy"] = ["cyy"]
        optional_parameter_columns["cxy"] = ["cxy"]
        optional_parameter_columns["cyx"] = ["cyx"]
        optional_parameter_columns["w"] = ["w", "speed"]
        default_dictionary["kyy"] = None
        default_dictionary["kxy"] = 0
        default_dictionary["kyx"] = 0
        default_dictionary["cyy"] = None
        default_dictionary["cxy"] = 0
        default_dictionary["cyx"] = 0
        default_dictionary["w"] = None
    elif element == "shaft":
        if sheet_type == "Model":
            header_key_word = "od_left"
        else:
            header_key_word = "material"
        parameter_columns["L"] = ["length"]
        parameter_columns["i_d"] = ["i_d", "id", "id_left"]
        parameter_columns["o_d"] = ["o_d", "od", "od_left"]
        parameter_columns["material"] = ["material", "matnum"]
        optional_parameter_columns["n"] = ["n", "elemnum"]
        optional_parameter_columns["axial_force"] = [
            "axial_force",
            "axial force",
            "axial",
        ]
        optional_parameter_columns["torque"] = ["torque"]
        optional_parameter_columns["shear_effects"] = [
            "shear_effects", "shear effects"
        ]
        optional_parameter_columns["rotary_inertia"] = [
            "rotary_inertia",
            "rotary inertia",
        ]
        optional_parameter_columns["gyroscopic"] = ["gyroscopic"]
        optional_parameter_columns["shear_method_calc"] = [
            "shear_method_calc",
            "shear method calc",
        ]
        default_dictionary["n"] = None
        default_dictionary["axial_force"] = 0
        default_dictionary["torque"] = 0
        default_dictionary["shear_effects"] = True
        default_dictionary["rotary_inertia"] = True
        default_dictionary["gyroscopic"] = True
        default_dictionary["shear_method_calc"] = "cowper"
    elif element == "disk":
        header_key_word = "ip"
        parameter_columns["n"] = ["unnamed: 0", "n"]
        parameter_columns["m"] = ["m", "mass"]
        parameter_columns["Id"] = ["it", "id"]
        parameter_columns["Ip"] = ["ip"]

    # Find table header and define if conversion is needed
    header_index = -1
    header_found = False
    convert_to_metric = False
    convert_to_rad_per_sec = False
    for index, row in df.iterrows():
        for i in range(0, row.size):
            if isinstance(row[i], str):
                if not header_found:
                    if row[i].lower() == header_key_word:
                        header_index = index
                        header_found = True
                if "inches" in row[i].lower() or "lbm" in row[i].lower():
                    convert_to_metric = True
                if "rpm" in row[i].lower():
                    convert_to_rad_per_sec = True
                if header_found and convert_to_metric and convert_to_rad_per_sec:
                    break
        if header_found and convert_to_metric:
            break
    if not header_found:
        raise ValueError(
            "Could not find the header. Make sure the table has a header "
            "containing the names of the columns. In the case of a " +
            element + ", "
            "there should be a column named " + header_key_word + ".")

    # Get specific data from the file
    new_materials = {}
    if element == "shaft" and sheet_type == "Model":
        material_header_index = -1
        material_header_found = False
        material_header_key_word = "matno"
        for index, row in df.iterrows():
            for i in range(0, row.size):
                if isinstance(row[i], str):
                    if row[i].lower() == material_header_key_word:
                        material_header_index = index
                        material_header_found = True
                        break
            if material_header_found:
                break
        if not material_header_found:
            raise ValueError(
                "Could not find the header for the materials. Make sure the table has a header "
                "with the parameters for the materials that will be used. There should be a column "
                "named " + material_header_key_word + ".")
        df_material = pd.read_excel(file,
                                    header=material_header_index,
                                    sheet_name=sheet_name)
        material_name = []
        material_rho = []
        material_e = []
        material_g_s = []
        for index, row in df_material.iterrows():
            if not pd.isna(row["matno"]):
                material_name.append(int(row["matno"]))
                material_rho.append(row["rhoa"])
                material_e.append(row["ea"])
                material_g_s.append(row["ga"])
            else:
                break
        if convert_to_metric:
            for i in range(0, len(material_name)):
                material_rho[i] = material_rho[i] * 27679.904
                material_e[i] = material_e[i] * 6894.757
                material_g_s[i] = material_g_s[i] * 6894.757
        for i in range(0, len(material_name)):
            new_material = Material(
                name="shaft_mat_" + str(material_name[i]),
                rho=material_rho[i],
                E=material_e[i],
                G_s=material_g_s[i],
            )
            new_materials["shaft_mat_" + str(material_name[i])] = new_material

    df = pd.read_excel(file, header=header_index, sheet_name=sheet_name)
    df.columns = df.columns.str.lower()

    # Find and isolate data rows
    first_data_row_found = False
    last_data_row_found = False
    indexes_to_drop = []
    for index, row in df.iterrows():
        if (not first_data_row_found
                and (isinstance(row[header_key_word], int)
                     or isinstance(row[header_key_word], float))
                and not pd.isna(row[header_key_word])):
            first_data_row_found = True
        elif not first_data_row_found:
            indexes_to_drop.append(index)
        elif first_data_row_found and not last_data_row_found:
            if (isinstance(row[header_key_word], int) or isinstance(
                    row[header_key_word],
                    float)) and not pd.isna(row[header_key_word]):
                continue
            else:
                last_data_row_found = True
                indexes_to_drop.append(index)
        elif last_data_row_found:
            indexes_to_drop.append(index)
    if not first_data_row_found:
        raise DataNotFoundError(
            "Could not find the data. Make sure you have at least one row containing "
            "data below the header.")
    if len(indexes_to_drop) > 0:
        df = df.drop(indexes_to_drop)

    # Build parameters list
    if element == "bearing":
        parameters["n"] = n
    for key, value in parameter_columns.items():
        for name in value:
            try:
                parameters[key] = df[name].tolist()
                break
            except KeyError:
                if name == value[-1]:
                    raise ValueError(
                        "Could not find a column with one of these names: " +
                        str(value))
                continue
    for key, value in optional_parameter_columns.items():
        for name in value:
            try:
                parameters[key] = df[name].tolist()
                break
            except KeyError:
                if name == value[-1]:
                    parameters[key] = [default_dictionary[key]] * df.shape[0]
                else:
                    continue
    if element == "shaft":
        new_n = parameters["n"]
        for i in range(0, df.shape[0]):
            new_n[i] -= 1
        parameters["n"] = new_n
        if sheet_type == "Model":
            new_material = parameters["material"]
            for i in range(0, df.shape[0]):
                new_material[i] = "shaft_mat_" + str(int(new_material[i]))
            parameters["material"] = new_material
    if convert_to_metric:
        for i in range(0, df.shape[0]):
            if element == "bearing":
                parameters["kxx"][i] = parameters["kxx"][i] * 175.126_836_986_4
                parameters["cxx"][i] = parameters["cxx"][i] * 175.126_836_986_4
                parameters["kyy"][i] = parameters["kyy"][i] * 175.126_836_986_4
                parameters["kxy"][i] = parameters["kxy"][i] * 175.126_836_986_4
                parameters["kyx"][i] = parameters["kyx"][i] * 175.126_836_986_4
                parameters["cyy"][i] = parameters["cyy"][i] * 175.126_836_986_4
                parameters["cxy"][i] = parameters["cxy"][i] * 175.126_836_986_4
                parameters["cyx"][i] = parameters["cyx"][i] * 175.126_836_986_4
            if element == "shaft":
                parameters["L"][i] = parameters["L"][i] * 0.0254
                parameters["i_d"][i] = parameters["i_d"][i] * 0.0254
                parameters["o_d"][i] = parameters["o_d"][i] * 0.0254
                parameters["axial_force"][i] = (parameters["axial_force"][i] *
                                                4.448_221_615_255)
            elif element == "disk":
                parameters["m"][i] = parameters["m"][i] * 0.453_592_37
                parameters["Id"][i] = parameters["Id"][i] * 0.000_292_639_7
                parameters["Ip"][i] = parameters["Ip"][i] * 0.000_292_639_7
    if convert_to_rad_per_sec:
        for i in range(0, df.shape[0]):
            if element == "bearing":
                parameters["w"][i] = parameters["w"][i] * 0.104_719_755_119_7
    parameters.update(new_materials)
    return parameters
Ejemplo n.º 4
0
    def __init__(
        self,
        L,
        i_d,
        o_d,
        material,
        n=None,
        axial_force=0,
        torque=0,
        shear_effects=True,
        rotary_inertia=True,
        gyroscopic=True,
        shear_method_calc="cowper",
    ):

        if type(material) is str:
            os.chdir(Path(os.path.dirname(ross.__file__)))
            self.material = Material.use_material(material)
        else:
            self.material = material

        self.shear_effects = shear_effects
        self.rotary_inertia = rotary_inertia
        self.gyroscopic = gyroscopic
        self.axial_force = axial_force
        self.torque = torque
        self._n = n
        self.n_l = n
        self.n_r = None
        if n is not None:
            self.n_r = n + 1

        self.shear_method_calc = shear_method_calc

        self.L = float(L)

        # diameters
        self.i_d = float(i_d)
        self.o_d = float(o_d)
        self.i_d_l = float(i_d)
        self.o_d_l = float(o_d)
        self.i_d_r = float(i_d)
        self.o_d_r = float(o_d)
        self.color = self.material.color

        self.A = np.pi * (o_d**2 - i_d**2) / 4
        self.volume = self.A * self.L
        self.m = self.material.rho * self.volume
        #  Ie is the second moment of area of the cross section about
        #  the neutral plane Ie = pi*r**2/4
        self.Ie = np.pi * (o_d**4 - i_d**4) / 64
        phi = 0

        # picking a method to calculate the shear coefficient
        # List of avaible methods:
        # hutchinson - kappa as per Hutchinson (2001)
        # cowper - kappa as per Cowper (1996)
        if shear_effects:
            r = i_d / o_d
            r2 = r * r
            r12 = (1 + r2)**2
            if shear_method_calc == "hutchinson":
                # Shear coefficient (phi)
                # kappa as per Hutchinson (2001)
                # fmt: off
                kappa = 6 * r12 * ((1 + self.material.Poisson) /
                                   ((r12 *
                                     (7 + 12 * self.material.Poisson +
                                      4 * self.material.Poisson**2) + 4 * r2 *
                                     (5 + 6 * self.material.Poisson +
                                      2 * self.material.Poisson**2))))
                # fmt: on
            elif shear_method_calc == "cowper":
                # kappa as per Cowper (1996)
                # fmt: off
                kappa = 6 * r12 * ((1 + self.material.Poisson) /
                                   (r12 *
                                    (7 + 6 * self.material.Poisson) + r2 *
                                    (20 + 12 * self.material.Poisson)))
                # fmt: on
            else:
                raise Warning(
                    "This method of calculating shear coefficients is not implemented. See guide for futher informations."
                )

            # fmt: off
            phi = 12 * self.material.E * self.Ie / (self.material.G_s * kappa *
                                                    self.A * L**2)
            # fmt: on

        self.phi = phi
Ejemplo n.º 5
0
def read_table_file(file, element, sheet_name=0, n=0, sheet_type="Model"):
    """Instantiate one or more element objects using inputs from an Excel table.
    Parameters
    ----------
    file: str
        Path to the file containing the shaft parameters.
    element: str
        Specify the type of element to be instantiated: bearing, shaft or disk.
    sheet_name: int or str, optional
        Position of the sheet in the file (starting from 0) or its name. If none is passed, it is
        assumed to be the first sheet in the file.
    n: int
        Exclusive for bearing elements, since this parameter is given outside the table file.
    sheet_type: str
        Exclusive for shaft elements, as they have a Model table in which more information can be passed,
        such as the material parameters.
    Returns
    -------
    A dictionary of parameters.
    Examples
    --------
    >>> import os
    >>> file_path = os.path.dirname(os.path.realpath(__file__)) + '/tests/data/shaft_si.xls'
    >>> read_table_file(file_path, "shaft", sheet_type="Model", sheet_name="Model") # doctest: +ELLIPSIS
    {'L': [0.03...
    """
    df = pd.read_excel(file, header=None, sheet_name=sheet_name)

    # Assign specific values to variables
    parameter_columns = {}
    optional_parameter_columns = {}
    header_key_word = ''
    default_dictionary = {}
    parameters = {}
    if element == 'bearing':
        header_key_word = 'kxx'
        parameter_columns['kxx'] = ['kxx']
        parameter_columns['cxx'] = ['cxx']
        optional_parameter_columns['kyy'] = ['kyy']
        optional_parameter_columns['kxy'] = ['kxy']
        optional_parameter_columns['kyx'] = ['kyx']
        optional_parameter_columns['cyy'] = ['cyy']
        optional_parameter_columns['cxy'] = ['cxy']
        optional_parameter_columns['cyx'] = ['cyx']
        optional_parameter_columns['w'] = ['w', 'speed']
        default_dictionary['kyy'] = None
        default_dictionary['kxy'] = 0
        default_dictionary['kyx'] = 0
        default_dictionary['cyy'] = None
        default_dictionary['cxy'] = 0
        default_dictionary['cyx'] = 0
        default_dictionary['w'] = None
    elif element == 'shaft':
        if sheet_type == 'Model':
            header_key_word = 'od_left'
        else:
            header_key_word = 'material'
        parameter_columns['L'] = ['length']
        parameter_columns['i_d'] = ['i_d', 'id', 'id_left']
        parameter_columns['o_d'] = ['o_d', 'od', 'od_left']
        parameter_columns['material'] = ['material', 'matnum']
        optional_parameter_columns['n'] = ['n', 'elemnum']
        optional_parameter_columns['axial_force'] = [
            'axial_force', 'axial force', 'axial'
        ]
        optional_parameter_columns['torque'] = ['torque']
        optional_parameter_columns['shear_effects'] = [
            'shear_effects', 'shear effects'
        ]
        optional_parameter_columns['rotary_inertia'] = [
            'rotary_inertia', 'rotary inertia'
        ]
        optional_parameter_columns['gyroscopic'] = ['gyroscopic']
        optional_parameter_columns['shear_method_calc'] = [
            'shear_method_calc', 'shear method calc'
        ]
        default_dictionary['n'] = None
        default_dictionary['axial_force'] = 0
        default_dictionary['torque'] = 0
        default_dictionary['shear_effects'] = True
        default_dictionary['rotary_inertia'] = True
        default_dictionary['gyroscopic'] = True
        default_dictionary['shear_method_calc'] = 'cowper'
    elif element == 'disk':
        header_key_word = 'ip'
        parameter_columns['n'] = ['unnamed: 0', 'n']
        parameter_columns['m'] = ['m', 'mass']
        parameter_columns['Id'] = ['it', 'id']
        parameter_columns['Ip'] = ['ip']

    # Find table header and define if conversion is needed
    header_index = -1
    header_found = False
    convert_to_metric = False
    convert_to_rad_per_sec = False
    for index, row in df.iterrows():
        for i in range(0, row.size):
            if isinstance(row[i], str):
                if not header_found:
                    if row[i].lower() == header_key_word:
                        header_index = index
                        header_found = True
                if 'inches' in row[i].lower() or 'lbm' in row[i].lower():
                    convert_to_metric = True
                if 'rpm' in row[i].lower():
                    convert_to_rad_per_sec = True
                if header_found and convert_to_metric and convert_to_rad_per_sec:
                    break
        if header_found and convert_to_metric:
            break
    if not header_found:
        raise ValueError(
            "Could not find the header. Make sure the table has a header "
            "containing the names of the columns. In the case of a " +
            element + ", "
            "there should be a column named " + header_key_word + ".")

    # Get specific data from the file
    new_materials = {}
    if element == 'shaft' and sheet_type == 'Model':
        material_header_index = -1
        material_header_found = False
        material_header_key_word = 'matno'
        for index, row in df.iterrows():
            for i in range(0, row.size):
                if isinstance(row[i], str):
                    if row[i].lower() == material_header_key_word:
                        material_header_index = index
                        material_header_found = True
                        break
            if material_header_found:
                break
        if not material_header_found:
            raise ValueError(
                "Could not find the header for the materials. Make sure the table has a header "
                "with the parameters for the materials that will be used. There should be a column "
                "named " + material_header_key_word + ".")
        df_material = pd.read_excel(file,
                                    header=material_header_index,
                                    sheet_name=sheet_name)
        material_name = []
        material_rho = []
        material_e = []
        material_g_s = []
        for index, row in df_material.iterrows():
            if not pd.isna(row['matno']):
                material_name.append(int(row['matno']))
                material_rho.append(row['rhoa'])
                material_e.append(row['ea'])
                material_g_s.append(row['ga'])
            else:
                break
        if convert_to_metric:
            for i in range(0, len(material_name)):
                material_rho[i] = material_rho[i] * 27679.904
                material_e[i] = material_e[i] * 6894.757
                material_g_s[i] = material_g_s[i] * 6894.757
        for i in range(0, len(material_name)):
            new_material = Material(
                name='shaft_mat_' + str(material_name[i]),
                rho=material_rho[i],
                E=material_e[i],
                G_s=material_g_s[i],
            )
            new_materials['shaft_mat_' + str(material_name[i])] = new_material

    df = pd.read_excel(file, header=header_index, sheet_name=sheet_name)
    df.columns = df.columns.str.lower()

    # Find and isolate data rows
    first_data_row_found = False
    last_data_row_found = False
    indexes_to_drop = []
    for index, row in df.iterrows():
        if not first_data_row_found \
                and (isinstance(row[header_key_word], int) or isinstance(row[header_key_word], float)) \
                and not pd.isna(row[header_key_word]):
            first_data_row_found = True
        elif not first_data_row_found:
            indexes_to_drop.append(index)
        elif first_data_row_found and not last_data_row_found:
            if (isinstance(row[header_key_word], int) or isinstance(row[header_key_word], float))\
                    and not pd.isna(row[header_key_word]):
                continue
            else:
                last_data_row_found = True
                indexes_to_drop.append(index)
        elif last_data_row_found:
            indexes_to_drop.append(index)
    if not first_data_row_found:
        raise DataNotFoundError(
            "Could not find the data. Make sure you have at least one row containing "
            "data below the header.")
    if len(indexes_to_drop) > 0:
        df = df.drop(indexes_to_drop)

    # Build parameters list
    if element == 'bearing':
        parameters['n'] = n
    for key, value in parameter_columns.items():
        for name in value:
            try:
                parameters[key] = df[name].tolist()
                break
            except KeyError:
                if name == value[-1]:
                    raise ValueError(
                        "Could not find a column with one of these names: " +
                        str(value))
                continue
    for key, value in optional_parameter_columns.items():
        for name in value:
            try:
                parameters[key] = df[name].tolist()
                break
            except KeyError:
                if name == value[-1]:
                    parameters[key] = [default_dictionary[key]] * df.shape[0]
                else:
                    continue
    if element == 'shaft':
        new_n = parameters['n']
        for i in range(0, df.shape[0]):
            new_n[i] -= 1
        parameters['n'] = new_n
        if sheet_type == 'Model':
            new_material = parameters['material']
            for i in range(0, df.shape[0]):
                new_material[i] = 'shaft_mat_' + str(int(new_material[i]))
            parameters['material'] = new_material
    if convert_to_metric:
        for i in range(0, df.shape[0]):
            if element == 'bearing':
                parameters['kxx'][i] = parameters['kxx'][i] * 175.1268369864
                parameters['cxx'][i] = parameters['cxx'][i] * 175.1268369864
                parameters['kyy'][i] = parameters['kyy'][i] * 175.1268369864
                parameters['kxy'][i] = parameters['kxy'][i] * 175.1268369864
                parameters['kyx'][i] = parameters['kyx'][i] * 175.1268369864
                parameters['cyy'][i] = parameters['cyy'][i] * 175.1268369864
                parameters['cxy'][i] = parameters['cxy'][i] * 175.1268369864
                parameters['cyx'][i] = parameters['cyx'][i] * 175.1268369864
            if element == 'shaft':
                parameters['L'][i] = parameters['L'][i] * 0.0254
                parameters['i_d'][i] = parameters['i_d'][i] * 0.0254
                parameters['o_d'][i] = parameters['o_d'][i] * 0.0254
                parameters['axial_force'][
                    i] = parameters['axial_force'][i] * 4.448221615255
            elif element == 'disk':
                parameters['m'][i] = parameters['m'][i] * 0.45359237
                parameters['Id'][i] = parameters['Id'][i] * 0.0002926397
                parameters['Ip'][i] = parameters['Ip'][i] * 0.0002926397
    if convert_to_rad_per_sec:
        for i in range(0, df.shape[0]):
            if element == 'bearing':
                parameters['w'][i] = parameters['w'][i] * 0.1047197551197
    parameters.update(new_materials)
    return parameters
Ejemplo n.º 6
0
    def from_table(cls, file, sheet_type="Simple", sheet_name=0):
        """Instantiate one or more shafts using inputs from an Excel table.

        A header with the names of the columns is required. These names should
        match the names expected by the routine (usually the names of the
        parameters, but also similar ones). The program will read every row
        bellow the header until they end or it reaches a NaN.

        Parameters
        ----------
        file: str
            Path to the file containing the shaft parameters.
        sheet_type: str, optional
            Describes the kind of sheet the function should expect:
                Simple: The input table should specify only the number of the materials to be used.
                They must be saved prior to calling the method.
                Model: The materials parameters must be passed along with the shaft parameters. Each
                material must have an id number and each shaft must reference one of the materials ids.
        sheet_name: int or str, optional
            Position of the sheet in the file (starting from 0) or its name. If none is passed, it is
            assumed to be the first sheet in the file.

        Returns
        -------
        shaft: list
            A list of shaft objects.
        """
        parameters = read_table_file(
            file, "shaft", sheet_name=sheet_name, sheet_type=sheet_type
        )
        list_of_shafts = []
        if sheet_type == "Model":
            new_materials = {}
            for i in range(0, len(parameters["matno"])):
                new_material = Material(
                    name="shaft_mat_" + str(parameters["matno"][i]),
                    rho=parameters["rhoa"][i],
                    E=parameters["ea"][i],
                    G_s=parameters["ga"][i],
                )
                new_materials["shaft_mat_" + str(parameters["matno"][i])] = new_material
            for i in range(0, len(parameters["L"])):
                list_of_shafts.append(
                    cls(
                        L=parameters["L"][i],
                        idl=parameters["idl"][i],
                        odl=parameters["odl"][i],
                        idr=parameters["idr"][i],
                        odr=parameters["odr"][i],
                        material=new_materials[parameters["material"][i]],
                        n=parameters["n"][i],
                        axial_force=parameters["axial_force"][i],
                        torque=parameters["torque"][i],
                        shear_effects=parameters["shear_effects"][i],
                        rotary_inertia=parameters["rotary_inertia"][i],
                        gyroscopic=parameters["gyroscopic"][i],
                        shear_method_calc=parameters["shear_method_calc"][i],
                    )
                )
        elif sheet_type == "Simple":
            for i in range(0, len(parameters["L"])):
                list_of_shafts.append(
                    cls(
                        L=parameters["L"][i],
                        idl=parameters["idl"][i],
                        odl=parameters["odl"][i],
                        idr=parameters["idr"][i],
                        odr=parameters["odr"][i],
                        material=parameters["material"][i],
                        n=parameters["n"][i],
                        axial_force=parameters["axial_force"][i],
                        torque=parameters["torque"][i],
                        shear_effects=parameters["shear_effects"][i],
                        rotary_inertia=parameters["rotary_inertia"][i],
                        gyroscopic=parameters["gyroscopic"][i],
                        shear_method_calc=parameters["shear_method_calc"][i],
                    )
                )
        return list_of_shafts
Ejemplo n.º 7
0
    def __init__(
        self,
        L,
        idl,
        odl,
        idr=None,
        odr=None,
        material=None,
        n=None,
        axial_force=0,
        torque=0,
        shear_effects=True,
        rotary_inertia=True,
        gyroscopic=True,
        shear_method_calc="cowper",
        tag=None,
    ):

        if idr is None:
            idr = idl
        if odr is None:
            odr = odl

        # After changing units to defined unit (see units.py), we go back to using only the magnitude
        # This could be modified later if we apply pint to all arguments and have consistency throughout the package
        L = L.m
        idl = idl.m
        odl = odl.m
        idr = idr.m
        odr = odr.m

        if material is None:
            raise AttributeError("Material is not defined.")

        if type(material) is str:
            os.chdir(Path(os.path.dirname(ross.__file__)))
            self.material = Material.use_material(material)
        else:
            self.material = material

        self.shear_effects = shear_effects
        self.rotary_inertia = rotary_inertia
        self.gyroscopic = gyroscopic
        self.axial_force = axial_force
        self.torque = torque
        self._n = n
        self.n_l = n
        self.n_r = None
        if n is not None:
            self.n_r = n + 1

        self.tag = tag
        self.shear_method_calc = shear_method_calc

        self.L = float(L)
        self.o_d = (float(odl) + float(odr)) / 2
        self.i_d = (float(idl) + float(idr)) / 2
        self.idl = float(idl)
        self.odl = float(odl)
        self.idr = float(idr)
        self.odr = float(odr)
        self.color = self.material.color

        # A_l = cross section area from the left side of the element
        # A_r = cross section area from the right side of the element
        A_l = np.pi * (odl ** 2 - idl ** 2) / 4
        A_r = np.pi * (odr ** 2 - idr ** 2) / 4
        self.A_l = A_l
        self.A_r = A_r

        # Second moment of area of the cross section from the left side
        # of the element
        Ie_l = np.pi * (odl ** 4 - idl ** 4) / 64

        outer = self.odl ** 2 + self.odl * self.odr + self.odr ** 2
        inner = self.idl ** 2 + self.idl * self.idr + self.idr ** 2
        self.volume = np.pi * (self.L / 12) * (outer - inner)
        self.m = self.material.rho * self.volume

        roj = odl / 2
        rij = idl / 2
        rok = odr / 2
        rik = idr / 2

        # geometrical coefficients
        delta_ro = rok - roj
        delta_ri = rik - rij
        a1 = 2 * np.pi * (roj * delta_ro - rij * delta_ri) / A_l
        a2 = np.pi * (roj ** 3 * delta_ro - rij ** 3 * delta_ri) / Ie_l
        b1 = np.pi * (delta_ro ** 2 - delta_ri ** 2) / A_l
        b2 = (
            3
            * np.pi
            * (roj ** 2 * delta_ro ** 2 - rij ** 2 * delta_ri ** 2)
            / (2 * Ie_l)
        )
        gama = np.pi * (roj * delta_ro ** 3 - rij * delta_ri ** 3) / Ie_l
        delta = np.pi * (delta_ro ** 4 - delta_ri ** 4) / (4 * Ie_l)

        self.a1 = a1
        self.a2 = a2
        self.b1 = b1
        self.b2 = b2
        self.gama = gama
        self.delta = delta

        # the area is calculated from the cross section located in the middle
        # of the element
        self.A = A_l * (1 + a1 * 0.5 + b1 * 0.5 ** 2)

        # Ie is the second moment of area of the cross section - located in
        # the middle of the element - about the neutral plane
        Ie = Ie_l * (1 + a2 * 0.5 + b2 * 0.5 ** 2 + gama * 0.5 ** 3 + delta * 0.5 ** 4)
        self.Ie = Ie
        self.Ie_l = Ie_l

        phi = 0

        # geometric center
        c1 = (
            roj ** 2
            + 2 * roj * rok
            + 3 * rok ** 2
            - rij ** 2
            - 2 * rij * rik
            - 3 * rik ** 2
        )
        c2 = (roj ** 2 + roj * rok + rok ** 2) - (rij ** 2 + rij * rik + rik ** 2)
        self.beam_cg = L * c1 / (4 * c2)
        self.axial_cg_pos = None

        # Slenderness ratio of beam elements (G*A*L^2) / (E*I)
        sld = (self.material.G_s * self.A * self.L ** 2) / (self.material.E * Ie)
        self.slenderness_ratio = sld

        # Moment of inertia
        # fmt: off
        self.Im = (
            (np.pi * L * (self.m / self.volume) / 10) *
            ((roj ** 4 + roj ** 3 * rok + roj ** 2 * rok ** 2 + roj * rok ** 3 + rok ** 4) -
             (rij ** 4 + rij ** 3 * rik + rij ** 2 * rik ** 2 + rij * rik ** 3 + rik ** 4))
        )
        # fmt: on

        # picking a method to calculate the shear coefficient
        # List of avaible methods:
        # hutchinson - kappa as per Hutchinson (2001)
        # cowper - kappa as per Cowper (1996)
        if shear_effects:
            r = ((idl + idr) / 2) / ((odl + odr) / 2)
            r2 = r * r
            r12 = (1 + r2) ** 2
            if shear_method_calc == "hutchinson":
                # Shear coefficient (phi)
                # kappa as per Hutchinson (2001)
                # fmt: off
                kappa = 6 * r12 * ((1 + self.material.Poisson) /
                        ((r12 * (7 + 12 * self.material.Poisson + 4 * self.material.Poisson ** 2) +
                        4 * r2 * (5 + 6 * self.material.Poisson + 2 * self.material.Poisson ** 2))))
                # fmt: on
            elif shear_method_calc == "cowper":
                # kappa as per Cowper (1996)
                # fmt: off
                kappa = 6 * r12 * (
                    (1 + self.material.Poisson)
                    / (r12 * (7 + 6 * self.material.Poisson) + r2 * (20 + 12 * self.material.Poisson))
                )
                # fmt: on
            else:
                raise Warning(
                    "This method of calculating shear coefficients is not implemented. See guide for futher informations."
                )

            # fmt: off
            phi = 12 * self.material.E * self.Ie / (self.material.G_s * kappa * self.A * L ** 2)
            # fmt: on
            self.kappa = kappa

        self.phi = phi
        self.dof_global_index = None
Ejemplo n.º 8
0
 def from_table(cls, file, sheet="Simple"):
     """Instantiate one or more shafts using inputs from a table, either excel or csv.
     Parameters
     ----------
     file: str
         Path to the file containing the shaft parameters.
     sheet: str, optional
         Describes the kind of sheet the function should expect:
             Simple: The input table should contain a header with column names equal
             to parameter names in the ShaftElement class, except for
             shear_effects, rotary_inertia, gyroscopic, and shear_method_calc.
             Model: The sheet must follow the expected format. The function will look
             for the parameters according to this format, in the positions they are supposed
             to be found. Headers should be in rows 4 and 20, just before parameters.
     Returns
     -------
     shaft : list
         A list of shaft objects.
     """
     if sheet == "Simple":
         try:
             df = pd.read_excel(file)
         except FileNotFoundError:
             sys.exit(file + " not found.")
         except xlrd.biffh.XLRDError:
             df = pd.read_csv(file)
         try:
             for index, row in df.iterrows():
                 for i in range(0, row.size):
                     if pd.isna(row[i]):
                         warnings.warn("NaN found in row " + str(index) +
                                       " column " + str(i) + ".\n"
                                       "It will be replaced with zero.")
                         row[i] = 0
             list_of_shafts = []
             for i, row in df.iterrows():
                 shear_effects = True
                 rotary_inertia = True
                 gyroscopic = True
                 shear_method_calc = "cowper"
                 try:
                     shear_effects = bool(row["shear_effects"])
                 except KeyError:
                     pass
                 try:
                     rotary_inertia = bool(row["rotary_inertia"])
                 except KeyError:
                     pass
                 try:
                     gyroscopic = bool(row["gyroscopic"])
                 except KeyError:
                     pass
                 try:
                     shear_method_calc = row["shear_method_calc"]
                 except KeyError:
                     pass
                 list_of_shafts.append(
                     cls(
                         row.L,
                         row.i_d,
                         row.o_d,
                         Material.use_material(row.material),
                         n=row.n,
                         axial_force=row.axial_force,
                         torque=row.torque,
                         shear_effects=shear_effects,
                         rotary_inertia=rotary_inertia,
                         gyroscopic=gyroscopic,
                         shear_method_calc=shear_method_calc,
                     ))
             return list_of_shafts
         except KeyError:
             sys.exit(
                 "One or more column names did not match the expected. "
                 "Make sure the table header contains the parameters for the "
                 "ShaftElement class. Also, make sure you have a material "
                 "with the given name.")
     elif sheet == "Model":
         try:
             df1 = pd.read_excel(file, header=3, nrows=10)
             df2 = pd.read_excel(file, header=19)
             df_unit = pd.read_excel(file, header=16, nrows=2)
         except FileNotFoundError:
             sys.exit(file + " not found.")
         except xlrd.biffh.XLRDError:
             df1 = pd.read_csv(file, header=3, nrows=10)
             df2 = pd.read_csv(file, header=19)
             df_unit = pd.read_csv(file, header=16, nrows=2)
         convert_to_metric = False
         if df_unit["Length"][1] != "meters":
             convert_to_metric = True
         material_name = []
         material_rho = []
         material_e = []
         material_g_s = []
         new_materials = {}
         for index, row in df1.iterrows():
             if not pd.isna(row["matno"]):
                 material_name.append(int(row["matno"]))
                 material_rho.append(row["rhoa"])
                 material_e.append(row["ea"])
                 material_g_s.append(row["ga"])
         if convert_to_metric:
             for i in range(0, len(material_name)):
                 material_rho[i] = material_rho[i] * 27679.904
                 material_e[i] = material_e[i] * 6894.757
                 material_g_s[i] = material_g_s[i] * 6894.757
         for i in range(0, len(material_name)):
             new_material = Material(
                 name="shaft_mat_" + str(material_name[i]),
                 rho=material_rho[i],
                 E=material_e[i],
                 G_s=material_g_s[i],
             )
             new_materials["shaft_mat_" +
                           str(material_name[i])] = new_material
         shaft_l = []
         shaft_i_d = []
         shaft_o_d = []
         shaft_material = []
         shaft_n = []
         shaft_axial_force = []
         for index, row in df2.iterrows():
             shaft_l.append(row["length"])
             shaft_i_d.append(row["id_Left"])
             shaft_o_d.append(row["od_Left"])
             shaft_material.append(int(row["matnum"]))
             shaft_n.append(row["elemnum"] - 1)
             shaft_axial_force.append(row["axial"])
         if convert_to_metric:
             for i in range(0, len(shaft_n)):
                 shaft_l[i] = shaft_l[i] * 0.0254
                 shaft_i_d[i] = shaft_i_d[i] * 0.0254
                 shaft_o_d[i] = shaft_o_d[i] * 0.0254
                 shaft_axial_force[i] = shaft_axial_force[i] * 4.448_221_61
         list_of_shafts = []
         for i in range(0, len(shaft_n)):
             list_of_shafts.append(
                 cls(
                     shaft_l[i],
                     shaft_i_d[i],
                     shaft_o_d[i],
                     new_materials["shaft_mat_" + str(shaft_material[i])],
                     n=shaft_n[i],
                     axial_force=shaft_axial_force[i],
                 ))
         return list_of_shafts
     else:
         sys.exit(
             "A valid choice must be given for the parameter 'sheet'. Either 'Simple' or 'Model' "
             "were expected. It was given " + sheet + ".")