Ejemplo n.º 1
0
def test_apply_LaminateModels_frames_p1():
    """Check built DataFrames have correct p for each Lamina.
    
    Using two functions to build DataFrames: make_dfs() and replicate_values().  
    This only tests four columns  ['layer', 'matl', 'type', 't(um)'].
    Be sure to test single, odd and even p, i.e. p = [1, 3, 4].
        
        1. Access DataFrames from laminate using frames
        2. Build dicts and expected dataframes for a range of ps
        3. Equate the dataframes and assert the truth of elements.
    
    UPDATE: the following functions should not be used.  makes_dfs is recommended
    for future tests.  
    """

    def make_actual_dfs(geos, p=1):
        """Returns a list of DataFrames using the API """
        load_params["p"] = p
        # print(load_params)
        case = la.distributions.Case(load_params, mat_props)
        case.apply(geos)
        # print(case.frames)
        return case.frames

    def make_expected_dfs(starter_dicts, keys, p=1):
        """Return a list of custom DataFrames with p number rows."""
        dfs = []
        for points in range(1, p + 1):  # skips 0 (empty df)
            for dict_ in make_dfs(starter_dicts, dict_keys=keys, p=p):
                dfs.append(pd.DataFrame(dict_))
            return dfs

    # Starting inputs
    geos_custom = [g1, g2, g3, g4, g5, g8]
    dicts = [d1, d2, d3, d4, d5, d8]
    keys = ["layer", "matl", "type", "t(um)"]
    load_params = {
        "R": 12e-3,  # specimen radius
        "a": 7.5e-3,  # support ring radius
        "p": 4,  # points/layer
        "P_a": 1,  # applied load
        "r": 2e-4,  # radial distance from center loading
    }
    mat_props = {"HA": [5.2e10, 0.25], "PSu": [2.7e9, 0.33]}
    p_range = 5  # test 1 to this number rows

    for n in range(1, p_range):
        actual = make_actual_dfs(geos_custom, p=n)
        expected = make_expected_dfs(dicts, keys, p=n)
        # print(type(expected))

        # Test all values in DataFrames are True (for column in keys)
        for i, df in enumerate(expected):
            # print(bool_test)
            # assert bool_test == True, 'False elements detected'
            # bool_test = actual[i][keys].sort(axis=1).equals(expected[i].sort(axis=1))
            # nt.assert_equal(bool_test, True)
            # nt.assert_true(bool_test)
            ut.assertFrameEqual(actual[i][keys], expected[i])
Ejemplo n.º 2
0
def test_laminator_type3():
    '''Check defaults triggerd if nothing is passed in.'''
    case1 = ut.laminator()
    LM = case1[0]
    actual = LM.frames[0]
    case2 = la.distributions.Case(dft.load_params, dft.mat_props)
    case2.apply(['400-200-800'])
    expected = case2.frames[0]
    ut.assertFrameEqual(actual, expected)
Ejemplo n.º 3
0
def test_Laminate_attr_extrema():
    case1 = ut.laminator(dft.geos_full, ps=[5])
    case2 = ut.laminator(dft.geos_full, ps=[2])

    for case_full, case_trimmed in zip(case1.values(), case2.values()):
        for LM_full, LM_trimmed in zip(case_full.LMs, case_trimmed.LMs):
            actual = LM_full.extrema
            actual.reset_index(drop=True, inplace=True)
            expected = LM_trimmed.LMFrame
            #print(actual)
            #print(expected)
            ut.assertFrameEqual(actual, expected)    
Ejemplo n.º 4
0
def test_apply_LaminateModels_cols_dimensions1():
    '''Test actual against expected DataFrames in .cvs files found in
    tests/controls_LT; IDs and dimensional columns.

    '''
    # Prepare file path.
    # Depends which directory nosetests is rum
    #path = os.getcwd()                                     # use for the test in the correct path
    ##path = os.path.join(os.getcwd(), 'lamana', 'tests', 'controls_LT')   # for builds
    sourcepath = os.path.abspath(os.path.dirname(la.__file__))
    path = os.path.join(sourcepath, 'tests', 'controls_LT')
    #path = path + r'\lamana\tests\controls_LT'             # for Main Script. Comment out in tests
    #path = path + r'\tests\controls_LT'                    # for test
    #path = os.path.join(os.getcwd(), 'tests', 'controls_LT')          # for test
    #path = path + r'\controls_LT'                          # for test
    logging.debug('Default path: {}'.format(path))

    # Read all files in the path (REF 013)
    for file, filepath in ut.read_csv_dir(path):
        #df_expected = file
        df = file
        #print(df_expected)

        df_expected, geometry, nplies, p, t_total = extract_dataframe(df)

        # Build actual Case using distributions API
        dft.load_params['p'] = p
        case = la.distributions.Case(dft.load_params, dft.mat_props)
        case.apply([geometry])
        df = case.frames[0]

        # Compare the dimensional columns only
        '''Bypassing z(m), z(m)*, intf and k for now'''
        # UPDATE: `k` added back in 0.4.4b
        ###
        cols = ['layer', 'side', 'type', 'matl',
        #        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'k', 'Z(m)', 'z(m)']
        #        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'k', 'Z(m)', ]
        #        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'Z(m)', ]      # removed; k redefined in 0.4.3c4d
        #        'label', 't(um)', 'h(m)', 'd(m)', 'intf']
        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'k']
        print('A .csv file is being processed with the following dimensional properties:')
        print(' Number of plies: {} \n p: {} \n total \
               t (m): {} \n geometry: {} \n'.format(nplies, p, t_total, geometry))

        actual = df[cols]
        expected = df_expected[cols]
        #print ('expected (file) \n', expected)
        #print('actual (API) \n', actual)
        #print(expected.dtypes)
        #print(actual.dtypes)
        print('\n')
        ut.assertFrameEqual(actual, expected)
Ejemplo n.º 5
0
def test_set_columns_seq1():
    '''Check reorders columns to existing sequence.'''
    # Pandas orders DataFrame columns alphabetically
    data = {'apple': 4, 'orange': 3, 'banana': 2, 'blueberry': 3}
    df = pd.DataFrame(data, index=['amount'])
    # apple  banana  blueberry  orange

    # We can resequence the columns
    seq = ['apple', 'orange', 'banana', 'blueberry']
    actual = ut.set_column_sequence(df, seq)
    expected = pd.DataFrame(data, index=['amount'], columns=seq)
    ut.assertFrameEqual(actual, expected)
Ejemplo n.º 6
0
def test_set_columns_seq2():
    '''Check reorders columns and adds columns not in sequence to the end.'''
    data = {'apple': 4, 'strawberry': 3, 'orange': 3, 'banana': 2}
    df = pd.DataFrame(data, index=['amount'])

    # Excluded names are appended to the end of the DataFrame
    seq = ['apple', 'strawberry']
    # apple  strawberry banana  orange
    actual = ut.set_column_sequence(df, seq)
    expected = pd.DataFrame(data, index=['amount'],
                            columns=['apple', 'strawberry', 'banana', 'orange'])
    ut.assertFrameEqual(actual, expected)
Ejemplo n.º 7
0
def test_Laminate_sanity9():
    '''Check Monoliths, p=1 have positive values.
    Now using ut.get_frames() for specific case selections.
    '''
    cases_selected = ut.get_frames(cases, name='Monolith', ps=[1])
    for LMs in cases_selected:
        df_numeric = LMs.select_dtypes(include=[np.number])
        df = df_numeric
        #print(df_numeric)
        actual = df_numeric[(df_numeric<0)]                # catches negative numbers if any
        expected = pd.DataFrame(index=df.index, columns=df.columns).fillna(np.nan)
        print(actual)
        print(expected)
        ut.assertFrameEqual(actual, expected)
Ejemplo n.º 8
0
def test_laminator_consistency1():
    '''Check laminator yields same LMFrame as classic case building.'''
    case = ut.laminator(geos=dft.geos_all, ps=[5])
    for case_ in case.values():
        case1 = case_
    case2 = la.distributions.Case(load_params, mat_props)
    case2.apply(dft.geos_all)
    #print(case1)
    #print(case2)
    ##for actual, expected in zip(case1, case2.LMs):
    for actual, expected in zip(case1.LMs, case2.LMs):
        #print(actual)
        #print(expected)
        ut.assertFrameEqual(actual.LMFrame, expected.LMFrame)
Ejemplo n.º 9
0
def test_theories_Exception_default1():
    '''Check LMFrame is set by LFrame if exception raised.'''
    # Force an exception in Wilson_LT; r must be non-zero
    zero_r = {'R' : 12e-3,                                 # specimen radius
              'a' : 7.5e-3,                                # support ring radius
              'p' : 5,                                     # points/layer
              'P_a' : 1,                                   # applied load 
              'r' : 0,          #                          # radial distance from center loading
              }
    case = ut.laminator(geos=dft.geos_standard, load_params=zero_r) 
    for case_ in case.values():
        for LM in case_.LMs:
            actual = LM.LMFrame
            expected = LM.LFrame
            #print(actual)                                 # should get LFrame
            ut.assertFrameEqual(actual, expected) 
Ejemplo n.º 10
0
def test_Case_apply_Snapshots1():
    """Test the native DataFrame elements and dtypes. Resorts columns.  Uses pandas equals test."""
    case1.apply(geos_full)
    cols = ["layer", "matl", "type", "t(um)"]
    d = {
        "layer": [1, 2, 3, 4, 5, 6, 7],
        "matl": ["HA", "PSu", "HA", "PSu", "HA", "PSu", "HA"],
        "type": ["outer", "inner", "inner", "middle", "inner", "inner", "outer"],
        "t(um)": [400.0, 100.0, 100.0, 800.0, 100.0, 100.0, 400.0],
    }

    actual = case1.snapshots[8]
    expected = pd.DataFrame(d)
    #     bool_test = actual[cols].sort(axis=1).equals(expected.sort(axis=1))
    #     #nt.assert_equal(bool_test, True)
    #     nt.assert_true(bool_test)
    ut.assertFrameEqual(actual[cols], expected[cols])
Ejemplo n.º 11
0
def test_Laminate_sanity5():
    '''Check intf_, k_ equal Nan for Monoliths with p < 2.'''
    cols = ['intf', 'k']
    for case in cases.values():
        for LM in case.LMs:
#     for LMs in cases.values():
#         for LM in LMs:
            if (LM.name == 'Monolith') & (LM.p < 2):
                df = LM.LMFrame
                df_null = pd.DataFrame(index=df.index, columns=df.columns)
                expected = df_null.fillna(np.nan)
                actual = df
                #print(actual[cols])
                #print(expected[cols])
                print(LM.Geometry)
                #print(LM.name)
                print(LM.p)
                ut.assertFrameEqual(actual[cols], expected[cols])
Ejemplo n.º 12
0
def test_Laminate_sanity4():
    '''Check values are mirrored across the neutral axis for Z_, z_'''
    cols = ['Z(m)', 'z(m)', 'z(m)*']
    for case in cases.values():
        for LM in case.LMs:
#     for LMs in cases.values():
#         for LM in LMs:
            if LM.p > 1:
                df = LM.LMFrame
                #print(df)
                tensile = LM.tensile.reset_index(drop=True)
                compressive = LM.compressive[::-1].reset_index(drop=True)
                #print(tensile[cols])
                #print(-compressive[cols])
                print(LM.Geometry)
                #print(LM.name)
                print(LM.p)
                print(LM.LMFrame)
                #assert tensile[cols] == compressive[cols]
                ut.assertFrameEqual(tensile[cols], -compressive[cols])
Ejemplo n.º 13
0
def test_apply_LaminateModels_cols_dimensions1():
    """Test actual against expected DataFrames in .cvs files found in
    tests/controls_LT; IDs and dimensional columns.

    """
    # Prepare file path.
    # Depends which directory nosetests is rum
    # path = os.getcwd()                                     # use for the test in the correct path
    path = os.path.join(os.getcwd(), "lamana", "tests", "controls_LT")  # for builds
    # path = path + r'\lamana\tests\controls_LT'             # for Main Script. Comment out in tests
    # path = path + r'\tests\controls_LT'                    # for test
    # path = os.path.join(os.getcwd(), 'tests', 'controls_LT')          # for test
    # path = path + r'\controls_LT'                          # for test

    # Read all files in the path (REF 013)
    for file in ut.read_csv_dir(path):
        # df_expected = file
        df = file
        # print(df_expected)

        df_expected, geometry, nplies, p, t_total = extract_dataframe(df)

        # Build actual Case using distributions API
        dft.load_params["p"] = p
        case = la.distributions.Case(dft.load_params, dft.mat_props)
        case.apply([geometry])
        df = case.frames[0]

        # Compare the dimensional columns only
        """Bypassing z(m), z(m)*, intf and k for now"""
        """UPDATE: k add back in 0.4.4b"""
        ###
        cols = [
            "layer",
            "side",
            "type",
            "matl",
            #        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'k', 'Z(m)', 'z(m)']
            #        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'k', 'Z(m)', ]
            #        'label', 't(um)', 'h(m)', 'd(m)', 'intf', 'Z(m)', ]      # removed; k redefined in 0.4.3c4d
            #        'label', 't(um)', 'h(m)', 'd(m)', 'intf']
            "label",
            "t(um)",
            "h(m)",
            "d(m)",
            "intf",
            "k",
        ]
        print("A .csv file is being processed with the following dimensional properties:")
        print(
            " Number of plies: {} \n p: {} \n total \
               t (m): {} \n geometry: {} \n".format(
                nplies, p, t_total, geometry
            )
        )

        actual = df[cols]
        expected = df_expected[cols]
        # print ('expected (file) \n', expected)
        # print('actual (API) \n', actual)
        # print(expected.dtypes)
        # print(actual.dtypes)
        print("\n")
        ut.assertFrameEqual(actual, expected)
Ejemplo n.º 14
0
def test_Case_apply_LaminateModels1():
    """Test the native DataFrame elements and dtypes. Resorts columns.
    Uses pandas equals() test.  p is even."""
    case1.apply(geos_full)
    d = {
        "layer": [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7],
        "matl": [
            "HA",
            "HA",
            "HA",
            "HA",
            "PSu",
            "PSu",
            "PSu",
            "PSu",
            "HA",
            "HA",
            "HA",
            "HA",
            "PSu",
            "PSu",
            "PSu",
            "PSu",
            "HA",
            "HA",
            "HA",
            "HA",
            "PSu",
            "PSu",
            "PSu",
            "PSu",
            "HA",
            "HA",
            "HA",
            "HA",
        ],
        "type": [
            "outer",
            "outer",
            "outer",
            "outer",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "middle",
            "middle",
            "middle",
            "middle",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "inner",
            "outer",
            "outer",
            "outer",
            "outer",
        ],
        "t(um)": [
            400.0,
            400.0,
            400.0,
            400.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            800.0,
            800.0,
            800.0,
            800.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            100.0,
            400.0,
            400.0,
            400.0,
            400.0,
        ],
    }
    cols = ["layer", "matl", "type", "t(um)"]
    actual = case1.frames[8][cols]
    expected = pd.DataFrame(d)
    # print(case1.materials)
    # print(actual)
    # print(expected)
    #     bool_test = actual.sort(axis=1).equals(expected.sort(axis=1))
    #     #nt.assert_equal(bool_test, True)
    #     nt.assert_true(bool_test)
    ut.assertFrameEqual(actual, expected)
Ejemplo n.º 15
0
 def test_assertframeeq2(self):
     '''Check helper function compares DataFrames, raises error is not equal.'''
     actual = ut.assertFrameEqual(self.df1, self.df3)
Ejemplo n.º 16
0
def test_apply_LaminateModels_cols_models1():
    '''Test .cvs files found in tests/controls_LT with API DataFrames.
    Comparing models columns only.

    Due to a different algorithms for calculating internal values,
    rows yielding maximum and minimum stress are the most reliable comparisons.

    Tests for internal points can varying depending on choice of z(m).
    So they will be excluded from this test.
    '''
    '''Wait for skipcols kwarg in read_csv in pandas 0.17'''

    def remove_units(cols):
        '''Return a dict of stress column labels with units removed.'''
        #cols = cols.tolist()
        dict_ = {}
        for idx, colname in enumerate(cols):
            if 'stress' in colname:
                tokens = colname.split(' ')                # works even w/o units
                unitless_name = tokens[0]
                #print(name)
                dict_[colname] = unitless_name
        return dict_

    # Prepare file path.
    # Depends which directory nosetests is rum
    #path = os.getcwd()                                     # use for the test in the correct path
    ##path = os.path.join(os.getcwd(), 'lamana', 'tests', 'controls_LT')  # for builds
    sourcepath = os.path.abspath(os.path.dirname(la.__file__))
    path = os.path.join(sourcepath, 'tests', 'controls_LT')
    #path = path + r'\lamana\tests\controls_LT'             # for Main Script. Comment out in tests
    #path = path + r'\tests\controls_LT'                    # for test
    #path = os.path.join(os.getcwd(), 'tests', 'controls_LT')          # for test
    #path = path + r'\controls_LT'                          # for test
    logging.debug('Default path: {}'.format(path))

    # Read all files in the path (REF 013)
    for file, filepath in ut.read_csv_dir(path):
        #df_expected = file
        df = file
        #print(df_expected)

        df_expected, geometry, nplies, p, t_total = extract_dataframe(df)

        # Build actual Case using distributions API
        dft.load_params['p'] = p
        case = la.distributions.Case(dft.load_params, dft.mat_props)
        case.apply([geometry])
        df = case.frames[0]

        # Compare only model-related columns; skip API columns
        IDs = ['layer', 'side', 'type', 'matl', 't(um)']   # except label_
        Dimensionals = ['h(m)', 'd(m)', 'intf', 'k', 'Z(m)', 'z(m)', 'z(m)*']
        #bypassed = ['z(m)', 'z(m)*', 'intf', 'k']
        skippedcols = IDs + Dimensionals
        actual_remainingcols = df.columns.difference(skippedcols)
        expected_remainingcols = df_expected.columns.difference(skippedcols)

        # Get model columns only and strip units from stress columns
        df_models = df[actual_remainingcols].copy()
        df_expected = df_expected[expected_remainingcols].copy()
        df_models.rename(columns=remove_units(actual_remainingcols), inplace=True)
        df_expected.rename(columns=remove_units(expected_remainingcols), inplace=True)
        #print(df_expected)

        print('A .csv file is being processed with the following dimensional properties:')
        print(' Number of plies: {} \n p: {} \n total \
               t (m): {} \n geometry: {} \n'.format(nplies, p, t_total, geometry))

        # Use all rows (including internals, optional)
        #actual = df_models
        #expected = df_expected[expected_remainingcols]

        # Only use max stress rows (interfacial)
        actual1 = df_models.loc[df_models['label'] == 'interface']
        expected1 = df_expected.loc[df_expected['label'] == 'interface']
        #expected1 = df_expected[expected_remainingcols].loc[df_expected['label'] == 'interface']

        # Only use min stress rows (discontunities)
        if p > 1:
            actual2 = df_models.loc[df_models['label'] == 'discont.']
            expected2 = df_expected.loc[df_expected['label'] == 'discont.']
            #expected2 = df_expected[expected_remainingcols].loc[df_expected['label'] == 'discont.']

        #print ('expected (file) \n', expected1)
        #print('actual (API) \n', actual1)
        #print ('expected (file) \n', expected2)
        #print('actual (API) \n', actual2)
        #print(type(expected1))
        #print(type(actual1))
        #print(expected1.dtypes)
        #print(actual1.dtypes)
        print('\n')

        ut.assertFrameEqual(actual1, expected1, check_dtype=False)  # max stress rows
        if p > 1:                                                   # min stress rows
            ut.assertFrameEqual(actual2, expected2, check_dtype=False)
Ejemplo n.º 17
0
 def test_assertframeeq1(self):
     '''Check helper function compares DataFrames, None.'''
     # See https://github.com/pydata/pandas/blob/master/pandas/util/testing.py
     actual = ut.assertFrameEqual(self.df1, self.df2)
     expected = None
     nt.assert_equal(actual, expected)