Spatial Algorithms




Pay Notebook Creator: Roy Hyunjin Han0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0
In [1]:
# CrossCompute
geometries_text_path = 'geometries.txt'
target_folder = '/tmp'
In [3]:
from shapely import wkt
from shapely.geometry import GeometryCollection

geometries = []
for line in open(geometries_text_path):
    geometries.append(wkt.loads(line))
GeometryCollection(geometries)
Out[3]:
<shapely.geometry.collection.GeometryCollection at 0x7efd0c3edd30>
In [4]:
from shapely.geometry import Point

def sum_distances(xy):
    return sum(Point(xy).distance(g) for g in geometries)

sum_distances((0, 0))
Out[4]:
2.8284271247461903
In [6]:
from numpy.random import rand
from scipy.optimize import minimize
initial_xy = rand(2)
r = minimize(sum_distances, initial_xy, method='L-BFGS-B')
r
Out[6]:
      fun: 2.732050807605542
 hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
      jac: array([ -5.19584376e-06,   9.10382880e-06])
  message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
     nfev: 21
      nit: 5
   status: 0
  success: True
        x: array([ -1.85893340e-06,   4.22656731e-01])
In [7]:
store_point = Point(r.x)
print(store_point)
POINT (-1.858933395716981e-06 0.4226567310577499)
In [8]:
from geotable import ColorfulGeometryCollection

geometry_collection = ColorfulGeometryCollection([
    GeometryCollection(geometries),
    store_point,
], colors=['blue', 'yellow'])
geometry_collection
Out[8]:
<geotable.ColorfulGeometryCollection at 0x7efceb06ef98>
In [9]:
from cairosvg import svg2png
from os.path import join

target_path = join(target_folder, 'geometries.png')
svg2png(
    bytestring=geometry_collection._repr_svg_(),
    write_to=target_path)
print('geometry_image_path = %s' % target_path)
geometry_image_path = /tmp/geometries.png
In [10]:
print('store_x = %s' % store_point.x)
print('store_y = %s' % store_point.y)
store_x = -1.8589333957169814e-06
store_y = 0.4226567310577499