├── .gitignore ├── LICENSE ├── README.rst ├── maxrect ├── __init__.py └── scripts │ ├── __init__.py │ └── cli.py ├── setup.cfg ├── setup.py └── tests ├── fixtures ├── polygon.geojson └── polygon2.geojson ├── test_cli.py └── test_mod.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # PyInstaller 26 | # Usually these files are written by a python script from a template 27 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 28 | *.manifest 29 | *.spec 30 | 31 | # Installer logs 32 | pip-log.txt 33 | pip-delete-this-directory.txt 34 | 35 | # Unit test / coverage reports 36 | htmlcov/ 37 | .tox/ 38 | .coverage 39 | .cache 40 | nosetests.xml 41 | coverage.xml 42 | 43 | # Translations 44 | *.mo 45 | *.pot 46 | 47 | # Django stuff: 48 | *.log 49 | 50 | # Sphinx documentation 51 | docs/_build/ 52 | 53 | # PyBuilder 54 | target/ 55 | 56 | # OS X 57 | .DS_Store 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | maxrect 2 | ======= 3 | 4 | Find the maximally inscribed, axis-aligned rectangle for a given polygon. 5 | Find the intersection of multiple polygons. 6 | 7 | .. image:: https://pl-amit.s3.amazonaws.com/demo/maxrect/maximal-rectangle.png 8 | 9 | 10 | Installation 11 | ------------ 12 | 13 | .. code-block:: bash 14 | 15 | pip install git+https://${GITHUB_TOKEN}@github.com/planetlabs/maxrect.git 16 | 17 | 18 | CLI 19 | --- 20 | 21 | .. code-block:: bash 22 | 23 | 24 | # For a given GeoJSON file 25 | $ max-rect [path/to/file] 26 | 27 | # Piping 28 | $ cat path/to/file.geojson | max-rect 29 | 30 | # For a quick visualization 31 | $ cat path/to/file.geojson | max-rect | geojsonio 32 | 33 | # For comparison between the original polygon and the inscribed rectangle 34 | $ cat path/to/file.geojson | max-rect --compare | geojsonio 35 | 36 | # Find the intersection of two geojson files 37 | poly-intersect path/to/file1.geojson path/to/file2.geojson | geojsonio 38 | 39 | # Find the largest inscribed rectangle that sits within multiple shapes 40 | poly-intersect path/to/file1.geojson path/to/file2.geojson | max-rect | geojsonio 41 | 42 | # Find the intersection of two geojson files 43 | poly-intersect path/to/file1.geojson path/to/file2.geojson | geojsonio 44 | 45 | # Find the largest inscribed rectangle that sits within multiple shapes 46 | poly-intersect path/to/file1.geojson path/to/file2.geojson | max-rect | geojsonio 47 | 48 | 49 | Python 50 | ------ 51 | 52 | .. code-block:: python 53 | 54 | from maxrect import get_intersection, get_maximal_rectangle, rect2poly 55 | 56 | # For a given convex polygon 57 | coordinates1 = [ [x0, y0], [x1, y1], ... [xn, yn] ] 58 | coordinates2 = [ [x0, y0], [x1, y1], ... [xn, yn] ] 59 | 60 | # find the intersection of the polygons 61 | _, coordinates = get_intersection([coordinates1, coordinates2]) 62 | 63 | # get the maximally inscribed rectangle 64 | ll, ur = get_maximal_rectangle(coordinates) 65 | 66 | # casting the rectangle to a GeoJSON-friendly closed polygon 67 | rect2poly(ll, ur) 68 | -------------------------------------------------------------------------------- /maxrect/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import cvxpy 4 | from shapely.geometry import Polygon 5 | 6 | 7 | def rect2poly(ll, ur): 8 | """ 9 | Convert rectangle defined by lower left/upper right 10 | to a closed polygon representation. 11 | """ 12 | x0, y0 = ll 13 | x1, y1 = ur 14 | 15 | return [ 16 | [x0, y0], 17 | [x0, y1], 18 | [x1, y1], 19 | [x1, y0], 20 | [x0, y0] 21 | ] 22 | 23 | 24 | def get_intersection(coords): 25 | """Given an input list of coordinates, find the intersection 26 | section of corner coordinates. Returns geojson of the 27 | interesection polygon. 28 | """ 29 | ipoly = None 30 | for coord in coords: 31 | if ipoly is None: 32 | ipoly = Polygon(coord) 33 | else: 34 | tmp = Polygon(coord) 35 | ipoly = ipoly.intersection(tmp) 36 | 37 | # close the polygon loop by adding the first coordinate again 38 | first_x = ipoly.exterior.coords.xy[0][0] 39 | first_y = ipoly.exterior.coords.xy[1][0] 40 | ipoly.exterior.coords.xy[0].append(first_x) 41 | ipoly.exterior.coords.xy[1].append(first_y) 42 | 43 | inter_coords = zip( 44 | ipoly.exterior.coords.xy[0], ipoly.exterior.coords.xy[1]) 45 | 46 | inter_gj = {"geometry": 47 | {"coordinates": [inter_coords], 48 | "type": "Polygon"}, 49 | "properties": {}, "type": "Feature"} 50 | 51 | return inter_gj, inter_coords 52 | 53 | 54 | def two_pts_to_line(pt1, pt2): 55 | """ 56 | Create a line from two points in form of 57 | 58 | a1(x) + a2(y) = b 59 | """ 60 | pt1 = [float(p) for p in pt1] 61 | pt2 = [float(p) for p in pt2] 62 | try: 63 | slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0]) 64 | except ZeroDivisionError: 65 | slp = 1e5 * (pt2[1] - pt1[1]) 66 | a1 = -slp 67 | a2 = 1. 68 | b = -slp * pt1[0] + pt1[1] 69 | 70 | return a1, a2, b 71 | 72 | 73 | def pts_to_leq(coords): 74 | """ 75 | Converts a set of points to form Ax = b, but since 76 | x is of length 2 this is like A1(x1) + A2(x2) = B. 77 | returns A1, A2, B 78 | """ 79 | 80 | A1 = [] 81 | A2 = [] 82 | B = [] 83 | for i in range(len(coords) - 1): 84 | pt1 = coords[i] 85 | pt2 = coords[i + 1] 86 | a1, a2, b = two_pts_to_line(pt1, pt2) 87 | A1.append(a1) 88 | A2.append(a2) 89 | B.append(b) 90 | return A1, A2, B 91 | 92 | 93 | def get_maximal_rectangle(coordinates): 94 | """ 95 | Find the largest, inscribed, axis-aligned rectangle. 96 | 97 | :param coordinates: 98 | A list of of [x, y] pairs describing a closed, convex polygon. 99 | """ 100 | 101 | coordinates = np.array(coordinates) 102 | x_range = np.max(coordinates, axis=0)[0]-np.min(coordinates, axis=0)[0] 103 | y_range = np.max(coordinates, axis=0)[1]-np.min(coordinates, axis=0)[1] 104 | 105 | scale = np.array([x_range, y_range]) 106 | sc_coordinates = coordinates/scale 107 | 108 | poly = Polygon(sc_coordinates) 109 | inside_pt = (poly.representative_point().x, 110 | poly.representative_point().y) 111 | 112 | A1, A2, B = pts_to_leq(sc_coordinates) 113 | 114 | bl = cvxpy.Variable(2) 115 | tr = cvxpy.Variable(2) 116 | br = cvxpy.Variable(2) 117 | tl = cvxpy.Variable(2) 118 | obj = cvxpy.Maximize(cvxpy.log(tr[0] - bl[0]) + cvxpy.log(tr[1] - bl[1])) 119 | constraints = [bl[0] == tl[0], 120 | br[0] == tr[0], 121 | tl[1] == tr[1], 122 | bl[1] == br[1], 123 | ] 124 | 125 | for i in range(len(B)): 126 | if inside_pt[0] * A1[i] + inside_pt[1] * A2[i] <= B[i]: 127 | constraints.append(bl[0] * A1[i] + bl[1] * A2[i] <= B[i]) 128 | constraints.append(tr[0] * A1[i] + tr[1] * A2[i] <= B[i]) 129 | constraints.append(br[0] * A1[i] + br[1] * A2[i] <= B[i]) 130 | constraints.append(tl[0] * A1[i] + tl[1] * A2[i] <= B[i]) 131 | 132 | else: 133 | constraints.append(bl[0] * A1[i] + bl[1] * A2[i] >= B[i]) 134 | constraints.append(tr[0] * A1[i] + tr[1] * A2[i] >= B[i]) 135 | constraints.append(br[0] * A1[i] + br[1] * A2[i] >= B[i]) 136 | constraints.append(tl[0] * A1[i] + tl[1] * A2[i] >= B[i]) 137 | 138 | prob = cvxpy.Problem(obj, constraints) 139 | prob.solve(solver=cvxpy.CVXOPT, verbose=False, max_iters=1000, reltol=1e-9) 140 | 141 | bottom_left = np.array(bl.value).T * scale 142 | top_right = np.array(tr.value).T * scale 143 | 144 | return list(bottom_left[0]), list(top_right[0]) 145 | -------------------------------------------------------------------------------- /maxrect/scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/planetlabs/maxrect/c91c240279cab57e77d348010c2683f944c653db/maxrect/scripts/__init__.py -------------------------------------------------------------------------------- /maxrect/scripts/cli.py: -------------------------------------------------------------------------------- 1 | 2 | import copy 3 | import json 4 | import click 5 | from maxrect import get_maximal_rectangle, rect2poly, get_intersection 6 | 7 | 8 | @click.command('max-rect') 9 | @click.argument('polygon', default='-', required=False, nargs=1) 10 | @click.option('--compare', is_flag=True, help='Leaves the original polygon in the feature collection') 11 | @click.pass_context 12 | def maxrect(ctx, polygon, compare): 13 | """ 14 | Get an approximately maximal area, axis-aligned rectangle 15 | for a polygon represented by GeoJSON. 16 | """ 17 | 18 | if polygon == '-': 19 | src = click.open_file('-') 20 | 21 | if not src.isatty(): 22 | data = src.read() 23 | else: 24 | click.echo(ctx.get_usage()) 25 | ctx.exit(1) 26 | else: 27 | with open(polygon, 'r') as src: 28 | data = src.read() 29 | 30 | geojson = json.loads(data) 31 | 32 | if geojson.get('type') == 'Feature': 33 | 34 | geojson = { 35 | 'type': 'FeatureCollection', 36 | 'features': [geojson] 37 | } 38 | 39 | features = geojson.get('features') 40 | n_features = len(features) 41 | 42 | if compare: 43 | features = features + copy.deepcopy(features) 44 | 45 | for feature in features[:n_features]: 46 | coordinates = get_maximal_rectangle(feature['geometry']['coordinates'][0]) 47 | feature['geometry']['coordinates'] = [rect2poly(*coordinates)] 48 | 49 | geojson['features'] = features 50 | click.echo(json.dumps(geojson)) 51 | 52 | 53 | @click.command('poly-intersect') 54 | @click.argument('input_geoms', required=True, nargs=-1) 55 | @click.pass_context 56 | def polyinter(ctx, input_geoms): 57 | """Find an intersection polygon given multiple geometry inputs""" 58 | coords = [] 59 | for ig in input_geoms: 60 | with open(ig, 'r') as src: 61 | data = src.read() 62 | geojson = json.loads(data) 63 | 64 | if geojson.get('type') == 'Feature': 65 | geojson = { 66 | 'type': 'FeatureCollection', 67 | 'features': [geojson] 68 | } 69 | 70 | features = geojson.get('features') 71 | n_features = len(features) 72 | 73 | for feature in features[:n_features]: 74 | c = feature['geometry']['coordinates'][0] 75 | coords.append(c) 76 | 77 | inter_geojson, _ = get_intersection(coords) 78 | 79 | geojson = { 80 | 'type': 'FeatureCollection', 81 | 'features': [inter_geojson] 82 | } 83 | 84 | click.echo(json.dumps(geojson)) 85 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/planetlabs/maxrect/c91c240279cab57e77d348010c2683f944c653db/setup.cfg -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from codecs import open as codecs_open 2 | from setuptools import setup, find_packages 3 | 4 | 5 | # Get the long description from the relevant file 6 | with codecs_open('README.rst', encoding='utf-8') as f: 7 | long_description = f.read() 8 | 9 | 10 | setup(name='maxrect', 11 | version='0.0.1', 12 | description=u"Find the maximal area rectangle from a polygon.", 13 | long_description=long_description, 14 | classifiers=[], 15 | keywords='', 16 | author=u"Amit Kapadia", 17 | author_email='amit@planet.com', 18 | url='https://github.com/kapadia/maxrect', 19 | license='MIT', 20 | packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), 21 | include_package_data=True, 22 | zip_safe=False, 23 | install_requires=[ 24 | 'click', 25 | 'numpy', 26 | 'shapely', 27 | 'cvxpy' 28 | ], 29 | extras_require={ 30 | 'test': ['pytest'], 31 | }, 32 | entry_points=""" 33 | [console_scripts] 34 | max-rect=maxrect.scripts.cli:maxrect 35 | poly-intersect=maxrect.scripts.cli:polyinter 36 | """ 37 | ) 38 | -------------------------------------------------------------------------------- /tests/fixtures/polygon.geojson: -------------------------------------------------------------------------------- 1 | { 2 | "type": "FeatureCollection", 3 | "features": [ 4 | { 5 | "type": "Feature", 6 | "properties": {}, 7 | "geometry": { 8 | "type": "Polygon", 9 | "coordinates": [ 10 | [ 11 | [ 12 | -101.6455078125, 13 | 42.293564192170095 14 | ], 15 | [ 16 | -94.39453125, 17 | 44.5278427984555 18 | ], 19 | [ 20 | -90.65917968749999, 21 | 42.84375132629023 22 | ], 23 | [ 24 | -91.97753906249999, 25 | 39.53793974517628 26 | ], 27 | [ 28 | -97.470703125, 29 | 37.61423141542417 30 | ], 31 | [ 32 | -103.798828125, 33 | 39.232253141714885 34 | ], 35 | [ 36 | -101.6455078125, 37 | 42.293564192170095 38 | ] 39 | ] 40 | ] 41 | } 42 | } 43 | ] 44 | } -------------------------------------------------------------------------------- /tests/fixtures/polygon2.geojson: -------------------------------------------------------------------------------- 1 | { 2 | "type": "FeatureCollection", 3 | "features": [ 4 | { 5 | "type": "Feature", 6 | "properties": {}, 7 | "geometry": { 8 | "type": "Polygon", 9 | "coordinates": [ 10 | [ 11 | [ 12 | -101.6455078125, 13 | 42.293564192170095 14 | ], 15 | [ 16 | -92.39453125, 17 | 44.5278427984555 18 | ], 19 | [ 20 | -90.65917968749999, 21 | 42.84375132629023 22 | ], 23 | [ 24 | -91.97753906249999, 25 | 39.53793974517628 26 | ], 27 | [ 28 | -97.470703125, 29 | 37.61423141542417 30 | ], 31 | [ 32 | -107.798828125, 33 | 39.232253141714885 34 | ], 35 | [ 36 | -101.6455078125, 37 | 42.293564192170095 38 | ] 39 | ] 40 | ] 41 | } 42 | } 43 | ] 44 | } -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | from click.testing import CliRunner 4 | from maxrect.scripts.cli import maxrect, polyinter 5 | 6 | 7 | def test_maxrect(): 8 | 9 | srcpath = os.path.join(os.path.dirname(__file__), 'fixtures/polygon.geojson') 10 | 11 | runner = CliRunner() 12 | result = runner.invoke(maxrect, [srcpath]) 13 | assert result.exit_code == 0 14 | 15 | 16 | def test_poly_intersect(): 17 | srcpath1 = os.path.join(os.path.dirname(__file__), 'fixtures/polygon.geojson') 18 | srcpath2 = os.path.join(os.path.dirname(__file__), 'fixtures/polygon2.geojson') 19 | 20 | runner = CliRunner() 21 | result = runner.invoke(polyinter, [srcpath1, srcpath2]) 22 | assert result.exit_code == 0 23 | -------------------------------------------------------------------------------- /tests/test_mod.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | import json 4 | 5 | import maxrect 6 | 7 | EPS = 1e-8 8 | 9 | 10 | def test_get_maximal_rectangle(): 11 | 12 | srcpath = os.path.join(os.path.dirname(__file__), 'fixtures/polygon.geojson') 13 | 14 | with open(srcpath) as src: 15 | data = src.read() 16 | geojson = json.loads(data) 17 | 18 | feature = geojson.get('features')[0] 19 | coordinates = feature.get('geometry').get('coordinates')[0] 20 | ll, ur = maxrect.get_maximal_rectangle(coordinates) 21 | 22 | expected_ll = [-101.645507812426, 39.222888638556988] 23 | expected_ur = [-92.877169942000137, 42.293564192171694] 24 | 25 | assert abs(expected_ll[0] - ll[0] < EPS) 26 | assert abs(expected_ll[1] - ll[1] < EPS) 27 | assert abs(expected_ur[0] - ur[0] < EPS) 28 | assert abs(expected_ur[1] - ur[1] < EPS) 29 | --------------------------------------------------------------------------------