mirror of
https://github.com/DOI-DO/j40-cejst-2.git
synced 2025-07-29 02:31:17 -07:00
Backend release branch to main (#1822)
* Create deploy_be_staging.yml (#1575) * Imputing income using geographic neighbors (#1559) Imputes income field with a light refactor. Needs more refactor and more tests (I spotchecked). Next ticket will check and address but a lot of "narwhal" architecture is here. * Adding HOLC indicator (#1579) Added HOLC indicator (Historic Redlining Score) from NCRC work; included 3.25 cutoff and low income as part of the housing burden category. * Update backend for Puerto Rico (#1686) * Update PR threshold count to 10 We now show 10 indicators for PR. See the discussion on the github issue for more info: https://github.com/usds/justice40-tool/issues/1621 * Do not use linguistic iso for Puerto Rico Closes 1350. Co-authored-by: Shelby Switzer <shelbyswitzer@gmail.com> * updating * Do not drop Guam and USVI from ETL (#1681) * Remove code that drops Guam and USVI from ETL * Add back code for dropping rows by FIPS code We may want this functionality, so let's keep it and just make the constant currently be an empty array. Co-authored-by: Shelby Switzer <shelbyswitzer@gmail.com> * Emma nechamkin/holc patch (#1742) Removing HOLC calculation from score narwhal. * updating ejscreen data, try two (#1747) * Rescaling linguistic isolation (#1750) Rescales linguistic isolation to drop puerto rico * adds UST indicator (#1786) adds leaky underground storage tanks * Changing LHE in tiles to a boolean (#1767) also includes merging / clean up of the release * added indoor plumbing to chas * added indoor plumbing to score housing burden * added indoor plumbing to score housing burden * first run through * Refactor DOE Energy Burden and COI to use YAML (#1796) * added tribalId for Supplemental dataset (#1804) * Setting zoom levels for tribal map (#1810) * NRI dataset and initial score YAML configuration (#1534) * update be staging gha * NRI dataset and initial score YAML configuration * checkpoint * adding data checks for release branch * passing tests * adding INPUT_EXTRACTED_FILE_NAME to base class * lint * columns to keep and tests * update be staging gha * checkpoint * update be staging gha * NRI dataset and initial score YAML configuration * checkpoint * adding data checks for release branch * passing tests * adding INPUT_EXTRACTED_FILE_NAME to base class * lint * columns to keep and tests * checkpoint * PR Review * renoving source url * tests * stop execution of ETL if there's a YAML schema issue * update be staging gha * adding source url as class var again * clean up * force cache bust * gha cache bust * dynamically set score vars from YAML * docsctrings * removing last updated year - optional reverse percentile * passing tests * sort order * column ordening * PR review * class level vars * Updating DatasetsConfig * fix pylint errors * moving metadata hint back to code Co-authored-by: lucasmbrown-usds <lucas.m.brown@omb.eop.gov> * Correct copy typo (#1809) * Add basic test suite for COI (#1518) * Update COI to use new yaml (#1518) * Add tests for DOE energy budren (1518 * Add dataset config for energy budren (1518) * Refactor ETL to use datasets.yml (#1518) * Add fake GEOIDs to COI tests (#1518) * Refactor _setup_etl_instance_and_run_extract to base (#1518) For the three classes we've done so far, a generic _setup_etl_instance_and_run_extract will work fine, for the moment we can reuse the same setup method until we decide future classes need more flexibility --- but they can also always subclass so... * Add output-path tests (#1518) * Update YAML to match constant (#1518) * Don't blindly set float format (#1518) * Add defaults for extract (#1518) * Run YAML load on all subclasses (#1518) * Update description fields (#1518) * Update YAML per final format (#1518) * Update fixture tract IDs (#1518) * Update base class refactor (#1518) Now that NRI is final I needed to make a small number of updates to my refactored code. * Remove old comment (#1518) * Fix type signature and return (#1518) * Update per code review (#1518) Co-authored-by: Jorge Escobar <83969469+esfoobar-usds@users.noreply.github.com> Co-authored-by: lucasmbrown-usds <lucas.m.brown@omb.eop.gov> Co-authored-by: Vim <86254807+vim-usds@users.noreply.github.com> * Update etl_score_geo.py Yikes! Fixing merge messup! * Create deploy_be_staging.yml (#1575) * Imputing income using geographic neighbors (#1559) Imputes income field with a light refactor. Needs more refactor and more tests (I spotchecked). Next ticket will check and address but a lot of "narwhal" architecture is here. * Adding HOLC indicator (#1579) Added HOLC indicator (Historic Redlining Score) from NCRC work; included 3.25 cutoff and low income as part of the housing burden category. * Update backend for Puerto Rico (#1686) * Update PR threshold count to 10 We now show 10 indicators for PR. See the discussion on the github issue for more info: https://github.com/usds/justice40-tool/issues/1621 * Do not use linguistic iso for Puerto Rico Closes 1350. Co-authored-by: Shelby Switzer <shelbyswitzer@gmail.com> * updating * Do not drop Guam and USVI from ETL (#1681) * Remove code that drops Guam and USVI from ETL * Add back code for dropping rows by FIPS code We may want this functionality, so let's keep it and just make the constant currently be an empty array. Co-authored-by: Shelby Switzer <shelbyswitzer@gmail.com> * Emma nechamkin/holc patch (#1742) Removing HOLC calculation from score narwhal. * updating ejscreen data, try two (#1747) * Rescaling linguistic isolation (#1750) Rescales linguistic isolation to drop puerto rico * adds UST indicator (#1786) adds leaky underground storage tanks * Changing LHE in tiles to a boolean (#1767) also includes merging / clean up of the release * added indoor plumbing to chas * added indoor plumbing to score housing burden * added indoor plumbing to score housing burden * first run through * Refactor DOE Energy Burden and COI to use YAML (#1796) * added tribalId for Supplemental dataset (#1804) * Setting zoom levels for tribal map (#1810) * NRI dataset and initial score YAML configuration (#1534) * update be staging gha * NRI dataset and initial score YAML configuration * checkpoint * adding data checks for release branch * passing tests * adding INPUT_EXTRACTED_FILE_NAME to base class * lint * columns to keep and tests * update be staging gha * checkpoint * update be staging gha * NRI dataset and initial score YAML configuration * checkpoint * adding data checks for release branch * passing tests * adding INPUT_EXTRACTED_FILE_NAME to base class * lint * columns to keep and tests * checkpoint * PR Review * renoving source url * tests * stop execution of ETL if there's a YAML schema issue * update be staging gha * adding source url as class var again * clean up * force cache bust * gha cache bust * dynamically set score vars from YAML * docsctrings * removing last updated year - optional reverse percentile * passing tests * sort order * column ordening * PR review * class level vars * Updating DatasetsConfig * fix pylint errors * moving metadata hint back to code Co-authored-by: lucasmbrown-usds <lucas.m.brown@omb.eop.gov> * Correct copy typo (#1809) * Add basic test suite for COI (#1518) * Update COI to use new yaml (#1518) * Add tests for DOE energy budren (1518 * Add dataset config for energy budren (1518) * Refactor ETL to use datasets.yml (#1518) * Add fake GEOIDs to COI tests (#1518) * Refactor _setup_etl_instance_and_run_extract to base (#1518) For the three classes we've done so far, a generic _setup_etl_instance_and_run_extract will work fine, for the moment we can reuse the same setup method until we decide future classes need more flexibility --- but they can also always subclass so... * Add output-path tests (#1518) * Update YAML to match constant (#1518) * Don't blindly set float format (#1518) * Add defaults for extract (#1518) * Run YAML load on all subclasses (#1518) * Update description fields (#1518) * Update YAML per final format (#1518) * Update fixture tract IDs (#1518) * Update base class refactor (#1518) Now that NRI is final I needed to make a small number of updates to my refactored code. * Remove old comment (#1518) * Fix type signature and return (#1518) * Update per code review (#1518) Co-authored-by: Jorge Escobar <83969469+esfoobar-usds@users.noreply.github.com> Co-authored-by: lucasmbrown-usds <lucas.m.brown@omb.eop.gov> Co-authored-by: Vim <86254807+vim-usds@users.noreply.github.com> * Update etl_score_geo.py Yikes! Fixing merge messup! * updated to fix linting errors (#1818) Cleans and updates base branch * Adding back MapComparison video * Add FUDS ETL (#1817) * Add spatial join method (#1871) Since we'll need to figure out the tracts for a large number of points in future tickets, add a utility to handle grabbing the tract geometries and adding tract data to a point dataset. * Add FUDS, also jupyter lab (#1871) * Add YAML configs for FUDS (#1871) * Allow input geoid to be optional (#1871) * Add FUDS ETL, tests, test-datae noteobook (#1871) This adds the ETL class for Formerly Used Defense Sites (FUDS). This is different from most other ETLs since these FUDS are not provided by tract, but instead by geographic point, so we need to assign FUDS to tracts and then do calculations from there. * Floats -> Ints, as I intended (#1871) * Floats -> Ints, as I intended (#1871) * Formatting fixes (#1871) * Add test false positive GEOIDs (#1871) * Add gdal binaries (#1871) * Refactor pandas code to be more idiomatic (#1871) Per Emma, the more pandas-y way of doing my counts is using np.where to add the values i need, then groupby and size. It is definitely more compact, and also I think more correct! * Update configs per Emma suggestions (#1871) * Type fixed! (#1871) * Remove spurious import from vscode (#1871) * Snapshot update after changing col name (#1871) * Move up GDAL (#1871) * Adjust geojson strategy (#1871) * Try running census separately first (#1871) * Fix import order (#1871) * Cleanup cache strategy (#1871) * Download census data from S3 instead of re-calculating (#1871) * Clarify pandas code per Emma (#1871) * Disable markdown check for link * Adding DOT composite to travel score (#1820) This adds the DOT dataset to the ETL and to the score. Note that currently we take a percentile of an average of percentiles. * Adding first street foundation data (#1823) Adding FSF flood and wildfire risk datasets to the score. * first run -- adding NCLD data to the ETL, but not yet to the score * Add abandoned mine lands data (#1824) * Add notebook to generate test data (#1780) * Add Abandoned Mine Land data (#1780) Using a similar structure but simpler apporach compared to FUDs, add an indicator for whether a tract has an abandonded mine. * Adding some detail to dataset readmes Just a thought! * Apply feedback from revieiw (#1780) * Fixup bad string that broke test (#1780) * Update a string that I should have renamed (#1780) * Reduce number of threads to reduce memory pressure (#1780) * Try not running geo data (#1780) * Run the high-memory sets separately (#1780) * Actually deduplicate (#1780) * Add flag for memory intensive ETLs (#1780) * Document new flag for datasets (#1780) * Add flag for new datasets fro rebase (#1780) Co-authored-by: Emma Nechamkin <97977170+emma-nechamkin@users.noreply.github.com> * Adding NLCD data (#1826) Adding NLCD's natural space indicator end to end to the score. * Add donut hole calculation to score (#1828) Adds adjacency index to the pipeline. Requires thorough QA * Adding eamlis and fuds data to legacy pollution in score (#1832) Update to add EAMLIS and FUDS data to score * Update to use new FSF files (#1838) backend is partially done! * Quick fix to kitchen or plumbing indicator Yikes! I think I messed something up and dropped the pctile field suffix from when the KP score gets calculated. Fixing right quick. * Fast flag update (#1844) Added additional flags for the front end based on our conversation in stand up this morning. * Tiles fix (#1845) Fixes score-geo and adds flags * Update etl_score_geo.py * Issue 1827: Add demographics to tiles and download files (#1833) * Adding demographics for use in sidebar and download files * Updates backend constants to N (#1854) * updated to show T/F/null vs T/F for AML and FUDS (#1866) * fix markdown * just testing that the boolean is preserved on gha * checking drop tracts works * OOPS! Old changes persisted * adding a check to the agvalue calculation for nri * updated with error messages * updated error message * tuple type * Score tests (#1847) * update Python version on README; tuple typing fix * Alaska tribal points fix (#1821) * Bump mistune from 0.8.4 to 2.0.3 in /data/data-pipeline (#1777) Bumps [mistune](https://github.com/lepture/mistune) from 0.8.4 to 2.0.3. - [Release notes](https://github.com/lepture/mistune/releases) - [Changelog](https://github.com/lepture/mistune/blob/master/docs/changes.rst) - [Commits](https://github.com/lepture/mistune/compare/v0.8.4...v2.0.3) --- updated-dependencies: - dependency-name: mistune dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * poetry update * initial pass of score tests * add threshold tests * added ses threshold (not donut, not island) * testing suite -- stopping for the day * added test for lead proxy indicator * Refactor score tests to make them less verbose and more direct (#1865) * Cleanup tests slightly before refactor (#1846) * Refactor score calculations tests * Feedback from review * Refactor output tests like calculatoin tests (#1846) (#1870) * Reorganize files (#1846) * Switch from lru_cache to fixture scorpes (#1846) * Add tests for all factors (#1846) * Mark smoketests and run as part of be deply (#1846) * Update renamed var (#1846) * Switch from named tuple to dataclass (#1846) This is annoying, but pylint in python3.8 was crashing parsing the named tuple. We weren't using any namedtuple-specific features, so I made the type a dataclass just to get pylint to behave. * Add default timout to requests (#1846) * Fix type (#1846) * Fix merge mistake on poetry.lock (#1846) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Jorge Escobar <jorge.e.escobar@omb.eop.gov> Co-authored-by: Jorge Escobar <83969469+esfoobar-usds@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Matt Bowen <83967628+mattbowen-usds@users.noreply.github.com> Co-authored-by: matt bowen <matthew.r.bowen@omb.eop.gov> * just testing that the boolean is preserved on gha (#1867) * updated with hopefully a fix; coercing aml, fuds, hrs to booleans for the raw value to preserve null character. * Adding tests to ensure proper calculations (#1871) * just testing that the boolean is preserved on gha * checking drop tracts works * adding a check to the agvalue calculation for nri * updated with error messages * tribal tiles fix (#1874) * Alaska tribal points fix (#1821) * tribal tiles fix * disabling child opportunity * lint * removing COI * removing commented out code * Pipeline tile tests (#1864) * temp update * updating with fips check * adding check on pfs * updating with pfs test * Update test_tiles_smoketests.py * Fix lint errors (#1848) * Add column names test (#1848) * Mark tests as smoketests (#1848) * Move to other score-related tests (#1848) * Recast Total threshold criteria exceeded to int (#1848) In writing tests to verify the output of the tiles csv matches the final score CSV, I noticed TC/Total threshold criteria exceeded was getting cast from an int64 to a float64 in the process of PostScoreETL. I tracked it down to the line where we merge the score dataframe with constants.DATA_CENSUS_CSV_FILE_PATH --- there where > 100 tracts in the national census CSV that don't exist in the score, so those ended up with a Total threshhold count of np.nan, which is a float, and thereby cast those columns to float. For the moment I just cast it back. * No need for low memeory (#1848) * Add additional tests of tiles.csv (#1848) * Drop pre-2010 rows before computing score (#1848) Note this is probably NOT the optimal place for this change; it might make more sense for each source to filter its own tracts down to the acceptable tract list. However, that would be a pretty invasive change, where this is central and plenty of other things are happening in score transform that could be moved to sources, so for today, here's where the change will live. * Fix typo (#1848) * Switch from filter to inner join (#1848) * Remove no-op lines from tiles (#1848) * Apply feedback from review, linter (#1848) * Check the values oeverything in the frame (#1848) * Refactor checker class (#1848) * Add test for state names (#1848) * cleanup from reviewing my own code (#1848) * Fix lint error (#1858) * Apply Emma's feedback from review (#1848) * Remove refs to national_df (#1848) * Account for new, fake nullable bools in tiles (#1848) To handle a geojson limitation, Emma converted some nullable boolean colunms to float64 in the tiles export with the values {0.0, 1.0, nan}, giving us the same expressiveness. Sadly, this broke my assumption that all columns between the score and tiles csvs would have the same dtypes, so I need to account for these new, fake bools in my test. * Use equals instead of my worse version (#1848) * Missed a spot where we called _create_score_data (#1848) * Update per safety (#1848) Co-authored-by: matt bowen <matthew.r.bowen@omb.eop.gov> * Add tests to make sure each source makes it to the score correctly (#1878) * Remove unused persistent poverty from score (#1835) * Test a few datasets for overlap in the final score (#1835) * Add remaining data sources (#1853) * Apply code-review feedback (#1835) * Rearrange a little for readabililty (#1835) * Add tract test (#1835) * Add test for score values (#1835) * Check for unmatched source tracts (#1835) * Cleanup numeric code to plaintext (#1835) * Make import more obvious (#1835) * Updating traffic barriers to include low pop threshold (#1889) Changing the traffic barriers to only be included for places with recorded population * Remove no land tracts from map (#1894) remove from map * Issue 1831: missing life expectancy data from Maine and Wisconsin (#1887) * Fixing missing states and adding tests for states to all classes * Removing low pop tracts from FEMA population loss (#1898) dropping 0 population from FEMA * 1831 Follow up (#1902) This code causes no functional change to the code. It does two things: 1. Uses difference instead of - to improve code style for working with sets. 2. Removes the line EXPECTED_MISSING_STATES = ["02", "15"], which is now redundant because of the line I added (in a previous pull request) of ALASKA_AND_HAWAII_EXPECTED_IN_DATA = False. * Add tests for all non-census sources (#1899) * Refactor CDC life-expectancy (1554) * Update to new tract list (#1554) * Adjust for tests (#1848) * Add tests for cdc_places (#1848) * Add EJScreen tests (#1848) * Add tests for HUD housing (#1848) * Add tests for GeoCorr (#1848) * Add persistent poverty tests (#1848) * Update for sources without zips, for new validation (#1848) * Update tests for new multi-CSV but (#1848) Lucas updated the CDC life expectancy data to handle a bug where two states are missing from the US Overall download. Since virtually none of our other ETL classes download multiple CSVs directly like this, it required a pretty invasive new mocking strategy. * Add basic tests for nature deprived (#1848) * Add wildfire tests (#1848) * Add flood risk tests (#1848) * Add DOT travel tests (#1848) * Add historic redlining tests (#1848) * Add tests for ME and WI (#1848) * Update now that validation exists (#1848) * Adjust for validation (#1848) * Add health insurance back to cdc places (#1848) Ooops * Update tests with new field (#1848) * Test for blank tract removal (#1848) * Add tracts for clipping behavior * Test clipping and zfill behavior (#1848) * Fix bad test assumption (#1848) * Simplify class, add test for tract padding (#1848) * Fix percentage inversion, update tests (#1848) Looking through the transformations, I noticed that we were subtracting a percentage that is usually between 0-100 from 1 instead of 100, and so were endind up with some surprising results. Confirmed with lucasmbrown-usds * Add note about first street data (#1848) * Issue 1900: Tribal overlap with Census tracts (#1903) * working notebook * updating notebook * wip * fixing broken tests * adding tribal overlap files * WIP * WIP * WIP, calculated count and names * working * partial cleanup * partial cleanup * updating field names * fixing bug * removing pyogrio * removing unused imports * updating test fixtures to be more realistic * cleaning up notebook * fixing black * fixing flake8 errors * adding tox instructions * updating etl_score * suppressing warning * Use projected CRSes, ignore geom types (#1900) I looked into this a bit, and in general the geometry type mismatch changes very little about the calculation; we have a mix of multipolygons and polygons. The fastest thing to do is just not keep geom type; I did some runs with it set to both True and False, and they're the same within 9 digits of precision. Logically we just want to overlaps, regardless of how the actual geometries are encoded between the frames, so we can in this case ignore the geom types and feel OKAY. I also moved to projected CRSes, since we are actually trying to do area calculations and so like, we should. Again, the change is small in magnitude but logically more sound. * Readd CDC dataset config (#1900) * adding comments to fips code * delete unnecessary loggers Co-authored-by: matt bowen <matthew.r.bowen@omb.eop.gov> * Improve score test documentation based on Lucas's feedback (#1835) (#1914) * Better document base on Lucas's feedback (#1835) * Fix typo (#1835) * Add test to verify GEOJSON matches tiles (#1835) * Remove NOOP line (#1835) * Move GEOJSON generation up for new smoketest (#1835) * Fixup code format (#1835) * Update readme for new somketest (#1835) * Cleanup source tests (#1912) * Move test to base for broader coverage (#1848) * Remove duplicate line (#1848) * FUDS needed an extra mock (#1848) * Add tribal count notebook (#1917) (#1919) * Add tribal count notebook (#1917) * test without caching * added comment Co-authored-by: lucasmbrown-usds <lucas.m.brown@omb.eop.gov> * Add tribal overlap to downloads (#1907) * Add tribal data to downloads (#1904) * Update test pickle with current cols (#1904) * Remove text of tribe names from GeoJSON (#1904) * Update test data (#1904) * Add tribal overlap to smoketests (#1904) * Issue 1910: Do not impute income for 0 population tracts (#1918) * should be working, has unnecessary loggers * removing loggers and cleaning up * updating ejscreen tests * adding tests and responding to PR feedback * fixing broken smoke test * delete smoketest docs * updating click * updating click * Bump just jupyterlab (#1930) * Fixing link checker (#1929) * Update deps safety says are vulnerable (#1937) (#1938) Co-authored-by: matt bowen <matt@mattbowen.net> * Add demos for island areas (#1932) * Backfill population in island areas (#1882) * Update smoketest to account for backfills (#1882) As I wrote in the commend: We backfill island areas with data from the 2010 census, so if THOSE tracts have data beyond the data source, that's to be expected and is fine to pass. If some other state or territory does though, this should fail This ends up being a nice way of documenting that behavior i guess! * Fixup lint issues (#1882) * Add in race demos to 2010 census pull (#1851) * Add backfill data to score (#1851) * Change column name (#1851) * Fill demos after the score (#1851) * Add income back, adjust test (#1882) * Apply code-review feedback (#1851) * Add test for island area backfill (#1851) * Fix bad rename (#1851) * Reorder download fields, add plumbing back (#1942) * Add back lack of plumbing fields (#1920) * Reorder fields for excel (#1921) * Reorder excel fields (#1921) * Fix formating, lint errors, pickes (#1921) * Add missing plumbing col, fix order again (#1921) * Update that pickle (#1921) * refactoring tribal (#1960) * updated with scoring comparison * updated for narhwal -- leaving commented code in for now * pydantic upgrade * produce a string for the front end to ingest (#1963) * wip * i believe this works -- let's see the pipeline * updated fixtures * Adding ADJLI_ET (#1976) * updated tile data * ensuring adjli_et in * Add back income percentile (#1977) * Add missing field to download (#1964) * Remove pydantic since it's unused (#1964) * Add percentile to CSV (#1964) * Update downloadable pickle (#1964) * Issue 105: Configure and run `black` and other pre-commit hooks (clean branch) (#1962) * Configure and run `black` and other pre-commit hooks Co-authored-by: matt bowen <matthew.r.bowen@omb.eop.gov> * Removing fixed python version for black (#1985) * Fixup TA_COUNT and TA_PERC (#1991) * Change TA_PERC, change TA_COUNT (#1988, #1989) - Make TA_PERC_STR back into a nullable float following the rules requestsed in #1989 - Move TA_COUNT to be TA_COUNT_AK, also add a null TA_COUNT_C for CONUS that we can fill in later. * Fix typo comment (#1988) * Issue 1992: Do not impute income for null population tracts (#1993) * Hotfix for DOT data source DNS issue (#1999) * Make tribal overlap set score N (#2004) * Add "Is a Tribal DAC" field (#1998) * Add tribal DACs to score N final (#1998) * Add new fields to downloads (#1998) * Make a int a float (#1998) * Update field names, apply feedback (#1998) * Add assertions around codebook (#2014) * Add assertion around codebook (#1505) * Assert csv and excel have same cols (#1505) * Remove suffixes from tribal lands (#1974) (#2008) * Data source location (#2015) * data source location * toml * cdc_places * cdc_svi_index * url updates * child oppy and dot travel * up to hud_recap * completed ticket * cache bust * hud_recap * us_army_fuds * Remove vars the frontend doesn't use (#2020) (#2022) I did a pretty rough and simple analysis of the variables we put in the tiles and grepped the frontend code to see if (1) they're ever accessed and (2) if they're used, even if they're read once. I removed everything I noticed was not accessed. * Disable file size limits on tiles (#2031) * Disable file size limits on tiles * Remove print debugs I know. * Update file name pattern (#2037) (#2038) * Update file name pattern (#2037) * Remove ETL from generation (2037) I looked more carefully, and this ETL step isn't used in the score, so there's no need to run it every time. Per previous steps, I removed it from constants so the code is there it won't run by default. * Round ALL the float fields for the tiles (#2040) * Round ALL the float fields for the tiles (#2033) * Floor in a simpler way (#2033) Emma pointed out that all teh stuff we're doing in floor_series is probably unnecessary for this case, so just use the built-in floor. * Update pickle I missed (#2033) * Clean commit of just aggregate burden notebook (#1819) added a burden notebook * Update the dockerfile (#2045) * Update so the image builds (#2026) * Fix bad dict (2026) * Rename census tract field in downloads (#2068) * Change tract ID field name (2060) * Update lockfile (#2061) * Bump safety, jupyter, wheel (#2061) * DOn't depend directly on wheel (2061) * Bring narwhal reqs in line with main * Update tribal area counts (#2071) * Rename tribal area field (2062) * Add missing file (#2062) * Add checks to create version (#2047) (#2052) * Fix failing safety (#2114) * Ignore vuln that doesn't affect us 2113 https://nvd.nist.gov/vuln/detail/CVE-2022-42969 landed recently and there's no fix in py (which is maintenance mode). From my analysis, that CVE cannot hurt us (famous last words), so we'll ignore the vuln for now. * 2113 Update our gdal ppa * that didn't work (2113) * Don't add the PPA, the package exists (#2113) * Fix type (#2113) * Force an update of wheel 2113 * Also remove PPA line from create-score-versions * Drop 3.8 because of wheel 2113 * Put back 3.8, use newer actions * Try another way of upgrading wheel 2113 * Upgrade wheel in tox too 2113 * Typo fix 2113 Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Emma Nechamkin <97977170+emma-nechamkin@users.noreply.github.com> Co-authored-by: Shelby Switzer <shelby.c.switzer@omb.eop.gov> Co-authored-by: Shelby Switzer <shelbyswitzer@gmail.com> Co-authored-by: Emma Nechamkin <Emma.J.Nechamkin@omb.eop.gov> Co-authored-by: Matt Bowen <83967628+mattbowen-usds@users.noreply.github.com> Co-authored-by: Jorge Escobar <83969469+esfoobar-usds@users.noreply.github.com> Co-authored-by: lucasmbrown-usds <lucas.m.brown@omb.eop.gov> Co-authored-by: Jorge Escobar <jorge.e.escobar@omb.eop.gov> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: matt bowen <matthew.r.bowen@omb.eop.gov> Co-authored-by: matt bowen <matt@mattbowen.net>
This commit is contained in:
parent
db75b8ae76
commit
b97e60bfbb
285 changed files with 20485 additions and 3880 deletions
0
data/data-pipeline/data_pipeline/tests/score/__init__.py
Normal file
0
data/data-pipeline/data_pipeline/tests/score/__init__.py
Normal file
230
data/data-pipeline/data_pipeline/tests/score/fixtures.py
Normal file
230
data/data-pipeline/data_pipeline/tests/score/fixtures.py
Normal file
|
@ -0,0 +1,230 @@
|
|||
import pandas as pd
|
||||
import pytest
|
||||
from data_pipeline.config import settings
|
||||
from data_pipeline.etl.score import constants
|
||||
from data_pipeline.score.field_names import GEOID_TRACT_FIELD
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def final_score_df():
|
||||
return pd.read_csv(
|
||||
settings.APP_ROOT / "data" / "score" / "csv" / "full" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: str},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def census_acs_df():
|
||||
census_acs_csv = constants.DATA_PATH / "dataset" / "census_acs" / "usa.csv"
|
||||
return pd.read_csv(
|
||||
census_acs_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def ejscreen_df():
|
||||
ejscreen_csv = constants.DATA_PATH / "dataset" / "ejscreen" / "usa.csv"
|
||||
return pd.read_csv(
|
||||
ejscreen_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def hud_housing_df():
|
||||
hud_housing_csv = (
|
||||
constants.DATA_PATH / "dataset" / "hud_housing" / "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
hud_housing_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cdc_places_df():
|
||||
cdc_places_csv = constants.DATA_PATH / "dataset" / "cdc_places" / "usa.csv"
|
||||
return pd.read_csv(
|
||||
cdc_places_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def census_acs_median_incomes_df():
|
||||
census_acs_median_incomes_csv = (
|
||||
constants.DATA_PATH
|
||||
/ "dataset"
|
||||
/ "census_acs_median_income_2019"
|
||||
/ "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
census_acs_median_incomes_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cdc_life_expectancy_df():
|
||||
cdc_life_expectancy_csv = (
|
||||
constants.DATA_PATH / "dataset" / "cdc_life_expectancy" / "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
cdc_life_expectancy_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def doe_energy_burden_df():
|
||||
doe_energy_burden_csv = (
|
||||
constants.DATA_PATH / "dataset" / "doe_energy_burden" / "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
doe_energy_burden_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def national_risk_index_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "national_risk_index" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def dot_travel_disadvantage_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "travel_composite" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fsf_fire_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "fsf_wildfire_risk" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fsf_flood_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "fsf_flood_risk" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def nature_deprived_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "nlcd_nature_deprived" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def eamlis_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "eamlis" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fuds_df():
|
||||
return pd.read_csv(
|
||||
constants.DATA_PATH / "dataset" / "us_army_fuds" / "usa.csv",
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def geocorr_urban_rural_df():
|
||||
geocorr_urban_rural_csv = (
|
||||
constants.DATA_PATH / "dataset" / "geocorr" / "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
geocorr_urban_rural_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def census_decennial_df():
|
||||
census_decennial_csv = (
|
||||
constants.DATA_PATH / "dataset" / "census_decennial_2010" / "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
census_decennial_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def census_2010_df():
|
||||
census_2010_csv = (
|
||||
constants.DATA_PATH / "dataset" / "census_acs_2010" / "usa.csv"
|
||||
)
|
||||
return pd.read_csv(
|
||||
census_2010_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def hrs_df():
|
||||
hrs_csv = constants.DATA_PATH / "dataset" / "historic_redlining" / "usa.csv"
|
||||
|
||||
return pd.read_csv(
|
||||
hrs_csv,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def national_tract_df():
|
||||
national_tract_csv = constants.DATA_CENSUS_CSV_FILE_PATH
|
||||
return pd.read_csv(
|
||||
national_tract_csv,
|
||||
names=[GEOID_TRACT_FIELD],
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
header=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def tribal_overlap():
|
||||
tribal_overlap = (
|
||||
constants.DATA_PATH / "dataset" / "tribal_overlap" / "usa.csv"
|
||||
)
|
||||
|
||||
return pd.read_csv(
|
||||
tribal_overlap,
|
||||
dtype={GEOID_TRACT_FIELD: "string"},
|
||||
low_memory=False,
|
||||
)
|
292
data/data-pipeline/data_pipeline/tests/score/test_calculation.py
Normal file
292
data/data-pipeline/data_pipeline/tests/score/test_calculation.py
Normal file
|
@ -0,0 +1,292 @@
|
|||
# flake8: noqa: W0613,W0611,F811
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
from data_pipeline.score import field_names
|
||||
from data_pipeline.score.score_narwhal import ScoreNarwhal
|
||||
from data_pipeline.utils import get_module_logger
|
||||
|
||||
from .fixtures import final_score_df # pylint: disable=unused-import
|
||||
|
||||
logger = get_module_logger(__name__)
|
||||
|
||||
pytestmark = pytest.mark.smoketest
|
||||
|
||||
|
||||
@dataclass
|
||||
class PercentileTestConfig:
|
||||
percentile_column_name: str
|
||||
threshold_column_name: str
|
||||
threshold: float
|
||||
percentile_column_need_suffix: bool = True
|
||||
|
||||
@property
|
||||
def full_percentile_column_name(self):
|
||||
if self.percentile_column_need_suffix:
|
||||
return (
|
||||
self.percentile_column_name
|
||||
+ field_names.PERCENTILE_FIELD_SUFFIX
|
||||
)
|
||||
return self.percentile_column_name
|
||||
|
||||
|
||||
def _check_percentile_against_threshold(df, config: PercentileTestConfig):
|
||||
"""Note - for the purpose of testing, this fills with False"""
|
||||
is_minimum_flagged_ok = (
|
||||
df[df[config.threshold_column_name].fillna(False)][
|
||||
config.full_percentile_column_name
|
||||
].min()
|
||||
>= config.threshold
|
||||
)
|
||||
|
||||
is_maximum_not_flagged_ok = (
|
||||
df[~df[config.threshold_column_name].fillna(False)][
|
||||
config.full_percentile_column_name
|
||||
].max()
|
||||
< config.threshold
|
||||
)
|
||||
errors = []
|
||||
if not is_minimum_flagged_ok:
|
||||
errors.append(
|
||||
f"For column {config.threshold_column_name}, there is someone flagged below {config.threshold} percentile!"
|
||||
)
|
||||
if not is_maximum_not_flagged_ok:
|
||||
errors.append(
|
||||
f"For column {config.threshold_column_name}, there is someone not flagged above {config.threshold} percentile!"
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
def test_percentile_columns(final_score_df):
|
||||
low_income = PercentileTestConfig(
|
||||
field_names.POVERTY_LESS_THAN_200_FPL_IMPUTED_FIELD,
|
||||
field_names.FPL_200_SERIES_IMPUTED_AND_ADJUSTED,
|
||||
ScoreNarwhal.LOW_INCOME_THRESHOLD,
|
||||
)
|
||||
population_loss = PercentileTestConfig(
|
||||
field_names.EXPECTED_POPULATION_LOSS_RATE_FIELD,
|
||||
field_names.EXPECTED_POPULATION_LOSS_EXCEEDS_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
agricultural_loss = PercentileTestConfig(
|
||||
field_names.EXPECTED_AGRICULTURE_LOSS_RATE_FIELD,
|
||||
field_names.EXPECTED_AGRICULTURAL_LOSS_EXCEEDS_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
building_loss = PercentileTestConfig(
|
||||
field_names.EXPECTED_BUILDING_LOSS_RATE_FIELD,
|
||||
field_names.EXPECTED_BUILDING_LOSS_EXCEEDS_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
flood = PercentileTestConfig(
|
||||
field_names.FUTURE_FLOOD_RISK_FIELD,
|
||||
field_names.HIGH_FUTURE_FLOOD_RISK_FIELD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
wildfire = PercentileTestConfig(
|
||||
field_names.FUTURE_WILDFIRE_RISK_FIELD,
|
||||
field_names.HIGH_FUTURE_WILDFIRE_RISK_FIELD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
low_high_school = PercentileTestConfig(
|
||||
field_names.HIGH_SCHOOL_ED_FIELD,
|
||||
field_names.LOW_HS_EDUCATION_FIELD,
|
||||
ScoreNarwhal.LACK_OF_HIGH_SCHOOL_MINIMUM_THRESHOLD,
|
||||
percentile_column_need_suffix=False,
|
||||
)
|
||||
donut_hole_income = PercentileTestConfig(
|
||||
field_names.POVERTY_LESS_THAN_200_FPL_IMPUTED_FIELD,
|
||||
field_names.FPL_200_SERIES_IMPUTED_AND_ADJUSTED_DONUTS,
|
||||
ScoreNarwhal.LOW_INCOME_THRESHOLD_DONUT,
|
||||
)
|
||||
donut_hole_adjacency = PercentileTestConfig(
|
||||
(field_names.SCORE_N_COMMUNITIES + field_names.ADJACENCY_INDEX_SUFFIX),
|
||||
field_names.ADJACENT_TRACT_SCORE_ABOVE_DONUT_THRESHOLD,
|
||||
ScoreNarwhal.SCORE_THRESHOLD_DONUT,
|
||||
percentile_column_need_suffix=False,
|
||||
)
|
||||
diesel = PercentileTestConfig(
|
||||
field_names.DIESEL_FIELD,
|
||||
field_names.DIESEL_EXCEEDS_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
dot_burden = PercentileTestConfig(
|
||||
field_names.DOT_TRAVEL_BURDEN_FIELD,
|
||||
field_names.DOT_BURDEN_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
traffic_proximity = PercentileTestConfig(
|
||||
field_names.TRAFFIC_FIELD,
|
||||
field_names.TRAFFIC_PROXIMITY_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
energy_burden = PercentileTestConfig(
|
||||
field_names.ENERGY_BURDEN_FIELD,
|
||||
field_names.ENERGY_BURDEN_EXCEEDS_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
pm25 = PercentileTestConfig(
|
||||
field_names.PM25_FIELD,
|
||||
field_names.PM25_EXCEEDS_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
kitchen_plumbing = PercentileTestConfig(
|
||||
field_names.NO_KITCHEN_OR_INDOOR_PLUMBING_FIELD,
|
||||
field_names.NO_KITCHEN_OR_INDOOR_PLUMBING_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
# Leadpaint is handled below in a separate method
|
||||
housing = PercentileTestConfig(
|
||||
field_names.HOUSING_BURDEN_FIELD,
|
||||
field_names.HOUSING_BURDEN_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
non_natural_space = PercentileTestConfig(
|
||||
field_names.TRACT_PERCENT_NON_NATURAL_FIELD_NAME,
|
||||
field_names.NON_NATURAL_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
rmp = PercentileTestConfig(
|
||||
field_names.RMP_FIELD,
|
||||
field_names.RMP_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
npl = PercentileTestConfig(
|
||||
field_names.NPL_FIELD,
|
||||
field_names.NPL_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
tsdf = PercentileTestConfig(
|
||||
field_names.TSDF_FIELD,
|
||||
field_names.TSDF_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
wastewater = PercentileTestConfig(
|
||||
field_names.WASTEWATER_FIELD,
|
||||
field_names.WASTEWATER_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
ust = PercentileTestConfig(
|
||||
field_names.UST_FIELD,
|
||||
field_names.UST_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
diabetes = PercentileTestConfig(
|
||||
field_names.DIABETES_FIELD,
|
||||
field_names.DIABETES_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
asthma = PercentileTestConfig(
|
||||
field_names.ASTHMA_FIELD,
|
||||
field_names.ASTHMA_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
heart_disease = PercentileTestConfig(
|
||||
field_names.HEART_DISEASE_FIELD,
|
||||
field_names.HEART_DISEASE_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
low_life_expectancy = PercentileTestConfig(
|
||||
field_names.LOW_LIFE_EXPECTANCY_FIELD,
|
||||
field_names.LOW_LIFE_EXPECTANCY_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
unemployment = PercentileTestConfig(
|
||||
field_names.UNEMPLOYMENT_FIELD,
|
||||
field_names.UNEMPLOYMENT_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
low_median_income = PercentileTestConfig(
|
||||
field_names.LOW_MEDIAN_INCOME_AS_PERCENT_OF_AMI_FIELD,
|
||||
field_names.LOW_MEDIAN_INCOME_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
linguist_isolation = PercentileTestConfig(
|
||||
field_names.LINGUISTIC_ISO_FIELD,
|
||||
field_names.LINGUISTIC_ISOLATION_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
poverty = PercentileTestConfig(
|
||||
field_names.POVERTY_LESS_THAN_100_FPL_FIELD,
|
||||
field_names.POVERTY_PCTILE_THRESHOLD,
|
||||
ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD,
|
||||
)
|
||||
errors = []
|
||||
for threshhold_config in (
|
||||
low_income,
|
||||
population_loss,
|
||||
agricultural_loss,
|
||||
building_loss,
|
||||
flood,
|
||||
wildfire,
|
||||
low_high_school,
|
||||
donut_hole_income,
|
||||
donut_hole_adjacency,
|
||||
dot_burden,
|
||||
diesel,
|
||||
traffic_proximity,
|
||||
energy_burden,
|
||||
pm25,
|
||||
kitchen_plumbing,
|
||||
housing,
|
||||
non_natural_space,
|
||||
rmp,
|
||||
npl,
|
||||
tsdf,
|
||||
wastewater,
|
||||
ust,
|
||||
diabetes,
|
||||
asthma,
|
||||
heart_disease,
|
||||
low_life_expectancy,
|
||||
unemployment,
|
||||
low_median_income,
|
||||
linguist_isolation,
|
||||
poverty,
|
||||
):
|
||||
errors.extend(
|
||||
_check_percentile_against_threshold(
|
||||
final_score_df, threshhold_config
|
||||
)
|
||||
)
|
||||
error_text = "\n".join(errors)
|
||||
assert not errors, error_text
|
||||
|
||||
|
||||
def test_lead_paint_indicator(
|
||||
final_score_df,
|
||||
):
|
||||
"""We need special logic here because this is a combined threshold, so we need this test to have two parts.
|
||||
|
||||
1. We construct our own threshold columns
|
||||
2. We make sure it's the same as the threshold column in the dataframe
|
||||
"""
|
||||
lead_pfs = (
|
||||
field_names.LEAD_PAINT_FIELD + field_names.PERCENTILE_FIELD_SUFFIX
|
||||
)
|
||||
home_val_pfs = (
|
||||
field_names.MEDIAN_HOUSE_VALUE_FIELD
|
||||
+ field_names.PERCENTILE_FIELD_SUFFIX
|
||||
)
|
||||
combined_proxy_boolean = field_names.LEAD_PAINT_PROXY_PCTILE_THRESHOLD
|
||||
|
||||
tmp_lead_threshold = (
|
||||
final_score_df[lead_pfs] >= ScoreNarwhal.ENVIRONMENTAL_BURDEN_THRESHOLD
|
||||
)
|
||||
tmp_mhv_threshold = (
|
||||
final_score_df[home_val_pfs]
|
||||
<= ScoreNarwhal.MEDIAN_HOUSE_VALUE_THRESHOLD
|
||||
)
|
||||
|
||||
true_combined_proxy = tmp_lead_threshold & tmp_mhv_threshold
|
||||
|
||||
assert (
|
||||
tmp_mhv_threshold.sum() > 0
|
||||
), "MHV threshold alone does not capture any homes"
|
||||
|
||||
assert final_score_df[combined_proxy_boolean].equals(
|
||||
true_combined_proxy
|
||||
), "Lead proxy calculated improperly"
|
||||
assert (
|
||||
tmp_lead_threshold.sum() > true_combined_proxy.sum()
|
||||
), "House value is not further limiting this proxy"
|
473
data/data-pipeline/data_pipeline/tests/score/test_output.py
Normal file
473
data/data-pipeline/data_pipeline/tests/score/test_output.py
Normal file
|
@ -0,0 +1,473 @@
|
|||
# flake8: noqa: W0613,W0611,F811,
|
||||
# pylint: disable=unused-import,too-many-arguments
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from data_pipeline.etl.score import constants
|
||||
from data_pipeline.etl.score.constants import TILES_ISLAND_AREA_FIPS_CODES
|
||||
from data_pipeline.score import field_names
|
||||
from data_pipeline.score.field_names import GEOID_TRACT_FIELD
|
||||
|
||||
from .fixtures import cdc_life_expectancy_df # noqa
|
||||
from .fixtures import cdc_places_df # noqa
|
||||
from .fixtures import census_2010_df # noqa
|
||||
from .fixtures import census_acs_df # noqa
|
||||
from .fixtures import census_acs_median_incomes_df # noqa
|
||||
from .fixtures import census_decennial_df # noqa
|
||||
from .fixtures import doe_energy_burden_df # noqa
|
||||
from .fixtures import dot_travel_disadvantage_df # noqa
|
||||
from .fixtures import eamlis_df # noqa
|
||||
from .fixtures import ejscreen_df # noqa
|
||||
from .fixtures import final_score_df # noqa
|
||||
from .fixtures import fsf_fire_df # noqa
|
||||
from .fixtures import fuds_df # noqa
|
||||
from .fixtures import geocorr_urban_rural_df # noqa
|
||||
from .fixtures import hrs_df # noqa
|
||||
from .fixtures import hud_housing_df # noqa
|
||||
from .fixtures import national_risk_index_df # noqa
|
||||
from .fixtures import national_tract_df # noqa
|
||||
from .fixtures import nature_deprived_df # noqa
|
||||
from .fixtures import tribal_overlap # noqa
|
||||
|
||||
pytestmark = pytest.mark.smoketest
|
||||
UNMATCHED_TRACT_THRESHOLD = 1000
|
||||
|
||||
|
||||
def _helper_test_count_exceeding_threshold(df, col, error_check=1000):
|
||||
"""Fills NA with False"""
|
||||
return df[df[col].fillna(False)].shape[0] >= error_check
|
||||
|
||||
|
||||
def _helper_single_threshold_test(df, col, socioeconomic_column, score_column):
|
||||
"""Note that this fills nulls in the threshold column where nulls exist"""
|
||||
nulls_dont_exist = (
|
||||
df[df[col].fillna(False) & df[socioeconomic_column]][score_column]
|
||||
.isna()
|
||||
.sum()
|
||||
== 0
|
||||
)
|
||||
only_trues = df[df[col].fillna(False) & df[socioeconomic_column]][
|
||||
score_column
|
||||
].min()
|
||||
return nulls_dont_exist, only_trues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ThresholdTestConfig:
|
||||
name: str
|
||||
threshhold_columns: List[str]
|
||||
ses_column_name: str = field_names.FPL_200_SERIES_IMPUTED_AND_ADJUSTED
|
||||
score_column_name: str = field_names.SCORE_N_COMMUNITIES
|
||||
|
||||
@property
|
||||
def error_message(self):
|
||||
return f"Eligibility columns have an error, {self.name}"
|
||||
|
||||
|
||||
def check_for_threshhold_errors(
|
||||
df: pd.DataFrame, config: ThresholdTestConfig
|
||||
) -> List[str]:
|
||||
errors = []
|
||||
for col in config.threshhold_columns:
|
||||
nulls_dont_exist, only_trues = _helper_single_threshold_test(
|
||||
df,
|
||||
col,
|
||||
config.ses_column_name,
|
||||
config.score_column_name,
|
||||
)
|
||||
proper_threshold_identification = (
|
||||
_helper_test_count_exceeding_threshold(df, col)
|
||||
)
|
||||
if not nulls_dont_exist:
|
||||
errors.append(
|
||||
f"For {col}, threshold is not calculated right -- there are NaNs in Score"
|
||||
)
|
||||
if not only_trues:
|
||||
errors.append(
|
||||
f"For {col} and {config.ses_column_name}, threshold is not calculated right "
|
||||
f"-- there are Falses where there should only be Trues"
|
||||
)
|
||||
if not proper_threshold_identification:
|
||||
errors.append(
|
||||
f"Threshold {col} returns too few tracts, are you sure it's nationally-representative?"
|
||||
)
|
||||
if errors:
|
||||
errors.append(config.error_message)
|
||||
return errors
|
||||
|
||||
|
||||
def test_threshholds(final_score_df):
|
||||
climate_thresholds = ThresholdTestConfig(
|
||||
"climate",
|
||||
[
|
||||
field_names.EXPECTED_POPULATION_LOSS_EXCEEDS_PCTILE_THRESHOLD,
|
||||
field_names.EXPECTED_AGRICULTURAL_LOSS_EXCEEDS_PCTILE_THRESHOLD,
|
||||
field_names.EXPECTED_BUILDING_LOSS_EXCEEDS_PCTILE_THRESHOLD,
|
||||
field_names.HIGH_FUTURE_FLOOD_RISK_FIELD,
|
||||
field_names.HIGH_FUTURE_WILDFIRE_RISK_FIELD,
|
||||
],
|
||||
)
|
||||
energy_thresholds = ThresholdTestConfig(
|
||||
"energy",
|
||||
[
|
||||
field_names.ENERGY_BURDEN_EXCEEDS_PCTILE_THRESHOLD,
|
||||
field_names.PM25_EXCEEDS_PCTILE_THRESHOLD,
|
||||
],
|
||||
)
|
||||
transportation_thresholds = ThresholdTestConfig(
|
||||
"transportation",
|
||||
[
|
||||
field_names.DIESEL_EXCEEDS_PCTILE_THRESHOLD,
|
||||
field_names.DOT_BURDEN_PCTILE_THRESHOLD,
|
||||
field_names.TRAFFIC_PROXIMITY_PCTILE_THRESHOLD,
|
||||
],
|
||||
)
|
||||
housing_thresholds = ThresholdTestConfig(
|
||||
"housing",
|
||||
[
|
||||
field_names.HISTORIC_REDLINING_SCORE_EXCEEDED,
|
||||
field_names.NO_KITCHEN_OR_INDOOR_PLUMBING_PCTILE_THRESHOLD,
|
||||
field_names.LEAD_PAINT_PROXY_PCTILE_THRESHOLD,
|
||||
field_names.HOUSING_BURDEN_PCTILE_THRESHOLD,
|
||||
field_names.NON_NATURAL_PCTILE_THRESHOLD,
|
||||
],
|
||||
)
|
||||
pollution_thresholds = ThresholdTestConfig(
|
||||
"pollution",
|
||||
[
|
||||
field_names.RMP_PCTILE_THRESHOLD,
|
||||
field_names.NPL_PCTILE_THRESHOLD,
|
||||
field_names.TSDF_PCTILE_THRESHOLD,
|
||||
field_names.AML_BOOLEAN,
|
||||
field_names.ELIGIBLE_FUDS_BINARY_FIELD_NAME,
|
||||
],
|
||||
)
|
||||
water_thresholds = ThresholdTestConfig(
|
||||
"water",
|
||||
[
|
||||
field_names.WASTEWATER_PCTILE_THRESHOLD,
|
||||
field_names.UST_PCTILE_THRESHOLD,
|
||||
],
|
||||
)
|
||||
health_thresholds = ThresholdTestConfig(
|
||||
"health",
|
||||
[
|
||||
field_names.DIABETES_PCTILE_THRESHOLD,
|
||||
field_names.ASTHMA_PCTILE_THRESHOLD,
|
||||
field_names.HEART_DISEASE_PCTILE_THRESHOLD,
|
||||
field_names.LOW_LIFE_EXPECTANCY_PCTILE_THRESHOLD,
|
||||
],
|
||||
)
|
||||
workforce_base_thresholds = ThresholdTestConfig(
|
||||
"workforce (not island areas)",
|
||||
[
|
||||
field_names.UNEMPLOYMENT_PCTILE_THRESHOLD,
|
||||
field_names.LOW_MEDIAN_INCOME_PCTILE_THRESHOLD,
|
||||
field_names.LINGUISTIC_ISOLATION_PCTILE_THRESHOLD,
|
||||
field_names.POVERTY_PCTILE_THRESHOLD,
|
||||
],
|
||||
ses_column_name=field_names.LOW_HS_EDUCATION_FIELD,
|
||||
)
|
||||
errors = []
|
||||
for threshhold_config in [
|
||||
climate_thresholds,
|
||||
energy_thresholds,
|
||||
transportation_thresholds,
|
||||
housing_thresholds,
|
||||
pollution_thresholds,
|
||||
water_thresholds,
|
||||
health_thresholds,
|
||||
workforce_base_thresholds,
|
||||
]:
|
||||
errors.extend(
|
||||
check_for_threshhold_errors(final_score_df, threshhold_config)
|
||||
)
|
||||
error_text = "\n".join(errors)
|
||||
assert not errors, error_text
|
||||
|
||||
|
||||
def test_max_40_percent_DAC(final_score_df):
|
||||
score_col_with_donuts = field_names.FINAL_SCORE_N_BOOLEAN
|
||||
total_population_col = field_names.TOTAL_POP_FIELD
|
||||
assert (
|
||||
final_score_df[score_col_with_donuts].isna().sum() == 0
|
||||
), f"Error: {score_col_with_donuts} contains NULLs"
|
||||
assert (
|
||||
final_score_df[final_score_df[score_col_with_donuts]][
|
||||
total_population_col
|
||||
].sum()
|
||||
/ final_score_df[total_population_col].sum()
|
||||
) < 0.4, "Error: the scoring methodology identifies >40% of people in the US as disadvantaged"
|
||||
assert (
|
||||
final_score_df[score_col_with_donuts].sum() > 0
|
||||
), "FYI: You've identified no tracts at all!"
|
||||
|
||||
|
||||
def test_donut_hole_addition_to_score_n(final_score_df):
|
||||
score_col_with_donuts = field_names.FINAL_SCORE_N_BOOLEAN
|
||||
score_col = field_names.SCORE_N_COMMUNITIES
|
||||
donut_hole_score_only = (
|
||||
field_names.SCORE_N_COMMUNITIES + field_names.ADJACENT_MEAN_SUFFIX
|
||||
)
|
||||
count_donuts = final_score_df[donut_hole_score_only].sum()
|
||||
count_n = final_score_df[score_col].sum()
|
||||
count_n_with_donuts = final_score_df[score_col_with_donuts].sum()
|
||||
new_donuts = final_score_df[
|
||||
final_score_df[donut_hole_score_only] & ~final_score_df[score_col]
|
||||
].shape[0]
|
||||
|
||||
assert (
|
||||
new_donuts + count_n == count_n_with_donuts
|
||||
), "The math doesn't work! The number of new donut hole tracts plus score tracts (base) does not equal the total number of tracts identified"
|
||||
|
||||
assert (
|
||||
count_donuts < count_n
|
||||
), "There are more donut hole tracts than base tracts. How can it be?"
|
||||
|
||||
assert (
|
||||
new_donuts > 0
|
||||
), "FYI: The adjacency index is doing nothing. Consider removing it?"
|
||||
|
||||
|
||||
def test_data_sources(
|
||||
final_score_df,
|
||||
hud_housing_df,
|
||||
ejscreen_df,
|
||||
census_acs_df,
|
||||
cdc_places_df,
|
||||
census_acs_median_incomes_df,
|
||||
cdc_life_expectancy_df,
|
||||
doe_energy_burden_df,
|
||||
national_risk_index_df,
|
||||
dot_travel_disadvantage_df,
|
||||
fsf_fire_df,
|
||||
nature_deprived_df,
|
||||
eamlis_df,
|
||||
fuds_df,
|
||||
geocorr_urban_rural_df,
|
||||
census_decennial_df,
|
||||
census_2010_df,
|
||||
hrs_df,
|
||||
tribal_overlap,
|
||||
):
|
||||
data_sources = {
|
||||
key: value for key, value in locals().items() if key != "final_score_df"
|
||||
}
|
||||
|
||||
# For each data source that's injected via the fixtures, do the following:
|
||||
# * Ensure at least one column from the source shows up in the score
|
||||
# * Ensure any tracts NOT in the data source are NA/null in the score
|
||||
# * Ensure the data source doesn't have a large number of tract IDs that are not
|
||||
# included in the final score, since that implies the source is using 2020
|
||||
# tract IDs
|
||||
# * Verify that the data from the source that's in the final score output
|
||||
# is the "equal" to the data from the ETL, allowing for the minor
|
||||
# differences that come from floating point comparisons
|
||||
for data_source_name, data_source in data_sources.items():
|
||||
final = "_final"
|
||||
df: pd.DataFrame = final_score_df.merge(
|
||||
data_source,
|
||||
on=GEOID_TRACT_FIELD,
|
||||
indicator="MERGE",
|
||||
suffixes=(final, f"_{data_source_name}"),
|
||||
how="outer",
|
||||
)
|
||||
|
||||
# Make our lists of columns for later comparison
|
||||
core_cols = data_source.columns.intersection(
|
||||
final_score_df.columns
|
||||
).drop(GEOID_TRACT_FIELD)
|
||||
data_source_columns = [f"{col}_{data_source_name}" for col in core_cols]
|
||||
final_columns = [f"{col}{final}" for col in core_cols]
|
||||
assert (
|
||||
final_columns
|
||||
), f"No columns from data source show up in final score in source {data_source_name}"
|
||||
|
||||
# Make sure we have NAs for any tracts in the final data that aren't
|
||||
# included in the data source
|
||||
has_additional_non_null_tracts = not np.all(
|
||||
df[df.MERGE == "left_only"][final_columns].isna()
|
||||
)
|
||||
if has_additional_non_null_tracts:
|
||||
# We backfill island areas with data from the 2010 census, so if THOSE tracts
|
||||
# have data beyond the data source, that's to be expected and is fine to pass.
|
||||
# If some other state or territory does though, this should fail
|
||||
left_only = df.loc[(df.MERGE == "left_only")]
|
||||
left_only_has_value = left_only.loc[
|
||||
~df[final_columns].isna().all(axis=1)
|
||||
]
|
||||
fips_with_values = set(
|
||||
left_only_has_value[field_names.GEOID_TRACT_FIELD].str[0:2]
|
||||
)
|
||||
non_island_fips_codes = fips_with_values.difference(
|
||||
TILES_ISLAND_AREA_FIPS_CODES
|
||||
)
|
||||
assert not non_island_fips_codes
|
||||
|
||||
# Make sure the datasource doesn't have a ton of unmatched tracts, implying it
|
||||
# has moved to 2020 tracts
|
||||
assert len(df[df.MERGE == "right_only"]) < UNMATCHED_TRACT_THRESHOLD
|
||||
|
||||
df = df[df.MERGE == "both"]
|
||||
|
||||
# Compare every column for equality, using close equality for numerics and
|
||||
# `equals` equality for non-numeric columns
|
||||
for final_column, data_source_column in zip(
|
||||
data_source_columns, final_columns
|
||||
):
|
||||
error_message = (
|
||||
f"Column {final_column} not equal "
|
||||
f"between {data_source_name} and final score"
|
||||
)
|
||||
# For non-numeric types, we can use the built-in equals from pandas
|
||||
if df[final_column].dtype in [
|
||||
np.dtype(object),
|
||||
np.dtype(bool),
|
||||
np.dtype(str),
|
||||
]:
|
||||
assert df[final_column].equals(
|
||||
df[data_source_column]
|
||||
), error_message
|
||||
# For numeric sources, use np.close so we don't get harmed by
|
||||
# float equaity weirdness
|
||||
else:
|
||||
assert np.allclose(
|
||||
df[final_column],
|
||||
df[data_source_column],
|
||||
equal_nan=True,
|
||||
), error_message
|
||||
|
||||
|
||||
def test_island_demographic_backfill(final_score_df, census_decennial_df):
|
||||
# Copied from score_etl because there's no better source of truth for it
|
||||
ISLAND_DEMOGRAPHIC_BACKFILL_FIELDS = [
|
||||
field_names.PERCENT_BLACK_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_AMERICAN_INDIAN_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_ASIAN_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_HAWAIIAN_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_TWO_OR_MORE_RACES_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_NON_HISPANIC_WHITE_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_HISPANIC_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.PERCENT_OTHER_RACE_FIELD_NAME
|
||||
+ field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
field_names.TOTAL_POP_FIELD + field_names.ISLAND_AREA_BACKFILL_SUFFIX,
|
||||
]
|
||||
|
||||
# rename the columns from the decennial census to be their final score names
|
||||
decennial_cols = {
|
||||
col_name: col_name.replace(field_names.ISLAND_AREA_BACKFILL_SUFFIX, "")
|
||||
for col_name in ISLAND_DEMOGRAPHIC_BACKFILL_FIELDS
|
||||
}
|
||||
census_decennial_df: pd.DataFrame = census_decennial_df.rename(
|
||||
columns=decennial_cols
|
||||
)
|
||||
|
||||
# Merge decennial data with the final score
|
||||
df: pd.DataFrame = final_score_df.merge(
|
||||
census_decennial_df,
|
||||
on=GEOID_TRACT_FIELD,
|
||||
indicator="MERGE",
|
||||
suffixes=("_final", "_decennial"),
|
||||
how="outer",
|
||||
)
|
||||
|
||||
# Make sure columns from both the decennial census and final score overlap
|
||||
core_cols = census_decennial_df.columns.intersection(
|
||||
final_score_df.columns
|
||||
).drop(GEOID_TRACT_FIELD)
|
||||
final_columns = [f"{col}_final" for col in core_cols]
|
||||
assert (
|
||||
final_columns
|
||||
), "No columns from decennial census show up in final score, extremely weird"
|
||||
|
||||
# Make sure we're only grabbing island tracts for the decennial data
|
||||
assert (
|
||||
sorted(
|
||||
df[df.MERGE == "both"][field_names.GEOID_TRACT_FIELD]
|
||||
.str[:2]
|
||||
.unique()
|
||||
)
|
||||
== constants.TILES_ISLAND_AREA_FIPS_CODES
|
||||
), "2010 Decennial census contributed unexpected tracts"
|
||||
|
||||
df = df[df.MERGE == "both"]
|
||||
|
||||
# Make sure for all the backfill tracts, the data made it into the
|
||||
# final score. This can be simple since it's all perenctages and an int
|
||||
for col in final_columns:
|
||||
assert np.allclose(
|
||||
df[col],
|
||||
df[col.replace("_final", "_decennial")],
|
||||
equal_nan=True,
|
||||
), f"Data mismatch in decennial census backfill for {col}"
|
||||
|
||||
|
||||
def test_output_tracts(final_score_df, national_tract_df):
|
||||
df = final_score_df.merge(
|
||||
national_tract_df,
|
||||
on=GEOID_TRACT_FIELD,
|
||||
how="outer",
|
||||
indicator="MERGE",
|
||||
)
|
||||
counts = df.value_counts("MERGE")
|
||||
assert counts.loc["left_only"] == 0
|
||||
assert counts.loc["right_only"] == 0
|
||||
|
||||
|
||||
def test_all_tracts_have_scores(final_score_df):
|
||||
assert not final_score_df[field_names.SCORE_N_COMMUNITIES].isna().any()
|
||||
|
||||
|
||||
def test_imputed_tracts(final_score_df):
|
||||
# Make sure that any tracts with zero population have null imputed income
|
||||
tracts_with_zero_population_df = final_score_df[
|
||||
final_score_df[field_names.TOTAL_POP_FIELD] == 0
|
||||
]
|
||||
assert (
|
||||
tracts_with_zero_population_df[
|
||||
field_names.POVERTY_LESS_THAN_200_FPL_IMPUTED_FIELD
|
||||
]
|
||||
.isna()
|
||||
.all()
|
||||
)
|
||||
|
||||
# Make sure that any tracts with null population have null imputed income
|
||||
tracts_with_null_population_df = final_score_df[
|
||||
final_score_df[field_names.TOTAL_POP_FIELD].isnull()
|
||||
]
|
||||
assert (
|
||||
tracts_with_null_population_df[
|
||||
field_names.POVERTY_LESS_THAN_200_FPL_IMPUTED_FIELD
|
||||
]
|
||||
.isna()
|
||||
.all()
|
||||
)
|
||||
|
||||
# Make sure that no tracts with population have null imputed income
|
||||
# We DO NOT impute income for island areas, so remove those from the test
|
||||
is_island_area = (
|
||||
final_score_df[field_names.GEOID_TRACT_FIELD]
|
||||
.str[:2]
|
||||
.isin(constants.TILES_ISLAND_AREA_FIPS_CODES)
|
||||
)
|
||||
|
||||
tracts_with_some_population_df = final_score_df[
|
||||
(final_score_df[field_names.TOTAL_POP_FIELD] > 0) & ~is_island_area
|
||||
]
|
||||
assert (
|
||||
not tracts_with_some_population_df[
|
||||
field_names.POVERTY_LESS_THAN_200_FPL_IMPUTED_FIELD
|
||||
]
|
||||
.isna()
|
||||
.any()
|
||||
)
|
|
@ -0,0 +1,85 @@
|
|||
# pylint: disable=protected-access
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from data_pipeline.config import settings
|
||||
from data_pipeline.etl.score.etl_score import ScoreETL
|
||||
from data_pipeline.score import field_names
|
||||
from data_pipeline.utils import get_module_logger
|
||||
|
||||
logger = get_module_logger(__name__)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def toy_score_df(scope="module"):
|
||||
return pd.read_csv(
|
||||
settings.APP_ROOT
|
||||
/ "tests"
|
||||
/ "score"
|
||||
/ "test_utils"
|
||||
/ "data"
|
||||
/ "test_drop_tracts_from_percentile.csv",
|
||||
dtype={field_names.GEOID_TRACT_FIELD: str},
|
||||
)
|
||||
|
||||
|
||||
def _helper_test_dropping_tracts(toy_score_df, drop_tracts):
|
||||
logger.info(drop_tracts)
|
||||
test_frame = toy_score_df[
|
||||
~toy_score_df[field_names.GEOID_TRACT_FIELD].isin(drop_tracts)
|
||||
]
|
||||
return_df = ScoreETL._add_percentiles_to_df(
|
||||
df=toy_score_df,
|
||||
input_column_name="to_rank",
|
||||
output_column_name_root="to_rank_auto",
|
||||
drop_tracts=drop_tracts,
|
||||
)
|
||||
|
||||
test_frame = test_frame.assign(
|
||||
true_rank=test_frame["to_rank"].rank(pct=True)
|
||||
)
|
||||
|
||||
check_frame = test_frame.merge(
|
||||
return_df[
|
||||
[
|
||||
field_names.GEOID_TRACT_FIELD,
|
||||
"to_rank_auto" + field_names.PERCENTILE_FIELD_SUFFIX,
|
||||
]
|
||||
],
|
||||
on=[field_names.GEOID_TRACT_FIELD],
|
||||
)
|
||||
|
||||
return check_frame["true_rank"].equals(
|
||||
check_frame["to_rank_auto" + field_names.PERCENTILE_FIELD_SUFFIX]
|
||||
)
|
||||
|
||||
|
||||
def test_drop_0_tracts(toy_score_df):
|
||||
assert _helper_test_dropping_tracts(
|
||||
toy_score_df, drop_tracts=[]
|
||||
), "Percentile in score fails when we do not drop any tracts"
|
||||
|
||||
|
||||
def test_drop_1_tract(toy_score_df):
|
||||
assert _helper_test_dropping_tracts(
|
||||
toy_score_df, drop_tracts=["1"]
|
||||
), "Percentile in score fails when we do drop a single tract"
|
||||
|
||||
|
||||
def test_drop_2_tracts(toy_score_df):
|
||||
assert _helper_test_dropping_tracts(
|
||||
toy_score_df, drop_tracts=["1", "2"]
|
||||
), "Percentile in score fails when we drop two tracts"
|
||||
|
||||
|
||||
def test_drop_many_tracts(toy_score_df):
|
||||
assert _helper_test_dropping_tracts(
|
||||
toy_score_df,
|
||||
drop_tracts=toy_score_df[field_names.GEOID_TRACT_FIELD].to_list()[:5],
|
||||
), "Percentile in score fails when we drop many tracts"
|
||||
|
||||
|
||||
def test_drop_all_tracts(toy_score_df):
|
||||
assert _helper_test_dropping_tracts(
|
||||
toy_score_df,
|
||||
drop_tracts=toy_score_df[field_names.GEOID_TRACT_FIELD].to_list(),
|
||||
), "Percentile in score fails when we drop all tracts"
|
|
@ -0,0 +1,276 @@
|
|||
# flake8: noqa: W0613,W0611,F811
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
import geopandas as gpd
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from data_pipeline.config import settings
|
||||
from data_pipeline.etl.score import constants
|
||||
from data_pipeline.etl.score.constants import THRESHOLD_COUNT_TO_SHOW_FIELD_NAME
|
||||
from data_pipeline.etl.score.constants import TILES_SCORE_COLUMNS
|
||||
from data_pipeline.etl.score.constants import (
|
||||
USER_INTERFACE_EXPERIENCE_FIELD_NAME,
|
||||
)
|
||||
from data_pipeline.score import field_names
|
||||
|
||||
from .fixtures import final_score_df # pylint: disable=unused-import
|
||||
|
||||
pytestmark = pytest.mark.smoketest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tiles_df(scope="session"):
|
||||
return pd.read_csv(
|
||||
settings.APP_ROOT / "data" / "score" / "csv" / "tiles" / "usa.csv",
|
||||
dtype={"GTF": str},
|
||||
low_memory=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def tiles_geojson_df():
|
||||
return gpd.read_file(
|
||||
settings.APP_ROOT / "data" / "score" / "geojson" / "usa-high.json"
|
||||
)
|
||||
|
||||
|
||||
PERCENTILE_FIELDS = [
|
||||
"DF_PFS",
|
||||
"AF_PFS",
|
||||
"HDF_PFS",
|
||||
"DSF_PFS",
|
||||
"EBF_PFS",
|
||||
"EALR_PFS",
|
||||
"EBLR_PFS",
|
||||
"EPLR_PFS",
|
||||
"HBF_PFS",
|
||||
"LLEF_PFS",
|
||||
"LIF_PFS",
|
||||
"LMI_PFS",
|
||||
"PM25F_PFS",
|
||||
"P100_PFS",
|
||||
"P200_I_PFS",
|
||||
"LPF_PFS",
|
||||
"KP_PFS",
|
||||
"NPL_PFS",
|
||||
"RMP_PFS",
|
||||
"TSDF_PFS",
|
||||
"TF_PFS",
|
||||
"UF_PFS",
|
||||
"WF_PFS",
|
||||
"UST_PFS",
|
||||
]
|
||||
|
||||
|
||||
def test_percentiles(tiles_df):
|
||||
for col in PERCENTILE_FIELDS:
|
||||
assert tiles_df[col].min() >= 0, f"Negative percentile exists for {col}"
|
||||
assert (
|
||||
tiles_df[col].max() <= 1
|
||||
), f"Percentile over 100th exists for {col}"
|
||||
assert (tiles_df[col].median() >= 0.4) & (
|
||||
tiles_df[col].median() <= 0.6
|
||||
), f"Percentile distribution for {col} is decidedly not uniform"
|
||||
return True
|
||||
|
||||
|
||||
def test_count_of_fips_codes(tiles_df, final_score_df):
|
||||
final_score_state_count = (
|
||||
final_score_df[field_names.GEOID_TRACT_FIELD].str[:2].nunique()
|
||||
)
|
||||
assert (
|
||||
tiles_df["GTF"].str[:2].nunique() == final_score_state_count
|
||||
), "Some states are missing from tiles"
|
||||
pfs_columns = tiles_df.filter(like="PFS").columns.to_list()
|
||||
assert (
|
||||
tiles_df.dropna(how="all", subset=pfs_columns)["GTF"].str[:2].nunique()
|
||||
== 56
|
||||
), "Some states do not have any percentile data"
|
||||
|
||||
|
||||
def test_column_presence(tiles_df):
|
||||
expected_column_names = set(TILES_SCORE_COLUMNS.values()) | {
|
||||
THRESHOLD_COUNT_TO_SHOW_FIELD_NAME,
|
||||
USER_INTERFACE_EXPERIENCE_FIELD_NAME,
|
||||
}
|
||||
actual_column_names = set(tiles_df.columns)
|
||||
extra_columns = actual_column_names - expected_column_names
|
||||
missing_columns = expected_column_names - expected_column_names
|
||||
assert not (
|
||||
extra_columns
|
||||
), f"tiles/usa.csv has columns not specified in TILE_SCORE_COLUMNS: {extra_columns}"
|
||||
assert not (
|
||||
missing_columns
|
||||
), f"tiles/usa.csv is missing columns from TILE_SCORE_COLUMNS: {missing_columns}"
|
||||
|
||||
|
||||
def test_tract_equality(tiles_df, final_score_df):
|
||||
assert tiles_df.shape[0] == final_score_df.shape[0]
|
||||
|
||||
|
||||
def is_col_fake_bool(col) -> bool:
|
||||
if col.dtype == np.dtype("float64"):
|
||||
fake_bool = {1.0, 0.0, None}
|
||||
# Replace the nans in the column values with None for
|
||||
# so we can just use issubset below
|
||||
col_values = set(
|
||||
not np.isnan(val) and val or None
|
||||
for val in col.value_counts(dropna=False).index
|
||||
)
|
||||
return len(col_values) <= 3 and col_values.issubset(fake_bool)
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ColumnValueComparison:
|
||||
final_score_column: pd.Series
|
||||
tiles_column: pd.Series
|
||||
col_name: str
|
||||
|
||||
@property
|
||||
def _is_tiles_column_fake_bool(self) -> bool:
|
||||
return is_col_fake_bool(self.tiles_column)
|
||||
|
||||
@property
|
||||
def _is_dtype_ok(self) -> bool:
|
||||
if self.final_score_column.dtype == self.tiles_column.dtype:
|
||||
return True
|
||||
if (
|
||||
self.final_score_column.dtype == np.dtype("O")
|
||||
and self.tiles_column.dtype == np.dtype("float64")
|
||||
and self._is_tiles_column_fake_bool
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
def __post_init__(self):
|
||||
self._is_value_ok = False
|
||||
if self._is_dtype_ok:
|
||||
if self._is_tiles_column_fake_bool:
|
||||
# Cast to actual bool for useful comparison
|
||||
self.tiles_column = self.tiles_column.apply(
|
||||
lambda val: bool(val) if not np.isnan(val) else np.nan
|
||||
)
|
||||
if self.tiles_column.dtype == np.dtype("float64"):
|
||||
self._is_value_ok = np.allclose(
|
||||
self.final_score_column,
|
||||
self.tiles_column,
|
||||
atol=float(f"1e-{constants.TILES_ROUND_NUM_DECIMALS}"),
|
||||
equal_nan=True,
|
||||
)
|
||||
else:
|
||||
self._is_value_ok = self.final_score_column.equals(
|
||||
self.tiles_column
|
||||
)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return self._is_dtype_ok and bool(self._is_value_ok)
|
||||
|
||||
@property
|
||||
def error_message(self) -> Optional[str]:
|
||||
if not self._is_dtype_ok:
|
||||
return (
|
||||
f"Column {self.col_name} dtype mismatch: "
|
||||
f"score_df: {self.final_score_column.dtype}, "
|
||||
f"tile_df: {self.tiles_column.dtype}"
|
||||
)
|
||||
if not self._is_value_ok:
|
||||
return f"Column {self.col_name} value mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def test_for_column_fidelitiy_from_score(tiles_df, final_score_df):
|
||||
# Verify the following:
|
||||
# * Shape and tracts match between score csv and tile csv
|
||||
# * If you rename score CSV columns, you are able to make the tile csv
|
||||
# * The dtypes and values of every renamed score column is "equal" to
|
||||
# every tile column
|
||||
# * Because tiles use rounded floats, we use close with a tolerance
|
||||
assert (
|
||||
set(TILES_SCORE_COLUMNS.values()) - set(tiles_df.columns) == set()
|
||||
), "Some TILES_SCORE_COLUMNS are missing from the tiles dataframe"
|
||||
|
||||
# Keep only the tiles score columns in the final score data
|
||||
final_score_df = final_score_df.rename(columns=TILES_SCORE_COLUMNS).drop(
|
||||
final_score_df.columns.difference(TILES_SCORE_COLUMNS.values()),
|
||||
axis=1,
|
||||
errors="ignore",
|
||||
)
|
||||
|
||||
# Drop the UI-specific fields from the tiles dataframe
|
||||
tiles_df = tiles_df.drop(
|
||||
columns=[
|
||||
"SF", # State field, added at geoscore
|
||||
"CF", # County field, added at geoscore,
|
||||
constants.THRESHOLD_COUNT_TO_SHOW_FIELD_NAME,
|
||||
constants.USER_INTERFACE_EXPERIENCE_FIELD_NAME,
|
||||
]
|
||||
)
|
||||
errors = []
|
||||
|
||||
# Are the dataframes the same shape truly
|
||||
assert tiles_df.shape == final_score_df.shape
|
||||
assert tiles_df["GTF"].equals(final_score_df["GTF"])
|
||||
assert sorted(tiles_df.columns) == sorted(final_score_df.columns)
|
||||
|
||||
# Are all the dtypes and values the same?
|
||||
comparisons = []
|
||||
for col_name in final_score_df.columns:
|
||||
value_comparison = ColumnValueComparison(
|
||||
final_score_df[col_name], tiles_df[col_name], col_name
|
||||
)
|
||||
comparisons.append(value_comparison)
|
||||
errors = [comp for comp in comparisons if not comp]
|
||||
error_message = "\n".join(error.error_message for error in errors)
|
||||
assert not errors, error_message
|
||||
|
||||
|
||||
def test_for_geojson_fidelity_from_tiles_csv(tiles_df, tiles_geojson_df):
|
||||
tiles_geojson_df = tiles_geojson_df.drop(columns=["geometry"]).rename(
|
||||
columns={"GEOID10": "GTF"}
|
||||
)
|
||||
assert tiles_df.shape == tiles_geojson_df.shape
|
||||
assert tiles_df["GTF"].equals(tiles_geojson_df["GTF"])
|
||||
assert sorted(tiles_df.columns) == sorted(tiles_geojson_df.columns)
|
||||
|
||||
# Are all the dtypes and values the same?
|
||||
for col_name in tiles_geojson_df.columns:
|
||||
if is_col_fake_bool(tiles_df[col_name]):
|
||||
tiles_df[col_name] = (
|
||||
tiles_df[col_name]
|
||||
.astype("float64")
|
||||
.replace({0.0: False, 1.0: True})
|
||||
)
|
||||
if is_col_fake_bool(tiles_geojson_df[col_name]):
|
||||
tiles_geojson_df[col_name] = (
|
||||
tiles_geojson_df[col_name]
|
||||
.astype("float64")
|
||||
.replace({0.0: False, 1.0: True})
|
||||
)
|
||||
tiles_geojson_df[col_name] = tiles_df[col_name].replace({None: np.nan})
|
||||
error_message = f"Column {col_name} not equal "
|
||||
# For non-numeric types, we can use the built-in equals from pandas
|
||||
if tiles_df[col_name].dtype in [
|
||||
np.dtype(object),
|
||||
np.dtype(bool),
|
||||
np.dtype(str),
|
||||
]:
|
||||
assert tiles_df[col_name].equals(
|
||||
tiles_geojson_df[col_name]
|
||||
), error_message
|
||||
# For numeric sources, use np.close so we don't get harmed by
|
||||
# float equaity weirdness
|
||||
else:
|
||||
assert np.allclose(
|
||||
tiles_df[col_name],
|
||||
tiles_geojson_df[col_name],
|
||||
equal_nan=True,
|
||||
), error_message
|
||||
|
||||
|
||||
def test_for_state_names(tiles_df):
|
||||
states = tiles_df["SF"].value_counts(dropna=False).index
|
||||
assert np.nan not in states
|
||||
assert states.all()
|
|
@ -0,0 +1,10 @@
|
|||
GEOID10_TRACT,included
|
||||
24027602100,True
|
||||
24027602303,True
|
||||
24027605503,True
|
||||
24027605502,True
|
||||
24027603004,False
|
||||
24027605104,True
|
||||
24027603003,True
|
||||
24027603001,True
|
||||
24027602201,True
|
|
|
@ -0,0 +1,101 @@
|
|||
GEOID10_TRACT,to_rank
|
||||
1,1
|
||||
2,2
|
||||
3,3
|
||||
4,4
|
||||
5,5
|
||||
6,6
|
||||
7,7
|
||||
8,8
|
||||
9,9
|
||||
10,10
|
||||
11,11
|
||||
12,12
|
||||
13,13
|
||||
14,14
|
||||
15,15
|
||||
16,16
|
||||
17,17
|
||||
18,18
|
||||
19,19
|
||||
20,20
|
||||
21,21
|
||||
22,22
|
||||
23,23
|
||||
24,24
|
||||
25,25
|
||||
26,26
|
||||
27,27
|
||||
28,28
|
||||
29,29
|
||||
30,30
|
||||
31,31
|
||||
32,32
|
||||
33,33
|
||||
34,34
|
||||
35,35
|
||||
36,36
|
||||
37,37
|
||||
38,38
|
||||
39,39
|
||||
40,40
|
||||
41,41
|
||||
42,42
|
||||
43,43
|
||||
44,44
|
||||
45,45
|
||||
46,46
|
||||
47,47
|
||||
48,48
|
||||
49,49
|
||||
50,50
|
||||
51,51
|
||||
52,52
|
||||
53,53
|
||||
54,54
|
||||
55,55
|
||||
56,56
|
||||
57,57
|
||||
58,58
|
||||
59,59
|
||||
60,60
|
||||
61,61
|
||||
62,62
|
||||
63,63
|
||||
64,64
|
||||
65,65
|
||||
66,66
|
||||
67,67
|
||||
68,68
|
||||
69,69
|
||||
70,70
|
||||
71,71
|
||||
72,72
|
||||
73,73
|
||||
74,74
|
||||
75,75
|
||||
76,76
|
||||
77,77
|
||||
78,78
|
||||
79,79
|
||||
80,80
|
||||
81,81
|
||||
82,82
|
||||
83,83
|
||||
84,84
|
||||
85,85
|
||||
86,86
|
||||
87,87
|
||||
88,88
|
||||
89,89
|
||||
90,90
|
||||
91,91
|
||||
92,92
|
||||
93,93
|
||||
94,94
|
||||
95,95
|
||||
96,96
|
||||
97,97
|
||||
98,98
|
||||
99,99
|
||||
100,100
|
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,73 @@
|
|||
# pylint: disable=protected-access
|
||||
# flake8: noqa=F841
|
||||
from contextlib import contextmanager
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from data_pipeline.etl.sources.geo_utils import get_tract_geojson
|
||||
from data_pipeline.score import field_names
|
||||
from data_pipeline.score.utils import (
|
||||
calculate_tract_adjacency_scores as original_calculate_tract_adjacency_score,
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patch_calculate_tract_adjacency_scores():
|
||||
# Use fixtures for tract data.
|
||||
tract_data_path = Path(__file__).parent / "data" / "us.geojson"
|
||||
|
||||
get_tract_geojson_mock = partial(
|
||||
get_tract_geojson, _tract_data_path=tract_data_path
|
||||
)
|
||||
with mock.patch(
|
||||
"data_pipeline.score.utils.get_tract_geojson",
|
||||
new=get_tract_geojson_mock,
|
||||
):
|
||||
yield original_calculate_tract_adjacency_score
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def score_data():
|
||||
score_csv = Path(__file__).parent / "data" / "scores.csv"
|
||||
return pd.read_csv(
|
||||
score_csv, dtype={field_names.GEOID_TRACT_FIELD: str, "included": bool}
|
||||
)
|
||||
|
||||
|
||||
def test_all_adjacent_are_true(score_data):
|
||||
score_data["included"] = True
|
||||
score_data.loc[
|
||||
score_data.GEOID10_TRACT == "24027603004", "included"
|
||||
] = False
|
||||
with patch_calculate_tract_adjacency_scores() as calculate_tract_adjacency_scores:
|
||||
adjancency_scores = calculate_tract_adjacency_scores(
|
||||
score_data, "included"
|
||||
)
|
||||
assert (
|
||||
adjancency_scores.loc[
|
||||
adjancency_scores.GEOID10_TRACT == "24027603004",
|
||||
"included" + field_names.ADJACENCY_INDEX_SUFFIX,
|
||||
].iloc[0]
|
||||
== 1.0
|
||||
)
|
||||
|
||||
|
||||
def test_all_adjacent_are_false(score_data):
|
||||
score_data["included"] = False
|
||||
score_data.loc[
|
||||
score_data.GEOID10_TRACT == "24027603004", "included"
|
||||
] = False
|
||||
with patch_calculate_tract_adjacency_scores() as calculate_tract_adjacency_scores:
|
||||
adjancency_scores = calculate_tract_adjacency_scores(
|
||||
score_data, "included"
|
||||
)
|
||||
assert (
|
||||
adjancency_scores.loc[
|
||||
adjancency_scores.GEOID10_TRACT == "24027603004",
|
||||
"included" + field_names.ADJACENCY_INDEX_SUFFIX,
|
||||
].iloc[0]
|
||||
== 0.0
|
||||
)
|
Loading…
Add table
Add a link
Reference in a new issue