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

packages = \
['maup']

package_data = \
{'': ['*']}

install_requires = \
['Shapely>=1.7.1,<2.0.0',
 'geopandas>=0.9.0,<0.10.0',
 'numpy>=1.20.3,<2.0.0',
 'pandas>=1.2.4,<2.0.0',
 'tqdm>=4.61.1,<5.0.0']

setup_kwargs = {
    'name': 'maup',
    'version': '1.0.2',
    'description': 'The geospatial toolkit for redistricting data',
    'long_description': '# maup\n\n[![maup tests](https://github.com/mggg/maup/actions/workflows/tests.yaml/badge.svg)](https://github.com/mggg/maup/actions/workflows/tests.yaml)\n[![codecov](https://codecov.io/gh/mggg/maup/branch/master/graph/badge.svg)](https://codecov.io/gh/mggg/maup)\n[![PyPI](https://img.shields.io/pypi/v/maup.svg?color=%23)](https://pypi.org/project/maup/)\n[![conda-forge Package](https://img.shields.io/conda/vn/conda-forge/maup.svg?color=%230099cd)](https://anaconda.org/conda-forge/maup)\n\n`maup` is the geospatial toolkit for redistricting data. The package streamlines\nthe basic workflows that arise when working with blocks, precincts, and\ndistricts, such as\n\n-   [Assigning precincts to districts](#assigning-precincts-to-districts),\n-   [Aggregating block data to precincts](#aggregating-block-data-to-precincts),\n-   [Disaggregating data from precincts down to blocks](#disaggregating-data-from-precincts-down-to-blocks),\n-   [Prorating data when units do not nest neatly](#prorating-data-when-units-do-not-nest-neatly),\n    and\n-   [Fixing topological issues, overlaps, and gaps](#fixing-topological-issues-overlaps-and-gaps)\n\nThe project\'s priorities are to be efficient by using spatial indices whenever\npossible and to integrate well with the existing ecosystem around\n[pandas](https://pandas.pydata.org/), [geopandas](https://geopandas.org) and\n[shapely](https://shapely.readthedocs.io/en/latest/). The package is distributed\nunder the MIT License.\n\n## Installation\n\nWe recommend installing `maup` from [conda-forge](https://conda-forge.org/)\nusing [conda](https://docs.conda.io/en/latest/):\n\n```console\nconda install -c conda-forge maup\n```\n\nYou can get conda by installing\n[Miniconda](https://docs.conda.io/en/latest/miniconda.html), a free Python\ndistribution made especially for data science and scientific computing. You\nmight also consider [Anaconda](https://www.anaconda.com/distribution/), which\nincludes many data science packages that you might find useful.\n\nTo install `maup` from PyPI, run `pip install maup` from your terminal.\n\n## Examples\n\nHere are some basic situations where you might find `maup` helpful. For these\nexamples, we use test data from Providence, Rhode Island, which you can find in\nour\n[Rhode Island shapefiles repo](https://github.com/mggg-states/RI-shapefiles), or\nin the `examples` folder of this repo.\n\n```python\n>>> import geopandas\n>>> import pandas\n>>>\n>>> blocks = geopandas.read_file("zip://./examples/blocks.zip")\n>>> precincts = geopandas.read_file("zip://./examples/precincts.zip")\n>>> districts = geopandas.read_file("zip://./examples/districts.zip")\n\n```\n\n### Assigning precincts to districts\n\nThe `assign` function in `maup` takes two sets of geometries called `sources`\nand `targets` and returns a pandas `Series`. The Series maps each geometry in\n`sources` to the geometry in `targets` that covers it. (Here, geometry _A_\n_covers_ geometry _B_ if every point of _A_ and its boundary lies in _B_ or its\nboundary.) If a source geometry is not covered by one single target geometry, it\nis assigned to the target geometry that covers the largest portion of its area.\n\n```python\n>>> import maup\n>>>\n>>> assignment = maup.assign(precincts, districts)\n>>> # Add the assigned districts as a column of the `precincts` GeoDataFrame:\n>>> precincts["DISTRICT"] = assignment\n>>> assignment.head()\n0     7\n1     5\n2    13\n3     6\n4     1\ndtype: int64\n\n```\n\nAs an aside, you can use that `assignment` object to create a\n[gerrychain](https://gerrychain.readthedocs.io/en/latest/) `Partition`\nrepresenting this districting plan.\n\n### Aggregating block data to precincts\n\nPrecinct shapefiles usually come with election data, but not demographic data.\nIn order to study their demographics, we need to aggregate demographic data from\ncensus blocks up to the precinct level. We can do this by assigning blocks to\nprecincts and then aggregating the data with a Pandas\n[`groupby`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html)\noperation:\n\n```python\n>>> variables = ["TOTPOP", "NH_BLACK", "NH_WHITE"]\n>>>\n>>> assignment = maup.assign(blocks, precincts)\n>>> precincts[variables] = blocks[variables].groupby(assignment).sum()\n>>> precincts[variables].head()\n   TOTPOP  NH_BLACK  NH_WHITE\n0    5907       886       380\n1    5636       924      1301\n2    6549       584      4699\n3    6009       435      1053\n4    4962       156      3713\n\n```\n\nIf you want to move data from one set of geometries to another but your source\nand target geometries do not nest neatly (i.e. have overlaps), see\n[Prorating data when units do not nest neatly](#prorating-data-when-units-do-not-nest-neatly).\n\n### Disaggregating data from precincts down to blocks\n\nIt\'s common to have data at a coarser scale that you want to attach to\nfiner-scaled geometries. Usually this happens when vote totals for a certain\nelection are only reported at the county level, and we want to attach that data\nto precinct geometries.\n\nLet\'s say we want to prorate the vote totals in the columns `"PRES16D"`,\n`"PRES16R"` from our `precincts` GeoDataFrame down to our `blocks` GeoDataFrame.\nThe first crucial step is to decide how we want to distribute a precinct\'s data\nto the blocks within it. Since we\'re prorating election data, it makes sense to\nuse a block\'s total population or voting-age population. Here\'s how we might\nprorate by population (`"TOTPOP"`):\n\n```python\n>>> election_columns = ["PRES16D", "PRES16R"]\n>>> assignment = maup.assign(blocks, precincts)\n>>>\n>>> # We prorate the vote totals according to each block\'s share of the overall\n>>> # precinct population:\n>>> weights = blocks.TOTPOP / assignment.map(precincts.TOTPOP)\n>>> prorated = maup.prorate(assignment, precincts[election_columns], weights)\n>>>\n>>> # Add the prorated vote totals as columns on the `blocks` GeoDataFrame:\n>>> blocks[election_columns] = prorated\n>>> # We\'ll call .round(2) to round the values for display purposes.\n>>> blocks[election_columns].round(2).head()\n   PRES16D  PRES16R\n0     0.00     0.00\n1    12.26     1.70\n2    15.20     2.62\n3    15.50     2.67\n4     3.28     0.45\n\n```\n\n#### Warning about areal interpolation\n\n**We strongly urge you _not_ to prorate by area!** The area of a census block is\n**not** a good predictor of its population. In fact, the correlation goes in the\nother direction: larger census blocks are _less_ populous than smaller ones.\n\n### Prorating data when units do not nest neatly\n\nSuppose you have a shapefile of precincts with some election results data and\nyou want to join that data onto a different, more recent precincts shapefile.\nThe two sets of precincts will have overlaps, and will not nest neatly like the\nblocks and precincts did in the above examples. (Not that blocks and precincts\nalways nest neatly...)\n\nWe can use `maup.intersections` to break the two sets of precincts into pieces\nthat nest neatly into both sets. Then we can disaggregate from the old precincts\nonto these pieces, and aggregate up from the pieces to the new precincts. This\nmove is a bit complicated, so `maup` provides a function called `prorate` that\ndoes just that.\n\nWe\'ll use our same `blocks` GeoDataFrame to estimate the populations of the\npieces for the purposes of proration.\n\nFor our "new precincts" shapefile, we\'ll use the VTD shapefile for Rhode Island\nthat the U.S. Census Bureau produced as part of their 2018 test run of for the\n2020 Census.\n\n```python\n>>> old_precincts = precincts\n>>> new_precincts = geopandas.read_file("zip://./examples/new_precincts.zip")\n>>>\n>>> columns = ["SEN18D", "SEN18R"]\n>>>\n>>> # Include area_cutoff=0 to ignore any intersections with no area,\n>>> # like boundary intersections, which we do not want to include in\n>>> # our proration.\n>>> pieces = maup.intersections(old_precincts, new_precincts, area_cutoff=0)\n>>>\n>>> # Weight by prorated population from blocks\n>>> weights = blocks["TOTPOP"].groupby(maup.assign(blocks, pieces)).sum()\n>>> # Normalize the weights so that votes are allocated according to their\n>>> # share of population in the old_precincts\n>>> weights = maup.normalize(weights, level=0)\n>>>\n>>> # Use blocks to estimate population of each piece\n>>> new_precincts[columns] = maup.prorate(\n...     pieces,\n...     old_precincts[columns],\n...     weights=weights\n... )\n>>> new_precincts[columns].head()\n   SEN18D  SEN18R\n0   752.0    51.0\n1   370.0    21.0\n2    97.0    17.0\n3   585.0    74.0\n4   246.0    20.0\n\n```\n\n### Progress bars\n\nFor long-running operations, the user might want to see a progress bar to\nestimate how much longer a task will take (and whether to abandon it altogether).\n\n`maup` provides an optional progress bar for this purpose. To temporarily activate\na progress bar for a certain operation, use `with maup.progress():`:\n\n```python\n>>> with maup.progress():\n...     assignment = maup.assign(precincts, districts)\n...\n\n```\n\nTo turn on progress bars for all applicable operations (e.g. for an entire script),\nset `maup.progress.enabled = True`:\n\n```python\n>>> maup.progress.enabled = True\n>>> # Now a progress bar will display while this function runs:\n>>> assignment = maup.assign(precincts, districts)\n>>> # And this one too:\n>>> pieces = maup.intersections(old_precincts, new_precincts, area_cutoff=0)\n\n```\n### Fixing topological issues, overlaps, and gaps\n\nPrecinct shapefiles are often created by stitching together collections of\nprecinct geometries sourced from different counties or different years. As a\nresult, the shapefile often has gaps or overlaps between precincts where the\ndifferent sources disagree about the boundaries. These gaps and overlaps pose\nproblems when you are interested in working with the adjacency graph of the\nprecincts, and not just in mapping the precincts. This adjacency information is\nespecially important when studying redistricting, because districts are almost\nalways expected to be contiguous.\n\n`maup` provides functions for closing gaps and resolving overlaps in a\ncollection of geometries. As an example, we\'ll apply both functions to these\ngeometries, which have both an overlap and a gap:\n\n![Four polygons with a gap and some overlaps](./examples/plot.png)\n\nUsually the gaps and overlaps in real shapefiles are tiny and easy to miss, but\nthis exaggerated example will help illustrate the functionality.\n\nFirst, we\'ll use `shapely` to create the polygons from scratch:\n\n```python\nfrom shapely.geometry import Polygon\ngeometries = geopandas.GeoSeries([\n    Polygon([(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]),\n    Polygon([(2, 0), (4, 0), (4, 2), (2, 2)]),\n    Polygon([(0, 2), (2, 2), (2, 4), (0, 4)]),\n    Polygon([(2, 1), (4, 1), (4, 4), (2, 4)]),\n])\n```\n\nNow we\'ll close the gap:\n\n```python\nwithout_gaps = maup.close_gaps(geometries)\n```\n\nThe `without_gaps` geometries look like this:\n\n![Four polygons with two overlapping](./examples/plot_without_gaps.png)\n\nAnd then resolve the overlaps:\n\n```python\nwithout_overlaps_or_gaps = maup.resolve_overlaps(without_gaps)\n```\n\nThe `without_overlaps_or_gaps` geometries look like this:\n\n![Four squares](./examples/plot_without_gaps_or_overlaps.png)\n\nAlternatively, there is also a convenience `maup.autorepair()` function provided that \nattempts to resolve topological issues as well as close gaps and resolve overlaps:\n\n```python\nwithout_overlaps_or_gaps = maup.autorepair(geometries)\n```\n\nThe functions `resolve_overlaps`, `close_gaps`, and `autorepair` accept a\n`relative_threshold` argument. This threshold controls how large of a gap or\noverlap the function will attempt to fix. The default value of\n`relative_threshold` is `0.1`, which means that the functions will leave alone\nany gap/overlap whose area is more than 10% of the area of the geometries that\nmight absorb that gap/overlap. In the above example, we set\n`relative_threshold=None` to ensure that no gaps or overlaps were ignored.\n\n## Modifiable areal unit problem\n\nThe name of this package comes from the\n[modifiable areal unit problem (MAUP)](https://en.wikipedia.org/wiki/Modifiable_areal_unit_problem):\nthe same spatial data will look different depending on how you divide up the\nspace. Since `maup` is all about changing the way your data is aggregated and\npartitioned, we have named it after the MAUP to encourage users to use the\ntoolkit thoughtfully and responsibly.\n',
    'author': 'Max Hully',
    'author_email': 'max@mggg.org',
    'maintainer': None,
    'maintainer_email': None,
    'url': None,
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.7.1,<4.0.0',
}


setup(**setup_kwargs)
