pax_global_header00006660000000000000000000000064137517440320014520gustar00rootroot0000000000000052 comment=ac45f1e1fa95d10a2409409cf3c697f700cad314 branca-0.4.2/000077500000000000000000000000001375174403200127515ustar00rootroot00000000000000branca-0.4.2/.appveyor.yml000066400000000000000000000020431375174403200154160ustar00rootroot00000000000000build: false environment: PYTHON: "C:\\myminiconda3" matrix: - PY: 3.7 - PY: 3.8 init: - "ECHO %PYTHON_VERSION% %MINICONDA%" install: # Add path, activate `conda` and update conda. - set URL="https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe" - curl -fsS -o miniconda3.exe %URL% - start /wait "" miniconda3.exe /InstallationType=JustMe /RegisterPython=0 /S /D=%PYTHON% - "set PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" - call %PYTHON%\Scripts\activate - conda config --set always_yes yes --set changeps1 no --set show_channel_urls true - conda update conda --quiet - conda config --add channels conda-forge --force - conda config --set channel_priority strict - conda config --set safety_checks disabled # Create the test env. - conda create --name TEST python=%PY% --file requirements.txt --file requirements-dev.txt - activate TEST # Debug. - conda info --all - conda list test_script: - pip install -e . --no-deps --force-reinstall - pytest -n 2 -rxXs -m "not headless" tests branca-0.4.2/.gitattributes000066400000000000000000000000401375174403200156360ustar00rootroot00000000000000branca/_version.py export-subst branca-0.4.2/.gitignore000066400000000000000000000010451375174403200147410ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 include # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject #Mac *.DS_Store # IPython Notebook Checkpoints .ipynb_checkpoints #Virtualenv ENV .env # Tests products .cache data.png map.html examples/foo.html # documentation builds docs/_build geckodriver.exe geckodriver.log # Pycharm .idea/ branca-0.4.2/.travis.yml000066400000000000000000000074311375174403200150670ustar00rootroot00000000000000language: minimal sudo: false env: - MOZ_HEADLESS=1 addons: apt: packages: # Without libgtk (as of 2019-11-6), firefox cannot run properly - libgtk-3-0 firefox: latest env: global: - secure: "JrdAJJKe+Y564LIiIaGPmw9X9utvj2lVI2MkVyZX6CQ7cJwqPUB+ukZpa6MnGUEJSoI6S7/5ZqX/cvciVAKpcYadi/snlDGq6q+lLnA+6rtB6ppy99Ib64aqm+VqDyohvvvrNtSxqhBY48DLG9UuQEcvviabpx9CG4s439/osspsA80SRXgDm/dELjU8vuIJvL1EFPeOu4a01sAHsqhknQw4F4YSWWjUr1oNjZIhSKroxCJV0o/0ok600SwTrQrbwJNO8QmEBOTw1JO1kaxDRlMAsJ5JTBaeGWdhqWQ3IRH/RogkU3ukOyyybbeoWU9ou5xG08P0r4CM3dGh44M8qrTOOCUSSNrFIG5OhAW6ZdkSR/2w76fNnW6y25jKUQ2444kd8n8+TObsp8aNl1FkCwou6/SpPluKvtaFA+I1zbk8roG58tW9anf6o9zCdIyYhSFysEoKNNihSC6xc4zHlJUHWr61f4zC0mU1Xf/djgpvj2YUQLsQ4++K6FNb6I/CN7LDl67kkOiyVCKv60J1mHVXAPJpj2Y9SxR87ob+GH+na8oFy5IMPMDoym2hPImtl2cjGvpP6RvE+gVE+mfvc4BizWfsR1zO49DUD15U1Y6jqhbcPMCgk5FoQ3ZKiH6LBeFbmV0qMjwSC6pZONgz8s/2nTUMV3VU+9SBiah51ho=" matrix: fast_finish: true include: - name: "python-3.6" env: PY=3.6 - name: "python-3.7" env: PY=3.7 - name: "python-3.8" env: PY=3.8 - name: coding_standards env: PY=3.8 - name: docs env: PY=3.8 - name: "tarball" env: PY=3.8 before_install: # Install miniconda and create TEST env. - | wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh bash miniconda.sh -b -p $HOME/miniconda export PATH="$HOME/miniconda/bin:$PATH" conda config --set always_yes yes --set changeps1 no --set show_channel_urls true conda update --quiet conda conda config --add channels conda-forge --force conda config --set channel_priority strict conda config --set safety_checks disabled conda create --name TEST python=$PY --file requirements.txt --file requirements-dev.txt source activate TEST conda info --all # Install firefox headless driver. - | wget https://github.com/mozilla/geckodriver/releases/download/v0.23.0/geckodriver-v0.23.0-linux64.tar.gz -O geckodriver.tar.gz mkdir geckodriver tar -xzf geckodriver.tar.gz -C geckodriver export PATH=$PATH:$PWD/geckodriver install: - pip install -e . --no-deps --force-reinstall script: - if [[ $TRAVIS_JOB_NAME == python-* ]]; then cp -r tests/ examples/ /tmp ; pushd /tmp && pytest -n 2 -rxs --cov=branca -vv tests && popd ; fi - if [[ $TRAVIS_JOB_NAME == 'tarball' ]]; then python setup.py --version ; pip wheel . -w dist --no-deps ; check-manifest --verbose ; twine check dist/* ; fi - if [[ $TRAVIS_JOB_NAME == 'coding_standards' ]]; then pytest --flake8 -m flake8 ; fi - if [[ $TRAVIS_JOB_NAME == 'docs' ]]; then set -e ; conda install doctr ; pushd docs ; make clean html linkcheck ; popd ; python -m doctr deploy --sync --built-docs docs/build/html . ; fi doctr: require-master: true sync: False deploy: skip_cleanup: true provider: pypi user: "__token__" password: secure: "ncVXDcUpadOXESusbUv/F5mhXqzjp0fFM+llYdBOWBGpipP2B1cU/cWRUU5fkhL1KZG/0DfVboJsRnNQCebZklJ0fczW2Z2QUzL8zCAK8KLOUqr0Nk8i8Oi5eC0h8Ew+HkDNORsZUCPCjKvqcFHRuSZnVYvEqqPPguSj1fwDdyBm9kW7lfZdPeR9mr79WJs+Miv5UKXGZcQAuzCU7g3AmaizRoUfhXnSgPXd9Yp2DY5nsBUZhmqFTj1xjQwLvqp5w/BiFZGkdqMuWVP9b/HbVJEeRxWgCaDPw+XLkQa+HdfUsDGBvPWaaQ+o6OwuADdCjIHLnVmfA2/E2FSU64IBaIZ1xOkHZpm74P8Y0NF5aRogyipkqhrm0WErRWFD4OYj8ud4y9AHLCAmyyLsKCka76NSxotbTd4W4Xu9MX7fkhGOVzhYXg1GNS6SDTIMn+bujFNg5fZrZUptn6FcNa8THkh7yKrduBv2kgbBcgx0/EodH4q2Ds7yfbFvPkQD+l0mBiOPXOXflcQDOiu0CZ70X2XmLe3v3zIEf51oigEtb/KRkf7B3r/Ab+ayNdS33xbHsE8JYE/6KKjGf+fEr0f4XiidadtCbUmNGCw8fgHo7dY4g7blYMPvab7z4zcHmqekzrSTTwxw2uRtmGLWWJupmOerasRIuLsKiJxnk9oiS+k=" distributions: sdist bdist_wheel upload_docs: no on: repo: python-visualization/branca tags: true all_branches: master condition: '$TRAVIS_JOB_NAME == "tarball"' branca-0.4.2/CHANGES.txt000066400000000000000000000021311375174403200145570ustar00rootroot000000000000000.4.2 ~~~~~ - Fix special char encoding in notebooks, store as percent-encoded (@conengmo #76) 0.4.1 ~~~~~ - Prompt Jupyter users to trust notebook (@conengmo #75) - Removed Python 2 specific code (@ocefpaf #69) 0.4.0 ~~~~~ - Dropped Python 2 support - Store html content in a data-html attribute (#66) - Colormap alpha #64 - Fix caption being propagated in scale functions #62 - Assert color type in color_brewer #52 0.3.1 ~~~~~ - Added viridis scheme #47 (GillesC) - Fixed testing, auto PyPI upload, and docs 0.3.0 ~~~~~ - Add title to Figure (@fitoprincipe #33 and #39) - Move templates to class attributes (@psarka #34 and #38) - Explicit color support for range of ``n`` and diverging colormaps (@nanodan #29) - Added class for hosting step colormap (@matsavage #25) 0.2.0 ~~~~~ - Correct rendering utf-8 IFrame (@knil-sama #18) - Remove embedded IFrame's border (@deelaka #17) - Let IFrame contents go fullscreen (@sanga #13) - Add HTML Popup Class to element.py (@samchorlton #6) 0.1.0 ~~~~~ - Separate branca from folium (@bibmartin d678357) - Enable HTML embedding in Html (@samchorlton 90f6b13) branca-0.4.2/LICENSE.txt000066400000000000000000000020671375174403200146010ustar00rootroot00000000000000Copyright (C) 2013, Martin Journois Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. branca-0.4.2/MANIFEST.in000066400000000000000000000005261375174403200145120ustar00rootroot00000000000000include *.txt include README.rst include branca/_cnames.json include branca/_schemes.json include branca/scheme_info.json include branca/scheme_base_codes.json recursive-include branca *.py recursive-include branca *.js recursive-include branca/plugins * recursive-include branca/templates * include versioneer.py include branca/_version.py branca-0.4.2/README.md000066400000000000000000000013461375174403200142340ustar00rootroot00000000000000[![PyPI Package](https://img.shields.io/pypi/v/branca.svg)](https://pypi.python.org/pypi/branca) [![Build Status](https://travis-ci.org/python-visualization/branca.svg?branch=master)](https://travis-ci.org/python-visualization/branca) [![Gitter](https://badges.gitter.im/python-visualization/folium.svg)](https://gitter.im/python-visualization/folium) # Branca This library is a spinoff from [folium](https://github.com/python-visualization/folium), that would host the non-map-specific features. It may become a HTML+JS generation library in the future. It is based on Jinja2 only. There's no documentation, but you can [browse the examples](http://nbviewer.jupyter.org/github/python-visualization/branca/tree/master/examples) gallery. branca-0.4.2/branca/000077500000000000000000000000001375174403200141775ustar00rootroot00000000000000branca-0.4.2/branca/__init__.py000066400000000000000000000003251375174403200163100ustar00rootroot00000000000000import branca.colormap as colormap import branca.element as element from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = [ 'colormap', 'element', ] branca-0.4.2/branca/_cnames.json000066400000000000000000000067231375174403200165070ustar00rootroot00000000000000{"indigo": "#4B0082", "gold": "#FFD700", "hotpink": "#FF69B4", "firebrick": "#B22222", "indianred": "#CD5C5C", "sage": "#87AE73", "yellow": "#FFFF00", "mistyrose": "#FFE4E1", "darkolivegreen": "#556B2F", "olive": "#808000", "darkseagreen": "#8FBC8F", "pink": "#FFC0CB", "tomato": "#FF6347", "lightcoral": "#F08080", "orangered": "#FF4500", "navajowhite": "#FFDEAD", "lime": "#00FF00", "palegreen": "#98FB98", "greenyellow": "#ADFF2F", "burlywood": "#DEB887", "seashell": "#FFF5EE", "mediumspringgreen": "#00FA9A", "fuchsia": "#FF00FF", "papayawhip": "#FFEFD5", "blanchedalmond": "#FFEBCD", "chartreuse": "#7FFF00", "dimgray": "#696969", "black": "#000000", "peachpuff": "#FFDAB9", "springgreen": "#00FF7F", "aquamarine": "#7FFFD4", "white": "#FFFFFF", "b": "#0000FF", "orange": "#FFA500", "lightsalmon": "#FFA07A", "darkslategray": "#2F4F4F", "brown": "#A52A2A", "ivory": "#FFFFF0", "dodgerblue": "#1E90FF", "peru": "#CD853F", "lawngreen": "#7CFC00", "chocolate": "#D2691E", "crimson": "#DC143C", "forestgreen": "#228B22", "slateblue": "#6A5ACD", "lightseagreen": "#20B2AA", "cyan": "#00FFFF", "mintcream": "#F5FFFA", "silver": "#C0C0C0", "antiquewhite": "#FAEBD7", "mediumorchid": "#BA55D3", "skyblue": "#87CEEB", "gray": "#808080", "darkturquoise": "#00CED1", "goldenrod": "#DAA520", "darkgreen": "#006400", "floralwhite": "#FFFAF0", "darkviolet": "#9400D3", "darkgray": "#A9A9A9", "moccasin": "#FFE4B5", "saddlebrown": "#8B4513", "darkslateblue": "#483D8B", "lightskyblue": "#87CEFA", "lightpink": "#FFB6C1", "mediumvioletred": "#C71585", "r": "#FF0000", "red": "#FF0000", "deeppink": "#FF1493", "limegreen": "#32CD32", "k": "#000000", "darkmagenta": "#8B008B", "palegoldenrod": "#EEE8AA", "plum": "#DDA0DD", "turquoise": "#40E0D0", "m": "#FF00FF", "lightgoldenrodyellow": "#FAFAD2", "darkgoldenrod": "#B8860B", "lavender": "#E6E6FA", "maroon": "#800000", "yellowgreen": "#9ACD32", "sandybrown": "#FAA460", "thistle": "#D8BFD8", "violet": "#EE82EE", "navy": "#000080", "magenta": "#FF00FF", "tan": "#D2B48C", "rosybrown": "#BC8F8F", "olivedrab": "#6B8E23", "blue": "#0000FF", "lightblue": "#ADD8E6", "ghostwhite": "#F8F8FF", "honeydew": "#F0FFF0", "cornflowerblue": "#6495ED", "linen": "#FAF0E6", "darkblue": "#00008B", "powderblue": "#B0E0E6", "seagreen": "#2E8B57", "darkkhaki": "#BDB76B", "snow": "#FFFAFA", "sienna": "#A0522D", "mediumblue": "#0000CD", "royalblue": "#4169E1", "lightcyan": "#E0FFFF", "green": "#008000", "mediumpurple": "#9370DB", "midnightblue": "#191970", "cornsilk": "#FFF8DC", "paleturquoise": "#AFEEEE", "bisque": "#FFE4C4", "slategray": "#708090", "darkcyan": "#008B8B", "khaki": "#F0E68C", "wheat": "#F5DEB3", "teal": "#008080", "darkorchid": "#9932CC", "deepskyblue": "#00BFFF", "salmon": "#FA8072", "y": "#FFFF00", "darkred": "#8B0000", "steelblue": "#4682B4", "g": "#008000", "palevioletred": "#DB7093", "lightslategray": "#778899", "aliceblue": "#F0F8FF", "lightgreen": "#90EE90", "orchid": "#DA70D6", "gainsboro": "#DCDCDC", "mediumseagreen": "#3CB371", "lightgray": "#D3D3D3", "c": "#00FFFF", "mediumturquoise": "#48D1CC", "darksage": "#598556", "lemonchiffon": "#FFFACD", "cadetblue": "#5F9EA0", "lightyellow": "#FFFFE0", "lavenderblush": "#FFF0F5", "coral": "#FF7F50", "purple": "#800080", "aqua": "#00FFFF", "lightsage": "#BCECAC", "whitesmoke": "#F5F5F5", "mediumslateblue": "#7B68EE", "darkorange": "#FF8C00", "mediumaquamarine": "#66CDAA", "darksalmon": "#E9967A", "beige": "#F5F5DC", "w": "#FFFFFF", "blueviolet": "#8A2BE2", "azure": "#F0FFFF", "lightsteelblue": "#B0C4DE", "oldlace": "#FDF5E6"}branca-0.4.2/branca/_schemes.json000066400000000000000000000501171375174403200166640ustar00rootroot00000000000000{"viridis":["#440154","#481567","#482677","#453781","#404788","#39568C","#33638D","#2D708E","#287D8E","#238A8D","#1F968B","#20A387","#29AF7F","#3CBB75","#55C667","#73D055","#95D840","#B8DE29","#DCE319","#FDE725"],"Pastel1_03":["#fbb4ae","#b3cde3","#ccebc5"],"Pastel1_05":["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6"],"Pastel1_04":["#fbb4ae","#b3cde3","#ccebc5","#decbe4"],"Pastel1_07":["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd"],"YlOrRd_04":["#ffffb2","#fecc5c","#fd8d3c","#e31a1c"],"Pastel1_09":["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"],"Pastel1_08":["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"],"Spectral_07":["#d53e4f","#fc8d59","#fee08b","#ffffbf","#e6f598","#99d594","#3288bd"],"RdYlBu_05":["#d7191c","#fdae61","#ffffbf","#abd9e9","#2c7bb6"],"PuBuGn_03":["#ece2f0","#a6bddb","#1c9099"],"Set1_08":["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"],"PuBuGn_05":["#f6eff7","#bdc9e1","#67a9cf","#1c9099","#016c59"],"PuBuGn_04":["#f6eff7","#bdc9e1","#67a9cf","#02818a"],"PuBuGn_07":["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"],"PuBuGn_06":["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#1c9099","#016c59"],"PuBuGn_09":["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],"PuBuGn_08":["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"],"YlOrBr_04":["#ffffd4","#fed98e","#fe9929","#cc4c02"],"YlOrBr_05":["#ffffd4","#fed98e","#fe9929","#d95f0e","#993404"],"Set1_07":["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"],"YlOrBr_03":["#fff7bc","#fec44f","#d95f0e"],"Set1_05":["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"],"YlOrRd_03":["#ffeda0","#feb24c","#f03b20"],"PuOr_06":["#b35806","#f1a340","#fee0b6","#d8daeb","#998ec3","#542788"],"PuOr_07":["#b35806","#f1a340","#fee0b6","#f7f7f7","#d8daeb","#998ec3","#542788"],"PuOr_04":["#e66101","#fdb863","#b2abd2","#5e3c99"],"PuOr_05":["#e66101","#fdb863","#f7f7f7","#b2abd2","#5e3c99"],"PuOr_03":["#f1a340","#f7f7f7","#998ec3"],"Purples_09":["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],"Set2_06":["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f"],"RdYlBu_11":["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],"PuOr_08":["#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788"],"PuOr_09":["#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788"],"Paired_03":["#a6cee3","#1f78b4","#b2df8a"],"RdBu_03":["#ef8a62","#f7f7f7","#67a9cf"],"RdYlBu_10":["#a50026","#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],"Paired_07":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f"],"Paired_06":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c"],"Paired_05":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99"],"Paired_04":["#a6cee3","#1f78b4","#b2df8a","#33a02c"],"Paired_09":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6"],"Paired_08":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00"],"RdGy_03":["#ef8a62","#ffffff","#999999"],"PiYG_04":["#d01c8b","#f1b6da","#b8e186","#4dac26"],"Accent_03":["#7fc97f","#beaed4","#fdc086"],"BuGn_08":["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"],"BuGn_09":["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],"BuGn_04":["#edf8fb","#b2e2e2","#66c2a4","#238b45"],"BuGn_05":["#edf8fb","#b2e2e2","#66c2a4","#2ca25f","#006d2c"],"BuGn_06":["#edf8fb","#ccece6","#99d8c9","#66c2a4","#2ca25f","#006d2c"],"BuGn_07":["#edf8fb","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"],"BuGn_03":["#e5f5f9","#99d8c9","#2ca25f"],"YlGnBu_07":["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"],"YlGnBu_06":["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#2c7fb8","#253494"],"YlGnBu_05":["#ffffcc","#a1dab4","#41b6c4","#2c7fb8","#253494"],"YlGnBu_04":["#ffffcc","#a1dab4","#41b6c4","#225ea8"],"YlGnBu_03":["#edf8b1","#7fcdbb","#2c7fb8"],"RdBu_06":["#b2182b","#ef8a62","#fddbc7","#d1e5f0","#67a9cf","#2166ac"],"RdBu_05":["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"],"RdBu_04":["#ca0020","#f4a582","#92c5de","#0571b0"],"Accent_08":["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],"RdBu_09":["#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac"],"RdBu_08":["#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac"],"Set2_04":["#66c2a5","#fc8d62","#8da0cb","#e78ac3"],"YlGnBu_09":["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],"YlGnBu_08":["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"],"Blues_08":["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"],"Blues_09":["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],"RdPu_09":["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],"RdPu_08":["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"],"Set3_07":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69"],"Set3_06":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462"],"RdPu_05":["#feebe2","#fbb4b9","#f768a1","#c51b8a","#7a0177"],"RdPu_04":["#feebe2","#fbb4b9","#f768a1","#ae017e"],"RdPu_07":["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"],"RdPu_06":["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#c51b8a","#7a0177"],"Blues_06":["#eff3ff","#c6dbef","#9ecae1","#6baed6","#3182bd","#08519c"],"Blues_07":["#eff3ff","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"],"RdPu_03":["#fde0dd","#fa9fb5","#c51b8a"],"Blues_05":["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"],"Paired_10":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a"],"Paired_11":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99"],"Paired_12":["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],"PuBu_06":["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#2b8cbe","#045a8d"],"PuBu_07":["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"],"PuBu_04":["#f1eef6","#bdc9e1","#74a9cf","#0570b0"],"PuBu_05":["#f1eef6","#bdc9e1","#74a9cf","#2b8cbe","#045a8d"],"PuRd_05":["#f1eef6","#d7b5d8","#df65b0","#dd1c77","#980043"],"PuBu_03":["#ece7f2","#a6bddb","#2b8cbe"],"PuRd_07":["#f1eef6","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"],"PuRd_06":["#f1eef6","#d4b9da","#c994c7","#df65b0","#dd1c77","#980043"],"PuRd_09":["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],"PuRd_08":["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"],"Set2_07":["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494"],"PuBu_08":["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"],"PuBu_09":["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],"RdBu_10":["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],"RdBu_11":["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],"Accent_06":["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f"],"Set3_03":["#8dd3c7","#ffffb3","#bebada"],"Set3_05":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3"],"Set3_12":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],"Set3_10":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd"],"Set3_04":["#8dd3c7","#ffffb3","#bebada","#fb8072"],"RdGy_11":["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],"RdGy_10":["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],"Set1_03":["#e41a1c","#377eb8","#4daf4a"],"Set1_09":["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],"Set3_09":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9"],"BuPu_08":["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"],"BuPu_09":["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],"RdYlGn_11":["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],"Blues_03":["#deebf7","#9ecae1","#3182bd"],"Set2_05":["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854"],"BuPu_03":["#e0ecf4","#9ebcda","#8856a7"],"BuPu_06":["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8856a7","#810f7c"],"BuPu_07":["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"],"BuPu_04":["#edf8fb","#b3cde3","#8c96c6","#88419d"],"BuPu_05":["#edf8fb","#b3cde3","#8c96c6","#8856a7","#810f7c"],"Accent_04":["#7fc97f","#beaed4","#fdc086","#ffff99"],"YlOrRd_05":["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"],"YlOrBr_08":["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"],"Oranges_08":["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"],"Oranges_09":["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],"Oranges_06":["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#e6550d","#a63603"],"Oranges_07":["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"],"Oranges_04":["#feedde","#fdbe85","#fd8d3c","#d94701"],"YlOrBr_09":["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],"Oranges_03":["#fee6ce","#fdae6b","#e6550d"],"YlOrBr_06":["#ffffd4","#fee391","#fec44f","#fe9929","#d95f0e","#993404"],"Dark2_06":["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02"],"Blues_04":["#eff3ff","#bdd7e7","#6baed6","#2171b5"],"YlOrBr_07":["#ffffd4","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"],"RdYlGn_05":["#d7191c","#fdae61","#ffffbf","#a6d96a","#1a9641"],"Set3_08":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5"],"YlOrRd_06":["#ffffb2","#fed976","#feb24c","#fd8d3c","#f03b20","#bd0026"],"Dark2_03":["#1b9e77","#d95f02","#7570b3"],"Accent_05":["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0"],"RdYlGn_08":["#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850"],"RdYlGn_09":["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"],"PuOr_11":["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],"YlOrRd_07":["#ffffb2","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"],"Spectral_11":["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],"RdGy_08":["#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d"],"RdGy_09":["#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d"],"RdGy_06":["#b2182b","#ef8a62","#fddbc7","#e0e0e0","#999999","#4d4d4d"],"RdGy_07":["#b2182b","#ef8a62","#fddbc7","#ffffff","#e0e0e0","#999999","#4d4d4d"],"RdGy_04":["#ca0020","#f4a582","#bababa","#404040"],"RdGy_05":["#ca0020","#f4a582","#ffffff","#bababa","#404040"],"RdYlGn_04":["#d7191c","#fdae61","#a6d96a","#1a9641"],"PiYG_09":["#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221"],"RdYlGn_06":["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"],"RdYlGn_07":["#d73027","#fc8d59","#fee08b","#ffffbf","#d9ef8b","#91cf60","#1a9850"],"Spectral_04":["#d7191c","#fdae61","#abdda4","#2b83ba"],"Spectral_05":["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"],"Spectral_06":["#d53e4f","#fc8d59","#fee08b","#e6f598","#99d594","#3288bd"],"PiYG_08":["#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221"],"Set2_03":["#66c2a5","#fc8d62","#8da0cb"],"Spectral_03":["#fc8d59","#ffffbf","#99d594"],"Reds_08":["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"],"Set1_04":["#e41a1c","#377eb8","#4daf4a","#984ea3"],"Spectral_08":["#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd"],"Spectral_09":["#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd"],"Set2_08":["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],"Reds_09":["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],"Greys_07":["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"],"Greys_06":["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#636363","#252525"],"Greys_05":["#f7f7f7","#cccccc","#969696","#636363","#252525"],"Greys_04":["#f7f7f7","#cccccc","#969696","#525252"],"Greys_03":["#f0f0f0","#bdbdbd","#636363"],"PuOr_10":["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],"Accent_07":["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17"],"Reds_06":["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#de2d26","#a50f15"],"Greys_09":["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],"Greys_08":["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"],"Reds_07":["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"],"RdYlBu_08":["#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4"],"RdYlBu_09":["#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4"],"BrBG_09":["#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e"],"BrBG_08":["#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e"],"BrBG_07":["#8c510a","#d8b365","#f6e8c3","#f5f5f5","#c7eae5","#5ab4ac","#01665e"],"BrBG_06":["#8c510a","#d8b365","#f6e8c3","#c7eae5","#5ab4ac","#01665e"],"BrBG_05":["#a6611a","#dfc27d","#f5f5f5","#80cdc1","#018571"],"BrBG_04":["#a6611a","#dfc27d","#80cdc1","#018571"],"BrBG_03":["#d8b365","#f5f5f5","#5ab4ac"],"PiYG_06":["#c51b7d","#e9a3c9","#fde0ef","#e6f5d0","#a1d76a","#4d9221"],"Reds_03":["#fee0d2","#fc9272","#de2d26"],"Set3_11":["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5"],"Set1_06":["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33"],"PuRd_03":["#e7e1ef","#c994c7","#dd1c77"],"PiYG_07":["#c51b7d","#e9a3c9","#fde0ef","#f7f7f7","#e6f5d0","#a1d76a","#4d9221"],"RdBu_07":["#b2182b","#ef8a62","#fddbc7","#f7f7f7","#d1e5f0","#67a9cf","#2166ac"],"Pastel1_06":["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc"],"Spectral_10":["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],"PuRd_04":["#f1eef6","#d7b5d8","#df65b0","#ce1256"],"OrRd_03":["#fee8c8","#fdbb84","#e34a33"],"PiYG_03":["#e9a3c9","#f7f7f7","#a1d76a"],"Oranges_05":["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"],"OrRd_07":["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"],"OrRd_06":["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#e34a33","#b30000"],"OrRd_05":["#fef0d9","#fdcc8a","#fc8d59","#e34a33","#b30000"],"OrRd_04":["#fef0d9","#fdcc8a","#fc8d59","#d7301f"],"Reds_04":["#fee5d9","#fcae91","#fb6a4a","#cb181d"],"Reds_05":["#fee5d9","#fcae91","#fb6a4a","#de2d26","#a50f15"],"OrRd_09":["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],"OrRd_08":["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"],"BrBG_10":["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],"BrBG_11":["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],"PiYG_05":["#d01c8b","#f1b6da","#f7f7f7","#b8e186","#4dac26"],"YlOrRd_08":["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"],"GnBu_04":["#f0f9e8","#bae4bc","#7bccc4","#2b8cbe"],"GnBu_05":["#f0f9e8","#bae4bc","#7bccc4","#43a2ca","#0868ac"],"GnBu_06":["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#43a2ca","#0868ac"],"GnBu_07":["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"],"Purples_08":["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"],"GnBu_03":["#e0f3db","#a8ddb5","#43a2ca"],"Purples_06":["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#756bb1","#54278f"],"Purples_07":["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"],"Purples_04":["#f2f0f7","#cbc9e2","#9e9ac8","#6a51a3"],"Purples_05":["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"],"GnBu_08":["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"],"GnBu_09":["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],"YlOrRd_09":["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],"Purples_03":["#efedf5","#bcbddc","#756bb1"],"RdYlBu_04":["#d7191c","#fdae61","#abd9e9","#2c7bb6"],"PRGn_09":["#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837"],"PRGn_08":["#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837"],"PRGn_07":["#762a83","#af8dc3","#e7d4e8","#f7f7f7","#d9f0d3","#7fbf7b","#1b7837"],"PRGn_06":["#762a83","#af8dc3","#e7d4e8","#d9f0d3","#7fbf7b","#1b7837"],"PRGn_05":["#7b3294","#c2a5cf","#f7f7f7","#a6dba0","#008837"],"PRGn_04":["#7b3294","#c2a5cf","#a6dba0","#008837"],"PRGn_03":["#af8dc3","#f7f7f7","#7fbf7b"],"RdYlBu_06":["#d73027","#fc8d59","#fee090","#e0f3f8","#91bfdb","#4575b4"],"RdYlGn_10":["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],"YlGn_08":["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"],"YlGn_09":["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],"RdYlBu_07":["#d73027","#fc8d59","#fee090","#ffffbf","#e0f3f8","#91bfdb","#4575b4"],"PiYG_10":["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],"PiYG_11":["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],"YlGn_03":["#f7fcb9","#addd8e","#31a354"],"YlGn_04":["#ffffcc","#c2e699","#78c679","#238443"],"YlGn_05":["#ffffcc","#c2e699","#78c679","#31a354","#006837"],"YlGn_06":["#ffffcc","#d9f0a3","#addd8e","#78c679","#31a354","#006837"],"YlGn_07":["#ffffcc","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"],"Dark2_05":["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e"],"Dark2_04":["#1b9e77","#d95f02","#7570b3","#e7298a"],"Dark2_07":["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d"],"Pastel2_03":["#b3e2cd","#fdcdac","#cbd5e8"],"Pastel2_04":["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4"],"Pastel2_05":["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9"],"Pastel2_06":["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae"],"Pastel2_07":["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc"],"Pastel2_08":["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],"RdYlBu_03":["#fc8d59","#ffffbf","#91bfdb"],"Dark2_08":["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],"RdYlGn_03":["#fc8d59","#ffffbf","#91cf60"],"PRGn_11":["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],"Greens_08":["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"],"Greens_09":["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],"Greens_06":["#edf8e9","#c7e9c0","#a1d99b","#74c476","#31a354","#006d2c"],"Greens_07":["#edf8e9","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"],"Greens_04":["#edf8e9","#bae4b3","#74c476","#238b45"],"Greens_05":["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"],"PRGn_10":["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],"Greens_03":["#e5f5e0","#a1d99b","#31a354"]} branca-0.4.2/branca/_version.py000066400000000000000000000441111375174403200163760ustar00rootroot00000000000000 # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = " (HEAD -> master, tag: v0.4.2)" git_full = "ac45f1e1fa95d10a2409409cf3c697f700cad314" git_date = "2020-11-08 11:27:38 +0100" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "v" cfg.parentdir_prefix = "" cfg.versionfile_source = "branca/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} branca-0.4.2/branca/colormap.py000066400000000000000000000412371375174403200163740ustar00rootroot00000000000000""" Colormap -------- Utility module for dealing with colormaps. """ import json import math import os from jinja2 import Template from branca.element import ENV, Figure, JavascriptLink, MacroElement from branca.utilities import legend_scaler rootpath = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(rootpath, '_cnames.json')) as f: _cnames = json.loads(f.read()) with open(os.path.join(rootpath, '_schemes.json')) as f: _schemes = json.loads(f.read()) def _is_hex(x): return x.startswith('#') and len(x) == 7 def _parse_hex(color_code): return (int(color_code[1:3], 16), int(color_code[3:5], 16), int(color_code[5:7], 16)) def _parse_color(x): if isinstance(x, (tuple, list)): color_tuple = tuple(x)[:4] elif isinstance(x, (str, bytes)) and _is_hex(x): color_tuple = _parse_hex(x) elif isinstance(x, (str, bytes)): cname = _cnames.get(x.lower(), None) if cname is None: raise ValueError('Unknown color {!r}.'.format(cname)) color_tuple = _parse_hex(cname) else: raise ValueError('Unrecognized color code {!r}'.format(x)) if max(color_tuple) > 1.: color_tuple = tuple(u/255. for u in color_tuple) return tuple(map(float, (color_tuple+(1.,))[:4])) def _base(x): if x > 0: base = pow(10, math.floor(math.log10(x))) return round(x/base)*base else: return 0 class ColorMap(MacroElement): """A generic class for creating colormaps. Parameters ---------- vmin: float The left bound of the color scale. vmax: float The right bound of the color scale. caption: str A caption to draw with the colormap. """ _template = ENV.get_template('color_scale.js') def __init__(self, vmin=0., vmax=1., caption=''): super(ColorMap, self).__init__() self._name = 'ColorMap' self.vmin = vmin self.vmax = vmax self.caption = caption self.index = [vmin, vmax] def render(self, **kwargs): """Renders the HTML representation of the element.""" self.color_domain = [self.vmin + (self.vmax-self.vmin) * k/499. for k in range(500)] self.color_range = [self.__call__(x) for x in self.color_domain] self.tick_labels = legend_scaler(self.index) super(ColorMap, self).render(**kwargs) figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') figure.header.add_child(JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"), name='d3') # noqa def rgba_floats_tuple(self, x): """ This class has to be implemented for each class inheriting from Colormap. This has to be a function of the form float -> (float, float, float, float) describing for each input float x, the output color in RGBA format; Each output value being between 0 and 1. """ raise NotImplementedError def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x)) def rgb_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B) with int values between 0 and 255. """ return self.rgba_bytes_tuple(x)[:3] def rgb_hex_str(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBB". """ return '#%02x%02x%02x' % self.rgb_bytes_tuple(x) def rgba_hex_str(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA". """ return '#%02x%02x%02x%02x' % self.rgba_bytes_tuple(x) def __call__(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA". """ return self.rgba_hex_str(x) def _repr_html_(self): return ( '' + ''.join( [('').format( i=i*1, color=self.rgba_hex_str( self.vmin + (self.vmax-self.vmin)*i/499.) ) for i in range(500)]) + '{}'.format(self.vmin) + '{}'.format( self.vmax) + '') class LinearColormap(ColorMap): """Creates a ColorMap based on linear interpolation of a set of colors over a given index. Parameters ---------- colors : list-like object with at least two colors. The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: `(255, 255, 0)` or `(255, 255, 0, 255)`) * tuples of RGBA floats between 0. and 1. (e.g: `(1.,1.,0.)` or `(1., 1., 0., 1.)`) * HTML-like string (e.g: `"#ffff00`) * a color name or shortcut (e.g: `"y"` or `"yellow"`) index : list of floats, default None The values corresponding to each color. It has to be sorted, and have the same length as `colors`. If None, a regular grid between `vmin` and `vmax` is created. vmin : float, default 0. The minimal value for the colormap. Values lower than `vmin` will be bound directly to `colors[0]`. vmax : float, default 1. The maximal value for the colormap. Values higher than `vmax` will be bound directly to `colors[-1]`.""" def __init__(self, colors, index=None, vmin=0., vmax=1., caption=''): super(LinearColormap, self).__init__(vmin=vmin, vmax=vmax, caption=caption) n = len(colors) if n < 2: raise ValueError('You must provide at least 2 colors.') if index is None: self.index = [vmin + (vmax-vmin)*i*1./(n-1) for i in range(n)] else: self.index = list(index) self.colors = [_parse_color(x) for x in colors] def rgba_floats_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with float values between 0. and 1. """ if x <= self.index[0]: return self.colors[0] if x >= self.index[-1]: return self.colors[-1] i = len([u for u in self.index if u < x]) # 0 < i < n. if self.index[i-1] < self.index[i]: p = (x - self.index[i-1])*1./(self.index[i]-self.index[i-1]) elif self.index[i-1] == self.index[i]: p = 1. else: raise ValueError('Thresholds are not sorted.') return tuple((1.-p) * self.colors[i-1][j] + p*self.colors[i][j] for j in range(4)) def to_step(self, n=None, index=None, data=None, method=None, quantiles=None, round_method=None): """Splits the LinearColormap into a StepColormap. Parameters ---------- n : int, default None The number of expected colors in the ouput StepColormap. This will be ignored if `index` is provided. index : list of floats, default None The values corresponding to each color bounds. It has to be sorted. If None, a regular grid between `vmin` and `vmax` is created. data : list of floats, default None A sample of data to adapt the color map to. method : str, default 'linear' The method used to create data-based colormap. It can be 'linear' for linear scale, 'log' for logarithmic, or 'quant' for data's quantile-based scale. quantiles : list of floats, default None Alternatively, you can provide explicitely the quantiles you want to use in the scale. round_method : str, default None The method used to round thresholds. * If 'int', all values will be rounded to the nearest integer. * If 'log10', all values will be rounded to the nearest order-of-magnitude integer. For example, 2100 is rounded to 2000, 2790 to 3000. Returns ------- A StepColormap with `n=len(index)-1` colors. Examples: >> lc.to_step(n=12) >> lc.to_step(index=[0, 2, 4, 6, 8, 10]) >> lc.to_step(data=some_list, n=12) >> lc.to_step(data=some_list, n=12, method='linear') >> lc.to_step(data=some_list, n=12, method='log') >> lc.to_step(data=some_list, n=12, method='quantiles') >> lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1]) >> lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1], ... round_method='log10') """ msg = 'You must specify either `index` or `n`' if index is None: if data is None: if n is None: raise ValueError(msg) else: index = [self.vmin + (self.vmax-self.vmin)*i*1./n for i in range(1+n)] scaled_cm = self else: max_ = max(data) min_ = min(data) scaled_cm = self.scale(vmin=min_, vmax=max_) method = ('quantiles' if quantiles is not None else method if method is not None else 'linear' ) if method.lower().startswith('lin'): if n is None: raise ValueError(msg) index = [min_ + i*(max_-min_)*1./n for i in range(1+n)] elif method.lower().startswith('log'): if n is None: raise ValueError(msg) if min_ <= 0: msg = ('Log-scale works only with strictly ' 'positive values.') raise ValueError(msg) index = [math.exp( math.log(min_) + i * (math.log(max_) - math.log(min_)) * 1./n ) for i in range(1+n)] elif method.lower().startswith('quant'): if quantiles is None: if n is None: msg = ('You must specify either `index`, `n` or' '`quantiles`.') raise ValueError(msg) else: quantiles = [i*1./n for i in range(1+n)] p = len(data)-1 s = sorted(data) index = [s[int(q*p)] * (1.-(q*p) % 1) + s[min(int(q*p) + 1, p)] * ((q*p) % 1) for q in quantiles] else: raise ValueError('Unknown method {}'.format(method)) else: scaled_cm = self.scale(vmin=min(index), vmax=max(index)) n = len(index)-1 if round_method == 'int': index = [round(x) for x in index] if round_method == 'log10': index = [_base(x) for x in index] colors = [scaled_cm.rgba_floats_tuple(index[i] * (1.-i/(n-1.)) + index[i+1] * i/(n-1.)) for i in range(n)] return StepColormap(colors, index=index, vmin=index[0], vmax=index[-1]) def scale(self, vmin=0., vmax=1.): """Transforms the colorscale so that the minimal and maximal values fit the given parameters. """ return LinearColormap( self.colors, index=[vmin + (vmax-vmin)*(x-self.vmin)*1./(self.vmax-self.vmin) for x in self.index], # noqa vmin=vmin, vmax=vmax, caption=self.caption, ) class StepColormap(ColorMap): """Creates a ColorMap based on linear interpolation of a set of colors over a given index. Parameters ---------- colors : list-like object The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of int between 0 and 255 (e.g: `(255,255,0)` or `(255, 255, 0, 255)`) * tuples of floats between 0. and 1. (e.g: `(1.,1.,0.)` or `(1., 1., 0., 1.)`) * HTML-like string (e.g: `"#ffff00`) * a color name or shortcut (e.g: `"y"` or `"yellow"`) index : list of floats, default None The values corresponding to each color. It has to be sorted, and have the same length as `colors`. If None, a regular grid between `vmin` and `vmax` is created. vmin : float, default 0. The minimal value for the colormap. Values lower than `vmin` will be bound directly to `colors[0]`. vmax : float, default 1. The maximal value for the colormap. Values higher than `vmax` will be bound directly to `colors[-1]`. """ def __init__(self, colors, index=None, vmin=0., vmax=1., caption=''): super(StepColormap, self).__init__(vmin=vmin, vmax=vmax, caption=caption) n = len(colors) if n < 1: raise ValueError('You must provide at least 1 colors.') if index is None: self.index = [vmin + (vmax-vmin)*i*1./n for i in range(n+1)] else: self.index = list(index) self.colors = [_parse_color(x) for x in colors] def rgba_floats_tuple(self, x): """ Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with float values between 0. and 1. """ if x <= self.index[0]: return self.colors[0] if x >= self.index[-1]: return self.colors[-1] i = len([u for u in self.index if u < x]) # 0 < i < n. return tuple(self.colors[i-1]) def to_linear(self, index=None): """ Transforms the StepColormap into a LinearColormap. Parameters ---------- index : list of floats, default None The values corresponding to each color in the output colormap. It has to be sorted. If None, a regular grid between `vmin` and `vmax` is created. """ if index is None: n = len(self.index)-1 index = [self.index[i]*(1.-i/(n-1.))+self.index[i+1]*i/(n-1.) for i in range(n)] colors = [self.rgba_floats_tuple(x) for x in index] return LinearColormap(colors, index=index, vmin=self.vmin, vmax=self.vmax) def scale(self, vmin=0., vmax=1.): """Transforms the colorscale so that the minimal and maximal values fit the given parameters. """ return StepColormap( self.colors, index=[vmin + (vmax-vmin)*(x-self.vmin)*1./(self.vmax-self.vmin) for x in self.index], # noqa vmin=vmin, vmax=vmax, caption=self.caption, ) class _LinearColormaps(object): """A class for hosting the list of built-in linear colormaps.""" def __init__(self): self._schemes = _schemes.copy() self._colormaps = {key: LinearColormap(val) for key, val in _schemes.items()} for key, val in _schemes.items(): setattr(self, key, LinearColormap(val)) def _repr_html_(self): return Template(""" {% for key,val in this._colormaps.items() %} {% endfor %}
{{key}}{{val._repr_html_()}}
""").render(this=self) linear = _LinearColormaps() class _StepColormaps(object): """A class for hosting the list of built-in step colormaps.""" def __init__(self): self._schemes = _schemes.copy() self._colormaps = {key: StepColormap(val) for key, val in _schemes.items()} for key, val in _schemes.items(): setattr(self, key, StepColormap(val)) def _repr_html_(self): return Template(""" {% for key,val in this._colormaps.items() %} {% endfor %}
{{key}}{{val._repr_html_()}}
""").render(this=self) step = _StepColormaps() branca-0.4.2/branca/element.py000066400000000000000000000531371375174403200162130ustar00rootroot00000000000000""" Element ------- A generic class for creating Elements. """ import base64 import json import warnings from collections import OrderedDict import urllib.parse from urllib.request import urlopen from uuid import uuid4 from jinja2 import Environment, PackageLoader, Template from .utilities import _camelify, _parse_size, none_max, none_min ENV = Environment(loader=PackageLoader('branca', 'templates')) class Element(object): """Basic Element object that does nothing. Other Elements may inherit from this one. Parameters ---------- template : str, default None A jinaj2-compatible template string for rendering the element. If None, template will be: .. code-block:: jinja {% for name, element in this._children.items() %} {{element.render(**kwargs)}} {% endfor %} so that all the element's children are rendered. template_name : str, default None If no template is provided, you can also provide a filename. """ _template = Template( '{% for name, element in this._children.items() %}\n' ' {{element.render(**kwargs)}}' '{% endfor %}' ) def __init__(self, template=None, template_name=None): self._name = 'Element' self._id = uuid4().hex self._env = ENV self._children = OrderedDict() self._parent = None if template is not None: self._template = Template(template) elif template_name is not None: self._template = ENV.get_template(template_name) def get_name(self): """Returns a string representation of the object. This string has to be unique and to be a python and javascript-compatible variable name. """ return _camelify(self._name) + '_' + self._id def _get_self_bounds(self): """Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]] """ return [[None, None], [None, None]] def get_bounds(self): """Computes the bounds of the object and all it's children in the form [[lat_min, lon_min], [lat_max, lon_max]]. """ bounds = self._get_self_bounds() for child in self._children.values(): child_bounds = child.get_bounds() bounds = [ [ none_min(bounds[0][0], child_bounds[0][0]), none_min(bounds[0][1], child_bounds[0][1]), ], [ none_max(bounds[1][0], child_bounds[1][0]), none_max(bounds[1][1], child_bounds[1][1]), ], ] return bounds def add_children(self, child, name=None, index=None): """Add a child.""" warnings.warn('Method `add_children` is deprecated. Please use `add_child` instead.', FutureWarning, stacklevel=2) return self.add_child(child, name=name, index=index) def add_child(self, child, name=None, index=None): """Add a child.""" if name is None: name = child.get_name() if index is None: self._children[name] = child else: items = [item for item in self._children.items() if item[0] != name] items.insert(int(index), (name, child)) self._children = OrderedDict(items) child._parent = self return self def add_to(self, parent, name=None, index=None): """Add element to a parent.""" parent.add_child(self, name=name, index=index) return self def to_dict(self, depth=-1, ordered=True, **kwargs): """Returns a dict representation of the object.""" if ordered: dict_fun = OrderedDict else: dict_fun = dict out = dict_fun() out['name'] = self._name out['id'] = self._id if depth != 0: out['children'] = dict_fun([(name, child.to_dict(depth=depth-1)) for name, child in self._children.items()]) # noqa return out def to_json(self, depth=-1, **kwargs): """Returns a JSON representation of the object.""" return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs) def get_root(self): """Returns the root of the elements tree.""" if self._parent is None: return self else: return self._parent.get_root() def render(self, **kwargs): """Renders the HTML representation of the element.""" return self._template.render(this=self, kwargs=kwargs) def save(self, outfile, close_file=True, **kwargs): """Saves an Element into a file. Parameters ---------- outfile : str or file object The file (or filename) where you want to output the html. close_file : bool, default True Whether the file has to be closed after write. """ if isinstance(outfile, str) or isinstance(outfile, bytes): fid = open(outfile, 'wb') else: fid = outfile root = self.get_root() html = root.render(**kwargs) fid.write(html.encode('utf8')) if close_file: fid.close() class Link(Element): """An abstract class for embedding a link in the HTML.""" def get_code(self): """Opens the link and returns the response's content.""" if self.code is None: self.code = urlopen(self.url).read() return self.code def to_dict(self, depth=-1, **kwargs): """Returns a dict representation of the object.""" out = super(Link, self).to_dict(depth=-1, **kwargs) out['url'] = self.url return out class JavascriptLink(Link): """Create a JavascriptLink object based on a url. Parameters ---------- url : str The url to be linked download : bool, default False Whether the target document shall be loaded right now. """ _template = Template( '{% if kwargs.get("embedded",False) %}' '' '{% else %}' '' '{% endif %}' ) def __init__(self, url, download=False): super(JavascriptLink, self).__init__() self._name = 'JavascriptLink' self.url = url self.code = None if download: self.get_code() class CssLink(Link): """Create a CssLink object based on a url. Parameters ---------- url : str The url to be linked download : bool, default False Whether the target document shall be loaded right now. """ _template = Template( '{% if kwargs.get("embedded",False) %}' '' '{% else %}' '' '{% endif %}' ) def __init__(self, url, download=False): super(CssLink, self).__init__() self._name = 'CssLink' self.url = url self.code = None if download: self.get_code() class Figure(Element): """Create a Figure object, to plot things into it. Parameters ---------- width : str, default "100%" The width of the Figure. It may be a percentage or pixel value (like "300px"). height : str, default None The height of the Figure. It may be a percentage or a pixel value (like "300px"). ratio : str, default "60%" A percentage defining the aspect ratio of the Figure. It will be ignored if height is not None. title : str, default None Figure title. figsize : tuple of two int, default None If you're a matplotlib addict, you can overwrite width and height. Values will be converted into pixels in using 60 dpi. For example figsize=(10, 5) will result in width="600px", height="300px". """ _template = Template( '\n' '' '{% if this.title %}{{this.title}}{% endif %}' ' {{this.header.render(**kwargs)}}\n' '\n' '' ' {{this.html.render(**kwargs)}}\n' '\n' '\n' ) def __init__(self, width='100%', height=None, ratio='60%', title=None, figsize=None): super(Figure, self).__init__() self._name = 'Figure' self.header = Element() self.html = Element() self.script = Element() self.header._parent = self self.html._parent = self self.script._parent = self self.width = width self.height = height self.ratio = ratio self.title = title if figsize is not None: self.width = str(60*figsize[0])+'px' self.height = str(60*figsize[1])+'px' # Create the meta tag. self.header.add_child(Element( ''), # noqa name='meta_http') def to_dict(self, depth=-1, **kwargs): """Returns a dict representation of the object.""" out = super(Figure, self).to_dict(depth=depth, **kwargs) out['header'] = self.header.to_dict(depth=depth-1, **kwargs) out['html'] = self.html.to_dict(depth=depth-1, **kwargs) out['script'] = self.script.to_dict(depth=depth-1, **kwargs) return out def get_root(self): """Returns the root of the elements tree.""" return self def render(self, **kwargs): """Renders the HTML representation of the element.""" for name, child in self._children.items(): child.render(**kwargs) return self._template.render(this=self, kwargs=kwargs) def _repr_html_(self, **kwargs): """Displays the Figure in a Jupyter notebook. Percent-encoded HTML is stored in data-html attribute, which is used to populate the iframe. This approach does not encounter the 2MB limit in Chrome for storing the HTML in the src attribute with a data URI. The alternative of using a srcdoc attribute is not supported in Microsoft Internet Explorer and Edge. """ html = urllib.parse.quote(self.render(**kwargs)) onload = ( 'this.contentDocument.open();' 'this.contentDocument.write(' ' decodeURIComponent(this.getAttribute(\'data-html\'))' ');' 'this.contentDocument.close();' ) if self.height is None: iframe = ( '
' '
' # noqa 'Make this Notebook Trusted to load map: File -> Trust Notebook' # noqa '' '
' ).format(html=html, onload=onload, width=self.width, ratio=self.ratio) else: iframe = ( '' ).format(html=html, onload=onload, width=self.width, height=self.height) return iframe def add_subplot(self, x, y, n, margin=0.05): """Creates a div child subplot in a matplotlib.figure.add_subplot style. Parameters ---------- x : int The number of rows in the grid. y : int The number of columns in the grid. n : int The cell number in the grid, counted from 1 to x*y. Example: >>> fig.add_subplot(3,2,5) # Create a div in the 5th cell of a 3rows x 2columns grid(bottom-left corner). """ width = 1./y height = 1./x left = ((n-1) % y)*width top = ((n-1)//y)*height left = left+width*margin top = top+height*margin width = width*(1-2.*margin) height = height*(1-2.*margin) div = Div(position='absolute', width='{}%'.format(100.*width), height='{}%'.format(100.*height), left='{}%'.format(100.*left), top='{}%'.format(100.*top), ) self.add_child(div) return div class Html(Element): """Create an HTML div object for embedding data. Parameters ---------- data : str The HTML data to be embedded. script : bool If True, data will be embedded without escaping (suitable for embedding html-ready code) width : int or str, default '100%' The width of the output div element. Ex: 120 , '120px', '80%' height : int or str, default '100%' The height of the output div element. Ex: 120 , '120px', '80%' """ _template = Template( '
' # noqa '{% if this.script %}{{this.data}}{% else %}{{this.data|e}}{% endif %}
' ) # noqa def __init__(self, data, script=False, width='100%', height='100%'): super(Html, self).__init__() self._name = 'Html' self.script = script self.data = data self.width = _parse_size(width) self.height = _parse_size(height) class Div(Figure): """Create a Div to be embedded in a Figure. Parameters ---------- width: int or str, default '100%' The width of the div in pixels (int) or percentage (str). height: int or str, default '100%' The height of the div in pixels (int) or percentage (str). left: int or str, default '0%' The left-position of the div in pixels (int) or percentage (str). top: int or str, default '0%' The top-position of the div in pixels (int) or percentage (str). position: str, default 'relative' The position policy of the div. Usual values are 'relative', 'absolute', 'fixed', 'static'. """ _template = Template( '{% macro header(this, kwargs) %}' '' '{% endmacro %}' '{% macro html(this, kwargs) %}' '
{{this.html.render(**kwargs)}}
' '{% endmacro %}' ) def __init__(self, width='100%', height='100%', left='0%', top='0%', position='relative'): super(Figure, self).__init__() self._name = 'Div' # Size Parameters. self.width = _parse_size(width) self.height = _parse_size(height) self.left = _parse_size(left) self.top = _parse_size(top) self.position = position self.header = Element() self.html = Element( '{% for name, element in this._children.items() %}' '{{element.render(**kwargs)}}' '{% endfor %}' ) self.script = Element() self.header._parent = self self.html._parent = self self.script._parent = self def get_root(self): """Returns the root of the elements tree.""" return self def render(self, **kwargs): """Renders the HTML representation of the element.""" figure = self._parent assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') for name, element in self._children.items(): element.render(**kwargs) for name, element in self.header._children.items(): figure.header.add_child(element, name=name) for name, element in self.script._children.items(): figure.script.add_child(element, name=name) header = self._template.module.__dict__.get('header', None) if header is not None: figure.header.add_child(Element(header(self, kwargs)), name=self.get_name()) html = self._template.module.__dict__.get('html', None) if html is not None: figure.html.add_child(Element(html(self, kwargs)), name=self.get_name()) script = self._template.module.__dict__.get('script', None) if script is not None: figure.script.add_child(Element(script(self, kwargs)), name=self.get_name()) def _repr_html_(self, **kwargs): """Displays the Div in a Jupyter notebook.""" if self._parent is None: self.add_to(Figure()) out = self._parent._repr_html_(**kwargs) self._parent = None else: out = self._parent._repr_html_(**kwargs) return out class IFrame(Element): """Create a Figure object, to plot things into it. Parameters ---------- html : str, default None Eventual HTML code that you want to put in the frame. width : str, default "100%" The width of the Figure. It may be a percentage or pixel value (like "300px"). height : str, default None The height of the Figure. It may be a percentage or a pixel value (like "300px"). ratio : str, default "60%" A percentage defining the aspect ratio of the Figure. It will be ignored if height is not None. figsize : tuple of two int, default None If you're a matplotlib addict, you can overwrite width and height. Values will be converted into pixels in using 60 dpi. For example figsize=(10, 5) will result in width="600px", height="300px". """ def __init__(self, html=None, width='100%', height=None, ratio='60%', figsize=None): super(IFrame, self).__init__() self._name = 'IFrame' self.width = width self.height = height self.ratio = ratio if figsize is not None: self.width = str(60*figsize[0])+'px' self.height = str(60*figsize[1])+'px' if isinstance(html, str) or isinstance(html, bytes): self.add_child(Element(html)) elif html is not None: self.add_child(html) def render(self, **kwargs): """Renders the HTML representation of the element.""" html = super(IFrame, self).render(**kwargs) html = "data:text/html;charset=utf-8;base64," + base64.b64encode(html.encode('utf8')).decode('utf8') # noqa if self.height is None: iframe = ( '
' '
' # noqa '' '
' ).format(html=html, width=self.width, ratio=self.ratio) else: iframe = ( '' ).format(html=html, width=self.width, height=self.height) return iframe class MacroElement(Element): """This is a parent class for Elements defined by a macro template. To compute your own element, all you have to do is: * To inherit from this class * Overwrite the '_name' attribute * Overwrite the '_template' attribute with something of the form:: {% macro header(this, kwargs) %} ... {% endmacro %} {% macro html(this, kwargs) %} ... {% endmacro %} {% macro script(this, kwargs) %} ... {% endmacro %} """ _template = Template(u'') def __init__(self): super(MacroElement, self).__init__() self._name = 'MacroElement' def render(self, **kwargs): """Renders the HTML representation of the element.""" figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') header = self._template.module.__dict__.get('header', None) if header is not None: figure.header.add_child(Element(header(self, kwargs)), name=self.get_name()) html = self._template.module.__dict__.get('html', None) if html is not None: figure.html.add_child(Element(html(self, kwargs)), name=self.get_name()) script = self._template.module.__dict__.get('script', None) if script is not None: figure.script.add_child(Element(script(self, kwargs)), name=self.get_name()) for name, element in self._children.items(): element.render(**kwargs) branca-0.4.2/branca/plugins/000077500000000000000000000000001375174403200156605ustar00rootroot00000000000000branca-0.4.2/branca/plugins/__init__.py000066400000000000000000000002001375174403200177610ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Branca plugins -------------- Add different objects/effects in a branca webpage. """ __all__ = [] branca-0.4.2/branca/scheme_base_codes.json000066400000000000000000000005101375174403200205010ustar00rootroot00000000000000{"codes": ["Spectral", "RdYlGn", "PuBu", "Accent", "OrRd", "Set1", "Set2", "Set3", "BuPu", "Dark2", "RdBu", "Oranges", "BuGn", "PiYG", "YlOrBr", "YlGn", "Pastel2", "RdPu", "Greens", "PRGn", "YlGnBu", "RdYlBu", "Paired", "BrBG", "Purples", "Reds", "Pastel1", "GnBu", "Greys", "RdGy", "YlOrRd", "PuOr", "PuRd", "Blues", "PuBuGn"]}branca-0.4.2/branca/scheme_info.json000066400000000000000000000012301375174403200173450ustar00rootroot00000000000000{"Spectral": "Diverging", "RdYlGn": "Diverging", "Set2": "Qualitative", "Accent": "Qualitative", "OrRd": "Sequential", "Set1": "Qualitative", "PuBu": "Sequential", "Set3": "Qualitative", "BuPu": "Sequential", "Dark2": "Qualitative", "RdBu": "Diverging", "BuGn": "Sequential", "PiYG": "Diverging", "YlOrBr": "Sequential", "YlGn": "Sequential", "RdPu": "Sequential", "PRGn": "Diverging", "YlGnBu": "Sequential", "RdYlBu": "Diverging", "Paired": "Qualitative", "Pastel2": "Qualitative", "Pastel1": "Qualitative", "GnBu": "Sequential", "RdGy": "Diverging", "YlOrRd": "Sequential", "PuOr": "Diverging", "PuRd": "Sequential", "BrBg": "Diverging", "PuBuGn": "Sequential"}branca-0.4.2/branca/templates/000077500000000000000000000000001375174403200161755ustar00rootroot00000000000000branca-0.4.2/branca/templates/color_scale.js000066400000000000000000000042641375174403200210260ustar00rootroot00000000000000{% macro script(this, kwargs) %} var {{this.get_name()}} = {}; {%if this.color_range %} {{this.get_name()}}.color = d3.scale.threshold() .domain({{this.color_domain}}) .range({{this.color_range}}); {%else%} {{this.get_name()}}.color = d3.scale.threshold() .domain([{{ this.color_domain[0] }}, {{ this.color_domain[-1] }}]) .range(['{{ this.fill_color }}', '{{ this.fill_color }}']); {%endif%} {{this.get_name()}}.x = d3.scale.linear() .domain([{{ this.color_domain[0] }}, {{ this.color_domain[-1] }}]) .range([0, 400]); {{this.get_name()}}.legend = L.control({position: 'topright'}); {{this.get_name()}}.legend.onAdd = function (map) {var div = L.DomUtil.create('div', 'legend'); return div}; {{this.get_name()}}.legend.addTo({{this._parent.get_name()}}); {{this.get_name()}}.xAxis = d3.svg.axis() .scale({{this.get_name()}}.x) .orient("top") .tickSize(1) .tickValues({{ this.tick_labels }}); {{this.get_name()}}.svg = d3.select(".legend.leaflet-control").append("svg") .attr("id", 'legend') .attr("width", 450) .attr("height", 40); {{this.get_name()}}.g = {{this.get_name()}}.svg.append("g") .attr("class", "key") .attr("transform", "translate(25,16)"); {{this.get_name()}}.g.selectAll("rect") .data({{this.get_name()}}.color.range().map(function(d, i) { return { x0: i ? {{this.get_name()}}.x({{this.get_name()}}.color.domain()[i - 1]) : {{this.get_name()}}.x.range()[0], x1: i < {{this.get_name()}}.color.domain().length ? {{this.get_name()}}.x({{this.get_name()}}.color.domain()[i]) : {{this.get_name()}}.x.range()[1], z: d }; })) .enter().append("rect") .attr("height", 10) .attr("x", function(d) { return d.x0; }) .attr("width", function(d) { return d.x1 - d.x0; }) .style("fill", function(d) { return d.z; }); {{this.get_name()}}.g.call({{this.get_name()}}.xAxis).append("text") .attr("class", "caption") .attr("y", 21) .text('{{ this.caption }}'); {% endmacro %}branca-0.4.2/branca/utilities.py000066400000000000000000000321731375174403200165720ustar00rootroot00000000000000""" Utilities ------- Utility module for Folium helper functions. """ import base64 import json import math import os import struct import zlib from jinja2 import Environment, PackageLoader try: import pandas as pd except ImportError: pd = None try: import numpy as np except ImportError: np = None rootpath = os.path.abspath(os.path.dirname(__file__)) def get_templates(): """Get Jinja templates.""" return Environment(loader=PackageLoader('branca', 'templates')) def legend_scaler(legend_values, max_labels=10.0): """ Downsamples the number of legend values so that there isn't a collision of text on the legend colorbar (within reason). The colorbar seems to support ~10 entries as a maximum. """ if len(legend_values) < max_labels: legend_ticks = legend_values else: spacer = int(math.ceil(len(legend_values)/max_labels)) legend_ticks = [] for i in legend_values[::spacer]: legend_ticks += [i] legend_ticks += ['']*(spacer-1) return legend_ticks def linear_gradient(hexList, nColors): """ Given a list of hexcode values, will return a list of length nColors where the colors are linearly interpolated between the (r, g, b) tuples that are given. Examples -------- >>> linear_gradient([(0, 0, 0), (255, 0, 0), (255, 255, 0)], 100) """ def _scale(start, finish, length, i): """ Return the value correct value of a number that is in between start and finish, for use in a loop of length *length*. """ base = 16 fraction = float(i) / (length - 1) raynge = int(finish, base) - int(start, base) thex = hex(int(int(start, base) + fraction * raynge)).split('x')[-1] if len(thex) != 2: thex = '0' + thex return thex allColors = [] # Separate (R, G, B) pairs. for start, end in zip(hexList[:-1], hexList[1:]): # Linearly intepolate between pair of hex ###### values and # add to list. nInterpolate = 765 for index in range(nInterpolate): r = _scale(start[1:3], end[1:3], nInterpolate, index) g = _scale(start[3:5], end[3:5], nInterpolate, index) b = _scale(start[5:7], end[5:7], nInterpolate, index) allColors.append(''.join(['#', r, g, b])) # Pick only nColors colors from the total list. result = [] for counter in range(nColors): fraction = float(counter) / (nColors - 1) index = int(fraction * (len(allColors) - 1)) result.append(allColors[index]) return result def color_brewer(color_code, n=6): """ Generate a colorbrewer color scheme of length 'len', type 'scheme. Live examples can be seen at http://colorbrewer2.org/ """ maximum_n = 253 minimum_n = 3 # Raise an error if the n requested is greater than the maximum. if n > maximum_n: raise ValueError('The maximum number of colors in a' ' ColorBrewer sequential color series is 253') if n < minimum_n: raise ValueError('The minimum number of colors in a' ' ColorBrewer sequential color series is 3') if not isinstance(color_code, str): raise ValueError('color should be a string, not a {}.' .format(type(color_code))) if color_code[-2:] == '_r': base_code = color_code[:-2] core_color_code = base_code + '_' + str(n).zfill(2) color_reverse = True else: base_code = color_code core_color_code = base_code + '_' + str(n).zfill(2) color_reverse = False with open(os.path.join(rootpath, '_schemes.json')) as f: schemes = json.loads(f.read()) with open(os.path.join(rootpath, '_cnames.json')) as f: scheme_info = json.loads(f.read()) with open(os.path.join(rootpath, 'scheme_base_codes.json')) as f: core_schemes = json.loads(f.read())['codes'] if base_code not in core_schemes: raise ValueError(base_code + ' is not a valid ColorBrewer code') try: schemes[core_color_code] explicit_scheme = True except KeyError: explicit_scheme = False # Only if n is greater than the scheme length do we interpolate values. if not explicit_scheme: # Check to make sure that it is not a qualitative scheme. if scheme_info[base_code] == 'Qualitative': matching_quals = [] for key in schemes: if base_code + '_' in key: matching_quals.append(int(key.split('_')[1])) raise ValueError('Expanded color support is not available' ' for Qualitative schemes; restrict the' ' number of colors for the ' + base_code + ' code to between ' + str(min(matching_quals)) + ' and ' + str(max(matching_quals)) ) else: if not color_reverse: color_scheme = linear_gradient(schemes.get(core_color_code), n) else: color_scheme = linear_gradient(schemes.get(core_color_code)[::-1], n) else: if not color_reverse: color_scheme = schemes.get(core_color_code, None) else: color_scheme = schemes.get(core_color_code, None)[::-1] return color_scheme def split_six(series=None): """ Given a Pandas Series, get a domain of values from zero to the 90% quantile rounded to the nearest order-of-magnitude integer. For example, 2100 is rounded to 2000, 2790 to 3000. Parameters ---------- series: Pandas series, default None Returns ------- list """ if pd is None: raise ImportError('The Pandas package is required' ' for this functionality') if np is None: raise ImportError('The NumPy package is required' ' for this functionality') def base(x): if x > 0: base = pow(10, math.floor(math.log10(x))) return round(x/base)*base else: return 0 quants = [0, 50, 75, 85, 90] # Some weirdness in series quantiles a la 0.13. arr = series.values return [base(np.percentile(arr, x)) for x in quants] def image_to_url(image, colormap=None, origin='upper'): """Infers the type of an image argument and transforms it into a URL. Parameters ---------- image: string, file or array-like object * If string, it will be written directly in the output file. * If file, it's content will be converted as embedded in the output file. * If array-like, it will be converted to PNG base64 string and embedded in the output. origin : ['upper' | 'lower'], optional, default 'upper' Place the [0, 0] index of the array in the upper left or lower left corner of the axes. colormap : callable, used only for `mono` image. Function of the form [x -> (r,g,b)] or [x -> (r,g,b,a)] for transforming a mono image into RGB. It must output iterables of length 3 or 4, with values between 0. and 1. Hint : you can use colormaps from `matplotlib.cm`. """ if hasattr(image, 'read'): # We got an image file. if hasattr(image, 'name'): # We try to get the image format from the file name. fileformat = image.name.lower().split('.')[-1] else: fileformat = 'png' url = 'data:image/{};base64,{}'.format( fileformat, base64.b64encode(image.read()).decode('utf-8')) elif (not (isinstance(image, str) or isinstance(image, bytes))) and hasattr(image, '__iter__'): # We got an array-like object. png = write_png(image, origin=origin, colormap=colormap) url = 'data:image/png;base64,' + base64.b64encode(png).decode('utf-8') else: # We got an URL. url = json.loads(json.dumps(image)) return url.replace('\n', ' ') def write_png(data, origin='upper', colormap=None): """ Transform an array of data into a PNG string. This can be written to disk using binary I/O, or encoded using base64 for an inline PNG like this: >>> png_str = write_png(array) >>> 'data:image/png;base64,'+png_str.encode('base64') Inspired from http://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image Parameters ---------- data: numpy array or equivalent list-like object. Must be NxM (mono), NxMx3 (RGB) or NxMx4 (RGBA) origin : ['upper' | 'lower'], optional, default 'upper' Place the [0,0] index of the array in the upper left or lower left corner of the axes. colormap : callable, used only for `mono` image. Function of the form [x -> (r,g,b)] or [x -> (r,g,b,a)] for transforming a mono image into RGB. It must output iterables of length 3 or 4, with values between 0. and 1. Hint: you can use colormaps from `matplotlib.cm`. Returns ------- PNG formatted byte string """ if np is None: raise ImportError('The NumPy package is required' ' for this functionality') if colormap is None: def colormap(x): return (x, x, x, 1) array = np.atleast_3d(data) height, width, nblayers = array.shape if nblayers not in [1, 3, 4]: raise ValueError('Data must be NxM (mono), ' 'NxMx3 (RGB), or NxMx4 (RGBA)') assert array.shape == (height, width, nblayers) if nblayers == 1: array = np.array(list(map(colormap, array.ravel()))) nblayers = array.shape[1] if nblayers not in [3, 4]: raise ValueError('colormap must provide colors of' 'length 3 (RGB) or 4 (RGBA)') array = array.reshape((height, width, nblayers)) assert array.shape == (height, width, nblayers) if nblayers == 3: array = np.concatenate((array, np.ones((height, width, 1))), axis=2) nblayers = 4 assert array.shape == (height, width, nblayers) assert nblayers == 4 # Normalize to uint8 if it isn't already. if array.dtype != 'uint8': array = array * 255./array.max(axis=(0, 1)).reshape((1, 1, 4)) array = array.astype('uint8') # Eventually flip the image. if origin == 'lower': array = array[::-1, :, :] # Transform the array to bytes. raw_data = b''.join([b'\x00' + array[i, :, :].tobytes() for i in range(height)]) def png_pack(png_tag, data): chunk_head = png_tag + data return (struct.pack('!I', len(data)) + chunk_head + struct.pack('!I', 0xFFFFFFFF & zlib.crc32(chunk_head))) return b''.join([ b'\x89PNG\r\n\x1a\n', png_pack(b'IHDR', struct.pack('!2I5B', width, height, 8, 6, 0, 0, 0)), png_pack(b'IDAT', zlib.compress(raw_data, 9)), png_pack(b'IEND', b'')]) def _camelify(out): return (''.join(['_' + x.lower() if i < len(out)-1 and x.isupper() and out[i+1].islower() # noqa else x.lower() + '_' if i < len(out)-1 and x.islower() and out[i+1].isupper() # noqa else x.lower() for i, x in enumerate(list(out))])).lstrip('_').replace('__', '_') # noqa def _parse_size(value): try: if isinstance(value, int) or isinstance(value, float): value_type = 'px' value = float(value) assert value > 0 else: value_type = '%' value = float(value.strip('%')) assert 0 <= value <= 100 except Exception: msg = 'Cannot parse value {!r} as {!r}'.format raise ValueError(msg(value, value_type)) return value, value_type def _locations_mirror(x): """Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]] """ if hasattr(x, '__iter__'): if hasattr(x[0], '__iter__'): return list(map(_locations_mirror, x)) else: return list(x[::-1]) else: return x def _locations_tolist(x): """Transforms recursively a list of iterables into a list of list. """ if hasattr(x, '__iter__'): return list(map(_locations_tolist, x)) else: return x def none_min(x, y): if x is None: return y elif y is None: return x else: return min(x, y) def none_max(x, y): if x is None: return y elif y is None: return x else: return max(x, y) def iter_points(x): """Iterates over a list representing a feature, and returns a list of points, whatever the shape of the array (Point, MultiPolyline, etc). """ if isinstance(x, (list, tuple)): if len(x): if isinstance(x[0], (list, tuple)): out = [] for y in x: out += iter_points(y) return out else: return [x] else: return [] else: raise ValueError('List/tuple type expected. Got {!r}.'.format(x)) branca-0.4.2/docs/000077500000000000000000000000001375174403200137015ustar00rootroot00000000000000branca-0.4.2/docs/Makefile000066400000000000000000000011101375174403200153320ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)branca-0.4.2/docs/source/000077500000000000000000000000001375174403200152015ustar00rootroot00000000000000branca-0.4.2/docs/source/colormap.rst000066400000000000000000000002041375174403200175430ustar00rootroot00000000000000:mod:`branca.colormap` ---------------------- .. automodule:: branca.colormap :members: :undoc-members: :show-inheritance:branca-0.4.2/docs/source/conf.py000066400000000000000000000123311375174403200165000ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'branca' copyright = '2018, Filipe Fernandes' author = 'Filipe Fernandes' from branca._version import get_versions version = release = get_versions()['version'] del get_versions # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.githubpages', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'nbsphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'brancadoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'branca.tex', 'branca Documentation', 'Filipe Fernandes', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'branca', 'branca Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'branca', 'branca Documentation', author, 'branca', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # -- Extension configuration ------------------------------------------------- branca-0.4.2/docs/source/element.rst000066400000000000000000000002011375174403200173550ustar00rootroot00000000000000:mod:`branca.element` --------------------- .. automodule:: branca.element :members: :undoc-members: :show-inheritance:branca-0.4.2/docs/source/index.rst000066400000000000000000000007101375174403200170400ustar00rootroot00000000000000.. branca documentation master file, created by sphinx-quickstart on Mon Nov 5 13:22:48 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to branca's documentation! ================================== .. toctree:: :maxdepth: 3 :caption: Contents: element colormap Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` branca-0.4.2/examples/000077500000000000000000000000001375174403200145675ustar00rootroot00000000000000branca-0.4.2/examples/Elements.ipynb000066400000000000000000000504411375174403200174120ustar00rootroot00000000000000{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import sys\n", "sys.path.insert(0, '..')\n", "\n", "from branca.element import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Element" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the base brick of `branca`. You can create an `Element` in providing a template string:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "e = Element(\"This is fancy text\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each element has an attribute `_name` and a unique `_id`. You also have a method `get_name` to get a unique string representation of the element." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Element a1d0f648f7444f96b526931944247fd6\n", "element_a1d0f648f7444f96b526931944247fd6\n" ] } ], "source": [ "print(e._name, e._id)\n", "print(e.get_name())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can render an `Element` using the method `render`:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'This is fancy text'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e.render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the template, you can use keyword `this` for accessing the object itself ; and the keyword `kwargs` for accessing any keyword argument provided in the `render` method:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'Hello World, my name is `element_6f17661abddb45c7bf2aa794cadd327d`.'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e = Element(\"Hello {{kwargs['you']}}, my name is `{{this.get_name()}}`.\")\n", "e.render(you='World')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Well, this is not really cool for now. What makes elements useful lies in the fact that you can create trees out of them. To do so, you can either use the method `add_child` or the method `add_to`." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [], "source": [ "child = Element('This is the child.')\n", "parent = Element('This is the parent.').add_child(child)\n", "\n", "parent = Element('This is the parent.')\n", "child = Element('This is the child.').add_to(parent)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now in the example above, embedding the one in the other does not change anything." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is the parent. This is the child.\n" ] } ], "source": [ "print(parent.render(), child.render())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But you can use the tree structure in the template." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "parent = Element(\"{% for child in this._children.values() %}{{child.render()}}{% endfor %}\")\n", "Element('').add_to(parent)\n", "Element('').add_to(parent)\n", "parent.render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, the child of an element are referenced in the `_children` attibute in the form of an `OrderedDict`. You can choose the key of each child in specifying a `name` in the `add_child` (or `add_to`) method:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "OrderedDict([('child_1', )])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "parent = Element(\"{% for child in this._children.values() %}{{child.render()}}{% endfor %}\")\n", "Element('').add_to(parent, name='child_1')\n", "parent._children" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That way, it's possible to overwrite a child in specifying the same name:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Element('').add_to(parent, name='child_1')\n", "parent.render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I hope you start to find it useful.\n", "\n", "In fact, the real interest of `Element` lies in the classes that inherit from it. The most important one is `Figure` described in the next section." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Figure\n", "\n", "A `Figure` represents an HTML document. It's composed of 3 parts (attributes):\n", "\n", "* `header` : corresponds to the `` part of the HTML document,\n", "* `html` : corresponds to the `` part,\n", "* `script` : corresponds to a `\n" ] } ], "source": [ "f = Figure()\n", "print(f.render())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can for example create a beatiful cyan \"hello-world\" webpage in doing:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " \n", " \n", " \n", "\n", " \n", "

Hello world

\n", "\n", "\n" ] } ], "source": [ "f.header.add_child(Element(\"\"))\n", "f.html.add_child(Element(\"

Hello world

\"))\n", "print(f.render())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can simply save the content of the `Figure` to a file, thanks to the `save` method:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " \n", " \n", " \n", "\n", " \n", "

Hello world

\n", "\n", "\n" ] } ], "source": [ "f.save('foo.html')\n", "print(open('foo.html').read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to visualize it in the notebook, you can let `Figure._repr_html_` method do it's job in typing: " ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If this rendering is too large for you, you can force it's width and height:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.width = 300\n", "f.height = 200\n", "f" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that you can also define a `Figure`'s size in a matplotlib way:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Figure(figsize=(5,5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MacroElement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It happens you need to create elements that have multiple effects on a Figure. For this, you can use `MacroElement` whose template contains macros ; each macro writes something into the parent Figure's header, body and script." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " \n", " \n", " This is header of macro_element_ea36a310ab8a4212a8c7ca754a4140fc\n", "\n", " \n", " This is html of macro_element_ea36a310ab8a4212a8c7ca754a4140fc\n", "\n", "\n" ] } ], "source": [ "macro = MacroElement()\n", "macro._template = Template(\n", " '{% macro header(this, kwargs) %}'\n", " 'This is header of {{this.get_name()}}'\n", " '{% endmacro %}'\n", "\n", " '{% macro html(this, kwargs) %}'\n", " 'This is html of {{this.get_name()}}'\n", " '{% endmacro %}'\n", "\n", " '{% macro script(this, kwargs) %}'\n", " 'This is script of {{this.get_name()}}'\n", " '{% endmacro %}'\n", " )\n", "\n", "print(Figure().add_child(macro).render())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Link" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To embed javascript and css links in the header, you can use these class:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "js_link = JavascriptLink('https://example.com/javascript.js')\n", "js_link.render()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "css_link = CssLink('https://example.com/style.css')\n", "css_link.render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Html" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An `Html` element enables you to create custom div to put in the *body* of your page." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'
Hello world
'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "html = Html('Hello world')\n", "html.render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's designed to render the text *as you gave it*, so it won't work directly it you want to embed HTML code inside the div." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'
<b>Hello world</b>
'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Html('Hello world').render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For this, you have to set `script=True` and it will work:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'
Hello world
'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Html('Hello world', script=True).render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## IFrame" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you need to embed a full webpage (with separate javascript environment), you can use `IFrame`." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'
'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "iframe = IFrame('Hello World')\n", "iframe.render()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, it will embed the full content of the iframe in a *base64* string so that the ouput looks like:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = Figure(height=180)\n", "f.html.add_child(Element(\"Before the frame\"))\n", "f.html.add_child(IFrame('In the frame', height='100px'))\n", "f.html.add_child(Element(\"After the frame\"))\n", "f" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Div" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At last, you have the `Div` element that behaves almost like `Html` with a few differences:\n", "\n", "* The style is put in the header, while `Html`'s style is embedded inline.\n", "* `Div` inherits from `MacroElement` so that:\n", " * It cannot be rendered unless it's embedded in a `Figure`.\n", " * It is a useful object toinherit from when you create new classes." ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " \n", " \n", " \n", "\n", " \n", "
Hello world
\n", "\n", "\n" ] } ], "source": [ "div = Div()\n", "div.html.add_child(Element('Hello world'))\n", "print(Figure().add_child(div).render())" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.1" } }, "nbformat": 4, "nbformat_minor": 0 } branca-0.4.2/github_deploy_key_python_visualization_branca.enc000066400000000000000000000105441375174403200250420ustar00rootroot00000000000000gAAAAABb4GrypVQIwD9JfsQudkyvOio8fA6n_4DJ9Im5XK17csgTBxQcCi3bWNQFukkMvcCV7cXARn1uQlnoEUvHhoJC0dNIGryiM5eRr8qLE9JSmJ9Vnf_snKr9-CmlVIEtwKf_QvWI_Ovg3Fu39vNnNgt48VfCOp4Q0KxUlHsh89yiQ14rOhmXvyyCV_l8t0gEZSO_yGiLkyGuVs6WfqnuqHFA_HwpQ5a1oQkbU58Bj_PyJ5atZqH-drOjd-aIA7Vh1y94YpYT4i_QKZi5gJdVmjrDrDy04w3OSiFlIHwi0Gy88J8TdjhjBNm_hpmsF3_e6Cq1E6ZLQMRWQWKsDz79_JkKvDRvKIIzPeEuhgVUkc3VQq61eYPqFM0UxHegxsGs_yOBczWYvp5MXDMSj5gZ5La0-wfFtwdEEZdoEq91prq99PyUsAy2Lo3bU08iT4yySrkRXGXwwMLxHWLJM8Naa4X1nwDbMh7Gd2h415lZolSSSagMfTnPc6ljtwRDog_1kJPZ08WuTqO0FhWAo1HIH0mgyDqegZSO2CGTAFXwPguUq2WuNNW1yGu6LS0wLMJPkCSOaw3fg6jbq5VeiOkV1cknTWDZRw26h2OHNtdlKLgckXqmwRfJBXH5HZ3_GWMKDlm4RUiPYO_g5S-YVxED_mbC3vcx5_0P-7ZzN0QljUz_5zjwU_pxoYV5QZph6DKjlt6DwGoLUngMfp3YLDcfCXYJ2NnkLoQ6VPKozFf1VF-Cf_uWyj6KrzKEk-7YU_7n0SkgoQj_pwj0SnhpcJLM-xeymo7L1cmHe-a5rAGnf3TGdUr39Ga7Fry1-DopsLXvb-P0mRpAx55vfQWt2TBCSZ2kFTRoZwDVmWAU0uDDGHD89Rf21wa_gET5wUF3RnrZXzsXfXUqVl1lr-c7P7wgzDIuaAaUFZmwe6ec5LtqL6-0GVlYuRk4DpcjdabUwYIUobEew8QBaf5aZFrzXN0mAJT4CQE56L6JIZCSI_TU6CM27wCoiSU-Xhs0eFRbkRKOJiekyQUvztvadRqzxdqO5Cksmuq4_EkMTa5KuAsCdEbh5-OJg2fYdjG4nBPkVWqEDtAN7f2dua8c5ay188Oc0PTMEWNQvz_rQimQoU9JrTogH9sJ5v9r2z61DZ8NZ-nxteYMDzsanVNk5xiaBkD086MLCLDZUN4_cYfzEFxaHdvar2ME6U-JyiRckO2ZatDy8utZbxbThjhZlV2P84_DxPJjGADU--COabiKHPQa5kONM8tLgE24IhEfKUljI1j8nVNmxF9bOOKKht2awsxZWbZmcAjzHkuxrIs67iFhkAl33SHjuj0R2xuosWoJYKCtYInW28qkaI2f0HZcvbBS9FUx03MPZFFhCdk9Jpd1aPFB-zeqVUWEjCt7SCOv532HJwxpaalrXC4JD8CcYfyAddWkYRTVCZDCmPplRzTJWpUvcrqtODQTRyQDGSYI2enLxQ_fRMMPAdeZQF0QG0VavDqgONzOifDJiDoXRxl44QKfvQ6-7b1nBMZQUUDXHL12YH2UkKRw6QzfKfr1ZG7zqHFGY-8OQIRdVEfcfQospAH9EMBMb0IdOlRMDCfTo3MFUxCJ-c4ex8wQOYbR_EIyxG9PVIPUrp-mLtwXmSo7atPI5zPcIXbZD3-FR-OU5yBcWTqjUeg5WJK_YBq7-e0Kj65Oe9gHLzuE4vaATk52B-FoQ_PetYYXB4rTCPUxGi8QBklUGgMbaeIwRQlpiGNM9-4JyNL68ZXm0SlpgTK44TIgsda7cEvQJsIYocjLuIPo2bjUXIpkR25uoKDS4yM9E1xrx1h0NJ590K96Jsb4CdiCSJOjV5P6VDc3CCWo-NCoKGcCXY589BJDBrdlMCsQKhrYRKfUuydOpTS543qJoN_IHCOyQC9-Ecun4evQ3LDSxMGa68l0YkIFZygx9GbyrA6SbtU3D5F3p03fbeJBZEWDQYplubMOGK2PwsvfJUGRzKKyUORH78nq5yQFYF5hWfONNSbotDonWatazPIqiAN9iCixlWLU3YkFuZnstd7IfJNpi7n4CA5DxrnKJvb46xzZS91WgI8P73s4AbZdpfZHd-FzRs96GVGJDCAy-A5ZQgMpbtrwCX76MAlO6l5BH_RrKFkDyIEATDyir7hA2z0gEpa83xVAGr2Xo94zruV9nzJKYXr3KQfTVS9do4_J2GzYGZZ_7cTbzWOzH6XaJeOJwA-YbcXdm8D98ncjjfiS5ttzFcjt2VD8QSnOVkx7qAklrajrWAYxi5TwC4QNCvuwm-DGHset1WODHiRT5Oym7C_Tq4H_CEUWuXQC9bNpvme8_UJWNCUkFn0o3qRHXwwRTHho4zaderaIIqT3tq-H9zhoRnfa5XBx_h2mc9N4fzmxd0HnYUNEMHf8JBYx4j7EzMnjvPycqD3XYOyl_G58jeX1ZXnq8LLNik8lZKosHQmTSgtKrJ2rHmrn8fy9uXXHXt47EfVISTfhoHtbx9Q3-ndh6SLt_pYD1S435Vh-c1DQ5rxLxBKJYmOSe1iWo1etPUiLrHHOvOS3Smd90-QWh3PuX_UYbUNWYdfN6GkSeEXQlNxgBvHA5aedoyDGZAudxPjb2OR_NTE5LomVeimbH2x0a9PXigz_so0H3RkM7zXrAHju6Z53_Yb4ncH7jfcdQr0ot4FKArE1TB5Vwyk6tnBQQAtEvf9_yhx6KFr3EnM3YKLRgLueH2t9UbYolbkMzkfXvuN3TtYaho5hNX6kNpQzbUSPax5xltUgSmFLwM7rQZeW9dXnRFA0DduLV9uk5-bYgIdOwDGaZHTgBlvnCM1c74v1ZTKZLlOGwmkUQJRGDPjj3hRKtoHk9U2cIh_1scFw0rXVjF3zvDZjDXgYmIaJ-5Muz1LzhwfBEIk_JV-WY1LRCXyB5a9XJdMLk_mCbhdYGDl8BzUthHzIi2T8xxMOp00oLdSQWTi2-9vltz1akmKNcY2Wnen4_GzFxoZ3PojcpZnAqaDFzQWOERPmuxa8qL6FRU7DH9pfgOQp2-b4RpGwhQosWasHxhj2DKFeVrJOioZ36fs0ghEPXRfMIS6UzUdWvk634Sze1bovv31nfyxOkQ0H7VoxmicGc8cYDttki6K66WHy8-xp5Qzp_2NJBaArhgMWZegRcQQiwEic-c1xV09Vv3H9NLJyWFIO9V2FV8CTuS6WP9k1LBmvY8dvWbiqsplKOyZfbZxLHF-O19YU5zR8ScvZ8yJMYOdFitaUUDAQay3iQ3rTQrNMQaPuWBO6cwLdbkvoYQ5ZD7uiMakN38dWbJRt62xZ6Vd0Qj1J9bizI0Zy8Hk9ruAqkcIHpqfNlV15AvWhDhhPVV2-V76NYf7GGpamTcBr_oKt3qkQ_R1kvkUMZXsNGVTzqRD3McL5378vcFTn8ox6nJbyX8kDGg2A36znyJdkpseJnWVx5uYUkfRy5QTGpuCYhpzHqYNX_brHpxrE_Ph5U2QXOtbShxI1dmAfUspw5lDXQV9qOymQcddQSnQPb57Iuh0Q6QEsEbBRJXAdIguJLe8IZK4ib0LURitsOoHKbGEtUj6IlGn6aU4oRpXyVbpJL2C8D3ziNWytDXxyVZTaGQXevL9VpcQP7DfyQlTfmo82JNlnvPIMABSX23JXwh0uh7q8hkN_-ziXLKJTGKN22ywvIB6XoScXmr0QEkG49rbn7l6Uwke8lDLFxYgELEIiimkBtBNutw-jWJwby5u4lWeBNhAs5z1fzsLaexV318EQdCgOMqwq58UnSLbxN-TyqYWCWkSQPHG4Y5Cq3FByIlLjYxcki103hRsRY2Y5B6xwvDpKoupxpOlErKAlQjMYTirNP1yofuTZQHzQ_mjXJdCzSRNpuw9urjYO9Hm-F4hFB1JxjwWFAZDVRdvUr54k8yA66-JT8RvHvn75zxu-edyq_i3dv1wS7L8WQMHKBRK3V2JwuIf1xVzLpZzbV4Kh72RGaILsCovl1Y0THwe2-NT0yYb0stGBRjkggZsDgBqEDeoekN0gJ2Aa8Wd97nR1ZPaQNfnKp8UBd71U8dEVyudL4vtGG-B7thJ1gcqbIb7oiHX8LERuCZJ50Xc3WlTragAd6I4Nf1GzIqcmFyP3RnsEQhvpgsCJSkescnt7pIZRLY5WaFEWblBPmOmvJ2r-5UiqQB4O0Lxzo7IW53NNgV221h_T2kjjcXms9P4mna34cQUgQZWVAZe6AnJvdnyTXAJJM35JXflow7oBoiIUQv_qWFlx91zw9LHRdY7LBcfwv_E6Kge-2HZGQlqSgZwn05khcprQLbplpMgUJXt8HsxSeI-f38TSJtWI66xGCMdRUq1hFdIXn453NuR4QT54r-4TOIxakFPOniK9MnSAsK6YP4pLfmjKNzJb5KWhinAekaInzeFF29MgbVbmxeEAijYfq9Z_fdDKZ8o9E2q_qa2xKcK0wQ==branca-0.4.2/requirements-dev.txt000066400000000000000000000003051375174403200170070ustar00rootroot00000000000000black check-manifest flake8 flake8-builtins flake8-comprehensions flake8-mutable flake8-print isort jupyter nbsphinx pylint pytest pytest-cov pytest-flake8 pytest-xdist selenium sphinx twine wheel branca-0.4.2/requirements.txt000066400000000000000000000000071375174403200162320ustar00rootroot00000000000000jinja2 branca-0.4.2/setup.cfg000066400000000000000000000013451375174403200145750ustar00rootroot00000000000000# See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] VCS = git style = pep440 versionfile_source = branca/_version.py versionfile_build = branca/_version.py tag_prefix = v parentdir_prefix = [tool:pytest] flake8-max-line-length = 105 flake8-ignore = docs/* ALL versioneer.py ALL branca/_version.py ALL markers = headless: mark headless tests (deselect with '-m "not headless"') [metadata] description-file = README.rst license_file = LICENSE.txt [check-manifest] ignore = .*.yml .coveragerc Makefile docs docs/* *.enc examples examples/* tests tests/* branca-0.4.2/setup.py000066400000000000000000000036611375174403200144710ustar00rootroot00000000000000import os from setuptools import setup import versioneer rootpath = os.path.abspath(os.path.dirname(__file__)) def read(*parts): return open(os.path.join(rootpath, *parts), "r").read() def walk_subpkg(name): data_files = [] package_dir = "branca" for parent, dirs, files in os.walk(os.path.join(package_dir, name)): # Remove package_dir from the path. sub_dir = os.sep.join(parent.split(os.sep)[1:]) for f in files: data_files.append(os.path.join(sub_dir, f)) return data_files pkg_data = { "": [ "*.js", "plugins/*.js", "plugins/*.html", "plugins/*.css", "plugins/*.tpl", "templates/*.html", "templates/*.js", "templates/*.txt", ] } pkgs = ["branca"] LICENSE = "MIT" long_description = "{}".format(read("README.md")) # Dependencies. with open("requirements.txt") as f: tests_require = f.readlines() install_requires = [t.strip() for t in tests_require] setup( name="branca", version=versioneer.get_version(), description="Generate complex HTML+JS pages with Python", long_description=long_description, long_description_content_type="text/markdown", author="Martin Journois", url="https://github.com/python-visualization/branca", keywords="data visualization", classifiers=[ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "License :: OSI Approved :: MIT License", "Development Status :: 5 - Production/Stable", ], packages=pkgs, package_data=pkg_data, include_package_data=True, cmdclass=versioneer.get_cmdclass(), tests_require=["pytest"], license=LICENSE, install_requires=install_requires, python_requires=">=3.5", zip_safe=False, ) branca-0.4.2/tests/000077500000000000000000000000001375174403200141135ustar00rootroot00000000000000branca-0.4.2/tests/test_colormap.py000066400000000000000000000033621375174403200173440ustar00rootroot00000000000000# -*- coding: utf-8 -*- """" Folium Colormap Module ---------------------- """ import branca.colormap as cm def test_simple_step(): step = cm.StepColormap(['green', 'yellow', 'red'], vmin=3., vmax=10., index=[3, 4, 8, 10], caption='step') step = cm.StepColormap(['r', 'y', 'g', 'c', 'b', 'm']) step._repr_html_() def test_simple_linear(): linear = cm.LinearColormap(['green', 'yellow', 'red'], vmin=3., vmax=10.) linear = cm.LinearColormap(['red', 'orange', 'yellow', 'green'], index=[0, 0.1, 0.9, 1.]) linear._repr_html_() def test_linear_to_step(): some_list = [30.6, 50, 51, 52, 53, 54, 55, 60, 70, 100] lc = cm.linear.YlOrRd_06 lc.to_step(n=12) lc.to_step(index=[0, 2, 4, 6, 8, 10]) lc.to_step(data=some_list, n=12) lc.to_step(data=some_list, n=12, method='linear') lc.to_step(data=some_list, n=12, method='log') lc.to_step(data=some_list, n=30, method='quantiles') lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1]) lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1], round_method='int') lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1], round_method='log10') def test_step_to_linear(): step = cm.StepColormap(['green', 'yellow', 'red'], vmin=3., vmax=10., index=[3, 4, 8, 10], caption='step') step.to_linear() def test_linear_object(): cm.linear.OrRd_06._repr_html_() cm.linear.PuBu_06.to_step(12) cm.linear.YlGn_06.scale(3, 12) cm.linear._repr_html_() def test_step_object(): cm.step.OrRd_06._repr_html_() cm.step.PuBu_06.to_linear() cm.step.YlGn_06.scale(3, 12) cm.step._repr_html_() branca-0.4.2/tests/test_iframe.py000066400000000000000000000031351375174403200167710ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Folium Element Module class IFrame ---------------------- """ import os import pytest from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options import branca.element as elem def test_create_empty_iframe(): iframe = elem.IFrame() iframe.render() def test_create_iframe(): iframe = elem.IFrame(html='

test content

', width=60, height=45) iframe.render() @pytest.mark.headless def test_rendering_utf8_iframe(): iframe = elem.IFrame(html=u'

Cerrahpaşa Tıp Fakültesi

') options = Options() options.add_argument('-headless') driver = Firefox(options=options) driver.get('data:text/html,' + iframe.render()) driver.switch_to.frame(0) assert u'Cerrahpaşa Tıp Fakültesi' in driver.page_source @pytest.mark.headless def test_rendering_figure_notebook(): """Verify special characters are correctly rendered in Jupyter notebooks.""" text = '5/7 %, Линейная улица, "\u00e9 Berdsk"' figure = elem.Figure() elem.Html(text).add_to(figure.html) html = figure._repr_html_() filepath = 'temp_test_rendering_figure_notebook.html' filepath = os.path.abspath(filepath) with open(filepath, 'w') as f: f.write(html) options = Options() options.add_argument('-headless') driver = Firefox(options=options) try: driver.get('file://' + filepath) driver.switch_to.frame(0) text_div = driver.find_element_by_css_selector('div') assert text_div.text == text finally: os.remove(filepath) driver.quit() branca-0.4.2/tests/test_notebooks.py000066400000000000000000000024461375174403200175350ustar00rootroot00000000000000""" Branca Notebooks Tests ---------------------- Here we try to execute all notebooks that are in `branca/examples`. """ import os import nbconvert import branca.utilities rootpath = os.path.abspath(os.path.dirname(__file__)) class NotebookTester(object): def __init__(self, filename): self.filename = filename def __call__(self, exporter=None, filename=None): raw_nb = nbconvert.exporters.Exporter().from_filename(self.filename) raw_nb[0].metadata.setdefault('kernelspec', {})['name'] = 'python' exec_nb = nbconvert.preprocessors.ExecutePreprocessor().preprocess(*raw_nb) if exporter is not None: out_nb = nbconvert.exporters.MarkdownExporter().from_notebook_node(*exec_nb) if filename is None: assert self.filename.endswith('.ipynb') filename = self.filename[:-6] + exporter.file_extension open(filename, 'w').write(out_nb[0].encode('utf-8')) class TestNotebooks(object): _filepath = rootpath.rstrip('/')+'/../examples/' _nblist = [x for x in os.listdir(_filepath) if x.endswith('.ipynb')] for fn in TestNotebooks._nblist: setattr( TestNotebooks, 'test_'+branca.utilities._camelify(fn[:-6]), NotebookTester(TestNotebooks._filepath+fn).__call__ ) branca-0.4.2/tests/test_utilities.py000066400000000000000000000006301375174403200175360ustar00rootroot00000000000000import branca.utilities as ut def test_color_brewer_base(): scheme = ut.color_brewer('YlGnBu', 9) assert scheme == [ '#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58' ] def test_color_brewer_reverse(): scheme = ut.color_brewer('YlGnBu') scheme_r = ut.color_brewer('YlGnBu_r') assert scheme[::-1] == scheme_r branca-0.4.2/versioneer.py000066400000000000000000002060031375174403200155050ustar00rootroot00000000000000 # Version: 0.18 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](https://pypi.python.org/pypi/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/warner/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other langauges) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): """Main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)