Package: justice40-data-pipeline
Justice 40 Score applicationTable of ContentsJustice 40 Score applicationAbout this applicationUsing the data1. Source data2. Extract-Transform-Load (ETL) the data3. Combined dataset4. TilesetScore generation and comparison workflowWorkflow DiagramStep 0: Set up your environmentStep 1: Run the script to download census data or download from the Justice40 S3 URLStep 2: Run the ETL script for each data sourceStep 3: Calculate the Justice40 score experimentsStep 4: Compare the Justice40 score experiments to other indicesData SourcesRunning using DockerLocal developmentVSCodeMacOSWindows UsersSetting up PoetryDownloading Census Block Groups GeoJSON and Generating CBG CSVsGenerating Map TilesServe the map locallyRunning Jupyter notebooksActivating variable-enabled Markdown for Jupyter notebooksMiscellaneousTestingBackgroundConfiguration / FixturesUpdating PicklesFuture EnchancementsETL Unit TestsExtract TestsTransform TestsLoad TestsAbout this applicationThis application is used to compare experimental versions of the Justice40 score to established environmental justice indices, such as EJSCREEN, CalEnviroScreen, and so on.NOTE:These scoresdo notrepresent final versions of the Justice40 scores and are merely used for comparative purposes. As a result, the specific input columns and formulas used to calculate them are likely to change over time.Using the dataOne of our primary development principles is that the entire data pipeline should be open and replicable end-to-end. As part of this, in addition to all code being open, we also strive to make data visible and available for use at every stage of our pipeline. You can follow the instructions below in this README to spin up the data pipeline yourself in your own environment; you can also access the data we've already processed on our S3 bucket.In the sub-sections below, we outline what each stage of the data provenance looks like and where you can find the data output by that stage. If you'd like to actually perform each step in your own environment, skip down toScore generation and comparison workflow.1. Source dataIf you would like to find and use the raw source data, you can find the source URLs in theetl.pyfiles located within each directory indata/data-pipeline/etl/sources.2. Extract-Transform-Load (ETL) the dataThe first step of processing we perform is a simple ETL process for each of the source datasets. Code is available indata/data-pipeline/etl/sources, and the output of this process is a number of CSVs available at the following locations:EJScreen:https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/ejscreen_2019/usa.csvCensus ACS 2019:https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/census_acs_2019/usa.csvHousing and Transportation Index:https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/housing_and_transportation_index/usa.csvHUD Housing:https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/hud_housing/usa.csvEach CSV may have a different column name for the census tract or census block group identifier. You can find what the name is in the ETL code. Please note that when you view these files you should make sure that your text editor or spreadsheet software does not remove the initial0from this identifier field (many IDs begin with0).3. Combined datasetThe CSV with the combined data from all of these sourcescan be accessed here.4. TilesetOnce we have all the data from the previous stages, we convert it to tiles to make it usable on a map. We render the map on the client side which can be seen usingdocker-compose up.5. ShapefilesIf you want to use the shapefiles in mapping applications, you can access themhere.Score generation and comparison workflowThe descriptions below provide a more detailed outline of what happens at each step of ETL and score calculation workflow.Workflow DiagramTODO add mermaid diagramStep 0: Set up your environmentChoose whether you'd like to run this application using Docker or if you'd like to install the dependencies locally so you can contribute to the project.With Docker:Follow theseinstallation instructionsand skip down to theRunning with Docker sectionfor more informationFor Local Development:Skip down to theLocal Development sectionfor more detailed installation instructionsStep 1: Run the script to download census data or download from the Justice40 S3 URLCall thecensus_data_downloadcommand using the application managerapplication.pyNOTE:This may take several minutes to execute.With Docker:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application census-data-downloadWith Poetry:poetry run download_census(Install GDAL as describedbelow)If you have a high speed internet connection and don't want to generate the census data or installGDALlocally, you can download a zip version of the Census filehere. Then unzip and move the contents inside thedata/data-pipeline/data_pipeline/data/census/folder/Step 2: Run the ETL script for each data sourceTable of commandsVS code commandactual commandrun timewhat it doeswhere it writes tonotesETL runetl-runDownloads the data set filesdata/datasetcheck if there are any changes in data_pipeline/etl/sources. if there are none this can be skipped.Score runscore-run6 minsconsume the etl outputs and combine into a score csv full.data/score/csv/full/usa.csvGenerate Score postgenerate-score-post9 mins1. combines the score/csv/full with counties. 2. downloadable assets (xls, csv, zip), 3. creates the tiles/csvdata/score/csv/tiles/usa.csv, data/ score/downloadablecheck destination folder to see if newly createdCombine score and geoJsongeo-score26 mins1. combine the data/score/csv/tiles/usa.csv with the census tiger geojson data 2. aggregates into super tracts for usa-low layerdata/score/geojson (usa high / low)Generate Map Tilesgenerate-map-tiles35 minsogr-ogr pbf / mvt tiles generator that consume the geojson usa high / usa lowdata/score/tiles/ high or low / {zoomLevel}ETL stepsCall theetl-runcommand using the application managerapplication.pyNOTE:This may take several minutes to execute.With Docker:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application etl-runWith Poetry:poetry run python3 data_pipeline/application.py etl-runThis command will execute the corresponding ETL script for each data source indata_pipeline/etl/sources/. For example,data_pipeline/etl/sources/ejscreen/etl.pyis the ETL script for EJSCREEN data.Each ETL script will extract the data from its original source, then format the data into.csvfiles that get stored in the relevant folder indata_pipeline/data/dataset/. For example, HUD Housing data is stored indata_pipeline/data/dataset/hud_housing/usa.csvNOTE:You have the option to pass the name of a specific data source to theetl-runcommand using the-dflag, which will limit the execution of the ETL process to that specific data source.For example:poetry run python3 data_pipeline/application.py etl-run -d ejscreenwould only run the ETL process for EJSCREEN data.Step 3: Calculate the Justice40 score experimentsCall thescore-runcommand using the application managerapplication.pyNOTE:This may take several minutes to execute.With Docker:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application score-runWith Poetry:poetry run python3 data_pipeline/application.py score-runThescore-runcommand will execute theetl/score/etl.pyscript which loads the data from each of the source files added to thedata/dataset/directory by the ETL scripts in Step 1.These data sets are merged into a single dataframe using their Census Block Group GEOID as a common key, and the data in each of the columns is standardized in two ways:Theirpercentile rankis calculated, which tells us what percentage of other Census Block Groups have a lower value for that particular column.They are normalized usingmin-max normalization, which adjusts the scale of the data so that the Census Block Group with the highest value for that column is set to 1, the Census Block Group with the lowest value is set to 0, and all of the other values are adjusted to fit within that range based on how close they were to the highest or lowest value.The standardized columns are then used to calculate each of the Justice40 score experiments described in greater detail below, and the results are exported to a.csvfile indata_pipeline/data/score/csvStep 4: Compare the Justice40 score experiments to other indicesWe are building a comparison tool to enable easy (or at least straightforward) comparison of the Justice40 score with other existing indices. The goal of having this is so that as we experiment and iterate with a scoring methodology, we can understand how our score overlaps with or differs from other indices that communities, nonprofits, and governmentss use to inform decision making.Right now, our comparison tool exists simply as a python notebook indata/data-pipeline/data_pipeline/ipython/scoring_comparison.ipynb.To run this comparison tool:Make sure you've gone through the above steps to run the data ETL and score generation.From the package directory (data/data-pipeline/data_pipeline/), navigate to theipythondirectory:cd ipython.Ensure you havepandocinstalled on your computer. If you're on a Mac, runbrew install pandoc; for other OSes, see pandoc'sinstallation guide.Start the notebooks:jupyter notebookIn your browser, navigate to one of the URLs returned by the above command.Selectscoring_comparison.ipynbfrom the options in your browser.Run through the steps in the notebook. You can step through them one at a time by clicking the "Run" button for each cell, or open the "Cell" menu and click "Run all" to run them all at once.Reports and spreadsheets generated by the comparison tool will be available indata/data-pipeline/data_pipeline/data/comparison_outputs.NOTE:This may take several minutes or over an hour to fully execute and generate the reports.Data SourcesEJSCREEN:TODO Add description of data sourceCensus:TODO Add description of data sourceAmerican Communities Survey:TODO Add description of data sourceHousing and Transportation:TODO Add description of data sourceHUD Housing:TODO Add description of data sourceHUD Recap:TODO Add description of data sourceCalEnviroScreen:TODO Add description of data sourceRunning using DockerWe use Docker to install the necessary libraries in a container that can be run in any operating system.Important: To be able to run the data Docker containers, you need to increase the memory resource of your container to at leat 8096 MB.To build the docker container the first time, make sure you're in the root directory of the repository and rundocker-compose build --no-cache.Once completed, rundocker-compose up. Docker will spin up 3 containers: the client container, the static server container and the data container. Once all data is generated, you can see the application using a browser and navigating tohttp://localhost:8000.If you want to run specific data tasks, you can open a terminal window, navigate to the root folder for this repository and then execute any command for the application using this format:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application [command]Here's a list of commands:Get help:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application --helpGenerate census data:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application census-data-downloadRun all ETL and Generate score:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application score-full-runClean up the data directories:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application data-cleanupRun all ETL processes:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application etl-runGenerate Score:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application score-runCombine Score with Geojson and generate high and low zoom map tile sets:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application geo-scoreGenerate Map Tiles:docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application generate-map-tilesLocal developmentYou can run the Python code locally without Docker to develop, using Poetry. However, to generate the census data you will need theGDAL libraryinstalled locally. Also to generate tiles for a local map, you will needMapbox tippecanoe. Please refer to the repos for specific instructions for your OS.VSCodeIf you are using VSCode, you can make use of the.vscodefolder checked in underdata/data-pipeline/.vscode. To do this, open this directory withcode data/data-pipeline.Here's whats included:launch.json- launch commands that allow for debugging the various commands inapplication.py. Note that because we are using the otherwise excellentClick CLI, and Click in turn usesconsole_scriptsto parse and execute command line options, it is necessary to run the equivalent ofpython -m data_pipeline.application [command]withinlaunch.jsonto be able to set and hit breakpoints (this is what is currently implemented. Otherwise, you may find that the script times out after 5 seconds. More about thishere.settings.json- these ensure that you're using the default linter (pylint), formatter (flake8), and test library (pytest) that the team is using.tasks.json- these enable you to useTerminal->Run Taskto run our preferred formatters and linters within your project.Users are instructed to only add settings to this file that should be shared across the team, and not to add settings here that only apply to local development environments (particularly full absolute paths which can differ between setups). If you are looking to add something to this file, check in with the rest of the team to ensure the proposed settings should be shared.MacOSTo install the above-named executables:gdal:brew install gdalTippecanoe:brew install tippecanoeWindows UsersIf you want to run tile generation, please install TippeCanoefollowing these instructions. You also need some pre-requisites for Geopandas as specified in the Poetry requirements. Please followthese instructionsto install the Geopandas dependency locally. It's definitely easier if you have access to WSL (Windows Subsystem Linux), and install these packages using commands similar to ourDockerfile.Setting up PoetryStart a terminalChange to this directory (/data/data-pipeline/)Make sure you have at least Python 3.7 installed:python -Vorpython3 -VWe usePoetryfor managing dependencies and building the application. Please follow the instructions on their site to download.Install Poetry requirements withpoetry installThe Application entrypointAfter installing the poetry dependencies, you can see a list of commands with the following steps:Start a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Then runpoetry run python3 data_pipeline/application.py --helpDownloading Census Block Groups GeoJSON and Generating CBG CSVs (not normally required)Start a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)If you want to clear out all data and tiles from all directories, you can run:poetry run python3 data_pipeline/application.py data-cleanup.Then runpoetry run python3 data_pipeline/application.py census-data-downloadNote: Census files are hosted in the Justice40 S3 and you can skip this step by passing the-s awsor--data-source awsflag in the scripts belowRun all ETL, score and map generation processesStart a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Then runpoetry run python3 data_pipeline/application.py data-full-run -s awsNote: The-sflag is optional if you have generated/downloaded the census dataRun both ETL and score generation processesStart a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Then runpoetry run python3 data_pipeline/application.py score-full-runRun all ETL processesStart a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Then runpoetry run python3 data_pipeline/application.py etl-runGenerating Map TilesStart a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Then runpoetry run python3 data_pipeline/application.py generate-map-tiles -s awsIf you have S3 keys, you can sync to the dev repo by doingaws s3 sync ./data_pipeline/data/score/tiles/ s3://justice40-data/data-pipeline/data/score/tiles --acl public-read --deleteNote: The-sflag is optional if you have generated/downloaded the score dataServe the map locallyStart a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)For USA high zoom:docker run --rm -it -v ${PWD}/data/score/tiles/high:/data -p 8080:80 maptiler/tileserver-glRunning Jupyter notebooksStart a terminalChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Runpoetry run jupyter notebook. Your browser should open with a Jupyter Notebook tabActivating variable-enabled Markdown for Jupyter notebooksChange to the package directory (i.e.,cd data/data-pipeline/data_pipeline)Activate a Poetry Shell (see above)Runjupyter contrib nbextension install --userRunjupyter nbextension enable python-markdown/mainMake sure you've loaded the Jupyter notebook in a "Trusted" state. (See button near top right of Notebook screen.)For more information, seenbextensions docsand
seepython-markdown docs.TestingBackgroundFor this project, we make use ofpytestfor testing purposes. To run tests, simply runpoetry run pytestin this directory (i.e.,justice40-tool/data/data-pipeline).Test data is configured viafixtures.Score and post-processing testsThe fixtures used in the score post-processing tests are slightly different. These fixtures utilizepickle filesto store dataframes to disk. This is ultimately because if you assert equality on two dataframes, even if column values have the same "visible" value, if their types are mismatching they will be counted as not being equal.In a bit more detail:Pandas dataframes are typed, and by default, types are inferred when you create one from scratch. If you create a dataframe using theDataFrameconstructors, there is no guarantee that types will be correct, without explicitdtypeannotations. Explicitdtypeannotations are possible, but, and this leads us to point #2:Our transformations/dataframes in the source code under test itself doesn't always require specific types, and it is often sufficient in the code itself to just rely on theobjecttype. I attempted adding explicit typing based on the "logical" type of given columns, but in practice it resulted in non-matching dataframes thatactuallyhad the same value -- in particular it was very common to have one dataframe column of typestringand another of typeobjectthat carried the same values. So, that is to say, even if we did create a "correctly" typed dataframe (according to our logical assumptions about what types should be), they were still counted as mismatched against the dataframes that are actually used in our program. To fix this "the right way", it is necessary to explicitly annotate types at the point of theread_csvcall, which definitely has other potential unintended side effects and would need to be done carefully.For larger dataframes (some of these have 150+ values), it was initially deemed too difficult/time consuming to manually annotate all types, and further, to modify those type annotations based on what is expected in the souce code under test.Updating PicklesIf you update the score in any way, it is necessary to create new pickles so that data is validated correctly.It starts with thedata_pipeline/etl/score/tests/sample_data/score_data_initial.csv, which is the first two rows of thescore/full/usa.csv.To update this file, run a full score generation, then open a Python shell from thedata-pipelinedirectory (e.g.poetry run python3), and then update the file with the following commands:import pickle
from pathlib import Path
import pandas as pd
data_path = Path.cwd()

# score data expected
score_csv_path = data_path / "data_pipeline" / "data" / "score" / "csv" / "full" / "usa.csv"
score_initial_df = pd.read_csv(score_csv_path, dtype={"GEOID10_TRACT": "string"}, low_memory=False, nrows=2)
score_initial_df.to_csv(data_path / "data_pipeline" / "etl" / "score" / "tests" / "sample_data" /"score_data_initial.csv", index=False)Now you can move on to updating individual pickles for the tests. Note that it is helpful to do them in this order:We have four pickle files that correspond to expected files:score_data_expected.pkl: Initial score without countiesscore_transformed_expected.pkl: Intermediate score withetl._extract_scoreandetl. _transform_scoreapplied. There's no file for this intermediate process, so we need to capture the pickle mid-process.tile_data_expected.pkl: Score with columns to be baked in tilesdownloadable_data_expected.pk1: Downloadable csvTo update the pickles, let's go one by one:For thescore_transformed_expected.pkl, put a breakpoint onthis line, before thepdt.assert_frame_equaland run:pytest data_pipeline/etl/score/tests/test_score_post.py::test_transform_scoreOnce on the breakpoint, capture the df to a pickle as follows:import pickle
from pathlib import Path
data_path = Path.cwd()
score_transformed_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "score_transformed_expected.pkl", protocol=4)Then take out the breakpoint and re-run the test:pytest data_pipeline/etl/score/tests/test_score_post.py::test_transform_scoreFor thescore_data_expected.pkl, put a breakpoint onthis line, before thepdt.assert_frame_equaland run:pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_score_dataOnce on the breakpoint, capture the df to a pickle as follows:import pickle
from pathlib import Path
data_path = Path.cwd()
score_data_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "score_data_expected.pkl", protocol=4)Then take out the breakpoint and re-run the test:pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_score_dataFor thetile_data_expected.pkl, put a breakpoint onthis line, before thepdt.assert_frame_equaland run:pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_tile_dataOnce on the breakpoint, capture the df to a pickle as follows:import pickle
from pathlib import Path
data_path = Path.cwd()
output_tiles_df_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "tile_data_expected.pkl", protocol=4)Then take out the breakpoint and re-run the test:pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_tile_dataFor thedownloadable_data_expected.pk1, put a breakpoint onthis line, before thepdt.assert_frame_equaland run:pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_downloadable_dataOnce on the breakpoint, capture the df to a pickle as follows:import pickle
from pathlib import Path
data_path = Path.cwd()
output_downloadable_df_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "downloadable_data_expected.pkl", protocol=4)Then take out the breakpoint and re-run the test:pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_downloadable_dataFuture EnhancementsPickles have several downsides that we should consider alternatives for:They are opaque - it is necessary to open a python interpreter (as written above) to confirm its contentsThey are a bit harder for newcomers to python to grok.They potentially encode flawed typing assumptions (see above) which are paved over for future test runs.In the future, we could adopt any of the below strategies to work around this:We could usepytest-snapshotto automatically store the output of each test as data changes. This would make it so that you could avoid having to generate a pickle for each method - instead, you would only need to callgenerateonce , and only when the dataframe had changed.Additionally, you could use a pandas type schema annotation such aspanderato annotate input/output schemas for given functions, and your unit tests could use these to validate explicitly. This could be of very high value for annotating expectations.Alternatively, or in conjunction, you could move toward using a more strictly-typed container format for read/writes such as SQL/SQLite, and use something likeSQLModelto handle more explicit type guarantees.Fixtures used in ETL "snapshot tests"ETLs are tested for the results of their extract, transform, and load steps by
borrowing the concept of "snapshot testing" from the world of front-end development.Snapshots are easy to update and demonstrate the results of a series of changes to
the code base. They are good for making sure no results have changed if you don't
expect them to change, and they are good when you expect the results to significantly
change in a way that would be tedious to update in traditional unit tests.However, snapshot tests are also dangerous. An unthinking developer may update the
snapshot fixtures and unknowingly encode a bug into the supposed intended output of
the test.In order to update the snapshot fixtures of an ETL class, follow the following steps:If you need to manually update the fixtures, update the "furthest upstream" source
that is called by_setup_etl_instance_and_run_extract. For instance, this may
involve creating a new zip file that imitates the source data. (e.g., for the
National Risk Index test, updatedata_pipeline/tests/sources/national_risk_index/data/NRI_Table_CensusTracts.zipwhich is a 64kb imitation of the 405MB source NRI data.)Runpytest . -rsx --update_snapshotsto update snapshots for all files, or you
can pass a specific file name to pytest to be more precise (e.g.,pytest  data_pipeline/tests/sources/national_risk_index/test_etl.py -rsx --update_snapshots)Re-run pytest without theupdate_snapshotsflag (e.g.,pytest . -rsx) to
ensure the tests now pass.Carefully check thegit difffor the updates to all test fixtures to make sure
these are as expected. This part is very important. For instance, if you changed a
column name, you would only expect the column name to change in the output. If
you modified the calculation of some data, spot check the results to see if the
numbers in the updated fixtures are as expected.Other ETL Unit TestsOutside of the ETL snapshot tests discussed above, ETL unit tests are typically
organized into three buckets:Extract TestsTransform Tests, andLoad TestsThese are tested using different strategies explained below.Extract TestsExtract tests rely on the limited data transformations that occur as data is loaded from source files.In tests, we use fake, limited CSVs read viaStringIO, taken from the first several rows of the files of interest, and ensure data types are correct.Down the line, we could use a tool likePanderato enforce schemas, both for the tests and the classes themselves.Transform TestsTransform tests are the heart of ETL unit tests, and compare ideal dataframes with their actual counterparts.See aboveFixturessection for information about where data is coming from.Load TestsThese make use oftmp_path_factoryto create a file-system located undertemp_dir, and validate whether the correct files are written to the correct locations.Additional future modifications could include the use of Pandera and/or other schema validation tools, and or a more explicit test that the data written to file can be read back in and yield the same dataframe.