示例#1
0
def contains(x1, y1, x2, y2, radius, origin1=WGS84, origin2=WGS84, destination=PA_SP_SOUTH):
    '''
    :param x: x coordinate or longitude
    :param y: y coordiante or latitude
    :param radius: radius in miles
    :param projection:
    :return:
    '''
    # project input x1,y1 to PA state plane
    try:
        x, y = pyproj.transform(pyproj.Proj(origin1),
                                pyproj.Proj(destination, preserve_units=True),
                                x1, y1)
        # get circle from first input
        p = Point(x, y)
        circle = p.buffer(radius * MILES)

        # project x2, y2 to same plane
        x, y = pyproj.transform(pyproj.Proj(origin2),
                                pyproj.Proj(destination, preserve_units=True),
                                x2, y2)
        p = Point(x, y)
        return circle.contains(p)
    except:
        return False
示例#2
0
def circle_sensor(SensorName, Sensor_coord, r=1):
    """
    SensorName : nom du(des) sensor(s) souhaité(s), Sensor_coord : résultat de la fonction reading_gps_file
    r : rayon en metre, 1.00 m par défaut
    Output : 
    list_coord_circle = list des coordonnes des extremites de chaque cercle
    Shape_to_json     = list Proprietes geometriques de chaque cercle
    circle_name       = list de noms des sensors
    
    """
    list_coord_circle = []
    Shape_to_json = []
    circle_name = []

    for SensorName in SensorName:
        sensor_GPS = Sensor_coord.loc[Sensor_coord['SensorName'] == str(
            SensorName)]
        center = Point(sensor_GPS["x"], sensor_GPS["y"])  # point central
        circle = center.buffer(r)
        x_circle, y_circle = circle.exterior.xy  #Val de chaque extremitees du cercle
        list_coord_circle.append([np.array(x_circle), np.array(y_circle)])

        # Transfo des donnees en Geoseries :
        #Json -> https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
        # Format qui contient toutes les proprietes + points ext du cercle
        Shape_to_json.append(gpd.GeoSeries([circle]).to_json())
        circle_name.append(sensor_GPS['SensorName'])

    return list_coord_circle, Shape_to_json, circle_name
示例#3
0
 def test_get_intersects_select_nearest(self):
     pt = Point(-99, 39)
     return_indices = [True, False]
     use_spatial_index = [True, False]
     select_nearest = [True, False]
     abstraction = ['polygon', 'point']
     bounds = [True, False]
     for args in itertools.product(return_indices, use_spatial_index, select_nearest, abstraction, bounds):
         ri, usi, sn, a, b = args
         sdim = self.get_sdim(bounds=b)
         sdim.abstraction = a
         ret = sdim.get_intersects(pt.buffer(1), select_nearest=sn, return_indices=ri)
         ## return_indice will return a tuple if True
         if ri:
             ret, ret_slc = ret
         if sn:
             ## select_nearest=True always returns a single element
             self.assertEqual(ret.shape, (1, 1))
             try:
                 self.assertTrue(ret.geom.polygon.value[0,0].centroid.almost_equals(pt))
             ## polygons will not be present if the abstraction is point or there are no bounds on the created
             ## spatial dimension object
             except ImproperPolygonBoundsError:
                 if a == 'point' or b is False:
                     self.assertTrue(ret.geom.point.value[0, 0].almost_equals(pt))
                 else:
                     raise
         ## if we are not returning the nearest geometry...
         else:
             ## bounds with a spatial abstraction of polygon will have this dimension
             if b and a == 'polygon':
                 self.assertEqual(ret.shape, (3, 3))
             ## with points, there is only intersecting geometry
             else:
                 self.assertEqual(ret.shape, (1, 1))
示例#4
0
def gen_poly3(x1, x2, x3, y1, y2, y3):  # roundabout
    poly1 = Polygon(
        ((0, 0), (0, (y1 + y2 + y3) / 2 - y2), ((x1 + x2 + x3) / 2 - y2 * 3,
                                                (y1 + y2 + y3) / 2 - y2),
         ((x1 + x2 + x3) / 2 - x2,
          (y1 + y2 + y3) / 2 - y2 * 3), ((x1 + x2 + x3) / 2 - x2, 0)))
    poly2 = Polygon(((0, (y1 + y2 + y3) / 2 + y2), (0, y1 + y2 + y3),
                     ((x1 + x2 + x3) / 2 - x2, y1 + y2 + y3),
                     ((x1 + x2 + x3) / 2 - x2, (y1 + y2 + y3) / 2 + y2 * 3),
                     ((x1 + x2 + x3) / 2 - y2 * 3, (y1 + y2 + y3) / 2 + y2)))
    poly3 = Polygon(
        (((x1 + x2 + x3) / 2 + x2, 0), ((x1 + x2 + x3) / 2 + x2,
                                        (y1 + y2 + y3) / 2 - y2 * 3),
         ((x1 + x2 + x3) / 2 + y2 * 3, (y1 + y2 + y3) / 2 - y2),
         (x1 + x2 + x3, (y1 + y2 + y3) / 2 - y2), (x1 + x2 + x3, 0)))
    poly4 = Polygon(
        (((x1 + x2 + x3) / 2 + y2 * 3, (y1 + y2 + y3) / 2 + y2),
         ((x1 + x2 + x3) / 2 + x2, (y1 + y2 + y3) / 2 + y2 * 3),
         ((x1 + x2 + x3) / 2 + x2, y1 + y2 + y3), (x1 + x2 + x3, y1 + y2 + y3),
         (x1 + x2 + x3, (y1 + y2 + y3) / 2 + y2)))
    p = Point((x1 + x2 + x3) / 2, (y1 + y2 + y3) / 2)
    circle = p.buffer(y2)
    polyc = list(circle.exterior.coords)
    poly5 = Polygon(polyc)
    polys = [poly1, poly2, poly3, poly4, poly5]
    return gp.GeoDataFrame(geometry=polys)
示例#5
0
def create_base_stations_points(centers, radius):
    Bx = []
    for center in centers:
        point = Point(center[0], center[1])
        circle = point.buffer(radius)
        Bx.append(circle)

    return Bx
def draw_xg_circle (fig, ax, distance_x,distance_y,radius,color, e_color):
    p = Point(distance_x,distance_y)
    circle = p.buffer(radius)
    x,y = circle.exterior.xy
    x = np.array(x) / 1.05
    y = np.array(y) / 0.6
    ax.fill(x, y, alpha=0.5, fc=color, ec=e_color)
    return
示例#7
0
def calculate_fitness(worm, radius, city):

    circles = []
    for center in worm:
        point = Point(center[0], center[1])
        circles.append(point.buffer(radius))

    base_stations_polygon = cascaded_union(circles)
    intersection_area = base_stations_polygon.intersection(city).area
    return base_stations_polygon.intersection(city).area / city.area
def test_halve_line(line):
    """There should be
    - two lines returned
    - they should be of equal length
    - The last point in the first half should match the first point in the second half
    - The midpoint should intersect the original line
    """
    halves = split_line(line)

    assert len(halves) == 2
    assert np.allclose(halves[0].length, halves[1].length)

    midpoint = Point(halves[0].coords[-1])
    assert midpoint == Point(halves[1].coords[0])
    assert midpoint.buffer(.00000001).intersects(line)
示例#9
0
def buffer(input_args):

    #Casting to float
    lat = float(input_args["lat"])
    lon = float(input_args["lon"])
    range = float(input_args["range"])

    p = Point(lon, lat)

    buffer = p.buffer(1.0)
    feature = Feature(buffer, properties={'buffer_extent': '1'})
    json_response = dumps(feature, indent=2)
    resp = make_response(json_response, 200)

    resp.mimetype = "application/vnd.geo+json"  # So that browser knows what is the content type

    return resp
def count_xg_coef(polygon, direction, play):
    area = 0
    if direction[play] == 'True':
        p_1 = Point(94.5, 30)
        circle_1 = p_1.buffer(11.0)
        p_2 = Point(97.5, 30)
        circle_2 = p_2.buffer(8)
        p_3 = Point(100.5, 30)
        circle_3 = p_3.buffer(4.8)
    else:
        p_1 = Point(10.5, 30)
        circle_1 = p_1.buffer(11.0)
        p_2 = Point(7.5, 30)
        circle_2 = p_2.buffer(8)
        p_3 = Point(4.5, 30)
        circle_3 = p_3.buffer(4.8)
    if polygon.intersection(circle_3).area > 0:
        area += polygon.intersection(circle_3).area * 3
    if polygon.intersection(circle_2).area > 0: 
        area += polygon.intersection(circle_2).area * 2
    if polygon.intersection(circle_1).area > 0: 
        area += polygon.intersection(circle_1).area 
    return area
示例#11
0
 def simple_polygon(self):
     pt = Point(200, 0.0)
     return (pt.buffer(8, 1))
示例#12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Necessary pip install: shapely and shapely_geojson
#sudo pip install shapely shapely_geojson
#sudo pip install git+https://github.com/alekzvik/shapely-geojson

from shapely.geometry.point import Point
from shapely_geojson import dumps, Feature
p = Point(-8.2918, 41.4425)  # (lon,lat) 41.4425° N, 8.2918° W

buffer = p.buffer(1.0)
feature = Feature(buffer, properties={'buffer_extent': '1'})
f1 = open("./data/guimaraes_buffer.geojson", "w")
f1.write(dumps(feature, indent=2))
示例#13
0
 def simple_polygon(self):
     pt = Point(200,0.0)
     return(pt.buffer(8,1))
示例#14
0
import shapely
import matplotlib.pyplot as plt
from shapely.geometry.point import Point
from shapely.geometry import box
from shapely.geometry import Polygon
import math

pnt = Point(24, 34)
c1 = pnt.buffer(45)
x, y = c1.exterior.coords.xy

pnt1 = Point(35, 35)
c2 = pnt1.buffer(35)
x, y = c2.exterior.coords.xy

c3 = c1.difference(c2)
x, y = c3.exterior.coords.xy
plt.fill(x, y, color='r')

f = Polygon([(25, 40), (45, 31), (63, 40)])
x, y = f.exterior.coords.xy
plt.fill(x, y, color='r', linewidth=2.1)
y = Polygon([(45, 50), (37, 35), (56, 25)])
x, y = y.exterior.coords.xy
plt.fill(x, y, color='r', linewidth=2.1)
y3 = Polygon([(32, 25), (37, 35), (45, 31)])
x, y = y3.exterior.coords.xy
plt.fill(x, y, color='r', linewidth=2.1)

plt.show()
示例#15
0
import shapely
import matplotlib.pyplot as plt
from shapely.geometry.point import Point
from shapely.geometry import box
import random
import math

pnt = Point(10, 10)
c1 = pnt.buffer(20)
x, y = c1.exterior.coords.xy
#plt.fill(x,y, edgecolor='black', linewidth=0.5)

pnt1 = Point(30, 30)
c2 = pnt1.buffer(35)
x, y = c2.exterior.coords.xy
#plt.fill(x,y, edgecolor='black', linewidth=0.5)

#c3=c1.intersection(c2);
#x,y=c3.exterior.coords.xy;
#plt.fill(x,y, edgecolor='black', linewidth=0.5)

#c3=c1.union(c2);
#x,y=c3.exterior.coords.xy;
#plt.fill(x,y, edgecolor='black', linewidth=0.5)

c3 = c1.difference(c2)
x, y = c3.exterior.coords.xy
plt.fill(x, y, edgecolor='black', linewidth=0.5)

plt.show()
示例#16
0
import shapely
import matplotlib.pyplot as plt
from shapely.geometry.point import Point
from shapely.geometry import box
import random
import math

pnt = Point(5, 9)
c1 = pnt.buffer(20)
plt.figure()
x, y = c1.exterior.coords.xy
plt.plot(x, y)
plt.show()
示例#17
0
import shapely
import matplotlib.pyplot as plt
from shapely.geometry.point import Point
from shapely.geometry import LineString
from shapely.geometry import box
from shapely.geometry import Polygon
import random
import math

plt.figure()

pnt1 = Point(20, 27)
c2 = pnt1.buffer(20)
x, y = c2.exterior.coords.xy
plt.fill(x, y, color='yellow', edgecolor='black', linewidth=5)

pnt = Point(20, 27)
c1 = pnt.buffer(7, 5)
x, y = c1.exterior.coords.xy
plt.fill(x, y, edgecolor='white', color='blue', linewidth=5)

l = LineString([(5, 40), (13, 26)])
x, y = l.coords.xy
plt.plot(x, y, marker='o')

l2 = LineString([(25, 22), (21, 7)])
x, y = l2.coords.xy
plt.plot(x, y, marker='o')

l1 = LineString([(23, 34), (37, 37)])
x, y = l1.coords.xy
示例#18
0
import shapely
import matplotlib.pyplot as plt
from shapely.geometry.point import Point
from shapely.geometry import box
import random
import math

plt.figure()
for i in range(0, 500):
    a = random.uniform(0, 1000)
    b = random.uniform(0, 1000)
    d = random.uniform(0, 100)

    pnt = Point(a, b)
    c1 = pnt.buffer(d)
    x, y = c1.exterior.coords.xy
    plt.fill(x, y, edgecolor='black', linewidth=0.5)
plt.show()
示例#19
0
import math
from shapely import geometry
from shapely.geometry.point import Point
# Center of the Donmuang airport
p = Point(13.912189, 100.605319)
# Radius for 4 NM from center
circle = p.buffer(0.068176)
list_point = circle.exterior.coords


def process_by_line(config, flight_info, content):
    if flight_info["direction"]["direction"] == "arrival":
        if "Aerodrome" not in flight_info:
            # first time
            flight_info["Aerodrome"] = {"Aerodrome_dict": {}}
        latitude = content['position']['lat']
        longitude = content['position']['lon']
        t1 = geometry.Point(latitude, longitude)
        Aerodrome_dict = flight_info["Aerodrome"]["Aerodrome_dict"]

        if "not_Aerodrome" not in Aerodrome_dict and not circle.intersects(t1):
            # if not circle.intersects(t1):
            Aerodrome_dict["not_Aerodrome"] = {
                "time_out": content["data_time"],
                "lat_out": content['position']['lat'],
                "lon_out": content['position']['lon']
            }

        elif not circle.intersects(t1):
            # if not circle.intersects(t1):
            Aerodrome_dict["not_Aerodrome"] = {
示例#20
0
def poc_polar(hotspot, chals):

    H = Hotspots()
    haddr = hotspot['address']
    hlat, hlng = hotspot['lat'], hotspot['lng']
    hname = hotspot['name']

    if os.path.exists(hname):
        files = glob(hname + '\\*')
        for file in files:
            os.remove(file)
    else:
        os.mkdir(hname)

    wl = {}  #witnesslist
    rl = {
    }  #received list of hotspots(hotspot of intereset has been witness to these or received from them)
    c = 299792458

    for chal in chals:  # loop through challenges

        for p in chal['path']:  #path?

            if p['challengee'] == haddr:  # handles cases where hotspot of interest is transmitting
                for w in p[
                        'witnesses']:  #loop through witnesses so we can get rssi at each location challenge received
                    #print('witness',w)
                    lat = H.get_hotspot_by_addr(w['gateway'])['lat']
                    lng = H.get_hotspot_by_addr(w['gateway'])['lng']
                    name = H.get_hotspot_by_addr(w['gateway'])['name']
                    dist_km, heading = utils.haversine_km(hlat,
                                                          hlng,
                                                          lat,
                                                          lng,
                                                          return_heading=True)

                    fspl = 20 * log10((dist_km + 0.01) * 1000) + 20 * log10(
                        915000000) + 20 * log10(4 * pi / c) - 27

                    try:
                        wl[w['gateway']]['lat'] = lat
                        wl[w['gateway']]['lng'] = lng
                        wl[w['gateway']]['rssi'].append(w['signal'])
                    except KeyError:
                        wl[w['gateway']] = {
                            'rssi': [
                                w['signal'],
                            ],
                            'dist_km': dist_km,
                            'heading': heading,
                            'fspl': fspl,
                            'lat': lat,
                            'lng': lng,
                            'name': name
                        }
            else:  # hotspot of interest is not transmitting but may be a witness
                challengee = p['challengee']
                name = H.get_hotspot_by_addr(challengee)['name']
                for w in p['witnesses']:
                    if w['gateway'] != haddr:
                        continue
                    #print('transmitter ', name)
                    #print('witness ', H.get_hotspot_by_addr(w['gateway'])['name']) # hotspot of interest was a witness

                    lat = H.get_hotspot_by_addr(challengee)['lat']
                    lng = H.get_hotspot_by_addr(challengee)['lng']
                    #name=H.get_hotspot_by_addr(w['gateway'])['name']
                    dist_km, heading = utils.haversine_km(hlat,
                                                          hlng,
                                                          lat,
                                                          lng,
                                                          return_heading=True)

                    fspl = 20 * log10((dist_km + 0.01) * 1000) + 20 * log10(
                        915000000) + 20 * log10(4 * pi / c) - 27

                    try:
                        rl[challengee]['lat'] = lat
                        rl[challengee]['lng'] = lng
                        rl[challengee]['rssi'].append(w['signal'])
                    except KeyError:
                        rl[challengee] = {
                            'rssi': [
                                w['signal'],
                            ],
                            'dist_km': dist_km,
                            'heading': heading,
                            'fspl': fspl,
                            'lat': lat,
                            'lng': lng,
                            'name': name
                        }

    #print('rl:',rl)
    ratios = [1.0] * 16
    rratios = [1.0] * 16
    N = len(ratios) - 1
    angles = []
    rangles = []
    #angles = [n / float(N) *2 *pi for n in range(N+1)]
    angles = list(np.arange(0.0, 2 * np.pi + (2 * np.pi / N), 2 * np.pi / N))
    rangles = list(np.arange(0.0, 2 * np.pi + (2 * np.pi / N), 2 * np.pi / N))
    #print(angles,len(angles))
    #print(ratios,len(ratios))

    markers = []
    encoded = {}
    rencoded = {}
    for w in wl:  #for witness in witnesslist
        #print(wl[w])
        mean_rssi = sum(wl[w]['rssi']) / len(wl[w]['rssi'])
        ratio = wl[w]['fspl'] / mean_rssi * (-1)
        if ratio > 3.0:
            ratio = 3.0
        elif ratio < -3.0:
            ratio = -3.0
        ratios.append(ratio)
        angles.append(wl[w]['heading'] * pi / 180)

        #markers.append(folium.Marker([wl[w]['lat'],wl[w]['lng']],popup=wl[w]['name']))
        markers.append([[wl[w]['lat'], wl[w]['lng']], wl[w]['name']])

        # the histogram of the data
        #unique=set(wl[w]['rssi'])
        #num_unique=len(unique)

        n, bins, patches = plt.hist(
            wl[w]['rssi'], 10)  #, density=True, facecolor='g', alpha=0.75,)
        plt.xlabel('RSSI(dB)')
        plt.ylabel('Count(Number of Packets)')
        wit = str(wl[w]['name'])
        plt.title('Packets from ' + hname + ' measured at ' + wit)
        #plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
        #plt.xlim(40, 160)
        #plt.ylim(0, 0.03)
        plt.grid(True)
        #plt.show()
        strFile = str(wl[w]['name']) + '.jpg'
        strWitness = str(wl[w]['name'])

        if os.path.isfile(strFile):
            #print('remove')
            os.remove(strFile)  # Opt.: os.system("rm "+strFile)
        plt.savefig(hname + '//' + strFile)
        encoded[strWitness] = base64.b64encode(
            open(hname + '//' + strFile, 'rb').read())
        plt.close()

    for w in rl:  #for witness in witnesslist
        #print(rl[w])
        mean_rssi = sum(rl[w]['rssi']) / len(rl[w]['rssi'])
        rratio = rl[w]['fspl'] / mean_rssi * (-1)
        if rratio > 3.0:
            rratio = 3.0
        elif rratio < -3.0:
            rratio = -3.0
        rratios.append(rratio)
        rangles.append(rl[w]['heading'] * pi / 180)

        #markers.append([[wl[w]['lat'],wl[w]['lng']],wl[w]['name']])

        n, bins, patches = plt.hist(
            rl[w]['rssi'], 10)  #, density=True, facecolor='g', alpha=0.75,)
        plt.xlabel('RSSI(dB)')
        plt.ylabel('Count(Number of Packets)')
        wit = str(rl[w]['name'])
        plt.title('Packets from ' + wit + ' measured at ' + hname)

        plt.grid(True)
        #plt.show()
        strFile = 'rrr' + str(rl[w]['name']) + '.jpg'
        strWitness = str(rl[w]['name'])

        if os.path.isfile(strFile):
            #print('remove')
            os.remove(strFile)  # Opt.: os.system("rm "+strFile)
        plt.savefig(hname + '//' + strFile)
        rencoded[strWitness] = base64.b64encode(
            open(hname + '//' + strFile, 'rb').read())
        plt.close()

    # create polar chart
    angles, ratios = zip(*sorted(zip(angles, ratios)))
    rangles, rratios = zip(*sorted(zip(rangles, rratios)))
    angles, ratios = (list(t) for t in zip(*sorted(zip(angles, ratios))))
    rangles, rratios = (list(t) for t in zip(*sorted(zip(rangles, rratios))))

    fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    #ax.set_rmax(3)
    #ax.set_rmin(-3)
    ax.set_ylim(-3, 3)
    ax.plot(angles,
            ratios,
            marker='^',
            linestyle='solid',
            color='tomato',
            linewidth=2,
            markersize=5,
            label='Transmitting')  #markerfacecolor='m', markeredgecolor='k',
    ax.plot(rangles,
            rratios,
            marker='v',
            linestyle='solid',
            color='dodgerblue',
            linewidth=1,
            markersize=5,
            label='Receiving')  #, markerfacecolor='m', markeredgecolor='k'
    ax.legend(bbox_to_anchor=(0, 1),
              fancybox=True,
              framealpha=0,
              loc="lower left",
              facecolor='#000000')
    plt.xlabel('FSPL/RSSI')

    plt.savefig(hname + '//' + hname + '.png', transparent=True)
    #plt.show()

    # add polar chart as a custom icon in map
    m = folium.Map([hlat, hlng],
                   tiles='stamentoner',
                   zoom_start=18,
                   control_scale=True,
                   max_zoom=20)
    polargroup = folium.FeatureGroup(name='Polar Plot')

    icon = folium.features.CustomIcon(icon_image=hname + '//' +
                                      hotspot['name'] + '.png',
                                      icon_size=(640, 480))
    marker = folium.Marker([hlat, hlng], popup=hotspot['name'], icon=icon)
    polargroup.add_child(marker)

    # add witness markers
    hsgroup = folium.FeatureGroup(name='Witnesses')
    hsgroup.add_child(folium.Marker([hlat, hlng], popup=hotspot['name']))
    # add the witness markers
    for marker in markers:
        #html = '<img src="data:image/jpg;base64,{}">'.format
        html = '<p><img src="data:image/jpg;base64,{}" alt="" width=640 height=480 /></p> \
               <p><img src="data:image/jpg;base64,{}" alt="" width=640 height=480 /></p>'.format

        #print('marker',marker)
        try:
            iframe = IFrame(html(encoded[marker[1]].decode('UTF-8'),
                                 rencoded[marker[1]].decode('UTF-8')),
                            width=640 + 25,
                            height=960 + 40)
            popup = folium.Popup(iframe, max_width=2650)
            mark = folium.Marker(marker[0], popup=popup)
            hsgroup.add_child(mark)
        except KeyError:  # this means this witness never heard from us so there is no marker for it
            pass  # not sure where to put the receive packet histogram so just ignore for now

    radius = 0.01
    center = Point(hlat, hlng)
    circle = center.buffer(radius)  # Degrees Radius
    gjcircle = shapely.geometry.mapping(circle)
    circle = center.buffer(radius * 25)  # Degrees Radius
    gjcircle8 = shapely.geometry.mapping(circle)

    dcgroup = folium.FeatureGroup(name='Distance Circles', show=False)
    radius = 0.01
    center = Point(hlat, hlng)
    circle = center.buffer(radius)  # Degrees Radius
    gjcircle = shapely.geometry.mapping(circle)
    circle = gjcircle['coordinates'][0]
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=300,
                              popup='300m',
                              tooltip='300m')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=1000,
                              popup='1km',
                              tooltip='1km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=2000,
                              popup='2km',
                              tooltip='2km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=3000,
                              name='circles',
                              popup='3km',
                              tooltip='3km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=4000,
                              popup='4km',
                              tooltip='4km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=5000,
                              popup='5km',
                              tooltip='5km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=10000,
                              popup='10km',
                              tooltip='10km')
    dcgroup.add_child(my_Circle)

    h3colorgroup = folium.FeatureGroup(name='h3 Hexagon Grid Color Fill',
                                       show=False)
    style = {'fillColor': '#f5f5f5', 'lineColor': '#ffffbf'}
    #polygon = folium.GeoJson(gjson, style_function = lambda x: style).add_to(m)

    h3group = folium.FeatureGroup(name='h3 r11 Hex Grid', show=False)
    h3namegroup = folium.FeatureGroup(name='h3 r11 Hex Grid Names', show=False)
    h3fillgroup = folium.FeatureGroup(name='h3 r11 Hex Grid Color Fill',
                                      show=True)
    h3r8namegroup = folium.FeatureGroup(name='h3 r8 Hex Grid Names',
                                        show=False)
    h3r8group = folium.FeatureGroup(name='h3 r8 Hex Grid', show=False)
    hexagons = list(h3.polyfill(gjcircle, 11))
    hexagons8 = list(h3.polyfill(gjcircle8, 8))
    polylines = []

    lat = []
    lng = []
    i = 0
    #print('hexagon',hexagons[0])
    #print(dir(h3))
    home_hex = h3.geo_to_h3(hlat, hlng, 11)
    a = h3.k_ring(home_hex, 7)
    for h in a:
        gjhex = h3.h3_to_geo_boundary(h, geo_json=True)
        gjhex = geometry.Polygon(gjhex)
        mean_rsrp = -60
        folium.GeoJson(
            gjhex,
            style_function=lambda x, mean_rsrp=mean_rsrp: {
                'fillColor': map_color_rsrp(mean_rsrp),
                'color': map_color_rsrp(mean_rsrp),
                'weight': 1,
                'fillOpacity': 0.5
            },
            #tooltip='tooltip'
        ).add_to(h3fillgroup)

    for hex in hexagons:
        p2 = h3.h3_to_geo(hex)
        #p2 = [45.3311, -121.7113]
        folium.Marker(
            p2,
            name='hex_names',
            icon=DivIcon(
                #icon_size=(150,36),
                #icon_anchor=(35,-45),
                icon_anchor=(35, 0),
                html='<div style="font-size: 6pt; color : black">' + str(hex) +
                '</div>',
            )).add_to(h3namegroup)
        #m.add_child(folium.CircleMarker(p2, radius=15))

        polygons = h3.h3_set_to_multi_polygon([hex], geo_json=False)
        # flatten polygons into loops.
        outlines = [loop for polygon in polygons for loop in polygon]
        polyline = [outline + [outline[0]] for outline in outlines][0]
        lat.extend(map(lambda v: v[0], polyline))
        lng.extend(map(lambda v: v[1], polyline))
        polylines.append(polyline)

    for polyline in polylines:
        my_PolyLine = folium.PolyLine(locations=polyline,
                                      weight=1,
                                      color='blue')
        h3group.add_child(my_PolyLine)

    polylines = []

    lat = []
    lng = []
    #polylines8 = []
    for hex in hexagons8:
        p2 = h3.h3_to_geo(hex)
        folium.Marker(
            p2,
            name='hex_names',
            icon=DivIcon(
                #icon_size=(150,36),
                #icon_anchor=(35,-45),
                icon_anchor=(35, 0),
                html='<div style="font-size: 8pt; color : black">' + str(hex) +
                '</div>',
            )).add_to(h3r8namegroup)

        polygons = h3.h3_set_to_multi_polygon([hex], geo_json=False)
        # flatten polygons into loops.
        outlines = [loop for polygon in polygons for loop in polygon]
        polyline = [outline + [outline[0]] for outline in outlines][0]
        lat.extend(map(lambda v: v[0], polyline))
        lng.extend(map(lambda v: v[1], polyline))
        polylines.append(polyline)

    for polyline in polylines:
        my_PolyLine = folium.PolyLine(locations=polyline,
                                      weight=1,
                                      color='blue')
        h3r8group.add_child(my_PolyLine)

    # add possible tiles
    folium.TileLayer('cartodbpositron').add_to(m)
    folium.TileLayer('cartodbdark_matter').add_to(m)
    folium.TileLayer('openstreetmap').add_to(m)
    folium.TileLayer('Mapbox Bright').add_to(m)
    #folium.TileLayer('stamentoner').add_to(m)

    # add markers layer
    #marker_cluster = MarkerCluster().add_to(m)

    polargroup.add_to(m)  #polar plot
    hsgroup.add_to(m)  #hotspots
    dcgroup.add_to(m)  #distance circles
    h3group.add_to(m)
    h3namegroup.add_to(m)
    h3fillgroup.add_to(m)
    m.keep_in_front(h3group)
    h3r8group.add_to(m)
    h3r8namegroup.add_to(m)

    # add the layer control
    folium.LayerControl(collapsed=False).add_to(m)
    m.save(hname + '//' + hname + '_map.html')
示例#21
0
    def _measure_particle_in_cytoplasm(self, image, cfg):
        assert self._ix.any(), "no rows in the filtered dataframe"
        width, height = image.shape
        frame = Polygon([(0, 0), (0, height), (width, height), (width, 0)])

        nuclei = list()
        for _id, nuc in self._mdf.set_index("id").loc[self._ix,
                                                      "nuc_pix"].iteritems():
            nuclei.append({"id": _id, "boundary": shapely.wkt.loads(nuc)})

        for ix, row in self._mdf[self._ix].iterrows():
            _id = row["id"]
            nucl_bnd = shapely.wkt.loads(row["nuc_pix"])
            cell_bnd = shapely.wkt.loads(row["cell_pix"])
            x0, y0, xf, yf = [int(u) for u in nucl_bnd.bounds]

            valid_sample, reason = m.is_valid_sample(frame, cell_bnd, nucl_bnd,
                                                     nuclei)
            if not valid_sample: continue
            logger.debug("particle_in_cytoplasm for cell id %d" % _id)

            centr_crop = image[y0:yf, x0:xf]
            logger.info('applying centrosome algorithm for nuclei %d' % _id)

            # load boundaries of um space for dataframe construction
            n_bum = shapely.wkt.loads(row["nucleus"])
            c_bum = shapely.wkt.loads(row["cell"])

            cntr = m.centrosomes(centr_crop,
                                 min_size=0.2 * self.pix_per_um,
                                 max_size=0.5 * self.pix_per_um,
                                 threshold=0.01)
            cntr[:, 0] += x0
            cntr[:, 1] += y0
            cntrsmes = list()
            for k, c in enumerate(cntr):
                pt = Point(c[0], c[1])
                pti = m.integral_over_surface(image,
                                              pt.buffer(1 * self.pix_per_um))
                cntrsmes.append({
                    'id':
                    k,
                    'pt':
                    Point(c[0] / self.pix_per_um, c[1] / self.pix_per_um),
                    'i':
                    pti
                })
                cntrsmes = sorted(cntrsmes,
                                  key=lambda ki: ki['i'],
                                  reverse=True)

            logger.debug('found {:d} centrosomes'.format(len(cntrsmes)))

            twocntr = len(cntrsmes) >= 2
            c1 = cntrsmes[0] if len(cntrsmes) > 0 else None
            c2 = cntrsmes[1] if twocntr else None

            lc = 2 if c2 is not None else 1 if c1 is not None else np.nan
            # TODO: Add units support
            self._mdf.loc[ix, 'centrosomes'] = lc
            self._mdf.loc[ix, 'c1'] = c1['pt'].wkt if c1 is not None else None
            self._mdf.loc[ix, 'c2'] = c2['pt'].wkt if c2 is not None else None
            self._mdf.loc[ix, 'c1_int'] = c1['i'] if c1 is not None else np.nan
            self._mdf.loc[ix, 'c2_int'] = c2['i'] if c2 is not None else np.nan
            self._mdf.loc[ix, 'c1_d_nuc_centr'] = n_bum.centroid.distance(
                c1['pt']) if c1 is not None else np.nan
            self._mdf.loc[ix, 'c2_d_nuc_centr'] = n_bum.centroid.distance(
                c2['pt']) if twocntr else np.nan
            self._mdf.loc[ix, 'c1_d_nuc_bound'] = n_bum.exterior.distance(
                c1['pt']) if c1 is not None else np.nan
            self._mdf.loc[ix, 'c2_d_nuc_bound'] = n_bum.exterior.distance(
                c2['pt']) if twocntr else np.nan
            self._mdf.loc[ix, 'c1_d_cell_centr'] = c_bum.centroid.distance(
                c1['pt']) if c1 is not None else np.nan
            self._mdf.loc[ix, 'c2_d_cell_centr'] = c_bum.centroid.distance(
                c2['pt']) if twocntr else np.nan
            self._mdf.loc[ix, 'c1_d_cell_bound'] = c_bum.exterior.distance(
                c1['pt']) if c1 is not None else np.nan
            self._mdf.loc[ix, 'c2_d_cell_bound'] = c_bum.exterior.distance(
                c2['pt']) if twocntr else np.nan
            self._mdf.loc[ix,
                          'nuc_centr_d_cell_centr'] = n_bum.centroid.distance(
                              c_bum.centroid)
            self._mdf.loc[ix, 'c1_d_c2'] = c1['pt'].distance(
                c2['pt']) if twocntr else np.nan