Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make quality reports fault tolerant on missing relationships in metadata #489

Merged
merged 3 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions sdmetrics/reports/multi_table/_properties/base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""Multi table base property class."""
import warnings

import numpy as np
import pandas as pd

Expand Down Expand Up @@ -33,26 +35,34 @@ def _get_num_iterations(self, metadata):
elif self._num_iteration_case == 'table':
return len(metadata['tables'])
elif self._num_iteration_case == 'relationship':
return len(metadata['relationships'])
try:
return len(metadata['relationships'])
except KeyError as e:
message = f'{type(e).__name__}: {e}. No relationships found in the data.'
warnings.warn(message)
return 0
elif self._num_iteration_case == 'column_pair':
num_columns = [len(table['columns']) for table in metadata['tables'].values()]
return sum([(n_cols * (n_cols - 1)) // 2 for n_cols in num_columns])
elif self._num_iteration_case == 'inter_table_column_pair':
iterations = 0
for relationship in metadata['relationships']:
parent_columns = metadata['tables'][relationship['parent_table_name']]['columns']
child_columns = metadata['tables'][relationship['child_table_name']]['columns']
for relationship in metadata.get('relationships', []):
parent_columns = \
metadata['tables'][relationship['parent_table_name']]['columns']
child_columns = \
metadata['tables'][relationship['child_table_name']]['columns']
iterations += (len(parent_columns) * len(child_columns))
return iterations

def _compute_average(self):
"""Average the scores for each column."""
is_dataframe = isinstance(self.details, pd.DataFrame)
has_score_column = 'Score' in self.details.columns
assert_message = "The property details must be a DataFrame with a 'Score' column."
assert_message = "The property details must be in a DataFrame with a 'Score' column."

assert is_dataframe, assert_message
assert has_score_column, assert_message
if not has_score_column:
return np.nan

return self.details['Score'].mean()

Expand Down
19 changes: 10 additions & 9 deletions sdmetrics/reports/multi_table/_properties/inter_table_trends.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def _generate_details(self, real_data, synthetic_data, metadata, progress_bar=No
The progress bar object. Defaults to None.
"""
all_details = []
for relationship in metadata['relationships']:
for relationship in metadata.get('relationships', []):
parent = relationship['parent_table_name']
child = relationship['child_table_name']
foreign_key = relationship['child_foreign_key']
Expand Down Expand Up @@ -139,15 +139,16 @@ def _generate_details(self, real_data, synthetic_data, metadata, progress_bar=No
details['Column 2'] = details['Column 2'].str.replace(f'{child}.', '', n=1)
all_details.append(details)

self.details = pd.concat(all_details, axis=0).reset_index(drop=True)
detail_columns = [
'Parent Table', 'Child Table', 'Foreign Key', 'Column 1', 'Column 2',
'Metric', 'Score', 'Real Correlation', 'Synthetic Correlation'
]
if 'Error' in self.details.columns:
detail_columns.append('Error')
if len(all_details) > 0:
self.details = pd.concat(all_details, axis=0).reset_index(drop=True)
detail_columns = [
'Parent Table', 'Child Table', 'Foreign Key', 'Column 1', 'Column 2',
'Metric', 'Score', 'Real Correlation', 'Synthetic Correlation'
]
if 'Error' in self.details.columns:
detail_columns.append('Error')

self.details = self.details[detail_columns]
self.details = self.details[detail_columns]

def get_visualization(self, table_name=None):
"""Create a plot to show the inter table trends data.
Expand Down
21 changes: 21 additions & 0 deletions tests/integration/reports/multi_table/test_quality_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,3 +306,24 @@ def test_quality_report_with_errors():
assert score == 0.7008862433862433
pd.testing.assert_frame_equal(properties, expected_properties)
pd.testing.assert_frame_equal(details_column_shapes, expected_details)


def test_quality_report_with_no_relationships():
# Setup
real_data, synthetic_data, metadata = load_demo(modality='multi_table')

del metadata['relationships']
report = QualityReport()

# Run
report.generate(real_data, synthetic_data, metadata, verbose=True)
score = report.get_score()

# Assert
expected_properties = pd.DataFrame({
'Property': ['Column Shapes', 'Column Pair Trends', 'Cardinality', 'Intertable Trends'],
'Score': [0.792262, 0.424967, np.nan, np.nan]
})
properties = report.get_properties()
pd.testing.assert_frame_equal(properties, expected_properties)
assert score == 0.6086142240422239
13 changes: 3 additions & 10 deletions tests/unit/reports/multi_table/_properties/test_base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Test BaseMultiTableProperty class."""

import re
from unittest.mock import Mock

import numpy as np
Expand Down Expand Up @@ -176,21 +175,15 @@ def test__generate_details_raises_error(self):
with pytest.raises(NotImplementedError):
base_property._generate_details(None, None, None, None)

def test__compute_average_raises_error(self):
def test__compute_average_sends_nan(self):
"""Test that the method raises an error when _details has not been computed."""
# Setup
base_property = BaseMultiTableProperty()

# Run and Assert
expected_error_message = re.escape(
"The property details must be a DataFrame with a 'Score' column."
)
with pytest.raises(AssertionError, match=expected_error_message):
base_property._compute_average()

assert np.isnan(base_property._compute_average())
base_property.details = pd.DataFrame({'Column': ['a', 'b', 'c']})
with pytest.raises(AssertionError, match=expected_error_message):
base_property._compute_average()
assert np.isnan(base_property._compute_average())

def test_get_score(self):
"""Test the ``get_score`` method."""
Expand Down
Loading