def test_sample_table_valid_2(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     D = sample_table(C, 10, True)
     self.assertEqual(id(cm.get_ltable(D)), id(cm.get_ltable(C)))
     self.assertEqual(id(cm.get_rtable(D)), id(cm.get_rtable(C)))
     self.assertEqual(cm.get_fk_ltable(D), cm.get_fk_ltable(C))
     self.assertEqual(cm.get_fk_rtable(D), cm.get_fk_rtable(C))
     self.assertEqual(len(D), 10)
 def test_sample_table_valid_2(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     D = sample_table(C, 10, True)
     self.assertEqual(id(cm.get_ltable(D)), id(cm.get_ltable(C)))
     self.assertEqual(id(cm.get_rtable(D)), id(cm.get_rtable(C)))
     self.assertEqual(cm.get_fk_ltable(D), cm.get_fk_ltable(C))
     self.assertEqual(cm.get_fk_rtable(D), cm.get_fk_rtable(C))
     self.assertEqual(len(D), 10)
    def test_select_matcher_target_attr_not_present(self):
        A = read_csv_metadata(path_a, key='id')
        B = read_csv_metadata(path_b, key='id')
        # C = read_csv_metadata(path_c, ltable=A, rtable=B, fk_ltable='ltable.id',
        #                       fk_rtable='rtable.id', key='_id')
        # labels = [0] * 7
        # labels.extend([1] * 8)
        # C['labels'] = labels
        # feature_table = get_features_for_matching(A, B)
        # feature_vectors = extract_feature_vecs(C, feature_table=feature_table, attrs_after='gold')
        # feature_vectors.fillna(0, inplace=True)
        feature_vectors = read_csv_metadata(path_f, ltable=A, rtable=B)
        dtmatcher = DTMatcher()
        nbmatcher = NBMatcher()
        rfmatcher = RFMatcher()
        svmmatcher = SVMMatcher()
        linregmatcher = LinRegMatcher()
        logregmatcher = LogRegMatcher()
        matchers = [dtmatcher, nbmatcher, rfmatcher, svmmatcher, linregmatcher, logregmatcher]

        col_list = list(feature_vectors.columns)
        l = list_diff(col_list, [cm.get_fk_ltable(feature_vectors),
                                 cm.get_fk_rtable(feature_vectors)
                                 ])
        feature_vectors = feature_vectors[l]

        result = select_matcher(matchers, x=None, y=None, table=feature_vectors,
                                exclude_attrs='_id',
                                target_attr='labels1', k=2)
 def test_select_matcher_valid_2(self):
     A = read_csv_metadata(path_a, key='id')
     B = read_csv_metadata(path_b, key='id')
     # C = read_csv_metadata(path_c, ltable=A, rtable=B, fk_ltable='ltable.id',
     #                       fk_rtable='rtable.id', key='_id')
     # labels = [0] * 7
     # labels.extend([1] * 8)
     # C['labels'] = labels
     # feature_table = get_features_for_matching(A, B)
     # feature_vectors = extract_feature_vecs(C, feature_table=feature_table, attrs_after='gold')
     # feature_vectors.fillna(0, inplace=True)
     feature_vectors = read_csv_metadata(path_f, ltable=A, rtable=B)
     dtmatcher = DTMatcher()
     nbmatcher = NBMatcher()
     rfmatcher = RFMatcher()
     svmmatcher = SVMMatcher()
     linregmatcher = LinRegMatcher()
     logregmatcher = LogRegMatcher()
     matchers = [dtmatcher, nbmatcher, rfmatcher, svmmatcher, linregmatcher, logregmatcher]
     col_list = list(feature_vectors.columns)
     l = list_diff(col_list, [cm.get_key(feature_vectors), cm.get_fk_ltable(feature_vectors),
                              cm.get_fk_rtable(feature_vectors),
                              'gold'])
     X = feature_vectors[l]
     Y = feature_vectors['gold']
     result = select_matcher(matchers, x=X, y=Y)
     header = ['Name', 'Matcher', 'Num folds']
     result_df = result['drill_down_cv_stats']['precision']
     self.assertEqual(set(header) == set(list(result_df.columns[[0, 1, 2]])), True)
     self.assertEqual('Mean score', result_df.columns[len(result_df.columns) - 1])
     d = result_df.set_index('Name')
     p_max = d.ix[result['selected_matcher'].name, 'Mean score']
     a_max = pd.np.max(d['Mean score'])
     self.assertEqual(p_max, a_max)
    def test_copy_properties_valid_2(self):
        A = read_csv_metadata(path_a)
        B = read_csv_metadata(path_b)
        C = read_csv_metadata(path_c, ltable=A, rtable=B)

        C1 = pd.read_csv(path_c)
        cm.copy_properties(C, C1)
        self.assertEqual(cm.is_dfinfo_present(C1), True)
        p = cm.get_all_properties(C1)
        p1 = cm.get_all_properties(C1)
        self.assertEqual(p, p1)
        self.assertEqual(cm.get_key(C1), cm.get_key(C))
        self.assertEqual(cm.get_ltable(C1).equals(A), True)
        self.assertEqual(cm.get_rtable(C1).equals(B), True)
        self.assertEqual(cm.get_fk_ltable(C1), cm.get_fk_ltable(C))
        self.assertEqual(cm.get_fk_rtable(C1), cm.get_fk_rtable(C))
Exemple #6
0
 def test_select_matcher_target_attr_not_series(self):
     A = read_csv_metadata(path_a, key='id')
     B = read_csv_metadata(path_b, key='id')
     # C = read_csv_metadata(path_c, ltable=A, rtable=B, fk_ltable='ltable.id',
     #                       fk_rtable='rtable.id', key='_id')
     # labels = [0] * 7
     # labels.extend([1] * 8)
     # C['labels'] = labels
     # feature_table = get_features_for_matching(A, B)
     # feature_vectors = extract_feature_vecs(C, feature_table=feature_table, attrs_after='gold')
     # feature_vectors.fillna(0, inplace=True)
     feature_vectors = read_csv_metadata(path_f, ltable=A, rtable=B)
     dtmatcher = DTMatcher()
     nbmatcher = NBMatcher()
     rfmatcher = RFMatcher()
     svmmatcher = SVMMatcher()
     linregmatcher = LinRegMatcher()
     logregmatcher = LogRegMatcher()
     matchers = [
         dtmatcher, nbmatcher, rfmatcher, svmmatcher, linregmatcher,
         logregmatcher
     ]
     col_list = list(feature_vectors.columns)
     l = list_diff(col_list, [
         cm.get_fk_ltable(feature_vectors),
         cm.get_fk_rtable(feature_vectors), 'gold'
     ])
     X = feature_vectors[l]
     Y = feature_vectors[['gold']]
     result = select_matcher(matchers, x=X, y=Y)
    def test_valid_path_table_2(self):
        cm.del_catalog()
        del_files_in_dir(sndbx_path)
        A = read_csv_metadata(path_a)
        B = read_csv_metadata(path_b, key='ID')
        C = read_csv_metadata(path_c, ltable=A, rtable=B)
        p = os.sep.join([sndbx_path, 'C.pkl'])
        save_table(C, p)

        C1 = load_table(p)
        self.assertEqual(C.equals(C1), True)
        self.assertEqual(cm.get_key(C), cm.get_key(C1))
        # self.assertEqual(cm.get_ltable(C).equals(cm.get_ltable(C1)), True)
        # self.assertEqual(cm.get_rtable(C).equals(cm.get_rtable(C1)), True)
        self.assertEqual(cm.get_fk_ltable(C), cm.get_fk_ltable(C1))
        self.assertEqual(cm.get_fk_rtable(C), cm.get_fk_rtable(C1))
Exemple #8
0
 def handle_debug_button(self, index):
     """
     Function to handle debug button
     """
     r = self.current_dataframe.iloc[[index]]
     # Handle debug, show the tree to the user
     l_fkey = cm.get_fk_ltable(self.table)
     r_fkey = cm.get_fk_rtable(self.table)
     l_val = r.ix[r.index.values[0], l_fkey]
     r_val = r.ix[r.index.values[0], r_fkey]
     d1 = OrderedDict(self.l_df.ix[l_val])
     d2 = OrderedDict(self.r_df.ix[r_val])
     if self.matcher_type == 'dt':
         ret_val, node_list = em.vis_tuple_debug_dt_matcher(
             self.matcher, r, self.exclude_attrs_or_feature_table)
     elif self.matcher_type == 'rf':
         ret_val, node_list = em.vis_tuple_debug_rf_matcher(
             self.matcher, r, self.exclude_attrs_or_feature_table)
     else:
         raise TypeError('Unknown matcher type ')
     debug_result = [ret_val]
     debug_result.append(node_list)
     # Create the debug window manager
     debug_obj = DebugWindowManager(d1, d2, self.matcher_type, debug_result)
     # Show the debug window to the user
     debug_obj.show()
    def test_valid_path_table_2(self):
        cm.del_catalog()
        del_files_in_dir(sndbx_path)
        A = read_csv_metadata(path_a)
        B = read_csv_metadata(path_b, key='ID')
        C = read_csv_metadata(path_c, ltable=A, rtable=B)
        p = os.sep.join([sndbx_path, 'C.pkl'])
        save_table(C, p)

        C1 = load_table(p)
        self.assertEqual(C.equals(C1), True)
        self.assertEqual(cm.get_key(C), cm.get_key(C1))
        # self.assertEqual(cm.get_ltable(C).equals(cm.get_ltable(C1)), True)
        # self.assertEqual(cm.get_rtable(C).equals(cm.get_rtable(C1)), True)
        self.assertEqual(cm.get_fk_ltable(C), cm.get_fk_ltable(C1))
        self.assertEqual(cm.get_fk_rtable(C), cm.get_fk_rtable(C1))
Exemple #10
0
 def test_select_matcher_valid_2(self):
     A = read_csv_metadata(path_a, key='id')
     B = read_csv_metadata(path_b, key='id')
     # C = read_csv_metadata(path_c, ltable=A, rtable=B, fk_ltable='ltable.id',
     #                       fk_rtable='rtable.id', key='_id')
     # labels = [0] * 7
     # labels.extend([1] * 8)
     # C['labels'] = labels
     # feature_table = get_features_for_matching(A, B)
     # feature_vectors = extract_feature_vecs(C, feature_table=feature_table, attrs_after='gold')
     # feature_vectors.fillna(0, inplace=True)
     feature_vectors = read_csv_metadata(path_f, ltable=A, rtable=B)
     dtmatcher = DTMatcher()
     nbmatcher = NBMatcher()
     rfmatcher = RFMatcher()
     svmmatcher = SVMMatcher()
     linregmatcher = LinRegMatcher()
     logregmatcher = LogRegMatcher()
     matchers = [dtmatcher, nbmatcher, rfmatcher, svmmatcher, linregmatcher, logregmatcher]
     col_list = list(feature_vectors.columns)
     l = list_diff(col_list, [cm.get_key(feature_vectors), cm.get_fk_ltable(feature_vectors),
                              cm.get_fk_rtable(feature_vectors),
                              'gold'])
     X = feature_vectors[l]
     Y = feature_vectors['gold']
     result = select_matcher(matchers, x=X, y=Y)
     header = ['Name', 'Matcher', 'Num folds']
     result_df = result['drill_down_cv_stats']['precision']
     self.assertEqual(set(header) == set(list(result_df.columns[[0, 1, 2]])), True)
     self.assertEqual('Mean score', result_df.columns[len(result_df.columns) - 1])
     d = result_df.set_index('Name')
     p_max = d.loc[result['selected_matcher'].name, 'Mean score']
     a_max = pd.np.max(d['Mean score'])
     self.assertEqual(p_max, a_max)
 def handle_debug_button(self, index):
     """
     Function to handle debug button
     """
     r = self.current_dataframe.iloc[[index]]
     # Handle debug, show the tree to the user
     l_fkey = cm.get_fk_ltable(self.table)
     r_fkey = cm.get_fk_rtable(self.table)
     l_val = r.ix[r.index.values[0], l_fkey]
     r_val = r.ix[r.index.values[0], r_fkey]
     d1 = OrderedDict(self.l_df.ix[l_val])
     d2 = OrderedDict(self.r_df.ix[r_val])
     if self.matcher_type == 'dt':
         ret_val, node_list = em.vis_tuple_debug_dt_matcher(
             self.matcher, r,
             self.exclude_attrs_or_feature_table)
     elif self.matcher_type == 'rf':
         ret_val, node_list = em.vis_tuple_debug_rf_matcher(self.matcher, r,
                                                            self.exclude_attrs_or_feature_table)
     else:
         raise TypeError('Unknown matcher type ')
     debug_result = [ret_val]
     debug_result.append(node_list)
     # Create the debug window manager
     debug_obj = DebugWindowManager(d1, d2, self.matcher_type, debug_result)
     # Show the debug window to the user
     debug_obj.show()
Exemple #12
0
def _validate_lr_tables(blocker_output_list):
    """
    Validate the input blocker output list.
    """
    ltable_ids = []
    rtable_ids = []
    fk_ltable_list = []
    fk_rtable_list = []
    # Iterate through the DataFrame list and keep track the following
    # # 1) Validate whether the input objects are all DataFrames
    # # 2) Update the ltable, rtable (ids), fk_ltable and fk_rtable.
    for data_frame in blocker_output_list:
        py_entitymatching.utils.validation_helper.validate_object_type(data_frame, pd.DataFrame)
        ltable_ids.append(id(cm.get_ltable(data_frame)))
        rtable_ids.append(id(cm.get_rtable(data_frame)))
        fk_ltable_list.append(cm.get_fk_ltable(data_frame))
        fk_rtable_list.append(cm.get_fk_rtable(data_frame))

    # Check whether all the ltables in the catalog are same for the input
    # DataFrame list
    ltable_ids = set(ltable_ids)
    # # We expect all the ltable ids are same (i.e the len. of set should be 1)
    if not len(ltable_ids) == 1:
        logger.error('Candidate set list contains different left tables')
        raise AssertionError('Candidate set list contains different '
                             'left tables')

    # Check whether all the rtables in the catalog are same for the input
    # DataFrame list
    rtable_ids = set(rtable_ids)
    # # We expect all the ltable ids are same (i.e the len. of set should be 1)
    if not len(rtable_ids) == 1:
        logger.error('Candidate set list contains different right tables')
        raise AssertionError('Candidate set list contains different '
                             'right tables')

    # Check whether all the fk_ltable values in the catalog are same for the
    # input DataFrame list
    fk_ltable_set = set(fk_ltable_list)
    if not len(fk_ltable_set) == 1:
        logger.error('Candidate set list contains different foreign key '
                     'for left tables')
        raise AssertionError('Candidate set list contains different '
                             'foreign key for left tables')

    # Check whether all the fk_rtable values in the catalog are same for the
    # input DataFrame list
    fk_rtable_set = set(fk_rtable_list)
    if not len(fk_rtable_set) == 1:
        logger.error('Candidate set list contains different foreign key '
                     'for right tables')
        raise AssertionError('Candidate set list contains different '
                             'foreign key for right tables')

    # If everything looks fine then return True
    return True
 def test_valid_path_candset_wi_valid_metadata(self):
     cm.del_catalog()
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID') # not initializing with ID will raise key_error
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     pd_C = pd.read_csv(path_c)
     self.assertEqual(C.equals(pd_C), True)
     self.assertEqual(len(cm.get_all_properties(C).keys()), 5)
     self.assertEqual(cm.get_key(C), '_id')
     self.assertEqual(cm.get_fk_ltable(C), 'ltable_ID')
     self.assertEqual(cm.get_fk_rtable(C), 'rtable_ID')
 def test_valid_path_candset_wi_valid_metadata(self):
     cm.del_catalog()
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(
         path_b, key='ID')  # not initializing with ID will raise key_error
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     pd_C = pd.read_csv(path_c)
     self.assertEqual(C.equals(pd_C), True)
     self.assertEqual(len(cm.get_all_properties(C).keys()), 5)
     self.assertEqual(cm.get_key(C), '_id')
     self.assertEqual(cm.get_fk_ltable(C), 'ltable_ID')
     self.assertEqual(cm.get_fk_rtable(C), 'rtable_ID')
 def test_extract_feature_vecs_with_parralel_job_count_less_than_zero(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     col_pos = len(C.columns)
     C.insert(col_pos, 'label', [0] * len(C))
     feature_table = get_features_for_matching(A, B, validate_inferred_attr_types=False)
     F = extract_feature_vecs(C, attrs_before=['ltable_name', 'rtable_name'], feature_table=feature_table, n_jobs=-1)
     self.assertEqual(isinstance(F, pd.DataFrame), True)
     self.assertEqual(F.columns[0], '_id')
     self.assertEqual(F.columns[1], cm.get_fk_ltable(C))
     self.assertEqual(F.columns[2], cm.get_fk_rtable(C))
     self.assertEqual(F.columns[4], 'rtable_name')
     self.assertEqual(F.columns[len(F.columns) - 1] == 'label', False)
     self.assertEqual(cm.get_all_properties(C) == cm.get_all_properties(F), True)
Exemple #16
0
    def handle_show_button(self, index):
        """
        The function to handle the show butting
        """
        r = self.current_dataframe.iloc[[index]]
        l_fkey = cm.get_fk_ltable(self.table)
        r_fkey = cm.get_fk_rtable(self.table)

        l_val = r.ix[r.index.values[0], l_fkey]
        r_val = r.ix[r.index.values[0], r_fkey]
        d1 = OrderedDict(self.l_df.ix[l_val])
        d2 = OrderedDict(self.r_df.ix[r_val])
        # Create a window manager
        show_obj = ShowWindowManager(d1, d2)
        # Show the window to the user
        show_obj.show()
    def handle_show_button(self, index):
        """
        The function to handle the show butting
        """
        r = self.current_dataframe.iloc[[index]]
        l_fkey = cm.get_fk_ltable(self.table)
        r_fkey = cm.get_fk_rtable(self.table)

        l_val = r.ix[r.index.values[0], l_fkey]
        r_val = r.ix[r.index.values[0], r_fkey]
        d1 = OrderedDict(self.l_df.ix[l_val])
        d2 = OrderedDict(self.r_df.ix[r_val])
        # Create a window manager
        show_obj = ShowWindowManager(d1, d2)
        # Show the window to the user
        show_obj.show()
 def test_extract_feature_vecs_valid_8(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     col_pos = len(C.columns)
     C.insert(col_pos, 'label', [0] * len(C))
     feature_table = get_features_for_matching(A, B, validate_inferred_attr_types=False)
     F = extract_feature_vecs(C,
                              feature_table=pd.DataFrame(columns=feature_table.columns),
                              attrs_after=['label', '_id'])
     self.assertEqual(isinstance(F, pd.DataFrame), True)
     self.assertEqual(F.columns[0], '_id')
     self.assertEqual(F.columns[1], cm.get_fk_ltable(C))
     self.assertEqual(F.columns[2], cm.get_fk_rtable(C))
     # self.assertEqual(F.columns[3], 'ltable_name')
     self.assertEqual(F.columns[len(F.columns) - 1] == 'label', True)
     self.assertEqual(cm.get_all_properties(C) == cm.get_all_properties(F), True)
    def test_ml_matcher_valid_2(self):
        A = read_csv_metadata(fpath_a, key='id')
        B = read_csv_metadata(fpath_b, key='id')
        feature_vectors = read_csv_metadata(fpath_f, ltable=A, rtable=B)
        train_test = mu.split_train_test(feature_vectors)
        train, test = train_test['train'], train_test['test']
        dt = DTMatcher(name='DecisionTree')

        col_list = list(feature_vectors.columns)
        l = list_diff(col_list, [cm.get_key(feature_vectors), cm.get_fk_ltable(feature_vectors),
                                 cm.get_fk_rtable(feature_vectors),
                                 'gold'])
        X = train[l]
        Y = train['gold']

        dt.fit(x=X, y=Y)
        predictions = dt.predict(test[l])
        self.assertEqual(len(predictions), len(test))
Exemple #20
0
    def test_ml_matcher_valid_with_id_in_y(self):
        A = read_csv_metadata(fpath_a, key='id')
        B = read_csv_metadata(fpath_b, key='id')
        feature_vectors = read_csv_metadata(fpath_f, ltable=A, rtable=B)
        train_test = mu.split_train_test(feature_vectors)
        train, test = train_test['train'], train_test['test']
        dt = DTMatcher(name='DecisionTree')

        col_list = list(feature_vectors.columns)
        l = list_diff(col_list, [
            cm.get_fk_ltable(feature_vectors),
            cm.get_fk_rtable(feature_vectors), 'gold'
        ])
        X = train[l]
        Y = train[['_id', 'gold']]

        dt.fit(x=X, y=Y)
        predictions = dt.predict(test[l])
        self.assertEqual(len(predictions), len(test))
 def test_extract_feature_vecs_valid_2(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     col_pos = len(C.columns)
     C.insert(col_pos, 'label', [0] * len(C))
     feature_table = get_features_for_matching(A, B)
     F = extract_feature_vecs(C,
                              attrs_before=['ltable_name', 'rtable_name'],
                              feature_table=feature_table)
     self.assertEqual(isinstance(F, pd.DataFrame), True)
     self.assertEqual(F.columns[0], '_id')
     self.assertEqual(F.columns[1], cm.get_fk_ltable(C))
     self.assertEqual(F.columns[2], cm.get_fk_rtable(C))
     self.assertEqual(F.columns[3], 'ltable_name')
     self.assertEqual(F.columns[4], 'rtable_name')
     self.assertEqual(F.columns[len(F.columns) - 1] == 'label', False)
     self.assertEqual(
         cm.get_all_properties(C) == cm.get_all_properties(F), True)
Exemple #22
0
 def test_extract_feature_vecs_with_parralel_job_count_more_than_one(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     col_pos = len(C.columns)
     C.insert(col_pos, 'label', [0] * len(C))
     feature_table = get_features_for_matching(
         A, B, validate_inferred_attr_types=False)
     F = extract_feature_vecs(C,
                              attrs_before=['ltable_name', 'rtable_name'],
                              feature_table=feature_table,
                              n_jobs=2)
     self.assertEqual(isinstance(F, pd.DataFrame), True)
     self.assertEqual(F.columns[0], '_id')
     self.assertEqual(F.columns[1], cm.get_fk_ltable(C))
     self.assertEqual(F.columns[2], cm.get_fk_rtable(C))
     self.assertEqual(F.columns[4], 'rtable_name')
     self.assertEqual(F.columns[len(F.columns) - 1] == 'label', False)
     self.assertEqual(
         cm.get_all_properties(C) == cm.get_all_properties(F), True)
Exemple #23
0
 def test_extract_feature_vecs_valid_8(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b, key='ID')
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     col_pos = len(C.columns)
     C.insert(col_pos, 'label', [0] * len(C))
     feature_table = get_features_for_matching(
         A, B, validate_inferred_attr_types=False)
     F = extract_feature_vecs(
         C,
         feature_table=pd.DataFrame(columns=feature_table.columns),
         attrs_after=['label', '_id'])
     self.assertEqual(isinstance(F, pd.DataFrame), True)
     self.assertEqual(F.columns[0], '_id')
     self.assertEqual(F.columns[1], cm.get_fk_ltable(C))
     self.assertEqual(F.columns[2], cm.get_fk_rtable(C))
     # self.assertEqual(F.columns[3], 'ltable_name')
     self.assertEqual(F.columns[len(F.columns) - 1] == 'label', True)
     self.assertEqual(
         cm.get_all_properties(C) == cm.get_all_properties(F), True)
def _get_dataframe(table, ls):
    """
    This function returns the selection of the table based on ls.
    Specifically, ls is expected to contain a list of fk_ltable and fk_rtables.
    """

    # table = table.copy()
    # Get the column values.
    ret = pd.DataFrame(columns=table.columns.values)
    # If the list has some values then proceed
    if len(ls) > 0:
        fk_ltable = cm.get_fk_ltable(table)
        fk_rtable = cm.get_fk_rtable(table)
        # Set the index on fk_ltable, fk_rtable
        table = table.set_index([fk_ltable, fk_rtable], drop=False)
        # Do the selection
        d = table.ix[ls]
        ret = d
        ret.reset_index(inplace=True, drop=True)
    # Finally return the selected values
    return ret
def _get_dataframe(table, ls):
    """
    This function returns the selection of the table based on ls.
    Specifically, ls is expected to contain a list of fk_ltable and fk_rtables.
    """

    # table = table.copy()
    # Get the column values.
    ret = pd.DataFrame(columns=table.columns.values)
    # If the list has some values then proceed
    if len(ls) > 0:
        fk_ltable = cm.get_fk_ltable(table)
        fk_rtable = cm.get_fk_rtable(table)
        # Set the index on fk_ltable, fk_rtable
        table = table.set_index([fk_ltable, fk_rtable], drop=False)
        # Do the selection
        d = table.loc[ls]
        ret = d
        ret.reset_index(inplace=True, drop=True)
    # Finally return the selected values
    return ret
def combine_blocker_outputs_via_union(
        blocker_output_list,
        l_prefix='ltable_',
        r_prefix='rtable_',
        verbose=False):
    """
    Combines multiple blocker outputs by doing a union of their tuple pair
    ids (foreign key ltable, foreign key rtable).

    Specifically, this function takes in a list of DataFrames (candidate
    sets, typically the
    output from blockers) and returns a consolidated DataFrame. The output
    DataFrame contains the union of tuple pair ids (foreign key ltable,
    foreign key rtable) and other attributes from the input list of DataFrames.

    This function makes some assumptions about the input DataFrames. First,
    each DataFrame is expected to contain the following metadata in the
    catalog: key, fk_ltable, fk_rtable, ltable, and rtable. Second,
    all the DataFrames must be a result of blocking from the same underlying
    tables. Concretely the ltable and rtable properties must refer to the
    same DataFrame across all the input tables. Third, all the input
    DataFrames must have the same fk_ltable and fk_rtable properties.
    Finally, in each input DataFrame, for the attributes included from the
    ltable or rtable, the attribute names must be prefixed with the given
    l_prefix and r_prefix in the function.

    The input DataFrames may contain different attribute lists and it demands
    the question of how to combine them. Currently py_entitymatching takes an union
    of attribute names that has prefix l_prefix or r_prefix across
    input tables. After taking the union, for each tuple id pair included
    in output, the attribute values (for union-ed attribute names) are
    probed from ltable/rtable and included in the output.

    A subtle point to note here is,  if an input DataFrame has a column
    added by user (say label for some reason), then that column will not
    be present in the output. The reason is, the same column may not be
    present in other candidate sets so it is not clear about how to
    combine them. One possibility is to include label in output for all
    tuple id pairs, but set as NaN for the values not present. Currently
    py_entitymatching does not include such columns and addressing it will be part
    of future work.

    Args:
        blocker_output_list (list of DataFrames): The list of DataFrames that
            should be combined.
        l_prefix (string): The prefix given to the attributes from the ltable.
        r_prefix (string): The prefix given to the attributes from the rtable.
        verbose (boolean): A flag to indicate whether more detailed information
            about the execution steps should be printed out (default value is
            False).

    Returns:
        A new DataFrame with the combined tuple pairs and other attributes from
        all the blocker lists.

    Raises:
        AssertionError: If `l_prefix` is not of type string.
        AssertionError: If `r_prefix` is not of type string.
        AssertionError: If the length of the input DataFrame list is 0.
        AssertionError: If `blocker_output_list` is not a list of
            DataFrames.
        AssertionError: If the ltables are different across the input list of
            DataFrames.
        AssertionError: If the rtables are different across the input list of
            DataFrames.
        AssertionError: If the `fk_ltable` values are different across the
            input list of DataFrames.
        AssertionError: If the `fk_rtable` values are different across the
            input list of DataFrames.

    Examples:

        >>> import py_entitymatching as em
        >>> ab = em.AttrEquivalenceBlocker()
        >>> C = ab.block_tables(A, B, 'zipcode', 'zipcode')
        >>> ob = em.OverlapBlocker()
        >>> D = ob.block_candset(C, 'address', 'address')
        >>> block_f = em.get_features_for_blocking(A, B)
        >>> rb = em.RuleBasedBlocker()
        >>> rule = ['address_address_lev(ltuple, rtuple) > 6']
        >>> rb.add_rule(rule, block_f)
        >>> E = rb.block_tables(A, B)
        >>> F = em.combine_blocker_outputs_via_union([C, E])


    """

    # validate input parameters

    # The l_prefix is expected to be of type string
    py_entitymatching.utils.validation_helper.validate_object_type(l_prefix, six.string_types, 'l_prefix')

    # The r_prefix is expected to be of type string
    py_entitymatching.utils.validation_helper.validate_object_type(r_prefix, six.string_types, 'r_prefix')

    # We cannot combine empty DataFrame list
    if not len(blocker_output_list) > 0:
        logger.error('There no DataFrames to combine')
        raise AssertionError('There are no DataFrames to combine')

    # Validate the assumptions about the input tables.
    # # 1) All the input object must be DataFrames
    # # 2) All the input DataFrames must have the metadata as that of a
    # candidate set
    # # 3) All the input DataFrames must have the same fk_ltable and fk_rtable
    _validate_lr_tables(blocker_output_list)

    # # Get the ltable and rtable. We take it from the first DataFrame as all
    #  the DataFrames contain the same ltables and rtables
    ltable = cm.get_ltable(blocker_output_list[0])
    rtable = cm.get_rtable(blocker_output_list[0])

    # # Get the fk_ltable and fk_rtable. We take it from the first DataFrame as
    #  all the DataFrames contain the same ltables and rtables
    fk_ltable = cm.get_fk_ltable(blocker_output_list[0])
    fk_rtable = cm.get_fk_rtable(blocker_output_list[0])

    # Retrieve the keys for the ltable and rtables.
    l_key = cm.get_key(ltable)
    r_key = cm.get_key(rtable)

    # Check if the fk_ltable is starting with the given prefix, if not its
    # not an error. Just raise a warning.
    if fk_ltable.startswith(l_prefix) is False:
        logger.warning(
            'Foreign key for ltable is not starting with the given prefix ('
            '%s)', l_prefix)

    # Check if the fk_rtable is starting with the given prefix, if not its
    # not an error. Just raise a warning.
    if fk_rtable.startswith(r_prefix) is False:
        logger.warning(
            'Foreign key for rtable is not starting with the given prefix ('
            '%s)', r_prefix)

    # Initialize lists
    # # keep track of projected tuple pair ids
    tuple_pair_ids = []
    # # keep track of output attributes from the left table
    l_output_attrs = []
    # # keep track of output attributes from the right table
    r_output_attrs = []

    # for each DataFrame in the given list, project out tuple pair ids, get the
    #  attributes from the ltable and rtable
    for data_frame in blocker_output_list:
        # Project out the tuple pair ids. A tuple pair id is a fk_ltable,
        # fk_rtable pair
        projected_tuple_pair_ids = data_frame[[fk_ltable, fk_rtable]]
        # Update the list that tracks tuple pair ids
        tuple_pair_ids.append(projected_tuple_pair_ids)

        # Get the columns, which should be segregated into the attributes
        # from the ltable and table
        col_set = (
            gh.list_diff(list(data_frame.columns),
                         [fk_ltable, fk_rtable, cm.get_key(data_frame)]))

        # Segregate the columns as attributes from the ltable and rtable
        l_attrs, r_attrs = _lr_cols(col_set, l_prefix, r_prefix)

        # Update the l_output_attrs, r_output_attrs
        l_output_attrs.extend(l_attrs)
        # the reason we use extend because l_attrs a list
        r_output_attrs.extend(r_attrs)

    ch.log_info(logger, 'Concatenating the tuple pair ids across given '
                        'blockers ...', verbose)

    # concatenate the tuple pair ids from the list of input DataFrames
    concatenated_tuple_pair_ids = pd.concat(tuple_pair_ids)

    ch.log_info(logger, 'Concatenating the tuple pair ids ... DONE', verbose)
    ch.log_info(logger, 'Deduplicating the tuple pair ids ...', verbose)

    # Deduplicate the DataFrame. Now the returned DataFrame will contain
    # unique tuple pair ids.

    # noinspection PyUnresolvedReferences
    deduplicated_tuple_pair_ids = concatenated_tuple_pair_ids.drop_duplicates()

    ch.log_info(logger, 'Deduplicating the tuple pair ids ... DONE', verbose)

    # Construct output table
    # # Get unique list of attributes across different tables
    l_output_attrs = gh.list_drop_duplicates(l_output_attrs)
    r_output_attrs = gh.list_drop_duplicates(r_output_attrs)

    # Reset the index that might have lingered from concatenation.
    deduplicated_tuple_pair_ids.reset_index(inplace=True, drop=True)

    # Add the output attribtues from the ltable and rtable.
    # NOTE: This approach may be inefficient as it probes the ltable, rtable
    # to get the attribute values. A better way would be to fill the
    # attribute values from the input list of DataFrames. This attribute values
    # could be harvested (at the expense of some space) while we iterate the
    # input blocker output list for the first time.

    # noinspection PyProtectedMember
    consolidated_data_frame = gh._add_output_attributes(
        deduplicated_tuple_pair_ids, fk_ltable,
        fk_rtable,
        ltable, rtable, l_key, r_key,
        l_output_attrs, r_output_attrs,
        l_prefix,
        r_prefix,
        validate=False)
    # Sort the DataFrame ordered by fk_ltable and fk_rtable.
    # The function "sort" will be depreciated in the newer versions of
    # pandas DataFrame, and it will replaced by 'sort_values' function. So we
    # will first try to use sort_values if this fails we will use sort.
    try:
        consolidated_data_frame.sort_values([fk_ltable, fk_rtable],
                                            inplace=True)
    except AttributeError:
        consolidated_data_frame.sort([fk_ltable, fk_rtable], inplace=True)

    # update the catalog for the consolidated DataFrame
    # First get a column name for the key
    key = ch.get_name_for_key(consolidated_data_frame.columns)
    # Second, add the column name as the key
    consolidated_data_frame = ch.add_key_column(consolidated_data_frame, key)
    # Third, reset the index to remove any out of order index  values from
    # the sort.
    consolidated_data_frame.reset_index(inplace=True, drop=True)
    # Finally, set the properties for the consolidated DataFrame in the catalog
    cm.set_candset_properties(consolidated_data_frame, key, fk_ltable,
                              fk_rtable, ltable,
                              rtable)

    # Return the consolidated DataFrame
    return consolidated_data_frame
Exemple #27
0
def combine_blocker_outputs_via_union(blocker_output_list,
                                      l_prefix='ltable_',
                                      r_prefix='rtable_',
                                      verbose=False):
    """
    Combines multiple blocker outputs by doing a union of their tuple pair
    ids (foreign key ltable, foreign key rtable).

    Specifically, this function takes in a list of DataFrames (candidate
    sets, typically the
    output from blockers) and returns a consolidated DataFrame. The output
    DataFrame contains the union of tuple pair ids (foreign key ltable,
    foreign key rtable) and other attributes from the input list of DataFrames.

    This function makes some assumptions about the input DataFrames. First,
    each DataFrame is expected to contain the following metadata in the
    catalog: key, fk_ltable, fk_rtable, ltable, and rtable. Second,
    all the DataFrames must be a result of blocking from the same underlying
    tables. Concretely the ltable and rtable properties must refer to the
    same DataFrame across all the input tables. Third, all the input
    DataFrames must have the same fk_ltable and fk_rtable properties.
    Finally, in each input DataFrame, for the attributes included from the
    ltable or rtable, the attribute names must be prefixed with the given
    l_prefix and r_prefix in the function.

    The input DataFrames may contain different attribute lists and it demands
    the question of how to combine them. Currently py_entitymatching takes an union
    of attribute names that has prefix l_prefix or r_prefix across
    input tables. After taking the union, for each tuple id pair included
    in output, the attribute values (for union-ed attribute names) are
    probed from ltable/rtable and included in the output.

    A subtle point to note here is,  if an input DataFrame has a column
    added by user (say label for some reason), then that column will not
    be present in the output. The reason is, the same column may not be
    present in other candidate sets so it is not clear about how to
    combine them. One possibility is to include label in output for all
    tuple id pairs, but set as NaN for the values not present. Currently
    py_entitymatching does not include such columns and addressing it will be part
    of future work.

    Args:
        blocker_output_list (list of DataFrames): The list of DataFrames that
            should be combined.
        l_prefix (string): The prefix given to the attributes from the ltable.
        r_prefix (string): The prefix given to the attributes from the rtable.
        verbose (boolean): A flag to indicate whether more detailed information
            about the execution steps should be printed out (default value is
            False).

    Returns:
        A new DataFrame with the combined tuple pairs and other attributes from
        all the blocker lists.

    Raises:
        AssertionError: If `l_prefix` is not of type string.
        AssertionError: If `r_prefix` is not of type string.
        AssertionError: If the length of the input DataFrame list is 0.
        AssertionError: If `blocker_output_list` is not a list of
            DataFrames.
        AssertionError: If the ltables are different across the input list of
            DataFrames.
        AssertionError: If the rtables are different across the input list of
            DataFrames.
        AssertionError: If the `fk_ltable` values are different across the
            input list of DataFrames.
        AssertionError: If the `fk_rtable` values are different across the
            input list of DataFrames.
    """

    # validate input parameters

    # The l_prefix is expected to be of type string
    if not isinstance(l_prefix, six.string_types):
        logger.error('l_prefix is not of type string')
        raise AssertionError('l_prefix is not of type string')

    # The r_prefix is expected to be of type string
    if not isinstance(r_prefix, six.string_types):
        logger.error('r_prefix is not of type string')
        raise AssertionError('r_prefix is not of type string')

    # We cannot combine empty DataFrame list
    if not len(blocker_output_list) > 0:
        logger.error('There no DataFrames to combine')
        raise AssertionError('There are no DataFrames to combine')

    # Validate the assumptions about the input tables.
    # # 1) All the input object must be DataFrames
    # # 2) All the input DataFrames must have the metadata as that of a
    # candidate set
    # # 3) All the input DataFrames must have the same fk_ltable and fk_rtable
    _validate_lr_tables(blocker_output_list)

    # # Get the ltable and rtable. We take it from the first DataFrame as all
    #  the DataFrames contain the same ltables and rtables
    ltable = cm.get_ltable(blocker_output_list[0])
    rtable = cm.get_rtable(blocker_output_list[0])

    # # Get the fk_ltable and fk_rtable. We take it from the first DataFrame as
    #  all the DataFrames contain the same ltables and rtables
    fk_ltable = cm.get_fk_ltable(blocker_output_list[0])
    fk_rtable = cm.get_fk_rtable(blocker_output_list[0])

    # Retrieve the keys for the ltable and rtables.
    l_key = cm.get_key(ltable)
    r_key = cm.get_key(rtable)

    # Check if the fk_ltable is starting with the given prefix, if not its
    # not an error. Just raise a warning.
    if fk_ltable.startswith(l_prefix) is False:
        logger.warning(
            'Foreign key for ltable is not starting with the given prefix ('
            '%s)', l_prefix)

    # Check if the fk_rtable is starting with the given prefix, if not its
    # not an error. Just raise a warning.
    if fk_rtable.startswith(r_prefix) is False:
        logger.warning(
            'Foreign key for rtable is not starting with the given prefix ('
            '%s)', r_prefix)

    # Initialize lists
    # # keep track of projected tuple pair ids
    tuple_pair_ids = []
    # # keep track of output attributes from the left table
    l_output_attrs = []
    # # keep track of output attributes from the right table
    r_output_attrs = []

    # for each DataFrame in the given list, project out tuple pair ids, get the
    #  attributes from the ltable and rtable
    for data_frame in blocker_output_list:
        # Project out the tuple pair ids. A tuple pair id is a fk_ltable,
        # fk_rtable pair
        projected_tuple_pair_ids = data_frame[[fk_ltable, fk_rtable]]
        # Update the list that tracks tuple pair ids
        tuple_pair_ids.append(projected_tuple_pair_ids)

        # Get the columns, which should be segregated into the attributes
        # from the ltable and table
        col_set = (gh.list_diff(list(data_frame.columns),
                                [fk_ltable, fk_rtable,
                                 cm.get_key(data_frame)]))

        # Segregate the columns as attributes from the ltable and rtable
        l_attrs, r_attrs = _lr_cols(col_set, l_prefix, r_prefix)

        # Update the l_output_attrs, r_output_attrs
        l_output_attrs.extend(l_attrs)
        # the reason we use extend because l_attrs a list
        r_output_attrs.extend(r_attrs)

    ch.log_info(
        logger, 'Concatenating the tuple pair ids across given '
        'blockers ...', verbose)

    # concatenate the tuple pair ids from the list of input DataFrames
    concatenated_tuple_pair_ids = pd.concat(tuple_pair_ids)

    ch.log_info(logger, 'Concatenating the tuple pair ids ... DONE', verbose)
    ch.log_info(logger, 'Deduplicating the tuple pair ids ...', verbose)

    # Deduplicate the DataFrame. Now the returned DataFrame will contain
    # unique tuple pair ids.

    # noinspection PyUnresolvedReferences
    deduplicated_tuple_pair_ids = concatenated_tuple_pair_ids.drop_duplicates()

    ch.log_info(logger, 'Deduplicating the tuple pair ids ... DONE', verbose)

    # Construct output table
    # # Get unique list of attributes across different tables
    l_output_attrs = gh.list_drop_duplicates(l_output_attrs)
    r_output_attrs = gh.list_drop_duplicates(r_output_attrs)

    # Reset the index that might have lingered from concatenation.
    deduplicated_tuple_pair_ids.reset_index(inplace=True, drop=True)

    # Add the output attribtues from the ltable and rtable.
    # NOTE: This approach may be inefficient as it probes the ltable, rtable
    # to get the attribute values. A better way would be to fill the
    # attribute values from the input list of DataFrames. This attribute values
    # could be harvested (at the expense of some space) while we iterate the
    # input blocker output list for the first time.

    # noinspection PyProtectedMember
    consolidated_data_frame = gh._add_output_attributes(
        deduplicated_tuple_pair_ids,
        fk_ltable,
        fk_rtable,
        ltable,
        rtable,
        l_key,
        r_key,
        l_output_attrs,
        r_output_attrs,
        l_prefix,
        r_prefix,
        validate=False)
    # Sort the DataFrame ordered by fk_ltable and fk_rtable.
    # The function "sort" will be depreciated in the newer versions of
    # pandas DataFrame, and it will replaced by 'sort_values' function. So we
    # will first try to use sort_values if this fails we will use sort.
    try:
        consolidated_data_frame.sort_values([fk_ltable, fk_rtable],
                                            inplace=True)
    except AttributeError:
        consolidated_data_frame.sort([fk_ltable, fk_rtable], inplace=True)

    # update the catalog for the consolidated DataFrame
    # First get a column name for the key
    key = ch.get_name_for_key(consolidated_data_frame.columns)
    # Second, add the column name as the key
    consolidated_data_frame = ch.add_key_column(consolidated_data_frame, key)
    # Third, reset the index to remove any out of order index  values from
    # the sort.
    consolidated_data_frame.reset_index(inplace=True, drop=True)
    # Finally, set the properties for the consolidated DataFrame in the catalog
    cm.set_candset_properties(consolidated_data_frame, key, fk_ltable,
                              fk_rtable, ltable, rtable)

    # Return the consolidated DataFrame
    return consolidated_data_frame
 def test_get_fk_ltable_valid(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b)
     C = read_csv_metadata(path_c, ltable=A, rtable=B)
     self.assertEqual(cm.get_fk_ltable(C), cm.get_property(C, 'fk_ltable'))
     self.assertEqual(cm.get_fk_ltable(C), 'ltable_ID')
 def test_validate_and_set_fk_ltable_valid(self):
     A = read_csv_metadata(path_a)
     B = read_csv_metadata(path_b)
     C = pd.read_csv(path_c)
     cm.validate_and_set_fk_ltable(C, 'ltable_ID', A, 'ID')
     self.assertEqual(cm.get_fk_ltable(C), 'ltable_ID')
 def test_get_fk_ltable_invalid_df(self):
     cm.get_fk_ltable(None)