-
Notifications
You must be signed in to change notification settings - Fork 0
feat: sheet-checking-and-inspections #91
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
Open
g-pechorin
wants to merge
10
commits into
main
Choose a base branch
from
inspection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
fd3f862
adds an inspection function and a simple test of it
ca299fc
explicit imports in test
7061e7d
use dataclasses
6c1a3f8
Potential fix for pull request finding 'Explicit returns mixed with i…
g-pechorin f259669
fixed error
8927840
Merge branch 'inspection' of github.com:Health-Informatics-UoN/nuh-he…
79e1bcd
Merge branch 'main' into inspection
g-pechorin bb2ddf9
Potential fix for pull request finding 'Unused import'
g-pechorin f322878
typo
de839e7
organized imports
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| """This contains an inspection function and error record type to determine if a | ||
| spreadsheet has data in abnormal places. it's mean tot check for "little notes" which | ||
| are outside of the CDM and may have undocumented patient data""" | ||
|
|
||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
|
|
||
| from openpyxl.cell.cell import Cell | ||
| from openpyxl.worksheet.worksheet import Worksheet | ||
|
|
||
|
|
||
| class Error: | ||
| """base class for the errors. has a simplified __eq__ for `assert error in list`""" | ||
|
|
||
|
|
||
| @dataclass | ||
| class ExcessRows(Error): | ||
| """error indicating that there are extra rows in a spreadsheet that don't have a | ||
| patient id and won't be shifted""" | ||
|
|
||
| sheet_name: str | ||
| excess: list[int] | ||
|
|
||
|
|
||
| @dataclass | ||
| class UnlabeledColumns(Error): | ||
|
github-code-quality[bot] marked this conversation as resolved.
Fixed
|
||
| """indication that there are columns with data but no header; probably notes in the | ||
| margin about missing tests or (previously) dates related to patient's treatment to | ||
| explain the data in the spreadsheet.""" | ||
|
|
||
| sheet_name: str | ||
| columns: list[int] | ||
|
|
||
|
|
||
| @dataclass | ||
| class PatientColumnMissing(Error): | ||
|
github-code-quality[bot] marked this conversation as resolved.
Fixed
|
||
| """used to indicate that the patien column wasn't found in the spreadsheet""" | ||
| sheet_name: str | ||
| label: str | ||
|
|
||
|
|
||
| def format_errors(errors: list[Error]) -> str: | ||
|
github-code-quality[bot] marked this conversation as resolved.
Fixed
|
||
| """formats a collection of error objects into a human digestible string""" | ||
| message: str = "" | ||
| names = [] | ||
|
|
||
| # group the errors by sheet names | ||
| for error in errors: | ||
| if error.sheet_name not in names: | ||
| names.append(error.sheet_name) | ||
|
|
||
| for sheet_name in names: | ||
| message += f"on sheet {sheet_name=} ...\n" | ||
| for error in errors: | ||
| if error.sheet_name != sheet_name: | ||
| continue | ||
| match error: | ||
| case ExcessRows(): | ||
| message += ( | ||
| f"\tthere were {len(error.excess)} rows with data but no " | ||
| + "patient ID\n" | ||
| ) | ||
| message += f"\t\t{error.excess}\n" | ||
| case UnlabeledColumns(): | ||
| message += ( | ||
| f"\tthere were {len(error.columns)} columns with no data " | ||
| + "in their label\n" | ||
| ) | ||
| message += f"\t\t{error.columns}\n" | ||
| case PatientColumnMissing(): | ||
| label = error.label | ||
| message += f"\tthere was no patient column {label=}\n" | ||
| return message | ||
|
|
||
|
|
||
| def inspect(sheet_file: Path, sheet_configs: dict) -> list[Error]: | ||
| """Find data that's out of bounds in the spreadsheet. Uses the date-shifting | ||
| sheet_configs structure. Rather than throw exceptions, this returns a list of Error | ||
| objects that can be inspected or tested for.""" | ||
|
|
||
| from openpyxl import load_workbook | ||
|
|
||
| errors: list[Error] = [] | ||
|
|
||
| workbook = load_workbook(sheet_file, read_only=True, rich_text=False) | ||
| for sheet_name in workbook.sheetnames: | ||
| if sheet_name not in sheet_configs: | ||
| print(f"skipping sheet {sheet_name=} since there's no config for it") | ||
| continue | ||
|
|
||
| sheet = workbook[sheet_name] | ||
|
|
||
| # scan the header row to find out what the bounds of the spreadsheet should be | ||
| header_row = sheet_configs[sheet_name]["header_row"] | ||
| patient_id_col_text = sheet_configs[sheet_name]["patient_id_col"] | ||
| skip_rows = sheet_configs[sheet_name]["skip_rows_after_header"] | ||
|
|
||
| # we'll want to use the index in later checks | ||
| patient_id_col_index: None | int = None | ||
|
|
||
| # record the "blank" columns in the | ||
| blanks: list[int] = [] | ||
|
|
||
| # check each cell of the header | ||
| for col in range(0, sheet.max_column): | ||
| value = sheet.cell(header_row + 1, col + 1) | ||
| if blank_cell(value): | ||
| blanks.append(col) | ||
| elif value.value == patient_id_col_text: | ||
| patient_id_col_index = col | ||
|
|
||
| if blanks: | ||
| errors.append(UnlabeledColumns(sheet_name, blanks)) | ||
|
|
||
| # we can't do any further checks without the patient_id_col_index | ||
| if patient_id_col_index is None: | ||
| errors.append(PatientColumnMissing(sheet_name, patient_id_col_text)) | ||
| else: | ||
| excess = [] | ||
|
|
||
| # find any rows with data but no patient id | ||
| for row in range(0, sheet.max_row): | ||
| if row in skip_rows or row == header_row: | ||
| continue | ||
|
|
||
| # we will allow "blank" rows | ||
| # ... such as empty rows between groups of patients | ||
| should_be_blank = blank_cell( | ||
| sheet.cell(row + 1, patient_id_col_index + 1) | ||
| ) | ||
|
|
||
| # to allow "whitespace rows" we only check rows without a patient id | ||
| if should_be_blank and not blank_row(sheet, row): | ||
| excess.append(row) | ||
|
|
||
| if excess: | ||
| errors.append(ExcessRows(sheet_name, excess)) | ||
|
|
||
| return errors | ||
|
|
||
|
|
||
| def blank_cell(cell: Cell) -> bool: | ||
| """tests if a cell value is blank""" | ||
| return str(cell.value).strip() == "" or cell.value is None | ||
|
|
||
|
|
||
| def blank_row(sheet: Worksheet, row: int) -> bool: | ||
| """tests if a row of a Worksheet is blank""" | ||
| for c in range(0, sheet.max_column): | ||
| cell = sheet.cell(row + 1, c + 1) | ||
| if not blank_cell(cell): | ||
| return False | ||
| return True | ||
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| from nuh_helper.date_shift.validation import ( | ||
| ExcessRows, | ||
| Path, | ||
| UnlabeledColumns, | ||
| format_errors, | ||
| inspect, | ||
| ) | ||
|
|
||
|
|
||
| def test_inspect() -> None: | ||
| """ | ||
|
|
||
| https://github.com/Health-Informatics-UoN/nuh-helper/issues/78 | ||
|
|
||
| https://github.com/Health-Informatics-UoN/nuh-helper/issues/8 | ||
| """ | ||
|
|
||
| patients_src = Path(__file__).parent / "data/patients2with-extra-data.xlsx" | ||
|
|
||
| errors = inspect(patients_src, sheet_configs) | ||
|
|
||
| message = format_errors(errors) | ||
| print(">>>") | ||
| print(message) | ||
| print("<<<") | ||
|
|
||
| assert ExcessRows("measurements", [14]) in errors | ||
| assert UnlabeledColumns("measurements", [3, 4]) in errors | ||
|
|
||
| assert len(errors) == 2 | ||
|
|
||
|
|
||
| sheet_configs = { | ||
| "patients": { | ||
| "patient_id_col": "patient_id", | ||
| "header_row": 0, | ||
| "skip_rows_after_header": [], | ||
| "date_columns": [ | ||
| "dob", | ||
| "last_alive", | ||
| ], | ||
| }, | ||
| "results": { | ||
| "patient_id_col": "patient_id", | ||
| "header_row": 0, | ||
| "skip_rows_after_header": [], | ||
| "date_columns": [ | ||
| "date_result", | ||
| ], | ||
| }, | ||
| "measurements": { | ||
| "patient_id_col": "p_id", | ||
| "header_row": 1, | ||
| "skip_rows_after_header": [2, 3], | ||
| "date_columns": [ | ||
| "date8061", | ||
| ], | ||
| }, | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.