Example #1
0
def get_lat_long_climate_zones(latitude, longitude):
    ''' Get climate zones that contain lat/long coordinates.

    Parameters
    ----------
    latitude : float
        Latitude of point.
    longitude : float
        Longitude of point.

    Returns
    -------
    climate_zones: dict of str
        Region ids for each climate zone type.
    '''
    try:
        from shapely.geometry import Point
    except ImportError:  # pragma: no cover
        raise ImportError(
            'Finding climate zone of lat/long points requires shapely.')

    (
        iecc_climate_zones,
        iecc_moisture_regimes,
        ba_climate_zones,
        ca_climate_zones,
    ) = cached_data.climate_zone_geometry

    point = Point(longitude, latitude)  # x,y
    climate_zones = {}
    for iecc_climate_zone, shape in iecc_climate_zones:
        if shape.contains(point):
            climate_zones['iecc_climate_zone'] = iecc_climate_zone
            break
    else:
        climate_zones['iecc_climate_zone'] = None

    for iecc_moisture_regime, shape in iecc_moisture_regimes:
        if shape.contains(point):
            climate_zones['iecc_moisture_regime'] = iecc_moisture_regime
            break
    else:
        climate_zones['iecc_moisture_regime'] = None

    for ba_climate_zone, shape in ba_climate_zones:
        if shape.contains(point):
            climate_zones['ba_climate_zone'] = ba_climate_zone
            break
    else:
        climate_zones['ba_climate_zone'] = None

    for ca_climate_zone, shape in ca_climate_zones:
        if shape.contains(point):
            climate_zones['ca_climate_zone'] = ca_climate_zone
            break
    else:
        climate_zones['ca_climate_zone'] = None

    return climate_zones
Example #2
0
def check_zone(point):
    for shape in stadiums:
        if shape.contains(point):
            return "stadium"
    for shape in parks:
        if shape.contains(point):
            return "park"
    for shape in restaurants:
        if shape.contains(point):
            return "restaurant"
Example #3
0
def checkServiceBoundary(lon, lat, network):
    in_poly = None
    try:
        try:
            sh = servBounds[str(network)]
        except KeyError:
            sh = None

        # if multigeometry with multiple contours
        if isinstance(sh, list):
            for shape in sh:
                if shape is not None:
                    inpoly = shape.contains(Point(lon, lat))
                    if inpoly is True:
                        in_poly = 1
                        return in_poly
                    else:
                        in_poly = 0
        # if not multigeometry
        else:
            if sh is not None:
                inpoly = sh.contains(Point(lon, lat))
                if inpoly is True:
                    in_poly = 1
                else:
                    in_poly = 0
    except Exception as e:
        dbLogger.error("Exception: " + str(e))
    return in_poly
Example #4
0
def _random_point_in_shape(shape):  # type: (Any) -> Point
    minx, miny, maxx, maxy = shape.bounds

    while True:
        p = Point(random.uniform(minx, maxx), random.uniform(miny, maxy))

        if shape.contains(p):
            return p
Example #5
0
    def random_point_inside(self, shape):
        "return a random location contained inside shape"

        # get the bounding box.
        minx, miny, maxx, maxy = shape.bounds
        range_x = maxx - minx
        range_y = maxy - miny

        while True:
            # normal distribution with std.dev=range and mean = centroid of shape.
            x = range_x * np.random.randn() + shape.centroid.x
            y = range_y * np.random.randn() + shape.centroid.y
            p = Point(x, y)
            if shape.contains(p):
                break

        return p
def add_neighborhood_data(d, fjson=DC_GEOJSON, namekey='subhood'):
    """ read in neighborhood definitions from a geojson file, and attempt to
        update the dataframe with neighborhood names

    """
    nbhdDat = load_dc_geojson(fjson)
    shapelist = dc_geojson_to_shapelist(nbhdDat)

    lnglt = d[['longitude', 'latitude']]
    neigh = pandas.Series(name="neighborhood", index=d.index)

    for (subfeat, shape) in zip(nbhdDat['features'], shapelist):
        name = subfeat['properties'][namekey]
        matches = lnglt.apply(lambda pt: shape.contains(Point(pt[0], pt[1])), 1)
        neigh[matches] = name

    d['neigh'] = neigh
    return d
				lat = location.get("latitude")
				lon = location.get("longitude")
				if node["flags"].get("online") == True:
					online_coords[nodeinfo["hostname"]] = Point(lon, lat)
				known_coords[nodeinfo["hostname"]] = Point(lon, lat)
				withgeo += 1
			else:
				nogeo += 1
		else:
			nogeo += 1


# Tally nodes within the individual district shapes
for node in online_coords.values():
	for district, shape in district_shapes.items():
		if shape.contains(node):
			online_district_stats[district] += 1

for node in known_coords.values():
	for district, shape in district_shapes.items():
		if shape.contains(node):
			known_district_stats[district] += 1


# Set up object to dump to json
data_dump = {}
data_dump["timestamp"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
data_dump["counts"] = {}
data_dump["counts"]["with_geo"] = withgeo
data_dump["counts"]["without_geo"] = nogeo
data_dump["counts"]["online_within_boundary"] = sum(online_district_stats.values())
def confirmNeighbourhood(listings, neighbourhoods):
    wards = {}
    counter_names = 0
    counter_failed = 0
    counter_manual = 0
    ward_counter = 0
    listing_counter = 0
    print("finding neighbourhoods of listings")
    path_shapefile = path_to_wards_files + "/wards.shp"

    print("phase 1 - matching names")
    for feat in fiona.open(path_shapefile):
        listing_counter = 0
        ward_counter += 1
        print("ward: ", ward_counter)
        ward_properties = feat['properties']
        wards[ward_properties['ward_id']] = Ward(ward_properties['ward_id'],
                                                 ward_properties['name'], 0, 0)
        shape = shapely.geometry.asShape(feat['geometry'])
        #print(shape)

        for id, listing in listings.items():
            #this path only if neighbourhood = name_ward
            listing_counter += 1
            if (listing_counter % 500 == 0):
                print(listing_counter)
            if listing.counted == True:
                continue
            #print(neighbourhoods)
            if ward_properties['name'] not in neighbourhoods[
                    listing.neighbourhood]:
                continue
            point = shapely.geometry.Point(
                float(listing.longitude),
                float(listing.latitude))  # longitude, latitude
            #print("they have the same name! It's ", listing.neighbourhood)
            #print(float(listing.longitude), float(listing.latitude))
            #print (shape.bounds)
            if point.within(shape):
                listing.counted = True
                counter_names += 1
                wards[ward_properties['ward_id']].number_listings += 1
                wards[ward_properties[
                    'ward_id']].number_reviews += listing.number_reviews
                listing.neighbourhood = ward_properties['ward_id']
                print(listing.id)
            else:
                print("failed")
            print(counter_names, " listings had neighbourhoods, ",
                  counter_manual, " listings had coordinates, ",
                  counter_failed, " are not counted.")

    print("phase 2 - getting locations")
    ward_counter = 0
    listing_counter = 0
    for feat in fiona.open(path_shapefile):
        listing_counter += 1
        if (listing_counter % 500 == 0):
            print(listing_counter)
        ward_properties = feat['properties']
        shape = shapely.geometry.asShape(feat['geometry'])
        ward_counter += 1
        print("ward: ", ward_counter)
        for id, listing in listings.items():
            if listing.counted == True:
                continue
            point = shapely.geometry.Point(
                float(listing.longitude),
                float(listing.latitude))  # longitude, latitude
            if shape.contains(point):
                listing.counted = True
                counter_manual += 1
                wards[ward_properties['ward_id']].number_listings += 1
                wards[ward_properties[
                    'ward_id']].number_reviews += listing.number_reviews
                listing.neighbourhood = ward_properties['ward_id']
            #print(counter_names+counter_manual)
            print(counter_names, " listings had neighbourhoods, ",
                  counter_manual, " listings had coordinates, ",
                  counter_failed, " are not counted.")

    print(counter_names, " listings had neighbourhoods, ", counter_manual,
          " listings had coordinates, ", counter_failed, " are not counted.")

    uncounted = 0
    totreviews = 0
    for id, listing in listings.items():
        if listing.counted == False:
            uncounted += 1
    print("uncounted is: ", uncounted)
    print("total number of reviews is:")

    for name, ward in wards.items():
        print(
            f'\tNAME: {ward.name}, LISTINGS {ward.number_listings}, REVIEWS {ward.number_reviews}'
        )
        totreviews += ward.number_reviews

    print(totreviews)