# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['data_pipeline',
 'data_pipeline.content.config',
 'data_pipeline.data.census',
 'data_pipeline.data.census.csv',
 'data_pipeline.data.census.geojson',
 'data_pipeline.data.census.shp',
 'data_pipeline.data.dataset',
 'data_pipeline.data.score.csv',
 'data_pipeline.data.score.downloadable',
 'data_pipeline.data.score.geojson',
 'data_pipeline.data.score.shapefile',
 'data_pipeline.data.score.tiles',
 'data_pipeline.etl',
 'data_pipeline.etl.score',
 'data_pipeline.etl.score.tests',
 'data_pipeline.etl.score.tests.sample_data',
 'data_pipeline.etl.sources',
 'data_pipeline.etl.sources.calenviroscreen',
 'data_pipeline.etl.sources.cdc_life_expectancy',
 'data_pipeline.etl.sources.cdc_places',
 'data_pipeline.etl.sources.cdc_svi_index',
 'data_pipeline.etl.sources.census',
 'data_pipeline.etl.sources.census_acs',
 'data_pipeline.etl.sources.census_acs_2010',
 'data_pipeline.etl.sources.census_acs_median_income',
 'data_pipeline.etl.sources.census_decennial',
 'data_pipeline.etl.sources.child_opportunity_index',
 'data_pipeline.etl.sources.doe_energy_burden',
 'data_pipeline.etl.sources.ejscreen',
 'data_pipeline.etl.sources.ejscreen_areas_of_concern',
 'data_pipeline.etl.sources.energy_definition_alternative_draft',
 'data_pipeline.etl.sources.epa_rsei',
 'data_pipeline.etl.sources.geocorr',
 'data_pipeline.etl.sources.housing_and_transportation',
 'data_pipeline.etl.sources.hud_housing',
 'data_pipeline.etl.sources.hud_recap',
 'data_pipeline.etl.sources.mapping_for_ej',
 'data_pipeline.etl.sources.mapping_inequality',
 'data_pipeline.etl.sources.maryland_ejscreen',
 'data_pipeline.etl.sources.michigan_ejscreen',
 'data_pipeline.etl.sources.national_risk_index',
 'data_pipeline.etl.sources.persistent_poverty',
 'data_pipeline.etl.sources.tree_equity_score',
 'data_pipeline.ipython.experiment_4_weighting',
 'data_pipeline.score',
 'data_pipeline.tests',
 'data_pipeline.tests.sources',
 'data_pipeline.tests.sources.example',
 'data_pipeline.tests.sources.national_risk_index',
 'data_pipeline.tile']

package_data = \
{'': ['*'],
 'data_pipeline': ['files/*',
                   'ipython/*',
                   'ipython/home_foreclosures_analysis_nhpd/*'],
 'data_pipeline.etl.score.tests': ['snapshots/*'],
 'data_pipeline.etl.sources.mapping_inequality': ['data/*'],
 'data_pipeline.tests.sources.example': ['data/*'],
 'data_pipeline.tests.sources.national_risk_index': ['data/*']}

install_requires = \
['CensusData>=1.13,<2.0',
 'PyYAML>=6.0,<7.0',
 'click>=8.0.1,<9.0.0',
 'dynaconf>=3.1.4,<4.0.0',
 'geopandas>=0.9.0,<0.10.0',
 'ipdb>=0.13.9,<0.14.0',
 'ipython>=7.31.1,<8.0.0',
 'jupyter-contrib-nbextensions>=0.5.1,<0.6.0',
 'jupyter>=1.0.0,<2.0.0',
 'matplotlib>=3.4.2,<4.0.0',
 'numpy>=1.22.1,<2.0.0',
 'pandas>=1.2.5,<2.0.0',
 'pillow==9.0.1',
 'pylint>=2.11.1,<3.0.0',
 'pypandoc>=1.6.3,<2.0.0',
 'requests>=2.25.1,<3.0.0',
 'tqdm==4.62.0',
 'types-requests>=2.25.0,<3.0.0',
 'us>=2.0.2,<3.0.0',
 'xlsxwriter>=2.0.0,<3.0.0']

setup_kwargs = {
    'name': 'justice40-data-pipeline',
    'version': '0.1.0',
    'description': 'ETL, Score and Map Generation of Justice 40 Tool',
    'long_description': '# Justice 40 Score application\n\n<details open="open">\n<summary>Table of Contents</summary>\n\n<!-- TOC -->\n\n- [Justice 40 Score application](#justice-40-score-application)\n  - [About this application](#about-this-application)\n    - [Using the data](#using-the-data)\n      - [1. Source data](#1-source-data)\n      - [2. Extract-Transform-Load (ETL) the data](#2-extract-transform-load-etl-the-data)\n      - [3. Combined dataset](#3-combined-dataset)\n      - [4. Tileset](#4-tileset)\n    - [Score generation and comparison workflow](#score-generation-and-comparison-workflow)\n      - [Workflow Diagram](#workflow-diagram)\n      - [Step 0: Set up your environment](#step-0-set-up-your-environment)\n      - [Step 1: Run the script to download census data or download from the Justice40 S3 URL](#step-1-run-the-script-to-download-census-data-or-download-from-the-justice40-s3-url)\n      - [Step 2: Run the ETL script for each data source](#step-2-run-the-etl-script-for-each-data-source)\n      - [Step 3: Calculate the Justice40 score experiments](#step-3-calculate-the-justice40-score-experiments)\n      - [Step 4: Compare the Justice40 score experiments to other indices](#step-4-compare-the-justice40-score-experiments-to-other-indices)\n    - [Data Sources](#data-sources)\n  - [Running using Docker](#running-using-docker)\n  - [Local development](#local-development)\n    - [VSCode](#vscode)\n    - [MacOS](#macos)\n    - [Windows Users](#windows-users)\n    - [Setting up Poetry](#setting-up-poetry)\n    - [Downloading Census Block Groups GeoJSON and Generating CBG CSVs](#downloading-census-block-groups-geojson-and-generating-cbg-csvs)\n    - [Generating Map Tiles](#generating-map-tiles)\n    - [Serve the map locally](#serve-the-map-locally)\n    - [Running Jupyter notebooks](#running-jupyter-notebooks)\n    - [Activating variable-enabled Markdown for Jupyter notebooks](#activating-variable-enabled-markdown-for-jupyter-notebooks)\n  - [Miscellaneous](#miscellaneous)\n  - [Testing](#testing)\n    - [Background](#background)\n    - [Configuration / Fixtures](#configuration--fixtures)\n      - [Updating Pickles](#updating-pickles)\n      - [Future Enchancements](#future-enchancements)\n    - [ETL Unit Tests](#etl-unit-tests)\n      - [Extract Tests](#extract-tests)\n      - [Transform Tests](#transform-tests)\n      - [Load Tests](#load-tests)\n\n<!-- /TOC -->\n\n</details>\n\n## About this application\n\nThis application is used to compare experimental versions of the Justice40 score to established environmental justice indices, such as EJSCREEN, CalEnviroScreen, and so on.\n\n_**NOTE:** These scores **do not** represent 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._\n\n### Using the data\n\nOne 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.\n\nIn 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 to [Score generation and comparison workflow](#score-generation-and-comparison-workflow).\n\n#### 1. Source data\n\nIf you would like to find and use the raw source data, you can find the source URLs in the `etl.py` files located within each directory in `data/data-pipeline/etl/sources`.\n\n#### 2. Extract-Transform-Load (ETL) the data\n\nThe first step of processing we perform is a simple ETL process for each of the source datasets. Code is available in `data/data-pipeline/etl/sources`, and the output of this process is a number of CSVs available at the following locations:\n\n- EJScreen: <https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/ejscreen_2019/usa.csv>\n- Census ACS 2019: <https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/census_acs_2019/usa.csv>\n- Housing and Transportation Index: <https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/housing_and_transportation_index/usa.csv>\n- HUD Housing: <https://justice40-data.s3.amazonaws.com/data-pipeline/data/dataset/hud_housing/usa.csv>\n\nEach 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 initial `0` from this identifier field (many IDs begin with `0`).\n\n#### 3. Combined dataset\n\nThe CSV with the combined data from all of these sources [can be accessed here](https://justice40-data.s3.amazonaws.com/data-pipeline/data/score/csv/full/usa.csv).\n\n#### 4. Tileset\n\nOnce 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 using `docker-compose up`.\n\n#### 5. Shapefiles\n\nIf you want to use the shapefiles in mapping applications, you can access them [here](https://justice40-data.s3.amazonaws.com/data-pipeline/data/score/shapefile/usa.zip).\n\n\n### Score generation and comparison workflow\n\nThe descriptions below provide a more detailed outline of what happens at each step of ETL and score calculation workflow.\n\n#### Workflow Diagram\n\nTODO add mermaid diagram\n\n#### Step 0: Set up your environment\n\n1. Choose 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.\n   - **With Docker:** Follow these [installation instructions](https://docs.docker.com/get-docker/) and skip down to the [Running with Docker section](#running-with-docker) for more information\n   - **For Local Development:** Skip down to the [Local Development section](#local-development) for more detailed installation instructions\n\n#### Step 1: Run the script to download census data or download from the Justice40 S3 URL\n\n1. Call the `census_data_download` command using the application manager `application.py` **NOTE:** This may take several minutes to execute.\n   - 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-download`\n   - With Poetry: `poetry run download_census` (Install GDAL as described [below](#local-development))\n2. If you have a high speed internet connection and don\'t want to generate the census data or install `GDAL` locally, you can download a zip version of the Census file [here](https://justice40-data.s3.amazonaws.com/data-sources/census.zip). Then unzip and move the contents inside the `data/data-pipeline/data_pipeline/data/census/` folder/\n\n#### Step 2: Run the ETL script for each data source\n\n##### Table of commands\n\n| VS code command           | actual command      | run time | what it does                                                                                                                     | where it writes to                                     | notes                                                                                               |\n|---------------------------|---------------------|----------|----------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------|-----------------------------------------------------------------------------------------------------|\n| ETL run                   | etl-run             |          | Downloads the data set files                                                                                                     | data/dataset                                           | check if there are any changes in data_pipeline/etl/sources. if there are none this can be skipped. |\n| Score run                 | score-run           | 6 mins   | consume the etl outputs and combine into a score csv full.                                                                       | data/score/csv/full/usa.csv                            |                                                                                                     |\n| Generate Score post       | generate-score-post | 9 mins   | 1. combines the score/csv/full with counties. 2. downloadable assets (xls, csv, zip), 3. creates the tiles/csv                   | data/score/csv/tiles/usa.csv, data/ score/downloadable | check destination folder to see if newly created                                                    |\n| Combine score and geoJson | geo-score           | 26 mins  | 1. combine the data/score/csv/tiles/usa.csv with the census tiger geojson data 2. aggregates into super tracts for usa-low layer | data/score/geojson (usa high / low)                    |                                                                                                     |\n| Generate Map Tiles        | generate-map-tiles  |    35 mins | ogr-ogr pbf / mvt tiles generator that consume the geojson usa high / usa low                                                    | data/score/tiles/ high or low / {zoomLevel}            |                                                                                                     |\n\n##### ETL steps\n1. Call the `etl-run` command using the application manager `application.py` **NOTE:** This may take several minutes to execute.\n   - 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-run`\n   - With Poetry: `poetry run python3 data_pipeline/application.py etl-run`\n2. This command will execute the corresponding ETL script for each data source in `data_pipeline/etl/sources/`. For example, `data_pipeline/etl/sources/ejscreen/etl.py` is the ETL script for EJSCREEN data.\n3. Each ETL script will extract the data from its original source, then format the data into `.csv` files that get stored in the relevant folder in `data_pipeline/data/dataset/`. For example, HUD Housing data is stored in `data_pipeline/data/dataset/hud_housing/usa.csv`\n\n_**NOTE:** You have the option to pass the name of a specific data source to the `etl-run` command using the `-d` flag, which will limit the execution of the ETL process to that specific data source._\n_For example: `poetry run python3 data_pipeline/application.py etl-run -d ejscreen` would only run the ETL process for EJSCREEN data._\n\n#### Step 3: Calculate the Justice40 score experiments\n\n1. Call the `score-run` command using the application manager `application.py` **NOTE:** This may take several minutes to execute.\n   - 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-run`\n   - With Poetry: `poetry run python3 data_pipeline/application.py score-run`\n1. The `score-run` command will execute the `etl/score/etl.py` script which loads the data from each of the source files added to the `data/dataset/` directory by the ETL scripts in Step 1.\n1. 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:\n   - Their [percentile rank](https://en.wikipedia.org/wiki/Percentile_rank) is calculated, which tells us what percentage of other Census Block Groups have a lower value for that particular column.\n   - They are normalized using [min-max normalization](https://en.wikipedia.org/wiki/Feature_scaling), 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.\n1. 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 `.csv` file in [`data_pipeline/data/score/csv`](data_pipeline/data/score/csv)\n\n#### Step 4: Compare the Justice40 score experiments to other indices\n\nWe 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.\n\nRight now, our comparison tool exists simply as a python notebook in `data/data-pipeline/data_pipeline/ipython/scoring_comparison.ipynb`.\n\nTo run this comparison tool:\n\n1. Make sure you\'ve gone through the above steps to run the data ETL and score generation.\n1. From the package directory (`data/data-pipeline/data_pipeline/`), navigate to the `ipython` directory: `cd ipython`.\n1. Ensure you have `pandoc` installed on your computer. If you\'re on a Mac, run `brew install pandoc`; for other OSes, see pandoc\'s [installation guide](https://pandoc.org/installing.html).\n1. Start the notebooks: `jupyter notebook`\n1. In your browser, navigate to one of the URLs returned by the above command.\n1. Select `scoring_comparison.ipynb` from the options in your browser.\n1. 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.\n1. Reports and spreadsheets generated by the comparison tool will be available in `data/data-pipeline/data_pipeline/data/comparison_outputs`.\n\n_NOTE:_ This may take several minutes or over an hour to fully execute and generate the reports.\n\n### Data Sources\n\n- **[EJSCREEN](data_pipeline/etl/sources/ejscreen):** TODO Add description of data source\n- **[Census](data_pipeline/etl/sources/census):** TODO Add description of data source\n- **[American Communities Survey](data_pipeline/etl/sources/census_acs):** TODO Add description of data source\n- **[Housing and Transportation](data_pipeline/etl/sources/housing_and_transportation):** TODO Add description of data source\n- **[HUD Housing](data_pipeline/etl/sources/hud_housing):** TODO Add description of data source\n- **[HUD Recap](data_pipeline/etl/sources/hud_recap):** TODO Add description of data source\n- **[CalEnviroScreen](data_pipeline/etl/sources/calenviroscreen):** TODO Add description of data source\n\n## Running using Docker\n\nWe use Docker to install the necessary libraries in a container that can be run in any operating system.\n\n_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.\n\nTo build the docker container the first time, make sure you\'re in the root directory of the repository and run `docker-compose build --no-cache`.\n\nOnce completed, run `docker-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 to `http://localhost:8000`.\n\nIf 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:\n\n`docker run --rm -it -v ${PWD}/data/data-pipeline/data_pipeline/data:/data_pipeline/data j40_data_pipeline python3 -m data_pipeline.application [command]`\n\nHere\'s a list of commands:\n\n- 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 --help`\n- Generate 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-download`\n- Run 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-run`\n- Clean 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-cleanup`\n- Run 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-run`\n- 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-run`\n- Combine 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-score`\n- Generate 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-tiles`\n\n## Local development\n\nYou can run the Python code locally without Docker to develop, using Poetry. However, to generate the census data you will need the [GDAL library](https://github.com/OSGeo/gdal) installed locally. Also to generate tiles for a local map, you will need [Mapbox tippecanoe](https://github.com/mapbox/tippecanoe). Please refer to the repos for specific instructions for your OS.\n\n### VSCode\n\nIf you are using VSCode, you can make use of the `.vscode` folder checked in under `data/data-pipeline/.vscode`. To do this, open this directory with `code data/data-pipeline`.\n\nHere\'s whats included:\n\n1. `launch.json` - launch commands that allow for debugging the various commands in `application.py`. Note that because we are using the otherwise excellent [Click CLI](https://click.palletsprojects.com/en/8.0.x/), and Click in turn uses `console_scripts` to parse and execute command line options, it is necessary to run the equivalent of `python -m data_pipeline.application [command]` within `launch.json` to 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 this [here](https://stackoverflow.com/questions/64556874/how-can-i-debug-python-console-script-command-line-apps-with-the-vscode-debugger).\n\n2. `settings.json` - these ensure that you\'re using the default linter (`pylint`), formatter (`flake8`), and test library (`pytest`) that the team is using.\n\n3. `tasks.json` - these enable you to use `Terminal->Run Task` to run our preferred formatters and linters within your project.\n\nUsers 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.\n\n### MacOS\n\nTo install the above-named executables:\n\n- gdal: `brew install gdal`\n- Tippecanoe: `brew install tippecanoe`\n\n### Windows Users\n\nIf you want to run tile generation, please install TippeCanoe [following these instructions](https://github.com/GISupportICRC/ArcGIS2Mapbox#installing-tippecanoe-on-windows). You also need some pre-requisites for Geopandas as specified in the Poetry requirements. Please follow [these instructions](https://stackoverflow.com/questions/56958421/pip-install-geopandas-on-windows) to 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 our [Dockerfile](https://github.com/usds/justice40-tool/blob/main/data/data-pipeline/Dockerfile).\n\n### Setting up Poetry\n\n- Start a terminal\n- Change to this directory (`/data/data-pipeline/`)\n- Make sure you have at least Python 3.7 installed: `python -V` or `python3 -V`\n- We use [Poetry](https://python-poetry.org/) for managing dependencies and building the application. Please follow the instructions on their site to download.\n- Install Poetry requirements with `poetry install`\n\n### The Application entrypoint\n\nAfter installing the poetry dependencies, you can see a list of commands with the following steps:\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Then run `poetry run python3 data_pipeline/application.py --help`\n\n### Downloading Census Block Groups GeoJSON and Generating CBG CSVs (not normally required)\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- 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`.\n- Then run `poetry run python3 data_pipeline/application.py census-data-download`\n  Note: Census files are hosted in the Justice40 S3 and you can skip this step by passing the `-s aws` or `--data-source aws` flag in the scripts below\n\n### Run all ETL, score and map generation processes\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Then run `poetry run python3 data_pipeline/application.py data-full-run -s aws`\n- Note: The `-s` flag is optional if you have generated/downloaded the census data\n\n### Run both ETL and score generation processes\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Then run `poetry run python3 data_pipeline/application.py score-full-run`\n\n### Run all ETL processes\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Then run `poetry run python3 data_pipeline/application.py etl-run`\n\n### Generating Map Tiles\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Then run `poetry run python3 data_pipeline/application.py generate-map-tiles -s aws`\n- If you have S3 keys, you can sync to the dev repo by doing `aws s3 sync ./data_pipeline/data/score/tiles/ s3://justice40-data/data-pipeline/data/score/tiles --acl public-read --delete`\n- Note: The `-s` flag is optional if you have generated/downloaded the score data\n\n### Serve the map locally\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- For USA high zoom: `docker run --rm -it -v ${PWD}/data/score/tiles/high:/data -p 8080:80 maptiler/tileserver-gl`\n\n### Running Jupyter notebooks\n\n- Start a terminal\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Run `poetry run jupyter notebook`. Your browser should open with a Jupyter Notebook tab\n\n### Activating variable-enabled Markdown for Jupyter notebooks\n\n- Change to the package directory (i.e., `cd data/data-pipeline/data_pipeline`)\n- Activate a Poetry Shell (see above)\n- Run `jupyter contrib nbextension install --user`\n- Run `jupyter nbextension enable python-markdown/main`\n- Make sure you\'ve loaded the Jupyter notebook in a "Trusted" state. (See button near top right of Notebook screen.)\n\nFor more information, see [nbextensions docs](https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html) and\nsee [python-markdown docs](https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/master/src/jupyter_contrib_nbextensions/nbextensions/python-markdown).\n\n## Testing\n\n### Background\n\nFor this project, we make use of [pytest](https://docs.pytest.org/en/latest/) for testing purposes. To run tests, simply run `poetry run pytest` in this directory (i.e., `justice40-tool/data/data-pipeline`).\n\nTest data is configured via [fixtures](https://docs.pytest.org/en/latest/explanation/fixtures.html).\n\n### Score and post-processing tests\n\nThe fixtures used in the score post-processing tests are slightly different. These fixtures utilize [pickle files](https://docs.python.org/3/library/pickle.html) to 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.\n\nIn a bit more detail:\n\n1. Pandas dataframes are typed, and by default, types are inferred when you create one from scratch. If you create a dataframe using the `DataFrame` [constructors](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html#pandas.DataFrame), there is no guarantee that types will be correct, without explicit `dtype` annotations. Explicit `dtype` annotations are possible, but, and this leads us to point #2:\n\n2. 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 the `object` type. I attempted adding explicit typing based on the "logical" type of given columns, but in practice it resulted in non-matching dataframes that _actually_ had the same value -- in particular it was very common to have one dataframe column of type `string` and another of type `object` that 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 the `read_csv` call, which definitely has other potential unintended side effects and would need to be done carefully.\n\n3. 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.\n\n#### Updating Pickles\n\nIf you update the score in any way, it is necessary to create new pickles so that data is validated correctly.\n\nIt starts with the `data_pipeline/etl/score/tests/sample_data/score_data_initial.csv`, which is the first two rows of the `score/full/usa.csv`.\n\nTo update this file, run a full score generation, then open a Python shell from the `data-pipeline` directory (e.g. `poetry run python3`), and then update the file with the following commands:\n\n```\nimport pickle\nfrom pathlib import Path\nimport pandas as pd\ndata_path = Path.cwd()\n\n# score data expected\nscore_csv_path = data_path / "data_pipeline" / "data" / "score" / "csv" / "full" / "usa.csv"\nscore_initial_df = pd.read_csv(score_csv_path, dtype={"GEOID10_TRACT": "string"}, low_memory=False, nrows=2)\nscore_initial_df.to_csv(data_path / "data_pipeline" / "etl" / "score" / "tests" / "sample_data" /"score_data_initial.csv", index=False)\n```\n\nNow you can move on to updating individual pickles for the tests. Note that it is helpful to do them in this order:\n\nWe have four pickle files that correspond to expected files:\n\n- `score_data_expected.pkl`: Initial score without counties\n- `score_transformed_expected.pkl`: Intermediate score with `etl._extract_score` and `etl. _transform_score` applied. There\'s no file for this intermediate process, so we need to capture the pickle mid-process.\n- `tile_data_expected.pkl`: Score with columns to be baked in tiles\n- `downloadable_data_expected.pk1`: Downloadable csv\n\nTo update the pickles, let\'s go one by one:\n\nFor the `score_transformed_expected.pkl`, put a breakpoint on [this line](https://github.com/usds/justice40-tool/blob/main/data/data-pipeline/data_pipeline/etl/score/tests/test_score_post.py#L58), before the `pdt.assert_frame_equal` and run:\n`pytest data_pipeline/etl/score/tests/test_score_post.py::test_transform_score`\n\nOnce on the breakpoint, capture the df to a pickle as follows:\n\n```\nimport pickle\nfrom pathlib import Path\ndata_path = Path.cwd()\nscore_transformed_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "score_transformed_expected.pkl", protocol=4)\n```\n\nThen take out the breakpoint and re-run the test: `pytest data_pipeline/etl/score/tests/test_score_post.py::test_transform_score`\n\nFor the `score_data_expected.pkl`, put a breakpoint on [this line](https://github.com/usds/justice40-tool/blob/main/data/data-pipeline/data_pipeline/etl/score/tests/test_score_post.py#L78), before the `pdt.assert_frame_equal` and run:\n`pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_score_data`\n\nOnce on the breakpoint, capture the df to a pickle as follows:\n\n```\nimport pickle\nfrom pathlib import Path\ndata_path = Path.cwd()\nscore_data_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "score_data_expected.pkl", protocol=4)\n```\n\nThen take out the breakpoint and re-run the test: `pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_score_data`\n\nFor the `tile_data_expected.pkl`, put a breakpoint on [this line](https://github.com/usds/justice40-tool/blob/main/data/data-pipeline/data_pipeline/etl/score/tests/test_score_post.py#L86), before the `pdt.assert_frame_equal` and run:\n`pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_tile_data`\n\nOnce on the breakpoint, capture the df to a pickle as follows:\n\n```\nimport pickle\nfrom pathlib import Path\ndata_path = Path.cwd()\noutput_tiles_df_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "tile_data_expected.pkl", protocol=4)\n```\n\nThen take out the breakpoint and re-run the test: `pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_tile_data`\n\nFor the `downloadable_data_expected.pk1`, put a breakpoint on [this line](https://github.com/usds/justice40-tool/blob/main/data/data-pipeline/data_pipeline/etl/score/tests/test_score_post.py#L98), before the `pdt.assert_frame_equal` and run:\n`pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_downloadable_data`\n\nOnce on the breakpoint, capture the df to a pickle as follows:\n\n```\nimport pickle\nfrom pathlib import Path\ndata_path = Path.cwd()\noutput_downloadable_df_actual.to_pickle(data_path / "data_pipeline" / "etl" / "score" / "tests" / "snapshots" / "downloadable_data_expected.pkl", protocol=4)\n```\n\nThen take out the breakpoint and re-run the test: `pytest data_pipeline/etl/score/tests/test_score_post.py::test_create_downloadable_data`\n\n#### Future Enhancements\n\nPickles have several downsides that we should consider alternatives for:\n\n1. They are opaque - it is necessary to open a python interpreter (as written above) to confirm its contents\n2. They are a bit harder for newcomers to python to grok.\n3. They potentially encode flawed typing assumptions (see above) which are paved over for future test runs.\n\nIn the future, we could adopt any of the below strategies to work around this:\n\n1. We could use [pytest-snapshot](https://pypi.org/project/pytest-snapshot/) to 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 call `generate` once , and only when the dataframe had changed.\n\nAdditionally, you could use a pandas type schema annotation such as [pandera](https://pandera.readthedocs.io/en/stable/schema_models.html?highlight=inputschema#basic-usage) to 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.\n\nAlternatively, or in conjunction, you could move toward using a more strictly-typed container format for read/writes such as SQL/SQLite, and use something like [SQLModel](https://github.com/tiangolo/sqlmodel) to handle more explicit type guarantees.\n\n### Fixtures used in ETL "snapshot tests"\n\nETLs are tested for the results of their extract, transform, and load steps by\nborrowing the concept of "snapshot testing" from the world of front-end development.\n\nSnapshots are easy to update and demonstrate the results of a series of changes to\nthe code base. They are good for making sure no results have changed if you don\'t\nexpect them to change, and they are good when you expect the results to significantly\nchange in a way that would be tedious to update in traditional unit tests.\n\nHowever, snapshot tests are also dangerous. An unthinking developer may update the\nsnapshot fixtures and unknowingly encode a bug into the supposed intended output of\nthe test.\n\nIn order to update the snapshot fixtures of an ETL class, follow the following steps:\n\n1. If you need to manually update the fixtures, update the "furthest upstream" source\n   that is called by `_setup_etl_instance_and_run_extract`. For instance, this may\n   involve creating a new zip file that imitates the source data. (e.g., for the \n   National Risk Index test, update \n   `data_pipeline/tests/sources/national_risk_index/data/NRI_Table_CensusTracts.zip` \n   which is a 64kb imitation of the 405MB source NRI data.)\n2. Run `pytest . -rsx --update_snapshots` to update snapshots for all files, or you\n   can pass a specific file name to pytest to be more precise (e.g., `pytest \n   data_pipeline/tests/sources/national_risk_index/test_etl.py -rsx --update_snapshots`)\n3. Re-run pytest without the `update_snapshots` flag (e.g., `pytest . -rsx`) to\n   ensure the tests now pass.\n4. Carefully check the `git diff` for the updates to all test fixtures to make sure\n   these are as expected. This part is very important. For instance, if you changed a\n    column name, you would only expect the column name to change in the output. If \n    you modified the calculation of some data, spot check the results to see if the \n    numbers in the updated fixtures are as expected.\n\n### Other ETL Unit Tests\n\nOutside of the ETL snapshot tests discussed above, ETL unit tests are typically\norganized into three buckets:\n\n- Extract Tests\n- Transform Tests, and\n- Load Tests\n\nThese are tested using different strategies explained below.\n\n#### Extract Tests\n\nExtract tests rely on the limited data transformations that occur as data is loaded from source files.\n\nIn tests, we use fake, limited CSVs read via `StringIO` , taken from the first several rows of the files of interest, and ensure data types are correct.\n\nDown the line, we could use a tool like [Pandera](https://pandera.readthedocs.io/) to enforce schemas, both for the tests and the classes themselves.\n\n#### Transform Tests\n\nTransform tests are the heart of ETL unit tests, and compare ideal dataframes with their actual counterparts.\n\nSee above [Fixtures](#configuration--fixtures) section for information about where data is coming from.\n\n#### Load Tests\n\nThese make use of [tmp_path_factory](https://docs.pytest.org/en/latest/how-to/tmp_path.html) to create a file-system located under `temp_dir`, and validate whether the correct files are written to the correct locations.\n\nAdditional 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.\n',
    'author': 'Justice40 Engineering',
    'author_email': 'j40-engineering@lists.usds.gov',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/usds/justice40-tool/tree/main/data/data-pipeline',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.8,<4.0',
}


setup(**setup_kwargs)
