Example #1
0
def setup_cad250_grid(verbose=True, test=False):
    dt = models.DivisionType.objects.get(name='cad_250m_grid')
    camden_borough = models.Division.objects.get(type='borough', name='Camden')
    x_coords = np.arange(523750, 532000, 250)
    y_coords = np.arange(180750, 188000, 250)
    I, J = np.meshgrid(range(len(x_coords) - 1), range(len(y_coords) - 1))

    polys = []

    for (i, j) in zip(I.flatten(), J.flatten()):
        poly = Polygon((
            (x_coords[i], y_coords[j]),
            (x_coords[i], y_coords[j + 1]),
            (x_coords[i + 1], y_coords[j + 1]),
            (x_coords[i + 1], y_coords[j]),
            (x_coords[i], y_coords[j]),
        ))
        if poly.distance(camden_borough.mpoly) < 1.0:
            polys.append(poly)

    divs = []

    for i, p in enumerate(polys):
        d = models.Division(name=str(i),
                            code=str(i),
                            type=dt,
                            mpoly=MultiPolygon([p]))
        divs.append(d)

    if test:
        try:
            [x.save() for x in divs]
        except Exception as exc:
            ## FIXME: I have NO idea why this needs to be called twice in test mode
            [x.save() for x in divs]

    else:
        try:
            models.Division.objects.bulk_create(divs)
        except Exception as exc:
            print repr(exc)
            raise exc

    if verbose:
        print "Created %u grid areas" % len(polys)