Exemple #1
0
def dump(list_data, data, filename, geometry='route'):
    with open(filename, 'w') as jfile:
        rnd_color = RandomColor()
        colors = rnd_color.generate(count=len(list_data))
        features = []
        index = 1
        features.append(gs.MultiPoint(list(data.geo_data.values())))
        for item in list_data:
            color = colors.pop()
            terminal = [item[0], item[-1]]
            # get route coords by road
            if geometry == 'graph':
                # graph geometry
                RP = data.indexToCoord(item)
            else:
                # osrm geometry
                RP = item.route()
            coords = gs.Feature(geometry=gs.LineString(RP),
                properties={'label': 'Route #{}'.format(index+1), 'color': color})
            term = gs.Feature(geometry=gs.MultiPoint(data.indexToCoord(terminal)),
                properties={'label': 'Terminal #{}'.format(index+1), 'color': color})
            index += 1
            features.append(coords)
            features.append(term)
        feature_r = gs.FeatureCollection([features])
        gs.dump(features, jfile)
Exemple #2
0
def __to_geojson(coordinates, geojson_properties={}):
    coordinatePoints = geojson.MultiPoint(coordinates)
    dump = geojson.dumps(
        geojson.Feature(geometry=coordinatePoints,
                        properties=geojson_properties)
    )  # can add properties and id to feature (perhaps trip/section id?)
    return dump
def create_isochrones_hulls(graph,
                            start,
                            time,
                            PandaV,
                            partitions_sec=partitions_sec,
                            palette=palette):
    arrayT = graph.isochrones(start, time, partitions_sec)
    XY = PandaV[["stop_lat", "stop_lon"]]
    T = pandas.Series(arrayT, name="time", dtype=int)
    XYT = pandas.concat([XY, T], axis=1)
    grouped_by_time = XYT.groupby("time")
    Feature_list = []
    for t, group in grouped_by_time:
        if t < len(partitions_min):
            Poly = geojson.MultiPoint([(group["stop_lon"][i],
                                        group["stop_lat"][i])
                                       for i in group.index])
            Prop = {}
            if t < len(partitions_sec):
                Prop["isochrone"] = "< " + seconds_to_hours(partitions_sec[t])
            else:
                Prop["isochrone"] = "> " + seconds_to_hours(partitions_sec[-1])
            Prop["color"] = palette[t % len(palette)]
            Prop["type"] = "stop"
            Feature_list.append(geojson.Feature(geometry=Poly,
                                                properties=Prop))
    Feature_list.reverse()
    Feature_list.append(
        geojson.Feature(geometry=geojson.Point(
            (PandaV["stop_lon"][start], PandaV["stop_lat"][start])),
                        properties={
                            "centre": PandaV["station_name"][start],
                            "type": "center"
                        }))
    return geojson.FeatureCollection(Feature_list)
Exemple #4
0
 def __init__(self, list_of_tuples):
     if not list_of_tuples:
         raise ValueError("A MultiPoint cannot be empty")
     for t in list_of_tuples:
         assert_is_lon(t[0])
         assert_is_lat(t[1])
     self._geom = geojson.MultiPoint(list_of_tuples)
Exemple #5
0
    def test_nested_constructors(self):
        a = [5, 6]
        b = [9, 10]
        c = [-5, 12]
        mp = geojson.MultiPoint([geojson.Point(a), b])
        self.assertEqual(mp.coordinates, [a, b])

        mls = geojson.MultiLineString([geojson.LineString([a, b]), [a, c]])
        self.assertEqual(mls.coordinates, [[a, b], [a, c]])

        outer = [a, b, c, a]
        poly = geojson.Polygon(geojson.MultiPoint(outer))
        other = [[1, 1], [1, 2], [2, 1], [1, 1]]
        poly2 = geojson.Polygon([outer, other])
        self.assertEqual(geojson.MultiPolygon([poly, poly2]).coordinates,
                         [[outer], [outer, other]])
Exemple #6
0
    def to_geojson(
        self,
        draw_points=False,
        write_to=None,
        linestring_props=None,
        multipoint_props=None,
    ):
        geometry = geojson.Feature(
            geometry=geojson.LineString(self.to_lng_lat_tuples()),
            properties=linestring_props,
        )
        features = geojson.FeatureCollection([geometry])

        if draw_points:
            points = geojson.Feature(
                geometry=geojson.MultiPoint([(p.lng, p.lat)
                                             for p in self.coords]),
                properties=multipoint_props,
            )
            features = geojson.FeatureCollection([geometry, points])

        if write_to:
            with open(write_to, "w") as f:
                f.write(geojson.dumps(features))
        else:
            return features
Exemple #7
0
def getpoiResult():
    data = json.loads(request.form['json'])
    rs = []
    for line in data:
        rs.append((line['lng'], line['lat']))
    with open('POI.geojson', 'wt') as f:
        f.write(json.dumps(geojson.MultiPoint(rs)))
    return send_file('POI.geojson', as_attachment=True)
Exemple #8
0
 def _make_multipoint(self, vehicle, coords):
     return geojson.Feature(
         geometry=geojson.MultiPoint(coords),
         properties={
             "lineId":
             vehicle,
             "marker-color":
             "#{}".format(self.gtfs.routes[vehicle]['route_color']),
         })
Exemple #9
0
def __to_geojson_point(s_geo: icp_model.Geometry):
    coordinates = []
    for point in s_geo.points:
        coordinates.append([point.x, point.y])
    if len(coordinates) == 1:
        geo = geojson.Point(coordinates=coordinates[0])
    else:
        geo = geojson.MultiPoint(coordinates=coordinates)
    return geo
Exemple #10
0
def create_feature(geometry,
                   geo_type,
                   val,
                   feature_id=None,
                   color=(255, 0, 0),
                   weight=10,
                   opacity=1.0,
                   props={}):
    """
    :param geometry: Geometry structure that creates geojson string.  Options are:
                     Point: (lng, lat) as tuple
                     MultiPoint: [Point, Point] as array of points
                     Line(string): [Point, Point, Point] as array of points
                     Multiline(string): [Line, Line] as array of lines
                     Polygon without holes: [Point1, Point, Point, Point1] as array of points,
                        first and last point in array are the same point (example makes a triangle).
                    Polygon with hole: [[Point1, Point, Point, Point1], [Point2, Point, Point, Point2]] as array of polygons,
                        second polygon is the hole.
                    Multipolygon: [Polygon, Polygon] as array of polygons (must confirm...?)
    :param geo_type: string indicating the geometry type, must match id strings from class geojson_geometry
    :param val: value to put into properties.value for mapping and style color matching
    :param feature_id: id for the geojson string
    :param color: a 3 value tuple containing an rgb value
    :param weight: for lines/polygons, line width; for points, point size
    :param opacity: opacity of layer in leaflet, 1.0 = 100%, 0 = 0%
    :returns: dictionary with geojson feature string and a leaflet style created from input parameters
    """

    try:
        if geo_type == GeojsonGeometry.point:
            geo = geojson.Point(geometry)
        elif geo_type == GeojsonGeometry.multipoint:
            geo = geojson.MultiPoint(geometry)
        elif geo_type == GeojsonGeometry.line:
            geo = geojson.LineString(geometry)
        elif geo_type == GeojsonGeometry.multiline:
            geo = geojson.MultiLineString(geometry)
        elif geo_type == GeojsonGeometry.polygon:
            geo = geojson.Polygon(geometry)
        elif geo_type == GeojsonGeometry.multipolygon:
            geo = geojson.MultiPolygon(geometry)
        else:
            print("Unsupported geometry type: " + geo_type)
            return
    except Exception as e:
        print(e, "\n probably wrong input data structure for " + geo_type)
        return

    style = None  # leaflet_style_creator()
    props['value'] = val
    geo = geojson.Feature(id=feature_id, geometry=geo, properties=props)

    ret = {'geojson': geo, 'style': style}

    return ret
Exemple #11
0
def main(src, dest, key="POP10"):
    """
    Open *src* with fiona
    Filter out features with no population
    Run points_in_feature on each feature
    Write each point as a new Point feature to *dest*
    """
    # crs = from_epsg(4326)
    # schema = {"geometry": "MultiPoint", "properties": {}}
    with fiona.open(src) as source, open(dest, "w") as sink:
        features = filter(lambda f: f["properties"][key] > 0, iter(source))
        for feature in features:
            points = points_in_feature(feature, key)
            multipoint = geojson.MultiPoint(map(list, points))
            f = geojson.Feature(geometry=multipoint)
            sink.write(geojson.dumps(f) + "\n")
Exemple #12
0
def make_geo_coll(vehicle_id, limit):
    docs = get_vehicle_positions(vehicle_id, limit)

    coords = []
    for d in docs:
        coords.append(tuple(d['location']['coordinates']))

    gc = gj.GeometryCollection([gj.LineString(coords), gj.MultiPoint(coords)])

    start = arrow.get(docs[0]['timestamp']).to('America/Chicago').isoformat()
    end = arrow.get(docs[-1]['timestamp']).to('America/Chicago').isoformat()
    fname = 'GC_{vid}@{start}<-->{end}.geojson'.format(vid=vehicle_id,
                                                       start=start,
                                                       end=end)
    with open(fname, 'w') as f:
        gj.dump(gc, f)
Exemple #13
0
def get_map_for_coordinates(coordinates):
    ACCESS_TOKEN = os.getenv("MAPBOX_ACCESS_TOKEN")
    USERNAME = os.getenv("MAPBOX_STYLE_USER")
    STYLE_ID = os.getenv("MAPBOX_STYLE_ID")
    service = StaticStyle()
    multipoint = geojson.MultiPoint(coordinates)
    feature = geojson.Feature(geometry=multipoint)
    print(feature)

    response = service.image(username=USERNAME,
                             style_id=STYLE_ID,
                             features=[feature],
                             width=1200,
                             height=1200,
                             retina=True)
    print(response.status_code)

    with open(args.directory + '/_map.png', 'wb') as output:
        _ = output.write(response.content)
def convert_json_data_to_geodataframe(json_data, spatial_reference='4326'):
    """Convert raw JSON objects from EDDM to a GeoDataFrame."""
    features = []

    for feature in json_data:
        new_feature = {}

        # Assume the feature is a LineString object.
        try:
            new_feature['geometry'] = shapely.geometry.shape(
                geojson.MultiLineString(feature['geometry']['paths']))
        # If the feature is not a LineString, maybe it is a MultiPoint.
        except KeyError:
            new_feature['geometry'] = shapely.geometry.shape(
                geojson.MultiPoint(feature['geometry']['points']))
        new_feature['properties'] = feature['attributes']
        features.append(new_feature)

    return gpd.GeoDataFrame.from_features(features, crs=spatial_reference)
Exemple #15
0
def dship2geojson(filename, data, lonkey, latkey, attributes=None):
    """ Writes a geojson file from a parsed dship dataset. Required a the key for latitude and longitude
    attributes: 'all',None
    """
    #data[s]['data'].append(ttmp)
    crs = {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    }  # Reference coordinate system
    nrecords = len(data[lonkey]['data'])
    if True:
        features = []
        points = []
        for i in range(nrecords):
            lon = data[lonkey]['data'][i]
            lat = data[latkey]['data'][i]
            p = geojson.Point((lon, lat))
            points.append((lon, lat))
            prop = {}
            for o in data.keys():
                dat = data[o]['data'][i]
                if (type(dat) == datetime.datetime):
                    dat = datetime.datetime.strftime(dat, '%Y-%m-%d %H:%M:%S')
                elif (np.isnan(dat)):
                    dat = -9999

                prop[o] = dat

            feature = geojson.Feature(geometry=p, properties=prop)
            features.append(feature)

        mpoints = geojson.MultiPoint(points, crs=crs)
        featurecol = geojson.FeatureCollection(features, name='dship', crs=crs)
        with open(filename, 'w') as outfile:
            if (attributes == None):
                geojson.dump(mpoints, outfile)
            elif (attributes == 'all'):
                geojson.dump(featurecol, outfile)

        outfile.close()
Exemple #16
0
    def export(cls, folder, h5_file):
        with tables.open_file(h5_file, mode="r") as h5:
            table = h5.root.trajectories.model_results
            particles = sorted(list(set([ x["particle"] for x in table.iterrows() ])))

            features = []
            for puid in particles:
                points = [ (x["time"], (x['longitude'], x['latitude'])) for x in table.where("""particle == %s""" % puid) if x["latitude"] and x["longitude"] ]

                geo_mp = geojson.MultiPoint( [ x[1] for x in points ] )
                times  = [ x[0] for x in points ]

                feat = geojson.Feature(geometry=geo_mp, id=puid, properties={ "particle" : puid, "time" : times })
                features.append(feat)

            fc = geojson.FeatureCollection(features)

            if not os.path.exists(folder):
                os.makedirs(folder)
            filepath = os.path.join(folder, "particle_multipoint.geojson")
            with open(filepath, "wb") as r:
                r.write(geojson.dumps(fc).encode('utf-8'))
Exemple #17
0
 def query(self):
     geo = f"{self.latlng[0]},{self.latlng[1]},20mi"
     query = self.api.search(q='*',
                             lang='en',
                             rpp=10,
                             count=20,
                             geocode=geo)
     for quer in query['statuses']:
         coord = {'screen_name': '', 'location': [], 'text': ''}
         coord['screen_name'] = quer['user']['screen_name']
         loc = geocoder.google(quer['user']['location'])
         loc = loc.latlng
         if loc == None:
             loc = self.latlng
         coord['location'].append(loc[0])
         coord['location'].append(loc[1])
         coord['text'] = (quer['text'])
         self.user_info.append(
             geojson.Feature(geometry=geojson.MultiPoint(coord['location']),
                             properties={
                                 'screen_name': coord['screen_name'],
                                 'message': coord['text']
                             }))
     return self.user_info
Exemple #18
0
def load_taxi_data(querystr):
    print 'AJAX load data: {0}'.format(querystr)
    data = None
    taxi_df = appdata['taxi_df']
    uber_df = appdata['uber_df']
    hotspots_df = appdata['hotspots_df']
    queryitems = {}

    for p_pair in querystr.split('&'):
        p_key, p_value = p_pair.split('=')
        queryitems[p_key] = p_value

# fix sampling rate for varius time duration
    sample_scale = 1
    if (queryitems['hour'] != 'all'): sample_scale = 24
    if (queryitems['weekday'] == 'weekday'): sample_scale *= (7 / 5.0)
    if (queryitems['weekday'] == 'weekend'): sample_scale *= (7 / 2.0)

    # sample the data
    uberslice = uber_df.sample(n=1250 * sample_scale)
    dataslice = taxi_df.sample(n=4500 * sample_scale)

    # slice the hotspots according to the density
    # used when day and time = all
    hotspotsslice_1 = hotspots_df[800 < hotspots_df['items']]
    hotspotsslice_2 = hotspots_df[400 < hotspots_df['items']]
    hotspotsslice_3 = hotspots_df[200 < hotspots_df['items']]
    hotspotsslice_4 = hotspots_df[100 < hotspots_df['items']]

    # slice the trip data according to distance selected
    dataslice = {
        'all': dataslice,
        'long': dataslice[dataslice.trip_distance > 1.90],
        'short': dataslice[dataslice.trip_distance <= 1.90]
    }[queryitems['tripdist']]

    # slice on driver income
    df_hf = appdata['hack_fare_df']
    hacks = {
        'all': set(df_hf['hack_license']),
        'low': set(df_hf[:10000]['hack_license']),
        'high': set(df_hf[-10000:]['hack_license'])
    }[queryitems['income']]
    print '{0} drivers selected'.format(len(hacks))
    dataslice = dataslice[dataslice.hack_license.isin(hacks)]

    # slice on day and time
    if ((queryitems['weekday'] != 'all') or (queryitems['hour'] != 'all')):
        # set filter values
        weekday_filter = {
            'weekday': [0, 1, 2, 3, 4],  # 0 - Monday, 6 - Sunday
            'weekend': [5, 6],
            'all': range(7)
        }[queryitems['weekday']]
        hotspot_dow_filter = {
            'weekday': [1],
            'weekend': [0],
            'all': [0, 1]
        }[queryitems['weekday']]
        time_filter = {
            '0000': [0, 1],
            '0200': [2, 3],
            '0400': [4, 5],
            '0600': [6, 7],
            '0800': [8, 9],
            '1000': [10, 11],
            '1200': [12, 13],
            '1400': [14, 15],
            '1600': [16, 17],
            '1800': [18, 19],
            '2000': [20, 21],
            '2200': [22, 23],
            'peak': [8, 9, 16, 17],
            'night': [20, 21, 22, 23],
            'late': [1, 2, 3, 4],
            'all': range(24)
        }[queryitems['hour']]
        # do the slicing for trip data
        dataslice = dataslice[dataslice.pickup_datetime.dt.dayofweek.isin(weekday_filter) &\
            dataslice.pickup_datetime.dt.hour.isin(time_filter)]
        uberslice = uberslice[uberslice['datetime'].dt.dayofweek.isin(weekday_filter) &\
            uberslice['datetime'].dt.hour.isin(time_filter)]
        # slicing for hotspot data
        hotspotsslice_1 = hotspots_df[hotspots_df['weekdays'].isin(hotspot_dow_filter) &\
            hotspots_df['hour'].isin(time_filter) & (300 <= hotspots_df['items'])]
        hotspotsslice_2 = hotspots_df[hotspots_df['weekdays'].isin(hotspot_dow_filter) &\
            hotspots_df['hour'].isin(time_filter) & (100 <= hotspots_df['items']) & (hotspots_df['items'] < 300)]
        hotspotsslice_3 = hotspots_df[hotspots_df['weekdays'].isin(hotspot_dow_filter) &\
            hotspots_df['hour'].isin(time_filter) & (30 <= hotspots_df['items']) & (hotspots_df['items'] < 100)]
        hotspotsslice_4 = hotspots_df[hotspots_df['weekdays'].isin(hotspot_dow_filter) &\
            hotspots_df['hour'].isin(time_filter) & (10 <= hotspots_df['items']) & (hotspots_df['items'] < 30)]

# debug uses - print the statistics on server side
    print dataslice.describe()
    print uberslice.describe()
    print hotspotsslice_1.describe()
    print hotspotsslice_2.describe()
    print hotspotsslice_3.describe()
    print hotspotsslice_4.describe()

    # prepare geojson data
    pickup_points = geojson.MultiPoint([(x, y) for x, y in zip(
        dataslice['pickup_longitude'], dataslice['pickup_latitude'])])
    dropoff_points = geojson.MultiPoint([(x, y) for x, y in zip(
        dataslice['dropoff_longitude'], dataslice['dropoff_latitude'])])
    uber_points = geojson.MultiPoint([
        (x, y) for x, y in zip(uberslice['longitude'], uberslice['latitude'])
    ])
    hotspots_1_points = geojson.MultiPoint([
        (x, y) for x, y in zip(hotspotsslice_1['lng'], hotspotsslice_1['lat'])
    ])
    hotspots_2_points = geojson.MultiPoint([
        (x, y) for x, y in zip(hotspotsslice_2['lng'], hotspotsslice_2['lat'])
    ])
    hotspots_3_points = geojson.MultiPoint([
        (x, y) for x, y in zip(hotspotsslice_3['lng'], hotspotsslice_3['lat'])
    ])
    hotspots_4_points = geojson.MultiPoint([
        (x, y) for x, y in zip(hotspotsslice_4['lng'], hotspotsslice_4['lat'])
    ])

    # pack geojson data as features
    pickup_feature = geojson.Feature(geometry=pickup_points, properties={\
        'status':'pickup',
        'radius':2.5,
        'color': '#ff7800'})
    dropoff_feature = geojson.Feature(geometry=dropoff_points, properties={\
        'status':'dropoff',
        'radius':2.5,
        'color': '#006799'})
    uber_feature = geojson.Feature(geometry=uber_points, properties={\
        'status':'uber',
        'radius':2.5,
        'color': '#449933'})
    hotspots_1_feature = geojson.Feature(geometry=hotspots_1_points, properties={\
        'status':'hotspots',
        'hotspots':1,
        'radius':25,
        'color': '#dc143c'})
    hotspots_2_feature = geojson.Feature(geometry=hotspots_2_points, properties={\
        'status':'hotspots',
        'hotspots':1,
        'radius':15,
        'color': '#dc143c'})
    hotspots_3_feature = geojson.Feature(geometry=hotspots_3_points, properties={\
        'status':'hotspots',
        'hotspots':1,
        'radius':8.5,
        'color': '#dc143c'})
    hotspots_4_feature = geojson.Feature(geometry=hotspots_4_points, properties={\
        'status':'hotspots',
        'hotspots':1,
        'radius':5,
        'color': '#dc143c'})

    # pack into geojson FeatureCollection and send to webpage
    data = geojson.FeatureCollection([pickup_feature, dropoff_feature, uber_feature,\
        hotspots_1_feature, hotspots_2_feature, hotspots_3_feature, hotspots_4_feature])
    return geojson.dumps(data)
def build_snapped_feature(way_id, snapped_points, indices):
    return geojson.Feature(geometry=geojson.MultiPoint(
        [snapped_points[i] for i in indices]),
                           properties={'way_id': way_id})
Exemple #20
0
    def test_not_sequence(self):
        with self.assertRaises(ValueError) as cm:
            geojson.MultiPoint([5], validate=True)

        self.assertIn('each position must be a list', str(cm.exception))
Exemple #21
0
 def test_valid_multipoint_with_elevation(self):
     mpoint = geojson.MultiPoint([(10, 20, 30), (30, 40, 50)])
     self.assertEqual(is_valid(mpoint)['valid'], YES)
Exemple #22
0
 def test_valid_multipoint(self):
     mpoint = geojson.MultiPoint([(10, 20), (30, 40)])
     self.assertEqual(is_valid(mpoint)['valid'], YES)
Exemple #23
0
 def test_invalid_multipoint(self):
     mpoint = geojson.MultiPoint([(3.5887, ), (3.5887, 10.44558),
                                  (2.5555, 3.887, 4.56),
                                  (2.44, 3.44, 2.555, 4.56)])
     self.assertEqual(is_valid(mpoint)['valid'], NO)
Exemple #24
0
    def test_not_number(self):
        with self.assertRaises(ValueError) as cm:
            geojson.MultiPoint([[1, '?']], validate=False)

        self.assertIn('is not a JSON compliant number', str(cm.exception))
Exemple #25
0
def e2feature(graph, e, e_id, transport, e2layout, mask=DEFAULT_LAYER2MASK[DEFAULT_LAYER]):
    root = graph.getRoot()
    layout = root[VIEW_LAYOUT]
    s, t = graph.source(e), graph.target(e)

    xy = lambda n: (layout[n].getX(), layout[n].getY())
    wh = lambda n: (root[VIEW_SIZE][n].getW() / 2, root[VIEW_SIZE][n].getH() / 2)
    e_lo = layout[e]
    while e_lo and xy(s) == [e_lo[0][0], e_lo[0][1]]:
        e_lo = e_lo[1:]
    while e_lo and xy(t) == [e_lo[-1][0], e_lo[-1][1]]:
        e_lo = e_lo[:-1]
    s_x, s_y = get_border_coord(xy(s), (e_lo[0][0], e_lo[0][1]) if e_lo else xy(t), wh(s), root[TYPE][s])
    t_x, t_y = get_border_coord(xy(t), (e_lo[-1][0], e_lo[-1][1]) if e_lo else xy(s), wh(t),
                                root[TYPE][t])
    while e_lo and [s_x, s_y] == [e_lo[0][0], e_lo[0][1]]:
        e_lo = e_lo[1:]
    while e_lo and [t_x, t_y] == [e_lo[-1][0], e_lo[-1][1]]:
        e_lo = e_lo[:-1]

    e2layout[e_id] = [[s_x, s_y]] + [[it[0], it[1]] for it in e_lo] + [[t_x, t_y]]
    geom = geojson.MultiPoint(e2layout[e_id])
    generalized = graph.isMetaNode(s) or graph.isMetaNode(t)

    real_e = e
    while root.isMetaEdge(real_e):
        real_e = next((ee for ee in root[VIEW_META_GRAPH][real_e] if not root[UBIQUITOUS][ee]),
                      next(iter(root[VIEW_META_GRAPH][real_e])))
    ubiquitous = root[UBIQUITOUS][real_e]
    color = triplet(root[VIEW_COLOR][real_e])
    props = {WIDTH: get_e_size(root, e).getW(), TYPE: TYPE_EDGE, STOICHIOMETRY: graph[STOICHIOMETRY][e],
             COLOR: get_edge_color(ubiquitous, generalized, transport, color), LAYER: mask}
    if not transport:
        props[COMPARTMENT_ID] = root[COMPARTMENT_ID][s]
    else:
        props[LAYER] |= TRANSPORT_MASK
    if ubiquitous:
        props[LAYER] |= UBIQUITOUS_MASK
    features = [geojson.Feature(id=e_id, geometry=geom, properties=props)]

    # Draw an arrow if it's a edge between a reaction and a product or between a reversible reaction and a reactant
    t_reaction = root.target(real_e) if TYPE_REACTION == root[TYPE][root.target(real_e)] else None
    s_reaction = root.source(real_e) if TYPE_REACTION == root[TYPE][root.source(real_e)] else None
    p_x, p_y = None, None
    st_x, st_y = None, None
    if t_reaction and root[REVERSIBLE][t_reaction]:
        p_x, p_y = s_x, s_y
        st_x, st_y = (e_lo[0][0], e_lo[0][1]) if e_lo else (t_x, t_y)
    elif s_reaction:
        p_x, p_y = t_x, t_y
        st_x, st_y = (e_lo[-1][0], e_lo[-1][1]) if e_lo else (s_x, s_y)
    if p_x is not None and p_y is not None:
        alpha = atan2(p_y - st_y, p_x - st_x)
        if not math.isnan(alpha):
            l = .4
            # point (l, 0)
            # rotate alpha +- beta
            # move p_x, p_y
            up_x_y = [p_x + l * cos(alpha + BETA_UP), p_y + l * sin(alpha + BETA_UP)]
            down_x_y = [p_x + l * cos(alpha + BETA_DOWN), p_y + l * sin(alpha + BETA_DOWN)]
            arrow_up = geojson.Feature(id=e_id + "_up",
                                         geometry=geojson.MultiPoint([[p_x, p_y], up_x_y]),
                                         properties=props.copy())
            arrow_down = geojson.Feature(id=e_id + "_down",
                                         geometry=geojson.MultiPoint([[p_x, p_y], down_x_y]),
                                         properties=props.copy())
            features.append(arrow_down)
            features.append(arrow_up)
    return features
Exemple #26
0
def build_and_save_GeoJson(routes, routesNodesIds, nodesTab, fileName):
    flipLocationsRoutes = []
    flipLocationSegments = []
    routesNodesLocation = []
    routeNodesLocation = []
    i = 1

    for segments in routes:
        for segment in segments:
            flipLocationSegments.append([(sub[1], sub[0]) for sub in segment])
        flipLocationsRoutes.append(flipLocationSegments)
        flipLocationSegments = []

    features = []
    for flipLocations in flipLocationsRoutes:

        flipLocations = gjson.MultiLineString(flipLocations)
        features.append(gjson.Feature(geometry=flipLocations))
        geoJson = gjson.FeatureCollection(features)
        with open(fileName + str(i) + ".geojson", 'w') as f:
            gjson.dump(geoJson, f)
        i = i + 1
        features = []

    for route in routesNodesIds:
        for nodeId in route:
            for i in range(len(nodesTab.tab)):
                if nodesTab.tab[i].id == nodeId:
                    index = i
            routeNodesLocation.append(
                (nodesTab.tab[index].lon, nodesTab.tab[index].lat))
        routesNodesLocation.append(routeNodesLocation)
        routeNodesLocation = []

    depot = []
    i = 1
    for nodesLocation in routesNodesLocation:
        if (nodesLocation[0] not in depot):
            depot.append(nodesLocation.pop(0))
            nodesLocation.pop(-1)
        else:
            nodesLocation.pop(-1)
            nodesLocation.pop(0)

        index = 1
        with open(fileName + "_route_" + str(i) + "_points.csv",
                  mode='w') as myFile:
            csv_writer = csv.writer(myFile,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)

            csv_writer.writerow(["lon", "lat", "id"])
            for node in nodesLocation:
                csv_writer.writerow(
                    [node[0], node[1], routesNodesIds[i - 1][index]])
                index = index + 1
        i = i + 1
        geojsonPoints = gjson.MultiPoint(nodesLocation)
        features.append(gjson.Feature(geometry=geojsonPoints))

    geoJson = gjson.FeatureCollection(features)
    with open(fileName + "_points.geojson", 'w') as f:
        gjson.dump(geoJson, f)

    features = []
    depotGeojsonPoints = gjson.MultiPoint(depot)
    features.append(gjson.Feature(geometry=depotGeojsonPoints))
    geoJson = gjson.FeatureCollection(features)
    with open(fileName + "_depot.geojson", 'w') as f:
        gjson.dump(geoJson, f)
 def test_valid_multipoint(self):
     mpoint = geojson.MultiPoint([(10, 20), (30, 40)])
     self.assertEqual(mpoint.is_valid, True)
Exemple #28
0
                        [100.0, 1.0],
                        [100.0, 0.0],
                    ],
                    [
                        [100.8, 0.8],
                        [100.8, 0.2],
                        [100.2, 0.2],
                        [100.2, 0.8],
                        [100.8, 0.8],
                    ],
                ]
            )
        )


_multipoint = geojson.MultiPoint([[100.0, 0.0], [101.0, 1.0]])


def test_MultiPoint_valid():
    roax.geo.MultiPoint().validate(_multipoint)


def test_MultiPoint_str_bin():
    _test_str_bin(roax.geo.MultiPoint(), _multipoint)


_multilinestring = geojson.MultiLineString(
    [[[100.0, 0.0], [101.0, 1.0]], [[102.0, 2.0], [103.0, 3.0]]]
)

Exemple #29
0
db.row_factory = sqlite3.Row
cur = db.cursor()
cur2 = db.cursor()
cur3 = db.cursor()

features = []
cur.execute("select route_id from route")
for i in cur:
    cur2.execute("select route_seq from route_path where route_id = '" +
                 str(i[0]) + "'")
    rowresult = cur2.fetchone()
    if rowresult is None: continue
    obj_feature = geojson.Feature()
    obj_feature.properties['title'] = str(i[0])
    #obj_feature.properties['icon'] = 'crosshair'
    obj_point = geojson.MultiPoint()
    obj_point.coordinates = []
    for k in rowresult[0].split(','):
        cur3.execute("select stop_lat, stop_lon from stop where stop_id = " +
                     k)
        stoploc = cur3.fetchone()
        if stoploc is None: stoploc = [0, 0]
        obj_point.coordinates.append((stoploc[1], stoploc[0]))
    obj_feature.geometry = obj_point
    features.append(obj_feature)
obj_featurecollection = geojson.FeatureCollection(features)

cur.close()
cur2.close()
cur3.close()
db.close()
Exemple #30
0
# Polygons
geo_polygon = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28),
                                (-120.43, 19.15), (2.38, 57.322)]])
wkt_polygon = 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))'

# Polygons with holes
geo_polygon_with_hole = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28),
                                          (-120.43, 19.15), (2.38, 57.322)],
                                         [(-5.21, 23.51), (15.21, -10.81),
                                          (-20.51, 1.51), (-5.21, 23.51)]])
wkt_polygon_with_hole = ('POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10),'
                         ' (20 30, 35 35, 30 20, 20 30))')

# MultiPoints
geo_multipoint = geojson.MultiPoint([(-155.52, 19.61), (-156.22, 20.74),
                                     (-157.97, 21.46)])
wkt_multipoint = 'MULTIPOINT (10 40, 40 30, 20 20, 30 10)'
wkt_multipoint_alternate = 'MULTIPOINT ((10 40), (40 30), (20 20), (30 10))'

# MultiLineStrings
geo_multilinestring = geojson.MultiLineString([[(3.75, 9.25), (-130.95, 1.52)],
                                               [(23.15, -34.25),
                                                (-1.35, -4.65),
                                                (3.45, 77.95)]])
wkt_multilinestring = ('MULTILINESTRING ((10 10, 20 20, 10 40),'
                       ' (40 40, 30 30, 40 20, 30 10))')

# MultiPolygons
geo_multipolygon = geojson.MultiPolygon([[([(30, 20), (45, 40), (10, 40),
                                            (30, 20)]),
                                          ([(15, 5), (40, 10), (10, 20),