-
Notifications
You must be signed in to change notification settings - Fork 16
Refactor doctor_visits: Load source file only once #1978
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
minhkhul
wants to merge
32
commits into
main
Choose a base branch
from
doctor_visits_refactor_for_speed
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 16 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
c639049
replace modify_claims_drops with direct modification in update_sensor
minhkhul 1dd80be
cleanup Config
minhkhul 749ed2d
cleanup Config
minhkhul 9d8d521
change test
minhkhul ca38bb7
lint
minhkhul 17259d0
fix test geomap
minhkhul 6d841da
lint
minhkhul 4ec46df
lint
minhkhul 9740899
adding logging for comparing processing time
aysim319 aacc545
using dask for read/write large files
aysim319 dbde5c7
undo testing change and also using datetime instead of str for date p…
aysim319 1394d3d
refactored reading into seperate function
aysim319 dfc3be2
organizing code
aysim319 e07c697
only procesing once and passing along the dataframe
aysim319 d1ee4ce
added/updated tests
aysim319 fc2c58d
Merge pull request #1981 from cmu-delphi/optimize_with_dask
aysim319 b52d80a
in progress cleaning up writing csv
aysim319 58b51a6
Merge branch 'main' into doctor_visits_refactor_for_speed
minhkhul 81381d6
optimized write_csv
aysim319 bfa853a
lint
aysim319 073651f
reverting to assert
aysim319 dd06a91
cleaning more stuff
aysim319 4ddd5a0
version locking at 2024.6 due to pandas
aysim319 593279b
aligned preprocessing to match current & rollback write for consisten…
aysim319 9920821
pip versioning
aysim319 cd83691
rewording variable and also ensure that column order is the same
aysim319 79c34d3
Update doctor_visits/setup.py
aysim319 7896042
latest version supported for 3.8 is 2023.5.*
aysim319 e2f7953
fix param
aysim319 a4f67c0
added notes for when we upgrade to 3.9+
aysim319 9408c81
reverting unneeded change
aysim319 b2f8b0e
merge with main
aysim319 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
Binary file removed
BIN
-6.26 MB
doctor_visits/delphi_doctor_visits/input/SYNEDI_AGG_OUTPATIENT_18052020_1455CDT.csv.gz
Binary file not shown.
This file was deleted.
Oops, something went wrong.
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,101 @@ | ||
import dask.dataframe as dd | ||
from datetime import datetime | ||
import numpy as np | ||
import pandas as pd | ||
from pathlib import Path | ||
|
||
from .config import Config | ||
|
||
|
||
def write_to_csv(output_df: pd.DataFrame, geo_level: str, se:bool, out_name: str, logger, output_path="."): | ||
"""Write sensor values to csv. | ||
|
||
Args: | ||
output_dict: dictionary containing sensor rates, se, unique dates, and unique geo_id | ||
geo_level: geographic resolution, one of ["county", "state", "msa", "hrr", "nation", "hhs"] | ||
se: boolean to write out standard errors, if true, use an obfuscated name | ||
out_name: name of the output file | ||
output_path: outfile path to write the csv (default is current directory) | ||
""" | ||
if se: | ||
logger.info(f"========= WARNING: WRITING SEs TO {out_name} =========") | ||
|
||
out_n = 0 | ||
for d in set(output_df["date"]): | ||
filename = "%s/%s_%s_%s.csv" % (output_path, | ||
(d + Config.DAY_SHIFT).strftime("%Y%m%d"), | ||
geo_level, | ||
out_name) | ||
single_date_df = output_df[output_df["date"] == d] | ||
with open(filename, "w") as outfile: | ||
outfile.write("geo_id,val,se,direction,sample_size\n") | ||
|
||
for line in single_date_df.itertuples(): | ||
geo_id = line.geo_id | ||
sensor = 100 * line.val # report percentages | ||
se_val = 100 * line.se | ||
assert not np.isnan(sensor), "sensor value is nan, check pipeline" | ||
assert sensor < 90, f"strangely high percentage {geo_id, sensor}" | ||
if not np.isnan(se_val): | ||
assert se_val < 5, f"standard error suspiciously high! investigate {geo_id}" | ||
|
||
if se: | ||
assert sensor > 0 and se_val > 0, "p=0, std_err=0 invalid" | ||
outfile.write( | ||
"%s,%f,%s,%s,%s\n" % (geo_id, sensor, se_val, "NA", "NA")) | ||
else: | ||
# for privacy reasons we will not report the standard error | ||
outfile.write( | ||
"%s,%f,%s,%s,%s\n" % (geo_id, sensor, "NA", "NA", "NA")) | ||
out_n += 1 | ||
aysim319 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
logger.debug(f"wrote {out_n} rows for {geo_level}") | ||
|
||
|
||
def csv_to_df(filepath: str, startdate: datetime, enddate: datetime, dropdate: datetime, logger) -> pd.DataFrame: | ||
''' | ||
Reads csv using Dask and filters out based on date range and currently unused column, | ||
then converts back into pandas dataframe. | ||
Parameters | ||
---------- | ||
filepath: path to the aggregated doctor-visits data | ||
startdate: first sensor date (YYYY-mm-dd) | ||
enddate: last sensor date (YYYY-mm-dd) | ||
dropdate: data drop date (YYYY-mm-dd) | ||
|
||
------- | ||
''' | ||
filepath = Path(filepath) | ||
logger.info(f"Processing {filepath}") | ||
|
||
ddata = dd.read_csv( | ||
filepath, | ||
compression="gzip", | ||
dtype=Config.DTYPES, | ||
blocksize=None, | ||
) | ||
|
||
ddata = ddata.dropna() | ||
# rename inconsistent column names to match config column names | ||
ddata = ddata.rename(columns=Config.DEVIANT_COLS_MAP) | ||
|
||
ddata = ddata[Config.FILT_COLS] | ||
ddata[Config.DATE_COL] = dd.to_datetime(ddata[Config.DATE_COL]) | ||
|
||
# restrict to training start and end date | ||
startdate = startdate - Config.DAY_SHIFT | ||
|
||
assert startdate > Config.FIRST_DATA_DATE, "Start date <= first day of data" | ||
assert startdate < enddate, "Start date >= end date" | ||
assert enddate <= dropdate, "End date > drop date" | ||
|
||
date_filter = ((ddata[Config.DATE_COL] >= Config.FIRST_DATA_DATE) & (ddata[Config.DATE_COL] < dropdate)) | ||
|
||
df = ddata[date_filter].compute() | ||
|
||
# aggregate age groups (so data is unique by service date and FIPS) | ||
df = df.groupby([Config.DATE_COL, Config.GEO_COL]).sum(numeric_only=True).reset_index() | ||
assert np.sum(df.duplicated()) == 0, "Duplicates after age group aggregation" | ||
assert (df[Config.COUNT_COLS] >= 0).all().all(), "Counts must be nonnegative" | ||
|
||
logger.info(f"Done processing {filepath}") | ||
return df |
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
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 |
---|---|---|
|
@@ -11,6 +11,7 @@ | |
"pytest-cov", | ||
"pytest", | ||
"scikit-learn", | ||
"dask", | ||
] | ||
|
||
setup( | ||
|
Binary file added
BIN
+779 KB
.../tests/comparison/process_data/main_after_date_SYNEDI_AGG_OUTPATIENT_07022020_1455CDT.pkl
Binary file not shown.
Binary file modified
BIN
-7 Bytes
(100%)
doctor_visits/tests/test_data/SYNEDI_AGG_OUTPATIENT_07022020_1455CDT.csv.gz
Binary file not shown.
Binary file added
BIN
+779 KB
doctor_visits/tests/test_data/SYNEDI_AGG_OUTPATIENT_07022020_1455CDT.pkl
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: The following chunk needs a rewrite to simplify.
Use the built-in
pd.write_csv
.itertuples
is slow and unnecessary. The checks/conversions we're doing in theitertuples
loop either can be done in bulk (even before we split by date, actually) or have already been done (e.g. didn't we already multiplyse
by 100? Also assertions on values).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see Dmitry already commented on this with some example code to use.