Exemple #1
0
def plot_shapes(dict_of_multi_polygons, figsize):
    # Define plot
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111)

    # Settings
    number_of_polygon_groups = len(dict_of_multi_polygons.keys())
    transparency = max(0.3, 0.3 + 0.7 / number_of_polygon_groups)
    title_string = 'Plot showing polygons of:\n' + ', '.join(
        dict_of_multi_polygons.keys())

    # Find the boundaries of plot
    minx, miny, maxx, maxy = (np.NaN, np.NaN, np.NaN, np.NaN)
    for key in dict_of_multi_polygons.keys():
        multi_polygons = dict_of_multi_polygons[key]

        for polygon in multi_polygons:
            minx_temp, miny_temp, maxx_temp, maxy_temp = polygon.bounds
            minx, miny, maxx, maxy = (np.nanmin([minx, minx_temp]),
                                      np.nanmin([miny, miny_temp]),
                                      np.nanmax([maxx, maxx_temp]),
                                      np.nanmax([maxy, maxy_temp]))

    # Set boundaries
    w, h = maxx - minx, maxy - miny
    ax.set_xlim(12.4529, 12.6507)
    ax.set_ylim(55.6150, 55.7326)
    ax.set_aspect(1)

    # Plot polygons
    patches = []
    list_of_list_of_lines = []
    list_of_list_of_points = []
    for key in dict_of_multi_polygons.keys():
        multi_polygons = dict_of_multi_polygons[key]
        if (multi_polygons[0].type == 'LineString') or (multi_polygons[0].type
                                                        == 'MultiLineString'):
            list_of_list_of_lines.append(multi_polygons)
            continue
        if (multi_polygons[0].type == 'Point'):
            list_of_list_of_points.append(multi_polygons)
            continue
        else:
            mp = MultiPolygon(multi_polygons)

        # Colourmap
        cm = plt.get_cmap('RdBu')
        num_colours = len(mp)

        for idx, p in enumerate(mp):
            colour = cm(1. * idx / num_colours)
            patches.append(
                PolygonPatch(p,
                             fc='grey',
                             ec='#555555',
                             alpha=transparency,
                             zorder=2))

    # Plot lines
    for list_of_lines in list_of_list_of_lines:
        for line in list_of_lines:
            x, y = line.xy
            ax.plot(x,
                    y,
                    color='green',
                    linewidth=1,
                    zorder=2,
                    solid_capstyle='round')

    # Plot points
    for list_of_points in list_of_list_of_points:
        for point in list_of_points:
            patches.append(
                PolygonPatch(point.buffer(0.001),
                             fc='red',
                             ec='#555555',
                             alpha=0.9,
                             zorder=1))

    # Complete plot
    ax.add_collection(PatchCollection(patches, match_original=True))
    ax.set_xticks([])
    ax.set_yticks([])
    plt.title(title_string)
    plt.show()
Exemple #2
0
    ]

    #DEFININDO ALPHA
    alpha_shape = alphashape.alphashape(points, 0.)
    # alpha_shape = alphashape.alphashape(points) # calculo do alpha automatico

    fig, ax = plt.subplots()
    ax.scatter(*zip(*points))

    plt.xlim([np.min(dados_y), np.max(dados_y)])
    plt.ylim([np.min(dados_z), np.max(dados_z)])
    plt.axis("off")

    # fig.savefig('/home/feijo/Documents/carvao_ufc/pilhasegmentada2/fig01_{}.png'.format(i))

    ax.add_patch(PolygonPatch(alpha_shape, alpha=5))
    # plt.show()
    plt.xlim([np.min(dados_y),
              np.max(dados_y)])  # limitando o espaço de plotar em y
    plt.ylim([np.min(dados_z),
              np.max(dados_z)])  # limitando o espaço de plotar em z
    plt.axis("off")  # sem eixos

    fig.savefig(
        '/home/feijo/Documents/carvao_ufc/pilhasegmentada1/fig02_{}.png'.
        format(i))
    print(i)
    plt.close()

total = 0
for i in range(0, 1333):
    t = np.arange(0, numFrames * dt, dt)

    colors = ['b', 'g', 'r', 'c', 'm', 'k'] * 10

    gs = gridspec.GridSpec(5, 1)
    fig = plt.figure()

    # plot trajectories
    ax = plt.subplot(gs[0:3, 0])
    ax.set_aspect('equal')

    polygon_patches = []
    if ("obstacles" in jsn):
        for obs in jsn["obstacles"]:
            poly = Polygon(obs)
            polypatch = PolygonPatch(poly, color='gray', zorder=5)
            ax.add_patch(polypatch)

    for i in range(jsn["number_of_robots"]):
        ax.plot(jsn["originals"][i]["x"],
                jsn["originals"][i]["y"],
                linestyle="dashed",
                lw=2,
                zorder=10,
                color=colors[i],
                alpha=0.8)

    for i in range(jsn["number_of_robots"]):
        x = []
        y = []
        for frame in range(len(jsn["points"])):
             str(i),
             color='#00000022',
             fontsize=12.5,
             zorder=-1,
             ma='center',
             ha='center',
             va='center')
# Polygons --------------------------------------------------------------------
D = fun.disjoint_polygons(X, radius=.0075, n_angles=3)
for j in list(set(CLS_LB)):
    matches = [key for key, val in enumerate(CLS_LB) if val in set([j])]
    base = D.geometry[matches[0]]
    for i in range(len(matches)):
        base = base.union(D.geometry[matches[i]].buffer(0.00005))
    ax.add_patch(
        PolygonPatch(base, fc="none", ec='#6347ff', lw=1, alpha=.2, zorder=10))
    ax.add_patch(
        PolygonPatch(base, fc="none", ec='#ffffff', lw=.1, alpha=1, zorder=10))
ax.set_aspect(1)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.tick_params(axis='both',
               which='both',
               bottom=False,
               top=False,
               left=False,
               right=False,
               labelbottom=False,
               labelleft=False)
def plot_line(ax, ob):
    x, y = ob.xy
    ax.plot(x, y, color=GRAY, linewidth=3, solid_capstyle='round', zorder=1)

line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])

fig = pyplot.figure(1, figsize=SIZE, dpi=90)

# 1
ax = fig.add_subplot(121)

plot_line(ax, line)

dilated = line.buffer(0.5, cap_style=3)
patch1 = PolygonPatch(dilated, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
ax.add_patch(patch1)

ax.set_title('a) dilation, cap_style=3')

xrange = [-1, 4]
yrange = [-1, 3]
ax.set_xlim(*xrange)
ax.set_xticks(range(*xrange) + [xrange[-1]])
ax.set_ylim(*yrange)
ax.set_yticks(range(*yrange) + [yrange[-1]])
ax.set_aspect(1)

#2
ax = fig.add_subplot(122)
Exemple #6
0
from matplotlib import pyplot
from shapely.geometry import Point
from shapely.ops import cascaded_union
from descartes import PolygonPatch

from figures import SIZE, BLUE, GRAY, set_limits

polygons = [Point(i, 0).buffer(0.7) for i in range(5)]

fig = pyplot.figure(1, figsize=SIZE, dpi=90)

# 1
ax = fig.add_subplot(121)

for ob in polygons:
    p = PolygonPatch(ob, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)
    ax.add_patch(p)

ax.set_title('a) polygons')

set_limits(ax, -2, 6, -2, 2)

#2
ax = fig.add_subplot(122)

u = cascaded_union(polygons)
patch2b = PolygonPatch(u, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
ax.add_patch(patch2b)

ax.set_title('b) union')
Exemple #7
0
def plotGraphObjectGroups(graphObjectGroups,
                          showPopulationCounts=False,
                          showGraphIds=False,
                          showDistrictNeighborConnections=False,
                          showGraphHeatmapForFirstGroup=False,
                          saveImages=False,
                          saveDescription='Temp'):
    fig = pyplot.figure(figsize=(8, 8))
    ax = fig.gca()

    if showGraphHeatmapForFirstGroup:
        count = -1
    else:
        count = 0
    for graphObjectGroup in graphObjectGroups:
        if len(graphObjectGroup) is not 0:
            maxPopulation = max(
                [block.population for block in graphObjectGroup])
            heatMap = cm.get_cmap('Reds')
            heatmapNormalizer = colors.LogNorm(vmin=0.1,
                                               vmax=maxPopulation,
                                               clip=True)

            for graphObject in graphObjectGroup:
                if showDistrictNeighborConnections:
                    for neighborGroup in graphObject.allNeighbors:
                        ax.add_line(
                            getLineForPair(graphObject, neighborGroup,
                                           grayColor))
                if showGraphHeatmapForFirstGroup and graphObjectGroups.index(
                        graphObjectGroup) is 0:
                    normalizedEnergy = heatmapNormalizer(
                        graphObject.population)
                    heatColor = heatMap(normalizedEnergy)
                    ax.add_patch(
                        PolygonPatch(graphObject.geometry,
                                     fc=heatColor,
                                     ec=(0, 0, 0, 0),
                                     zorder=1))
                else:
                    ax.add_patch(
                        PolygonPatch(graphObject.geometry,
                                     fc=getColor(count),
                                     ec=getColor(count),
                                     alpha=0.5,
                                     zorder=2))

                if showPopulationCounts:
                    centerOfGroup = graphObject.geometry.centroid
                    ax.text(x=centerOfGroup.x,
                            y=centerOfGroup.y,
                            s=graphObject.population,
                            fontdict=font)

                if showGraphIds:
                    centerOfGroup = graphObject.geometry.centroid
                    ax.text(x=centerOfGroup.x,
                            y=centerOfGroup.y,
                            s=graphObject.graphId,
                            fontdict=font)

        count += 1

    ax.axis('scaled')

    if saveImages:
        directoryPath = path.expanduser('~/Documents/RedistrictingImages')
        if not path.exists(directoryPath):
            makedirs(directoryPath)
        filePath = path.expanduser('{0}/{1}.png'.format(
            directoryPath, saveDescription))
        pyplot.savefig(filePath)
    pyplot.show()
Exemple #8
0
def Draw_IDT(IDT_data):
    IDT = IDT_data['IDT']
    ax = plt.subplot(111)
    branch0 = IDT_data['electrodes']['elect0']
    branch1 = IDT_data['electrodes']['elect1']
    removal0 = IDT_data['removal']['removal0']
    removal1 = IDT_data['removal']['removal1']
    reticule = IDT_data['reticule']
    removal_center = IDT_data['removal']['removal_center']
    for polygon in IDT[0]:
        branch0 = branch0.union(polygon)
    branch0 = branch0.difference(removal1)
    if 'Hole_elect0' in IDT_data['removal'].keys():
        branch0 = branch0.difference(IDT_data['removal']['Hole_elect0'])
    branch0 = branch0.difference(removal_center)
    if type(branch0) is shapely_geom.polygon.Polygon:
        patch0 = PolygonPatch(branch0, fc=RED, ec=RED, alpha=0.5, zorder=2)
        ax.add_patch(patch0)
    else:
        tkMessageBox.showwarning(title='Warning',
                                 message='MultiPolygon detected')
        for polygon in branch0.geoms:
            patch0 = PolygonPatch(polygon, fc=RED, ec=RED, alpha=0.5, zorder=2)
            ax.add_patch(patch0)

    for polygon in IDT[1]:
        branch1 = branch1.union(polygon)
    branch1 = branch1.difference(removal0)
    if 'Hole_elect1' in IDT_data['removal'].keys():
        branch1 = branch1.difference(IDT_data['removal']['Hole_elect1'])
    branch1 = branch1.difference(removal_center)
    if type(branch1) is shapely_geom.polygon.Polygon:
        patch1 = PolygonPatch(branch1, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
        ax.add_patch(patch1)
    else:
        tkMessageBox.showwarning(title='Warning',
                                 message='MultiPolygon detected')
        for polygon in branch1.geoms:
            patch1 = PolygonPatch(polygon,
                                  fc=BLUE,
                                  ec=BLUE,
                                  alpha=0.5,
                                  zorder=2)
            ax.add_patch(patch1)

    for polygon in reticule:
        patch_ret = PolygonPatch(polygon,
                                 fc=GREY,
                                 ec=GREY,
                                 alpha=0.5,
                                 zorder=3)
        ax.add_patch(patch_ret)

    ax.set_title('IDT geometry')
    bounds0 = branch0.bounds
    bounds1 = branch1.bounds
    xrange = [
        1.1 * min([bounds0[0], bounds1[0]]),
        1.1 * max([bounds0[2], bounds1[2]])
    ]
    yrange = [
        1.1 * min([bounds0[1], bounds1[1]]),
        1.1 * max([bounds0[3], bounds1[3]])
    ]
    ax.axis([xrange[0], xrange[1], yrange[0], yrange[1]])
    ax.set_aspect(1)
    plt.show()
def GenerateNeighborhoodIndexMap(NeighborhoodIndex, ShapeFileLocation,
                                 FileLocation, FileName):

    fig, ax = plt.subplots(1, figsize=(14, 20))

    minval = np.min(NeighborhoodIndex[:, 0].astype(float))
    maxval = np.max(NeighborhoodIndex[:, 0].astype(float))
    norm = mpl.colors.Normalize(minval, maxval)
    #print minval,maxval
    cmap = cm.RdPu
    m = cm.ScalarMappable(norm=norm, cmap=cmap)
    temp = []
    ax.set_title('Estimated Value', fontsize=20)
    with collection(ShapeFileLocation, "r", encoding='utf8') as input:
        # schema = input.schema.copy()
        schema = {'geometry': 'Polygon', 'properties': {'NEIGHBORH1': 'str'}}
        for point in input:
            BoolPass = True
            ShapeFileDistrict = point['properties']['District_N']
            ShapeFileMunicipality = point['properties']['Municipali']

            temp.append([ShapeFileDistrict, ShapeFileMunicipality])

            try:
                select = np.logical_and(
                    NeighborhoodIndex[:, 1] == ShapeFileDistrict,
                    NeighborhoodIndex[:, 2] == ShapeFileMunicipality)
                EstVal = float(NeighborhoodIndex[select][0][0])
                BoolPass = True
            except Exception as e:
                BoolPass = False
                pass

            if BoolPass:
                poly = Polygon(np.array(point['geometry']['coordinates'][0]))
                x, y = poly.exterior.xy
                ring_patch = PolygonPatch(poly,
                                          fc=m.to_rgba(EstVal),
                                          ec=m.to_rgba(EstVal),
                                          alpha=0.9,
                                          zorder=2)
                ax.add_patch(ring_patch)
                ax.plot(x,
                        y,
                        color='#000000',
                        alpha=0.85,
                        linewidth=1,
                        solid_capstyle='butt',
                        zorder=2)

                x, y = poly.centroid.wkt.replace(')',
                                                 '').replace('(', '').replace(
                                                     'POINT ', '').split(' ')
                rx = float(x)
                ry = float(y)
                cx = rx  # + ring_patch.get_width()/2.0
                cy = ry  # + ring_patch.get_height()/2.0
                reshaped_text = arabic_reshaper.reshape(
                    point['properties'][u'District_N'])
                artext = get_display(reshaped_text)
                ax.annotate(artext, (cx, cy),
                            color='black',
                            weight='bold',
                            fontsize=4,
                            ha='center',
                            va='center')
            else:
                poly = Polygon(np.array(point['geometry']['coordinates'][0]))
                x, y = poly.exterior.xy
                ring_patch = PolygonPatch(poly,
                                          fc='#FFFFFF',
                                          ec='#FFFFFF',
                                          alpha=0.9,
                                          zorder=2)
                ax.add_patch(ring_patch)
                ax.plot(x,
                        y,
                        color='#000000',
                        alpha=0.85,
                        linewidth=1,
                        solid_capstyle='butt',
                        zorder=2)

                #Add the neighborhood name
                x, y = poly.centroid.wkt.replace(')',
                                                 '').replace('(', '').replace(
                                                     'POINT ', '').split(' ')
                rx = float(x)
                ry = float(y)
                cx = rx  # + ring_patch.get_width()/2.0
                cy = ry  # + ring_patch.get_height()/2.0
                reshaped_text = arabic_reshaper.reshape(
                    point['properties'][u'District_N'])
                artext = get_display(reshaped_text)
                ax.annotate(artext, (cx, cy),
                            color='black',
                            weight='bold',
                            fontsize=4,
                            ha='center',
                            va='center')

        #Get the min and max values of the method
        plt.xticks([])
        plt.yticks([])
        plt.savefig(FileLocation + '/' + FileName + '.png',
                    bbox_inches='tight',
                    dpi=300)
map_points = pd.Series([
    Point(m(mapped_x, mapped_y))
    for mapped_x, mapped_y in zip(biz_lons, biz_lats)
])

# In[12]:

df_map = pd.DataFrame({
    'poly': [Polygon(xy) for xy in m.ctmap],
    'ct_num': [float(tract['NAME']) for tract in m.ctmap_info]
})

# In[13]:

df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(
    x, fc='#555555', ec='#787878', lw=.25, alpha=.9, zorder=4))

# In[14]:

# Find out which census tract a business is in
for biz in pits_bizs:
    biz['ct_num'] = 0

for biz, lat, lon in zip(pits_bizs, biz_lats, biz_lons):

    map_point = Point(m(lon, lat))

    for ct_num, poly in zip(df_map['ct_num'], df_map['poly']):

        tract_poly = prep(poly)
        if tract_poly.contains(map_point):
Exemple #11
0
def Place_Electrodes(l,
                     phi_0,
                     lambda_approx,
                     electrodes_angle,
                     electrodes_thickness,
                     removal_thickness,
                     IDT_data,
                     electrode_type,
                     electrode_rotate_angle=0):
    plot = False
    Rlist = IDT_data['R']
    Thetalist = IDT_data['Theta']
    Rmin = []
    Rmax = []
    Rline = [[], []]
    for polarity in range(len(Rlist)):
        for i in range(len(Rlist[polarity])):
            R = Rlist[polarity][i]
            Theta = Thetalist[polarity][i]
            Rmin = min([R.min(), Rmin])
            Rmax = max([R.max(), Rmax])
            xy = pol2cart(Theta, R)
            if l == 0:
                #Rline[polarity].append(shapely_geom.LinearRing(shapely_geom.asLineString(xy)))
                Rline[polarity].append(shapely_geom.asLinearRing(xy))
            else:
                Rline[polarity].append(shapely_geom.asLineString(xy))
    Rmax = 1.5 * Rmax
    xyelect0 = pol2cart([electrodes_angle[0], electrodes_angle[0]],
                        [Rmin, Rmax])
    xyelect1 = pol2cart([electrodes_angle[1], electrodes_angle[1]],
                        [Rmin, Rmax])
    elect0 = shapely_geom.LineString([(xyelect0[0, 0], xyelect0[0, 1]),
                                      (xyelect0[1, 0], xyelect0[1, 1])])
    elect1 = shapely_geom.LineString([(xyelect1[0, 0], xyelect1[0, 1]),
                                      (xyelect1[1, 0], xyelect1[1, 1])])
    elect0 = shapely_affinity.rotate(elect0,
                                     electrode_rotate_angle,
                                     origin=(xyelect0[0, 0], xyelect0[0, 1]),
                                     use_radians=False)
    elect1 = shapely_affinity.rotate(elect1,
                                     electrode_rotate_angle,
                                     origin=(xyelect1[0, 0], xyelect1[0, 1]),
                                     use_radians=False)
    removal0 = deepcopy(elect0)
    removal1 = deepcopy(elect1)

    removal_center = shapely_geom.Point(
        0.,
        0.).buffer(Rmin -
                   electrodes_thickness * thickness_factor(electrode_type) / 2)

    Elect0_polyg = elect0.buffer(electrodes_thickness / 2)
    Elect1_polyg = elect1.buffer(electrodes_thickness / 2)

    IDT_data['removal'] = {
        'removal0': removal0.buffer(removal_thickness / 2),
        'removal1': removal1.buffer(removal_thickness / 2),
        'removal_center': removal_center
    }

    if False:  #electrode_rotate_angle != 0. : #draw hollow electrode to avoid forcing opposite voltage to the wave
        Hole_elect0 = elect0.buffer(
            electrodes_thickness /
            4)  #up to 50% of the power branch can be hollow
        Hole_elect1 = elect1.buffer(electrodes_thickness / 4)
        Phi_0 = Electrode_pattern(electrode_type, phi_0)
        N = Phi_0[0].size + Phi_0[1].size  #number of electrodes over lambda
        Hole_elect0 = Hole_elect0.intersection(
            shapely_geom.MultiLineString(Rline[1]).buffer(lambda_approx /
                                                          (4 * N)))
        Hole_elect1 = Hole_elect1.intersection(
            shapely_geom.MultiLineString(Rline[0]).buffer(lambda_approx /
                                                          (4 * N)))
        IDT_data['removal']['Hole_elect0'] = Hole_elect0
        IDT_data['removal']['Hole_elect1'] = Hole_elect1
        #Elect0_polyg  = Elect0_polyg.difference(Hole_elect0)
        #Elect1_polyg  = Elect1_polyg.difference(Hole_elect1)

    Rline = clean_edges(Rline, elect0, elect1)

    IDT_data['electrodes'] = {'elect0': Elect0_polyg, 'elect1': Elect1_polyg}
    IDT_data['Rline'] = Rline

    if plot:
        ax = plt.subplot(111)
        patch1 = PolygonPatch(elect0.buffer(electrodes_thickness / 2),
                              fc=RED,
                              ec=RED,
                              alpha=0.5,
                              zorder=2)
        ax.add_patch(patch1)
        patch2 = PolygonPatch(elect1.buffer(electrodes_thickness / 2),
                              fc=BLUE,
                              ec=BLUE,
                              alpha=0.5,
                              zorder=2)
        ax.add_patch(patch2)
        ax.set_title('a) dilation, cap_style=3')
        xrange = [-0.005, +0.005]
        yrange = [-0.005, +0.005]
        ax.axis([xrange[0], xrange[1], yrange[0], yrange[1]])
        ax.set_aspect(1)
        plt.show()
Exemple #12
0
# 1
#ax = fig.add_subplot(121)

#plot_line(ax, line)

dilated = line.buffer(0.5)
#patch1 = PolygonPatch(dilated, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
#ax.add_patch(patch1)

#2
ax = fig.add_subplot(122)

#patch2a = PolygonPatch(dilated, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)
#ax.add_patch(patch2a)

eroded = dilated.buffer(-0.3)

# GeoJSON-like data works as well

polygon = eroded.__geo_interface__
# >>> geo['type']
# 'Polygon'
# >>> geo['coordinates'][0][:2]
# ((0.50502525316941682, 0.78786796564403572), (0.5247963548222736, 0.8096820147509064))
patch2b = PolygonPatch(polygon, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
print("poligono {}".format(polygon))
ax.add_patch(patch2b)

pyplot.show()
Exemple #13
0
    def export_to_shape_fiona(self,
                              shp_folder="",
                              shp_filename="",
                              free_zone_only=True,
                              export_mask=None,
                              shape_fields=None):
        """
        export the grid to the shape file
        using fiona since pyshp was not compatible with arcgis
        :param export_mask: Mask to specify exactly which gridcells should be exported
        :param free_zone_only:
        :param shp_folder:
        :param shp_filename:
        """
        from fiona.crs import from_epsg, from_string
        import fiona

        proj = from_epsg(4326)
        # proj = from_epsg(4269)
        # proj = from_string("+units=m +lon_0=-97.0 +o_lon_p=180.0 +R=6370997.0 +o_proj=longlat +proj=ob_tran +o_lat_p=42.5")
        print(proj)
        print(dir(proj))
        # proj = from_epsg(900913)

        if isinstance(shp_folder, str):
            folder = Path(shp_folder)
        else:
            folder = shp_folder

        # create the directory if does not exist
        if not folder.is_dir():
            folder.mkdir()

        schema = {
            "geometry": "Polygon",
            "properties": OrderedDict([("i", "int"), ("j", "int")])
        }

        if shape_fields is not None:
            # additional fields
            for field_name, field in shape_fields.items():
                schema["properties"][field_name] = field.type_of_shp_field

        with fiona.open(str(folder.joinpath(shp_filename)),
                        mode="w",
                        driver="ESRI Shapefile",
                        crs=proj,
                        schema=schema) as output:

            lonr = [(i - (self.iref - 1)) * self.dx + self.xref
                    for i in range(self.ni)]
            latr = [(j - (self.jref - 1)) * self.dy + self.yref
                    for j in range(self.nj)]

            margin = 0
            if free_zone_only:
                margin = self.blendig + self.halo

            start_i = margin
            start_j = margin

            end_i = self.ni - margin - 1
            end_j = self.nj - margin - 1

            if export_mask is None:
                export_mask = np.ones((self.ni, self.nj), dtype=bool)

            polygons = []
            lake_fractions = []

            for i in range(start_i, end_i + 1):
                x = lonr[i]

                for j in range(start_j, end_j + 1):
                    y = latr[j]

                    if not export_mask[i, j]:
                        continue

                    p00 = self.rll.toGeographicLonLat(x - self.dx / 2.0,
                                                      y - self.dy / 2.0)
                    p01 = self.rll.toGeographicLonLat(x - self.dx / 2.0,
                                                      y + self.dy / 2.0)
                    p11 = self.rll.toGeographicLonLat(x + self.dx / 2.0,
                                                      y + self.dy / 2.0)
                    p10 = self.rll.toGeographicLonLat(x + self.dx / 2.0,
                                                      y - self.dy / 2.0)

                    # p00 = (x - self.dx / 2.0, y - self.dy / 2.0)
                    # p01 = (x - self.dx / 2.0, y + self.dy / 2.0)
                    # p11 = (x + self.dx / 2.0, y + self.dy / 2.0)
                    # p10 = (x + self.dx / 2.0, y - self.dy / 2.0)

                    poly = Polygon(shell=[p00, p01, p11, p10, p00])
                    props = OrderedDict([("i", i + 1), ("j", j + 1)])

                    polygons.append(PolygonPatch(poly))

                    if shape_fields is not None:

                        lake_fractions.append(shape_fields["lkfr"][i, j])
                        for field_name, field in shape_fields.items():
                            converter = float if field.type_of_shp_field.startswith(
                                "float") else int
                            props[field_name] = converter(field[i, j])

                    output.write({
                        "geometry": mapping(poly),
                        "properties": props
                    })
Exemple #14
0
def disegna_dbscan(labels,
                   facce,
                   facce_poligoni,
                   xmin,
                   ymin,
                   xmax,
                   ymax,
                   edges,
                   contours,
                   savefig=True,
                   format='pdf',
                   filepath='.',
                   savename='6_DBSCAN',
                   title=False):
    '''
	disegna le facce in base ai cluster ottenuti dal dbscan. Facce dello stesso cluster hanno stesso colore.
	'''
    fig, ax = setup_plot()
    savename = os.path.join(filepath, savename + '.' + format)

    colori_assegnati = []
    colors = []
    colors.extend(
        ('#800000', '#DC143C', '#FF0000', '#FF7F50', '#F08080', '#FF4500',
         '#FF8C00', '#FFD700', '#B8860B', '#EEE8AA', '#BDB76B', '#F0E68C',
         '#808000', '#9ACD32', '#7CFC00', '#ADFF2F', '#006400', '#90EE90',
         '#8FBC8F', '#00FA9A', '#20B2AA', '#00FFFF', '#4682B4', '#1E90FF',
         '#000080', '#0000FF', '#8A2BE2', '#4B0082', '#800080', '#FF00FF',
         '#DB7093', '#FFC0CB', '#F5DEB3', '#8B4513', '#808080'))
    #plt.subplot(224)
    if title:
        ax.set_title('6.dbscan')
    for label in set(labels):
        col = random.choice(colors)
        colori_assegnati.append(col)
        for index, l in enumerate(labels):
            if (l == label):
                f = facce[index]
                f_poly = facce_poligoni[index]
                f_patch = PolygonPatch(f_poly, fc=col, ec='BLACK')
                ax.add_patch(f_patch)
                ax.set_xlim(xmin, xmax)
                ax.set_ylim(ymin, ymax)
                sommax = 0
                sommay = 0
                for b in f.bordi:
                    sommax += (b.x1) + (b.x2)
                    sommay += (b.y1) + (b.y2)
                xtesto = sommax / (2 * len(f.bordi))
                ytesto = sommay / (2 * len(f.bordi))
                ax.text(xtesto, ytesto, str(l), fontsize=8)
    ascisse = []
    ordinate = []
    for edge in edges:
        if (edge.weight >= 0.3):
            ascisse.append(edge.x1)
            ascisse.append(edge.x2)
            ordinate.append(edge.y1)
            ordinate.append(edge.y2)
            ax.plot(ascisse, ordinate, color='k', linewidth=4.0)
            del ascisse[:]
            del ordinate[:]
    ascisse = []
    ordinate = []
    for c1 in contours:
        for c2 in c1:
            ascisse.append(c2[0][0])
            ordinate.append(c2[0][1])
        ax.plot(ascisse, ordinate, color='0.8', linewidth=3.0)
        del ascisse[:]
        del ordinate[:]
    if savefig:
        plt.savefig(savename, bbox_inches='tight')
    else:
        plt.show()
    return (colori_assegnati, fig, ax)
Exemple #15
0
def save_animation(file_name, bbox, continent, current_df, states, num_iter, step):
    # создаем рисунок
    fig, ax = plt.subplots(figsize=(15, 15))
    ax.set_xlabel('x, м')
    ax.set_ylabel('y, м')

    ax.set_xlim([bbox[0], bbox[2]])
    ax.set_ylim([bbox[1], bbox[3]])
    ax.add_patch(PolygonPatch(continent))
    ax.axis('equal')

    # добавляем поле скоростей
    df = current_df[(current_df['time'] == 1) & (current_df['depth'] == 1)]
    current_velocity = np.sqrt(df.loc[:, 'uo'] ** 2 + df.loc[:, 'vo'] ** 2)
    q = ax.quiver(
        df.loc[:, 'x'],
        df.loc[:, 'y'],
        df.loc[:, 'uo'],
        df.loc[:, 'vo'],
        current_velocity,
        norm=colors.Normalize(vmin=current_velocity.min(), vmax=current_velocity.max()),
        scale=7,
        scale_units='width',
        cmap='winter',
    )

    particles = {}
    transform_offset = transforms.offset_copy(ax.transData, fig=fig, x=0.05, y=0.10, units='inches')
    states_df = pd.read_csv('out.csv')
    for particle_id, group_df in states_df.groupby('id'):
        logger.info('Рисуем частицу %s', particle_id)
        particles[particle_id] = {'line': ax.plot([], [], linestyle='-', marker='', color='red')[0],
                                  'point': ax.plot([], [], linestyle='', marker='o')[0],
                                  'text': ax.text(0, 0, '', transform=transform_offset)}

    def init():
        """Initialize lines"""
        result = [q]
        for line in particles.values():
            result.append(line['line'])
            result.append(line['point'])
            result.append(line['text'])
        return result

    last_day = 0

    def update(frame):
        """Update frame"""
        nonlocal last_day
        logger.info('Рисуем кадр %s', frame)
        ax.set_title('{}, час'.format(frame * step // 3600))

        day = 1 + floor(frame * step / 86400)
        if day > last_day:
            df = current_df[(current_df['time'] == day) & (current_df['depth'] == 1)]
            q.set_UVC(df['uo'], df['vo'], np.sqrt(df['uo'] ** 2 + df['vo'] ** 2))
            last_day = day

        result = [q]
        for particle_id, particle_df in states_df.groupby('id'):
            if frame < particle_df.shape[0]:
                x = particle_df['x'].iloc[:frame + 1]
                y = particle_df['y'].iloc[:frame + 1]
                z = particle_df['z'].iloc[:frame + 1]

                particles[particle_id]['line'].set_data(x, y)
                particles[particle_id]['point'].set_data(x.iat[frame], y.iat[frame])
                particles[particle_id]['point'].set_color(
                    'red' if particle_df['is_active'].iat[frame] else 'black'
                )
                particles[particle_id]['text'].set_text(f'{z.iat[frame]:.2f}')
                particles[particle_id]['text'].set_x(x.iat[frame])
                particles[particle_id]['text'].set_y(y.iat[frame])
            result.append(particles[particle_id]['line'])
            result.append(particles[particle_id]['point'])
            result.append(particles[particle_id]['text'])
        result.append(q)

        return result

    ani = animation.FuncAnimation(
        fig,
        update,
        frames=num_iter - 1,
        init_func=init,
        interval=100,
        blit=True,
    )
    ani.save(file_name, writer=animation.FFMpegFileWriter())
    logger.info('Создан файл %s' % file_name)
Exemple #16
0
def plot_aggregation(subject_id, model=None, cluster_masks=None, arms=None):
    if model is None or cluster_masks is None or arms is None:
        print(model)
        model_path = os.path.join(
            'cluster-output', '{}.json'.format(subject_id)
        )
        masks_path = os.path.join('cluster_masks', '{}.npy'.format(subject_id))
        if not (os.path.exists(model_path) and os.path.exists(masks_path)):
            return
        with open(model_path) as f:
            model = json.load(f)
        with open(masks_path) as f:
            cluster_masks = np.load(f)
        arms = get_spiral_arms(subject_id, should_recreate=False)

    annotations = gu.classifications[
        gu.classifications['subject_ids'] == subject_id
    ]['annotations'].apply(json.loads)
    models = annotations\
        .apply(ash.remove_scaling)\
        .apply(pa.parse_annotation)\
        .apply(sanitize_model)
    spirals = models.apply(lambda d: d.get('spiral', None))
    geoms = pd.DataFrame(
        models.apply(get_geoms).values.tolist(),
        columns=('disk', 'bulge', 'bar')
    )

    logsps = [arm.reprojected_log_spiral for arm in arms]

    disk_cluster_geoms = geoms['disk'][cluster_masks[0]]
    bulge_cluster_geoms = geoms['bulge'][cluster_masks[1]]
    bar_cluster_geoms = geoms['bar'][cluster_masks[2]]

    aggregate_disk_geom = ash.make_ellipse(model['disk'])
    aggregate_bulge_geom = ash.make_ellipse(model['bulge'])
    aggregate_bar_geom = ash.make_box(model['bar'])

    gal, angle = gu.get_galaxy_and_angle(subject_id)
    pic_array, _ = gu.get_image(gal, subject_id, angle)

    def ts(s):
        return ash.transform_shape(s, pic_array.shape[0],
                                   gal['PETRO_THETA'].iloc[0])

    def tv(v):
        return ash.transform_val(v, pic_array.shape[0],
                                 gal['PETRO_THETA'].iloc[0])

    imshow_kwargs = {
        'cmap': 'gray',
        'origin': 'lower',
        'extent': [tv(0), tv(pic_array.shape[0])]*2,
    }
    fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(
        ncols=2, nrows=2,
        figsize=(10, 10),
        sharex=True, sharey=True
    )
    ax0.imshow(pic_array, **imshow_kwargs)
    for comp in geoms['disk'].values:
        if comp:
            ax0.add_patch(
                PolygonPatch(ts(comp), fc='C0', ec='k',
                             alpha=0.2, zorder=3)
            )
    ax1.imshow(pic_array, **imshow_kwargs)
    for comp in geoms['bulge'].values:
        if comp:
            ax1.add_patch(
                PolygonPatch(ts(comp), fc='C1', ec='k',
                             alpha=0.5, zorder=3)
            )
    ax2.imshow(pic_array, **imshow_kwargs)
    for comp in geoms['bar'].values:
        if comp:
            ax2.add_patch(
                PolygonPatch(ts(comp), fc='C2', ec='k',
                             alpha=0.2, zorder=3)
            )
    ax3.imshow(pic_array, **imshow_kwargs)
    for arm in arms:
        for a in arm.arms:
            ax3.plot(*tv(a).T)

    for i, ax in enumerate((ax0, ax1, ax2, ax3)):
        ax.set_xlim(imshow_kwargs['extent'][:2])
        ax.set_ylim(imshow_kwargs['extent'][2:])
        if i % 2 == 0:
            ax.set_ylabel('Arcseconds from center')
        if i > 1:
            ax.set_xlabel('Arcseconds from center')
    fig.subplots_adjust(wspace=0.05, hspace=0.05)
    plt.savefig('drawn_shapes/{}.pdf'.format(subject_id), bbox_inches='tight')
    plt.close()

    fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(
        ncols=2, nrows=2,
        figsize=(10, 10),
        sharex=True, sharey=True
    )
    ax0.imshow(pic_array, **imshow_kwargs)
    for comp in disk_cluster_geoms.values:
        ax0.add_patch(
            PolygonPatch(ts(comp), fc='C0', ec='k', alpha=0.1, zorder=3)
        )
    if model['disk'] is not None:
        aggregate_disk_geom = ash.make_ellipse(model['disk'])
        ax0.add_patch(
            PolygonPatch(ts(aggregate_disk_geom), fc='C1', ec='k', alpha=0.5,
                         zorder=3)
        )
    ax1.imshow(pic_array, **imshow_kwargs)
    for comp in bulge_cluster_geoms.values:
        ax1.add_patch(
            PolygonPatch(ts(comp), fc='C1', ec='k', alpha=0.1, zorder=3)
        )
    if aggregate_bulge_geom is not None:
        ax1.add_patch(
            PolygonPatch(ts(aggregate_bulge_geom), fc='C2', ec='k', alpha=0.5,
                         zorder=3)
        )
    ax2.imshow(pic_array, **imshow_kwargs)
    for comp in bar_cluster_geoms.values:
        ax2.add_patch(
            PolygonPatch(ts(comp), fc='C2', ec='k', alpha=0.1, zorder=3)
        )
    if aggregate_bar_geom is not None:
        ax2.add_patch(
            PolygonPatch(ts(aggregate_bar_geom), fc='C3', ec='k', alpha=0.5,
                         zorder=3)
        )
    ax3.imshow(pic_array, **imshow_kwargs)
    for arm in arms:
        plt.plot(*tv(arm.coords).T, '.', alpha=0.5, markersize=0.5)
    for arm in logsps:
        plt.plot(*tv(arm).T)

    for i, ax in enumerate((ax0, ax1, ax2, ax3)):
        ax.set_xlim(imshow_kwargs['extent'][:2])
        ax.set_ylim(imshow_kwargs['extent'][2:])
        if i % 2 == 0:
            ax.set_ylabel('Arcseconds from center')
        if i > 1:
            ax.set_xlabel('Arcseconds from center')
    fig.subplots_adjust(wspace=0.05, hspace=0.05)
    plt.savefig('clustered_shapes/{}.pdf'.format(subject_id),
                bbox_inches='tight')
    plt.close()

    fig = plt.figure(figsize=(10, 10))
    ax = plt.gca()
    ax.imshow(pic_array, **imshow_kwargs)
    if aggregate_disk_geom is not None:
        ax.add_patch(
            PolygonPatch(ts(aggregate_disk_geom), fc='C0', ec='k', alpha=0.25,
                         zorder=3)
        )
    if aggregate_bulge_geom is not None:
        ax.add_patch(
            PolygonPatch(ts(aggregate_bulge_geom), fc='C1', ec='k', alpha=0.25,
                         zorder=3)
        )
    if aggregate_bar_geom is not None:
        ax.add_patch(
            PolygonPatch(ts(aggregate_bar_geom), fc='C2', ec='k', alpha=0.25,
                         zorder=3)
        )
    for arm in logsps:
        plt.plot(*tv(arm).T, c='C3')

    ax.set_xlim(imshow_kwargs['extent'][:2])
    ax.set_ylim(imshow_kwargs['extent'][2:])
    ax.set_ylabel('Arcseconds from center')
    ax.set_xlabel('Arcseconds from center')
    plt.savefig('aggregate_model/{}.pdf'.format(subject_id),
                bbox_inches='tight')
    plt.close()
# convert into map coordinates, unpacking and then repacking tuples
window = list(zip(*m(*list(zip(*window)))))
window_map = pd.DataFrame({'poly': [Polygon(window)]})
window_polygon = prep(MultiPolygon(list(window_map['poly'].values)))

m.readshapefile(baseFile, 'oakland', color='blue', zorder=2)

# set up a map dataframe
df_map = pd.DataFrame({
    'poly': [Polygon(xy) for xy in m.oakland],
    'id': [obj['OBJECTID'] for obj in m.oakland_info],
    'zip': [obj['ZIP'] for obj in m.oakland_info],
    'yearBuilt': [obj['YEARBUILT'] for obj in m.oakland_info]
})
# draw tract patches from polygons
df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(
    x, fc='none', ec='#888888', lw=.25, alpha=.9, zorder=4))

# color code the errors
for (yb, p, i) in zip(df_map.yearBuilt, df_map.patches, range(50000)):
    if np.isnan(yb):
        p.set_color('green')
    elif yb < 1830:  # because the oldest building in Oakland is from the 1850s
        p.set_color('blue')
    elif yb > 2016:
        p.set_color('magenta')

## create colormap based on year built
#cmap_range = (1880, 1940)
#ncolors = 8
#yearBuilt_bins = np.linspace(min(cmap_range), max(cmap_range), ncolors+1)
#cmap = matplotlib.cm.coolwarm
def main():
    n = 2  # Nr of agents
    global dv, size_field, max_velocity, max_acceleration, t  # change this later
    size_field = 40
    max_velocity = 6  ##0.5 these works for smaller radiuses, also produces the dancing thingy mentioned in the paper
    max_acceleration = 2  ##0.5
    dv = 0.05  #0.1 # Step size when looking for new velocities
    t = 1  # timestep I guess
    simulation_time = 400
    radius = 1

    pos = []
    goal = []

    # generate start and end positions
    for t in range(n):
        for i in range(n):
            x = np.random.uniform(low=(size_field / 2 - 5),
                                  high=(size_field / 2 + 5))
            y = size_field + 10
            goal.append((x, y))
        for i in range(n):
            x = np.random.uniform(low=(size_field - 25), high=(size_field))
            y = 7
            pos.append((x, y))
        for i in range(n):
            x = np.random.uniform(low=(0), high=(5))
            y = 7
            pos.append((x, y))

    # pos = []
    # for x in range(5,35,3):
    #     if x ==5:
    #         pos.append((x-2.5,2))
    #     else:
    #         pos.append((x-2.5,2))
    #         pos.append((2.5,x-2.5))

    random.shuffle(pos)
    #goals = pos[::-1]
    agents = create_agents(n, radius, pos, goal)
    #agentA = Agents([1,1], [0.5, 0.5], [8,8], radius,'r') # position, velocity, goal, radius, color
    #agentB = Agents([8,8], [1, -0.5], [1,1], radius, 'b')
    #agentC = Agents([1,8], [1, 2], [8,1], radius, 'y')
    #agentD = Agents([8,1], [-1, 2], [1,8], radius, 'g')
    #agentF = Agents([1, 5], [1, 2], [8, 5], radius, 'b')
    #agentG = Agents([8, 5], [-1, 2], [1, 5], radius, 'b')
    #agents = [agentA, agentB]#, agentC, agentD, agentF, agentG]

    fig, ax = plt.subplots(
    )  # Fig ska man aldrig bry sig om om man inte vill ändra själva plotrutan
    boundary_polygons = init_map_old(size_field, ax, radius)
    # Consider the obstacles as agents with zero velocity! Don't consider these when updating velocities etc
    #obstacle_agents = create_fake_agents(len(boundary_polygons), radius, boundary_polygons, 1)
    time = 0
    #avoid = [agents+obstacle_agents] # want to send in both agents and obstacles when creating VOs
    while time < simulation_time:
        for agent in agents:
            VOs = agent.calculate_velocity_obstacles(agents, boundary_polygons)
            #if retreat:
            #    print("Fly din dåre!")
            #    print(agent.vel)
            #    preffered_vel = [agent.vel[0]*(-1), agent.vel[1]*(-1)] # Helt om!
            #    print(preffered_vel)
            #else:
            preffered_vel = agent.find_preffered_velocity()
            #print("preffered velocity", preffered_vel)
            new_velocity = agent.avoidance_strategy(preffered_vel)
            agent.pos = [
                agent.pos[0] + new_velocity[0] * t,
                agent.pos[1] + new_velocity[1] * t
            ]
            agent.vel = new_velocity

        if time == 0:
            anims = []
            patches = []
            fs = []
            for agent in agents:
                dd = ax.plot(agent.pos[0], agent.pos[1], 'go')
                anims.append(dd)
                if len(agent.velocity_objects) != 0:
                    ww = PolygonPatch(agent.velocity_objects[0],
                                      facecolor='#ff3333',
                                      edgecolor='#6699cc',
                                      alpha=0.5,
                                      zorder=2)
                    patches.append(ww)
                oo = ax.add_artist(agent.shape)
                fs.append(oo)
            #for patch in patches:
            #    ax.add_patch(patch)

            #anim1, anim2, anim3, anim4, anim5, anim6 = ax.plot(agentA.pos[0],agentA.pos[1],'go',agentB.pos[0],agentB.pos[1],'bo', agentC.pos[0],agentC.pos[1],'ro', agentD.pos[0],agentD.pos[1],'yo', agentF.pos[0],agentF.pos[1],'yo', agentG.pos[0],agentG.pos[1],'yo')
            #patch = PolygonPatch(agentA.velocity_objects[0], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch)
            #patch1a = PolygonPatch(agentA.velocity_objects[1], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch1a)
            #patch2 = PolygonPatch(agentA.velocity_objects[2], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch2)
            #patch3a = PolygonPatch(agentA.velocity_objects[3], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch3a)
            #patch4 = PolygonPatch(agentA.velocity_objects[4], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch4)

            ax.axis([-0, size_field, -0, size_field], 'equal')
            #f = ax.add_artist(agentA.shape)
            #f2 = ax.add_artist(agentB.shape)
            #f3 = ax.add_artist(agentC.shape)
            #f4 = ax.add_artist(agentD.shape)
            #f5 = ax.add_artist(agentF.shape)
            #f6 = ax.add_artist(agentG.shape)
            #vel1 = ax.quiver(agentB.pos[0], agentB.pos[1], agentB.vel[0], agentB.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #vel2 = ax.quiver(agentA.pos[0], agentA.pos[1], agentA.vel[0], agentA.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #vel3 = ax.quiver(agentC.pos[0], agentC.pos[1], agentC.vel[0], agentC.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #vel4 = ax.quiver(agentD.pos[0], agentD.pos[1], agentD.vel[0], agentD.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
        else:
            for (agent, anim, f) in zip(agents, anims, fs):
                if len(agent.velocity_objects) != 0:

                    print("KDSDASd")
                    patch = PolygonPatch(agent.velocity_objects[0],
                                         facecolor='#ff3333',
                                         edgecolor='#6699cc',
                                         alpha=0.5,
                                         zorder=2)
                    ax.add_patch(patch)
                anim[0].set_data(agent.pos[0], agent.pos[1])
                f.center = agent.pos[0], agent.pos[1]
                ax.plot(agent.goal[0], agent.goal[1], 'r*')

            #anim2.set_data(agentB.pos[0], agentB.pos[1])
            #anim3.set_data(agentC.pos[0], agentC.pos[1])
            #anim4.set_data(agentD.pos[0], agentD.pos[1])
            #anim5.set_data(agentF.pos[0], agentF.pos[1])
            #anim6.set_data(agentG.pos[0], agentG.pos[1])

            #velocity_object = Polygon([pos11, tp22, tp11])
            #s11 = patch.get_path()
            #print(s11)
            #patch.bounds= (ps11, tp22, tp11)# = PolygonPatch(agentA.velocity_objects[0], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #print(type(patch))

            #patch.remove()
            #patch = PolygonPatch(agentA.velocity_objects[0], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch)
            #patch1a.remove()
            #patch1a = PolygonPatch(agentA.velocity_objects[1], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch1a)
            #patch2.remove()
            #patch2 = PolygonPatch(agentA.velocity_objects[2], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch2)
            #patch3a.remove()
            #patch3a = PolygonPatch(agentA.velocity_objects[3], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch3a)
            #patch4.remove()
            #patch4 = PolygonPatch(agentA.velocity_objects[4], facecolor='#ff3333', edgecolor='#6699cc', alpha=0.5, zorder=2)
            #ax.add_patch(patch4)

            # patch2.remove()
            # patch2 = PolygonPatch(agentB.velocity_objects[0], facecolor='#FFFF00', edgecolor='#FFFF00', alpha=0.5, zorder=2)
            # ax.add_patch(patch2)
            # patch3.remove()
            # patch3 = PolygonPatch(agentC.velocity_objects[0], facecolor='#FFFF00', edgecolor='#FFFF00', alpha=0.5, zorder=2)
            # ax.add_patch(patch3)
            # patch4.remove()
            # patch4 = PolygonPatch(agentD.velocity_objects[0], facecolor='#FFFF00', edgecolor='#FFFF00', alpha=0.5, zorder=2)
            # ax.add_patch(patch4)

            #f.center= agentA.pos[0],agentA.pos[1]
            #f2.center = agentB.pos[0], agentB.pos[1]
            #f3.center = agentC.pos[0], agentC.pos[1]
            #f4.center = agentD.pos[0], agentD.pos[1]
            #f5.center = agentF.pos[0], agentF.pos[1]
            #f6.center = agentG.pos[0], agentG.pos[1]
            #vel1.remove()
            #vel2.remove()
            #vel3.remove()
            #vel4.remove()
            #vel1 = ax.quiver(agentB.pos[0], agentB.pos[1], agentB.vel[0], agentB.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #vel2 = ax.quiver(agentA.pos[0], agentA.pos[1], agentA.vel[0], agentA.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #vel3 = ax.quiver(agentC.pos[0], agentC.pos[1], agentC.vel[0], agentC.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #vel4 = ax.quiver(agentD.pos[0], agentD.pos[1], agentD.vel[0], agentD.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #f = ax.add_artist(agentA.shape)
            #f2 = ax.add_artist(agentB.shape)
            #ax.quiver(agentB.pos[0], agentB.pos[1], agentB.vel[0], agentB.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector
            #ax.quiver(agentA.pos[0], agentA.pos[1], agentA.vel[0], agentA.vel[1], scale=6, scale_units ='width') ##in case we want velocity vector

            #ax.plot(agentA.goal[0], agentA.goal[1],'r*')
            #ax.plot(agentB.goal[0], agentB.goal[1],'g*')
            #ax.plot(agentC.goal[0], agentC.goal[1],'b*')
            #ax.plot(agentD.goal[0], agentD.goal[1],'y*')
            #ax.plot(agentF.goal[0], agentF.goal[1],'b*')
            #ax.plot(agentG.goal[0], agentG.goal[1],'b*')

        time += 1
        print("time:", time)
        plt.pause(0.1)
def main():
    j = 1
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    mng = plt.get_current_fig_manager()
    mng.full_screen_toggle()
    cleo = True
    listpiw = []

    dancing = 0
    freeze = 0
    downwind_leeway, crosswind_leeway = leeway()
    errord = 0.12
    errorc = 0.094
    comprised = 0
    fov = 20
    plt.ion()
    plt.grid()
    soph = []  #holds all search areas - for all timestamps
    foundline = False
    eliminate_bug = True

    elly = False

    ###INITIAL POSITION###
    op = 50
    gg = 1000
    errors = []
    for error in range(200):
        errors.append([
            normalfunction(0.12, False),
            normalfunction(0.094, False)
        ])  ###### compute errors to simulate PIW uncertainty

    tin = 0
    ship_vel = 10.8  #m/s
    mob_signal_time = 180  #seconds
    distancetolkp = ship_vel * mob_signal_time
    ax.set_facecolor('#e6f5ff')
    locationuav = [50, 1000 + distancetolkp]
    locationuav_no2 = [50, 1000 + distancetolkp]
    start_point_uav = [50, 1000 + distancetolkp]
    goals = 1
    uavspeed = 15.0  #make sure that the loops align - search for "LOOP_PART" - there should be 3: 0, 1, 2 LOOP_PART0
    sum_path = 0
    theirgoal = 1
    p = [0, 0]
    piwlkp = [50, 1000]
    locationstoplotplsnohate = []
    piw_atmob = [
        piwlkp[0] + downwind_leeway * (mob_signal_time) - errord * 2 *
        (mob_signal_time), piwlkp[1]
    ]
    center_piw_atmob = [
        piwlkp[0] + downwind_leeway * (mob_signal_time), piwlkp[1]
    ]

    timestamp = 10  #1 timestamp = 10 seconds

    for i in range(
            0, 2000,
            timestamp):  ##########Caution: TIMESTAMPS############## LOOP_PART1
        t = i
        timothy = (time.time() - person_down)  #*10 + 100

        ax = plt.gca()
        ax.cla()  # optionally clear axes

        downwind_leeway, crosswind_leeway = leeway()

        gg = 50 + downwind_leeway * t
        op = 1000 + crosswind_leeway * t

        exp1 = 0.12 * 2 * 2 * t  #**2 #############EXPAND THE AREA every second##### on X
        exp2 = 0.094 * 2 * 2 * t  #**2  #### ON Y ####
        theirupdown = 0
        theirlist = []
        thier_sum_path = 0
        ells = Ellipse((gg, op), exp1, exp2, el_ang, color="#66c2ff")
        plt.plot(gg, op, color='g', marker='o')
        ells.set_alpha(0.4)
        ells.set_clip_box(ax.bbox)
        #ells.set_alpha(0.1)
        ax.add_artist(ells)

        if t >= mob_signal_time:
            polygon1 = []

            if foundline == False:  ###FIND the intercept - where the UAV should fly to intersect with the last position where the PIW may be
                for totot in range(t, 20000):
                    p = [
                        piw_atmob[0] + downwind_leeway *
                        (totot - mob_signal_time) - errord * 2 *
                        (totot - mob_signal_time), piw_atmob[1]
                    ]

                    cant = dist(locationuav[0], locationuav[1], p[0], p[1])

                    auxil = p[0] - piw_atmob[0]
                    if int(
                            dist(locationuav[0], locationuav[1], p[0], p[1]) /
                            uavspeed) <= int(auxil /
                                             (downwind_leeway - 2 * errord)):
                        firstone = totot - mob_signal_time
                        foundline = True
                        break
            pathuav = []
            pathuav.append([50, start_point_uav[1]])
            pathuav.append(p)
            plt.plot((50, p[0]), (start_point_uav[1], p[1]), 'b-')
            plt.plot(piw_atmob[0], piw_atmob[1], color='m', marker='D')
            plt.plot(p[0], p[1], color='m', marker='D')

            if t <= mob_signal_time + int(
                    dist(start_point_uav[0], start_point_uav[1], p[0], p[1]) /
                    uavspeed):
                errmm = (mob_signal_time + int(
                    dist(start_point_uav[0], start_point_uav[1], p[0], p[1]) /
                    uavspeed))
                deliminator = 0.1

                gg = 50 + downwind_leeway * errmm
                op = 1000 + crosswind_leeway * errmm

                exp1 = ((0.12) * 2) * 2 * errmm
                exp2 = ((0.094) * 2) * 2 * errmm

                ####PLOT the search area####
                ells = Ellipse((gg, op), exp1, exp2, el_ang, color="#ff0066")
                plt.plot(gg, op, color='g', marker='o')
                ells.set_alpha(0.3)
                ells.set_clip_box(ax.bbox)
                #ells.set_alpha(0.1)
                ax.add_artist(ells)

                if retursoph(
                        exp1, exp2, deliminator, gg, op
                ) not in soph:  #merge search areas over different timestamps

                    soph.append(
                        retursoph(exp1, exp2, deliminator, gg,
                                  op))  ####add polygons for each area(t)

                xs, ys = [], []

                for poop in range(0, len(soph[len(soph) - 1])):

                    xs.append(round(soph[len(soph) - 1][poop][0], 2))
                    ys.append(round(soph[len(soph) - 1][poop][1], 2))

                polygon1 = shape_pol(
                    list(zip(xs, ys))
                )  ### polygon in shapely (library) format ### --- so that we can merge them

                i += 1

            else:
                for i in range(
                        len(soph) + mob_signal_time + int(
                            dist(start_point_uav[0], start_point_uav[1], p[0],
                                 p[1]) / uavspeed), t):
                    deliminator = 0.1

                    gg = 50 + downwind_leeway * i  ###FIXED LEEWAY SPEED
                    op = 1000 + crosswind_leeway * i

                    exp1 = ((0.12) * 2) * 2 * i  #**2
                    exp2 = (
                        (0.094) * 2
                    ) * 2 * i  ###############EXPAND THE search area #############

                    if i == t:  ####PLOT the latest search area####
                        ells = Ellipse((gg, op),
                                       exp1,
                                       exp2,
                                       el_ang,
                                       color="#ff0066")
                        plt.plot(gg, op, color='g', marker='o')
                        ells.set_alpha(0.3)
                        ells.set_clip_box(ax.bbox)
                        #ells.set_alpha(0.1)
                        ax.add_artist(ells)

                    if i > 0:
                        if retursoph(exp1, exp2, deliminator, gg,
                                     op) not in soph:
                            soph.append(
                                retursoph(
                                    exp1, exp2, deliminator, gg,
                                    op))  ####add polygons for each area(t)

                        xs, ys = [], []

                        for poop in range(0, len(soph[len(soph) - 1])):

                            xs.append(round(soph[len(soph) - 1][poop][0], 2))
                            ys.append(round(soph[len(soph) - 1][poop][1], 2))

                        polygon1 = shape_pol(
                            list(zip(xs, ys))
                        )  ### polygon in shapely (library) format ### --- so that we can merge them

                    i += 1

            if polygon1 != []:  # > 0:
                if elly == True:  ####PUT POLYGONS TOGETHER
                    boundarii = cascaded_union([boundarii, polygon1])
                else:
                    boundarii = cascaded_union([polygon1])
                    elly = True
                patch2b = PolygonPatch(boundarii,
                                       fc='#3399ff',
                                       ec='#ff9900',
                                       alpha=1,
                                       zorder=2)
                patch2b.set_alpha(0.3)

            ax.add_patch(patch2b)
            plt.grid(color='#ffcce0', linestyle=':', linewidth=2)

            #####################STARTING TO PLOT THE PATH#######################################
            boing = list(
                boundarii.exterior.coords
            )  ###ASSIGN ALL POINTS IN FRAME POLYGON = list containing all points belonging to the polygon margins

            murs = len(boing)
            mid = boundarii.bounds[1] + (boundarii.bounds[3] -
                                         boundarii.bounds[1]) / 2
            upper = []
            lower = []
            ########SORT ABOUT MID
            for y in range(0, len(boing)):
                if boing[y][1] > mid:
                    upper.append(boing[y])
                    #plt.plot(boing[y][0], boing[y][1], color = 'r', marker = 'o')
                elif boing[y][1] <= mid:
                    lower.append(boing[y])
                    #plt.plot(boing[y][0], boing[y][1], color = 'b', marker = 'o')
                    #sort this??

            lower = sorted(lower)
            fov = 20

            lolo = []
            sum_path = 0

            upup = []

            ########################### KEEP POINTS AT FOV DISTANCE ####################

            lolo.append(lower[0])
            for y in range(0, len(lower)):
                keep = True
                if y == 0:
                    auxx = 50  #
                    auxy = 1000

                    upper_x = 50 + downwind_leeway * t + (0.12) * 2 * t  #**2

                    upper_y = 1000 + crosswind_leeway * t  #+ (0.094)*t

                else:
                    if dist(auxx, auxy, lower[y][0], lower[y][1]) > fov:

                        auxx = lower[y][0]
                        auxy = lower[y][1]
                        lolo.append(lower[y])

                        if dist(upper_x, upper_y, lower[y][0],
                                lower[y][1]) < fov - fov / 3:

                            break

            upup.append(upper[0])
            for y in range(0, len(upper)):
                keep = True
                if y == 0:

                    auxx = 50
                    auxy = 1000

                    upper_x = 50 + downwind_leeway * t + (0.12) * 2 * t  #**2

                    upper_y = 1000 + crosswind_leeway * t  #+ (0.094)*t

                else:
                    if dist(auxx, auxy, upper[y][0], upper[y][1]) > fov:

                        auxx = upper[y][0]
                        auxy = upper[y][1]
                        if int(upper[y][0]) != 50 and int(upper[y][1]) != 50:
                            upup.append(upper[y])

                        if dist(upper_x, upper_y, upper[y][0],
                                upper[y][1]) < fov - fov / 3:

                            break

            updown = 0
            pathuav = []
            pathuav.append([50, start_point_uav[1]])
            pathuav.append(p)

            pathuav.append([upup[0][0], upup[0][1]])
            pathuav.append(
                [upup[0][0], upup[0][1], 1000 + crosswind_leeway * 0])
            sum_path += dist(upup[0][0], upup[0][1], 50, 1000)
            upup.append([
                50 + downwind_leeway * t + (0.12) * 2 * t,
                1000 + crosswind_leeway * t
            ])
            lolo.append([
                50 + downwind_leeway * t + (0.12) * 2 * t,
                1000 + crosswind_leeway * t
            ])

            if len(lolo) < len(upup):
                memes = len(lolo) - 1
            else:
                memes = len(upup) - 1
            for mem in range(memes):
                plt.plot((upup[mem][0], lolo[mem][0]),
                         (upup[mem][1], lolo[mem][1]), 'r-')
                sum_path += dist(upup[mem][0], upup[mem][1], lolo[mem][0],
                                 lolo[mem][1])
                if updown == 0:

                    pathuav.append([upup[mem][0], upup[mem][1]])

                    pathuav.append([lolo[mem][0], lolo[mem][1]])

                    pathuav.append([lolo[mem + 1][0], lolo[mem + 1][1]])

                    updown = 1
                    sum_path += dist(lolo[mem + 1][0], lolo[mem + 1][1],
                                     lolo[mem][0], lolo[mem][1])
                else:

                    updown = 0
                    pathuav.append([lolo[mem][0], lolo[mem][1]])

                    pathuav.append([upup[mem][0], upup[mem][1]])

                    pathuav.append([upup[mem + 1][0], upup[mem + 1][1]])

            ey = 0
            for point in pathuav:

                if ey < len(pathuav) - 1:
                    plt.plot((pathuav[ey + 1][0], pathuav[ey][0]),
                             (pathuav[ey + 1][1], pathuav[ey][1]),
                             color='#339966',
                             marker='_')
                    ey += 1

            if t >= mob_signal_time:
                for i in range(int(uavspeed) * timestamp +
                               1):  ######## LOOP_PART2
                    if goals < len(pathuav):

                        p1 = locationuav
                        p2 = pathuav[goals]

                        x = p2[0] - p1[0]
                        y = p2[1] - p1[1]
                        #print (x, y)
                        angle = math.atan2(y, x)

                        locationuav = [p1[0] + cos(angle), p1[1] + sin(angle)]

                        if int(pathuav[goals][0]) in np.arange(
                                int(locationuav[0]) - 2.0,
                                int(locationuav[0]) + 2.0) and int(
                                    pathuav[goals][1]) in np.arange(
                                        int(locationuav[1]) - 2.0,
                                        int(locationuav[1]) + 2.0):
                            goals += 1
                        plt.plot(locationuav[0],
                                 locationuav[1],
                                 color='k',
                                 marker='o')  #339966

                        if cleo == False:

                            for point in listpiw:
                                if point[0] < locationuav[
                                        0] + fov / 2 and point[
                                            0] > locationuav[0] - fov / 2:
                                    if point[1] < locationuav[
                                            1] + fov / 2 and point[
                                                1] > locationuav[1] - fov / 2:
                                        print('seen')
                                        listpiw.remove(point)

# ################ PIW ################

        if cleo and t == 0:  ###########GENERATE POINTS, only once
            ggp = 50 + downwind_leeway * 1  ###FIXED LEEWAY SPEED
            opp = 1000 + crosswind_leeway * 1

            exp1p = ((0.12) * 2) * t  #**2
            exp2p = ((0.094) * 2) * t
            listpiw = genpoint(gg, op, exp1p, exp2p, el_ang, errors, t)
            cleo = False
            print('points generated')
            for point in listpiw:
                plt.plot(point[0], point[1], color='r', marker='o')

###################MOVE POINTS #########################

        elif t > 0:  #and tin < t:
            dancing = 0
            freeze = 0
            comprised = 0

            for point in range(len(listpiw)):
                if point / 2.0 == 0:
                    insteadofcrosswind_leeway = 0.1
                else:
                    insteadofcrosswind_leeway = -0.1

                add = piw_movement(listpiw[point][0], listpiw[point][1],
                                   downwind_leeway * (t - tin),
                                   crosswind_leeway * (t - tin),
                                   t)  #HOLD INITIAL POSITION OF POINT

                listpiw[point][0] += add[0] + errors[point][0] * (
                    t - tin
                )  ## set list of errors created before the while loop ##
                listpiw[point][1] += add[1] + errors[point][1] * (t - tin)

                freeze, dancing = insidecheck(
                    listpiw[point][0], listpiw[point][1], gg, op, exp1, exp2,
                    el_ang, freeze,
                    dancing)  #Display PIWs: red = not within the search area

            tin = t

        prev_t = t
        if goals > 1 or t < mob_signal_time:
            plt.axis([0, 1000, 700, 1300])
        else:
            plt.axis([0, 1000, 700, 1100 + ship_vel * mob_signal_time])

        ax.set_xlabel((t, str('s'), 'PIW spawned', 200, 'PIW remaining',
                       len(listpiw), 'UAV takeoff (s)', mob_signal_time,
                       'PIW speed (cm/s)', round(downwind_leeway, 2)),
                      fontsize=14)

        plt.draw()
        plt.pause(0.1)

        plt.show()

    time.sleep(1)
Exemple #20
0
    def plot_patch(self,
                   xc,
                   yc,
                   patch_size,
                   scale=1,
                   magn_base=4,
                   translate=True,
                   colordict={},
                   figsize=None,
                   vis_scale=True,
                   fig=None,
                   ax=None,
                   alpha=0.1,
                   **kwargs):

        if 'target_subsample' in kwargs:
            scale = kwargs.pop('target_subsample')
            warn('deprication warning', DeprecationWarning)
        if isinstance(patch_size, int) or isinstance(patch_size, float):
            patch_size = [int(patch_size)] * 2

        patch = self.get_patch(
            xc,
            yc,
            patch_size,
            scale=scale,
            magn_base=magn_base,
        )

        prois = self.get_patch_rois(xc,
                                    yc,
                                    patch_size,
                                    scale=scale,
                                    translate=translate)
        if fig is None:
            if ax is not None:
                fig = ax.get_figure()
            else:
                if len(kwargs) > 0 or figsize is not None:
                    fig, ax = plt.subplots(1, figsize=figsize, **kwargs)
                else:
                    fig = plt.gcf()
                    ax = fig.gca()
        elif ax is None:
            ax = fig.gca()

        ccycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
        ccycle = cycle(ccycle)

        out_patch_size = patch_size
        if scale != 1:
            if vis_scale:
                out_patch_size = [
                    int(np.round(ps / scale)) for ps in patch_size
                ]
                scale_ = lambda x: x
            else:

                def scale_(x):
                    origin = (0, 0) if translate else (xc, yc)
                    return affinity.scale(x, scale, scale, origin=origin)

        print('out_patch_size', out_patch_size)

        if translate:
            extent = (0, out_patch_size[0], out_patch_size[1], 0)
        else:
            extent = (
                xc - out_patch_size[0] // 2,
                xc + out_patch_size[0] // 2,
                yc + out_patch_size[1] // 2,
                yc - out_patch_size[1] // 2,
            )
        print('extent', extent)
        ax.imshow(patch, extent=extent)

        for name_, gg in prois.groupby('name'):
            flag = True
            if name_ in colordict:
                c = colordict[name_]
            else:
                c = next(ccycle)
            for _, pp_ in gg.iterrows():
                #print(pp_['name'])
                pp = pp_.polygon
                if scale != 1:
                    pp = scale_(pp)
                fc = list(colors.to_rgba(c))
                ec = list(colors.to_rgba(c))
                fc[-1] = alpha
                ax.add_patch(
                    PolygonPatch(pp,
                                 fc=fc,
                                 ec=ec,
                                 lw=2,
                                 label=name_ if flag else None))
                flag = False
        ax.relim()
        ax.autoscale_view()
        return fig, ax, patch, prois
Exemple #21
0
def plotBlocksForRedistrictingGroups(redistrictingGroups,
                                     showPopulationCounts=False,
                                     showBlockGraphIds=False,
                                     showDistrictNeighborConnections=False,
                                     showBlockNeighborConnections=False,
                                     showGraphHeatmap=False,
                                     showGeometryPoints=False):
    fig = pyplot.figure(figsize=(8, 8))
    ax = fig.gca()

    for redistrictingGroup in redistrictingGroups:
        if showDistrictNeighborConnections:
            for neighborGroup in redistrictingGroup.allNeighbors:
                if neighborGroup in redistrictingGroups:
                    ax.add_line(
                        getLineForPair(redistrictingGroup, neighborGroup,
                                       grayColor))

        if showGeometryPoints:
            centroid = redistrictingGroup.geometry.centroid
            ax.scatter(centroid.x, centroid.y)

        maxPopulationEnergy = max(
            [block.populationEnergy for block in redistrictingGroup.children])
        heatMap = cm.get_cmap('hot')
        heatmapNormalizer = colors.Normalize(vmin=0.0,
                                             vmax=maxPopulationEnergy)

        for block in redistrictingGroup.children:
            if block.isWater:
                ax.add_patch(
                    PolygonPatch(block.geometry,
                                 fc=blueColor,
                                 ec=blueColor,
                                 alpha=0.5,
                                 zorder=2))
            else:
                if showGraphHeatmap:
                    normalizedEnergy = heatmapNormalizer(
                        block.populationEnergy)
                    heatColor = heatMap(normalizedEnergy)
                    ax.add_patch(
                        PolygonPatch(block.geometry,
                                     fc=heatColor,
                                     ec=heatColor,
                                     alpha=0.5,
                                     zorder=2))
                else:
                    if redistrictingGroup.isBorderBlock(block):
                        if block in redistrictingGroup.northernChildBlocks:
                            borderBlockColor = purpleColor
                        elif block in redistrictingGroup.westernChildBlocks:
                            borderBlockColor = yellowColor
                        elif block in redistrictingGroup.southernChildBlocks:
                            borderBlockColor = orangeColor
                        else:
                            borderBlockColor = turquoiseColor

                        ax.add_patch(
                            PolygonPatch(block.geometry,
                                         fc=borderBlockColor,
                                         ec=borderBlockColor,
                                         alpha=0.5,
                                         zorder=2))
                    else:
                        ax.add_patch(
                            PolygonPatch(block.geometry,
                                         fc=greenColor,
                                         ec=greenColor,
                                         alpha=0.5,
                                         zorder=2))
            centerOfBlock = block.geometry.centroid

            if showPopulationCounts:
                ax.text(x=centerOfBlock.x,
                        y=centerOfBlock.y,
                        s=block.population,
                        fontdict=font)

            if showBlockGraphIds:
                ax.text(x=centerOfBlock.x,
                        y=centerOfBlock.y,
                        s=block.graphId,
                        fontdict=font)

            if showBlockNeighborConnections:
                for neighborBlock in block.allNeighbors:
                    ax.add_line(getLineForPair(block, neighborBlock,
                                               grayColor))

    ax.axis('scaled')
    pyplot.show()
from matplotlib import pyplot
from shapely.geometry import Point
from descartes import PolygonPatch
import sys

BLUE = "#6699cc"
GRAY = "#cecece"
SIZE = 10, 10

fig = pyplot.figure(1, figsize=SIZE, dpi=90)

ax = fig.add_subplot(111)

fin = open(sys.argv[1], 'r')
for line in fin:
    args = line.split(";")
    pt = Point(float(args[0]), float(args[1])).buffer(float(sys.argv[2]))
    patch = PolygonPatch(pt, fc=GRAY, ec=GRAY, alpha=0.7, zorder=1)
    ax.add_patch(patch)

# 1
xrange = [-10, 100]
yrange = [-10, 100]
ax.set_xlim(*xrange)
ax.set_xticks(range(*xrange) + [xrange[-1]])
ax.set_ylim(*yrange)
ax.set_yticks(range(*yrange) + [yrange[-1]])
ax.set_aspect(1)

pyplot.show()
Exemple #23
0
with open("geonames_pop.txt",'r') as f2:
    pop_str = f2.read()

cty_polygons = json.loads(cty_str)
places_pts = json.loads(pop_str)

counties = shape_maker(cty_polygons)
towns = shape_maker(places_pts)

cty_features = []
for cf in counties['features']:
    cty_features.append(cf)

patches = []
for cf in cty_features:
    if cf.geom_type == 'Polygon':
        patches.append(PolygonPatch(cf))
    elif cf.geom_type == 'MultiPolygon':
        for poly in cf:
            patches.append(PolygonPatch(poly))


for patch in patches:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    m = Basemap(llcrnrlon=-11.5,llcrnrlat=51.0,urcrnrlon=-5.0,urcrnrlat=56.0,
            resolution='i',projection='tmerc',lon_0=-7.36,lat_0=53.0, epsg = 29902)
    ax.add_patch(patch)
    plt.show()

Exemple #24
0
def _run(input_outlook_file_name, input_warning_file_name, border_colour,
         warning_colour, min_plot_latitude_deg, max_plot_latitude_deg,
         min_plot_longitude_deg, max_plot_longitude_deg, output_file_name):
    """Plots SPC convective outlook.

    This is effectively the main method.

    :param input_outlook_file_name: See documentation at top of file.
    :param input_warning_file_name: Same.
    :param border_colour: Same.
    :param warning_colour: Same.
    :param min_plot_latitude_deg: Same.
    :param max_plot_latitude_deg: Same.
    :param min_plot_longitude_deg: Same.
    :param max_plot_longitude_deg: Same.
    :param output_file_name: Same.
    """

    print(
        'Reading SPC outlook from: "{0:s}"...'.format(input_outlook_file_name))

    pickle_file_handle = open(input_outlook_file_name, 'rb')
    outlook_table = pickle.load(pickle_file_handle)
    pickle_file_handle.close()

    risk_type_enums = numpy.array([
        RISK_TYPE_STRING_TO_ENUM[s]
        for s in outlook_table[RISK_TYPE_COLUMN].values
    ],
                                  dtype=int)

    sort_indices = numpy.argsort(risk_type_enums)
    outlook_table = outlook_table.iloc[sort_indices]

    outlook_table = _get_bounding_boxes(outlook_table)

    if input_warning_file_name in ['', 'None']:
        warning_table = None
    else:
        print('Reading tornado warnings from: "{0:s}"...'.format(
            input_warning_file_name))

        pickle_file_handle = open(input_warning_file_name, 'rb')
        warning_table = pickle.load(pickle_file_handle)
        pickle_file_handle.close()

        warning_table = _get_bounding_boxes(warning_table)

    latitude_limits_deg, longitude_limits_deg = _get_plotting_limits(
        min_plot_latitude_deg=min_plot_latitude_deg,
        max_plot_latitude_deg=max_plot_latitude_deg,
        min_plot_longitude_deg=min_plot_longitude_deg,
        max_plot_longitude_deg=max_plot_longitude_deg,
        outlook_table=outlook_table,
        warning_table=warning_table)

    min_plot_latitude_deg = latitude_limits_deg[0]
    max_plot_latitude_deg = latitude_limits_deg[1]
    min_plot_longitude_deg = longitude_limits_deg[0]
    max_plot_longitude_deg = longitude_limits_deg[1]

    print(('Plotting limits = [{0:.2f}, {1:.2f}] deg N and [{2:.2f}, {3:.2f}] '
           'deg E').format(min_plot_latitude_deg, max_plot_latitude_deg,
                           min_plot_longitude_deg, max_plot_longitude_deg))

    latlng_limit_dict = {
        plotting_utils.MIN_LATITUDE_KEY: min_plot_latitude_deg,
        plotting_utils.MAX_LATITUDE_KEY: max_plot_latitude_deg,
        plotting_utils.MIN_LONGITUDE_KEY: min_plot_longitude_deg,
        plotting_utils.MAX_LONGITUDE_KEY: max_plot_longitude_deg
    }

    axes_object, basemap_object = plotting_utils.create_map_with_nwp_proj(
        model_name=nwp_model_utils.RAP_MODEL_NAME,
        grid_name=nwp_model_utils.NAME_OF_130GRID,
        xy_limit_dict=None,
        latlng_limit_dict=latlng_limit_dict,
        resolution_string='i')[1:]

    plotting_utils.plot_coastlines(basemap_object=basemap_object,
                                   axes_object=axes_object,
                                   line_colour=border_colour)

    plotting_utils.plot_countries(basemap_object=basemap_object,
                                  axes_object=axes_object,
                                  line_colour=border_colour)

    plotting_utils.plot_states_and_provinces(basemap_object=basemap_object,
                                             axes_object=axes_object,
                                             line_colour=border_colour)

    _, unique_risk_type_indices = numpy.unique(
        outlook_table[RISK_TYPE_COLUMN].values, return_index=True)

    num_outlooks = len(outlook_table.index)
    legend_handles = []
    legend_strings = []

    for i in range(num_outlooks):
        this_risk_type_string = outlook_table[RISK_TYPE_COLUMN].values[i]
        this_colour = RISK_TYPE_STRING_TO_COLOUR[this_risk_type_string]

        this_vertex_dict_latlng = polygons.polygon_object_to_vertex_arrays(
            outlook_table[POLYGON_COLUMN].values[i])

        these_x_coords_metres, these_y_coords_metres = basemap_object(
            this_vertex_dict_latlng[polygons.EXTERIOR_X_COLUMN],
            this_vertex_dict_latlng[polygons.EXTERIOR_Y_COLUMN])

        this_polygon_object_xy = polygons.vertex_arrays_to_polygon_object(
            exterior_x_coords=these_x_coords_metres,
            exterior_y_coords=these_y_coords_metres)

        this_patch_object = PolygonPatch(this_polygon_object_xy,
                                         lw=0.,
                                         ec=this_colour,
                                         fc=this_colour,
                                         alpha=OUTLOOK_OPACITY)
        this_handle = axes_object.add_patch(this_patch_object)

        if i in unique_risk_type_indices:
            this_string = '{0:s}{1:s}'.format(this_risk_type_string[0].upper(),
                                              this_risk_type_string[1:])

            legend_strings.append(this_string)
            legend_handles.append(this_handle)

    if warning_table is None:
        num_warnings = 0
    else:
        num_warnings = len(warning_table.index)

    warning_colour_tuple = plotting_utils.colour_from_numpy_to_tuple(
        warning_colour)

    for i in range(num_warnings):
        this_vertex_dict_latlng = polygons.polygon_object_to_vertex_arrays(
            warning_table[POLYGON_COLUMN].values[i])

        these_x_coords_metres, these_y_coords_metres = basemap_object(
            this_vertex_dict_latlng[polygons.EXTERIOR_X_COLUMN],
            this_vertex_dict_latlng[polygons.EXTERIOR_Y_COLUMN])

        axes_object.plot(these_x_coords_metres,
                         these_y_coords_metres,
                         color=warning_colour_tuple,
                         linestyle='solid',
                         linewidth=WARNING_LINE_WIDTH)

    axes_object.legend(legend_handles, legend_strings, loc='upper left')

    print('Saving figure to: "{0:s}"...'.format(output_file_name))

    file_system_utils.mkdir_recursive_if_necessary(file_name=output_file_name)
    pyplot.savefig(output_file_name, dpi=FIGURE_RESOLUTION_DPI)
    pyplot.close()

    imagemagick_utils.trim_whitespace(input_file_name=output_file_name,
                                      output_file_name=output_file_name)
def plot_buildings(gdf,
                   fig=None,
                   ax=None,
                   figsize=None,
                   color='#333333',
                   bgcolor='w',
                   set_bounds=True,
                   bbox=None,
                   save=False,
                   show=True,
                   close=False,
                   filename='image',
                   file_format='png',
                   dpi=600):
    """
    Plot a GeoDataFrame of building footprints.

    Parameters
    ----------
    gdf : GeoDataFrame
        building footprints
    fig : figure
    ax : axis
    figsize : tuple
    color : string
        the color of the building footprints
    bgcolor : string
        the background color of the plot
    set_bounds : bool
        if True, set bounds from either passed-in bbox or the spatial extent of
        the gdf
    bbox : tuple
        if True and if set_bounds is True, set the display bounds to this bbox
    save : bool
        whether to save the figure to disk or not
    show : bool
        whether to display the figure or not
    close : bool
        close the figure (only if show equals False) to prevent display
    filename : string
        the name of the file to save
    file_format : string
        the format of the file to save (e.g., 'jpg', 'png', 'svg')
    dpi : int
        the resolution of the image file if saving

    Returns
    -------
    GeoDataFrame
    """

    if fig is None or ax is None:
        fig, ax = plt.subplots(figsize=figsize, facecolor=bgcolor)
        ax.set_facecolor(bgcolor)

    # extract each polygon as a descartes patch, and add to a matplotlib patch
    # collection
    patches = []
    for geometry in gdf['geometry']:
        if isinstance(geometry, Polygon):
            patches.append(PolygonPatch(geometry))
        elif isinstance(geometry, MultiPolygon):
            for subpolygon in geometry:  #if geometry is multipolygon, go through each constituent subpolygon
                patches.append(PolygonPatch(subpolygon))
    pc = PatchCollection(patches,
                         facecolor=color,
                         edgecolor=color,
                         linewidth=0,
                         alpha=1)
    ax.add_collection(pc)

    if set_bounds:
        if bbox is None:
            # set the figure bounds to the polygons' bounds
            left, bottom, right, top = gdf.total_bounds
        else:
            top, bottom, right, left = bbox
        ax.set_xlim((left, right))
        ax.set_ylim((bottom, top))

    # turn off the axis display set the margins to zero and point the ticks in
    # so there's no space around the plot
    ax.axis('off')
    ax.margins(0)
    ax.tick_params(which='both', direction='in')
    fig.canvas.draw()

    # make everything square
    ax.set_aspect('equal')
    fig.canvas.draw()

    fig, ax = save_and_show(fig=fig,
                            ax=ax,
                            save=save,
                            show=show,
                            close=close,
                            filename=filename,
                            file_format=file_format,
                            dpi=dpi,
                            axis_off=True)

    return fig, ax
Exemple #26
0
def _plot_kriged_cps(args,
                     fig_size,
                     bck_polys_list,
                     krige_x_coords_mesh,
                     krige_y_coords_mesh,
                     anom_type,
                     cont_levels,
                     out_figs_dir,
                     x_coords,
                     y_coords,
                     best_cps_min_anoms,
                     best_cps_max_anoms,
                     best_cps_std_anoms,
                     msgs):

    (cp_nos,
     krige_z_coords_mesh,
     cp_x_coords_list,
     cp_y_coords_list,
     vgs_list,
     cp_rules_arr) = args

    max_n_coords = 10
    n_x_coords = x_coords.shape[0]
    n_y_coords = y_coords.shape[0]

    x_ticks_pos = np.arange(0, n_x_coords)
    y_ticks_pos = np.arange(0, n_y_coords)

    if n_x_coords > max_n_coords:
        x_step_size = n_x_coords // max_n_coords
    else:
        x_step_size = 1

    if n_y_coords > max_n_coords:
        y_step_size = n_y_coords // max_n_coords
    else:
        y_step_size = 1

    cmap = plt.get_cmap('autumn')

    min_cbar_val = min(best_cps_min_anoms.min(),
                       best_cps_max_anoms.min())

    max_cbar_val = max(best_cps_min_anoms.max(),
                       best_cps_max_anoms.max())

    # CP
    cps_fig = plt.figure(figsize=fig_size)
    cps_ax = cps_fig.gca()

    cp_std_fig = plt.figure(figsize=fig_size)
    cp_std_ax = cp_std_fig.gca()

    for j, cp_no in enumerate(range(cp_nos[0], cp_nos[1])):
        if msgs:
            print('Plotting CP No.', cp_no)

        plt.figure(cps_fig.number)

        if bck_polys_list is not None:
            for poly in bck_polys_list:
                cps_ax.add_patch(PolygonPatch(poly,
                                              alpha=0.5,
                                              fc='#999999',
                                              ec='#999999'))

        cs = cps_ax.contour(krige_x_coords_mesh,
                            krige_y_coords_mesh,
                            krige_z_coords_mesh[j],
                            levels=cont_levels,
                            vmin=0.0,
                            vmax=1.0,
                            linestyles='solid',
                            extend='both')

        if anom_type != 'd':
            cps_ax.scatter(cp_x_coords_list[j], cp_y_coords_list[j])

        cps_ax.set_title('CP no. %d, %s' % (cp_no, vgs_list[j]))

        cps_ax.set_xlim(krige_x_coords_mesh.min(),
                        krige_x_coords_mesh.max())
        cps_ax.set_ylim(krige_y_coords_mesh.min(),
                        krige_y_coords_mesh.max())

        cps_ax.set_xlabel('Eastings')
        cps_ax.set_ylabel('Northings')

        cps_ax.clabel(cs, inline=True, inline_spacing=0.01, fontsize=10)

        plt.savefig(str(out_figs_dir / ('cp_map_%0.2d.png' % (cp_no))),
                    bbox_inches='tight')

        cps_ax.cla()

        # CP Std.
        plt.figure(cp_std_fig.number)
        cax = cp_std_ax.imshow(best_cps_std_anoms[cp_no],
                               origin='upper',
                               interpolation=None,
                               cmap=cmap)

        if anom_type != 'd':
            _cp_rules_str = (
                cp_rules_arr[j].reshape(
                    best_cps_std_anoms[cp_no].shape).astype('|U'))

            txt_x_corrs = np.tile(range(_cp_rules_str.shape[1]),
                                  _cp_rules_str.shape[0])

            txt_y_corrs = np.repeat(range(_cp_rules_str.shape[0]),
                                    _cp_rules_str.shape[1])

            for k in range(txt_x_corrs.shape[0]):
                cp_std_ax.text(txt_x_corrs[k],
                               txt_y_corrs[k],
                               _cp_rules_str[txt_y_corrs[k],
                                             txt_x_corrs[k]],
                               va='center',
                               ha='center',
                               color='black')

        cp_std_ax.set_xticks(x_ticks_pos[::x_step_size])
        cp_std_ax.set_yticks(y_ticks_pos[::y_step_size])

        cp_std_ax.set_xticklabels(x_coords[::x_step_size])
        cp_std_ax.set_yticklabels(y_coords[::y_step_size])

        cp_std_ax.set_xlabel('Eastings')
        cp_std_ax.set_ylabel('Northings')

        cbar = cp_std_fig.colorbar(cax, orientation='horizontal')
        cbar.set_label('Anomaly Std.')

        cp_std_ax.set_title('Std. CP no. %d' % (cp_no))

        plt.savefig(str(out_figs_dir / ('std_cp_map_%0.2d.png' % (cp_no))),
                    bbox_inches='tight')
        cbar.remove()
        cp_std_ax.cla()

        # CP Min. and Max.
        cp_min_max_fig = plt.figure(figsize=fig_size)
        cp_min_max_grid = gridspec.GridSpec(1, 2)
        cp_min_ax = plt.subplot(cp_min_max_grid[0, 0])
        cp_max_ax = plt.subplot(cp_min_max_grid[0, 1])

        plt.figure(cp_min_max_fig.number)

        # Min
        cax_min = cp_min_ax.imshow(best_cps_min_anoms[cp_no],
                                   origin='upper',
                                   interpolation=None,
                                   vmin=min_cbar_val,
                                   vmax=max_cbar_val,
                                   cmap=cmap)

        cp_min_ax.set_xticks(x_ticks_pos[::x_step_size])
        cp_min_ax.set_yticks(y_ticks_pos[::y_step_size])

        cp_min_ax.set_xticklabels(x_coords[::x_step_size])
        cp_min_ax.set_yticklabels(y_coords[::y_step_size])

        cp_min_ax.set_xlabel('Eastings')
        cp_min_ax.set_ylabel('Northings')

        cp_min_ax.set_title('Min. Anomaly CP no. %d' % (cp_no))

        # Max
        cp_max_ax.imshow(best_cps_max_anoms[cp_no],
                         origin='upper',
                         interpolation=None,
                         vmin=min_cbar_val,
                         vmax=max_cbar_val,
                         cmap=cmap)

        cp_max_ax.set_xticks(x_ticks_pos[::x_step_size])
        cp_max_ax.set_yticks(y_ticks_pos[::y_step_size])

        cp_max_ax.set_xticklabels(x_coords[::x_step_size])
        cp_max_ax.set_yticklabels([])

        cp_max_ax.set_xlabel('Eastings')

        cbar = cp_min_max_fig.colorbar(cax_min,
                                       ax=[cp_min_ax, cp_max_ax],
                                       orientation='horizontal')

        cp_max_ax.set_title('Max. Anomaly CP no. %d' % (cp_no))

        plt.savefig(str(out_figs_dir /
                        ('min_max_cp_map_%0.2d.png' % (cp_no))),
                    bbox_inches='tight')

        plt.close()

    plt.close('all')
    return
Exemple #27
0
# SEPARAR EM SLICES NO EIXO X COM INTERVALOR DE 1000
intervalo= 1000 # se ficar menor não fecha o polígono
total = 0
voltotal=0
for i in range(len(dados_x)//intervalo):
    points = [(y,z) for y,z in zip(dados_y[i*intervalo: (i+1)*intervalo],dados_z[i*intervalo: (i+1)*intervalo])]

    # DEFININDO ALPHA
    alpha_shape = alphashape.alphashape(points,0.)
    # alpha_shape = alphashape.alphashape(points) # calculo do alpha automatico
    
    fig, ax = plt.subplots()
    ax.scatter(*zip(*points))
    
    ax.add_patch(PolygonPatch(alpha_shape, alpha=0.2)) #0,2
    
    # Plotar arquivo .txt de cada slice
    # fig.savefig(root+'selecao_teste/fig_{}.png'.format(i))
    print(i) 

    points_slice = [(x,y,z) for x,y,z in zip(dados_x[i*intervalo: (i+1)*intervalo],dados_y[i*intervalo: (i+1)*intervalo],dados_z[i*intervalo: (i+1)*intervalo])]

    plt.close(fig)
    #plt.close(allfig)

    dados_df2= np.array(points_slice)[:,:3] # ajustar arquivo txt - (linha , coluna)
    dados2 = dados_df2[dados_df2[:,0].argsort()] #ordenar eixo x
    dados_x2= dados2[:,0]
    dados_y2= dados2[:,1]
    dados_z2= dados2[:,2]
Exemple #28
0
    def make_collection(self, shp, index_field=None,
                        s=20, fc='0.8', ec='k', lw=0.5, alpha=0.5,
                        color_field=None,
                        cbar=False, clim=(), cmap='jet', cbar_label=None,
                        simplify_patches=100,
                        zorder=5,
                        convert_coordinates=1,
                        remove_offset=True,
                        collection_name=None,
                        **kwargs):

        if collection_name is None:
            collection_name = os.path.split(shp)[-1].split('.')[0]
        df = shp2df(shp)

        if index_field is not None:
            df.index = df[index_field]

        proj4 = get_proj4(shp)

        if proj4 != self.proj4:
            df['geometry'] = projectdf(df, proj4, self.proj4)

        # convert projected coordinate units and/or get rid z values if the shapefile has them
        if convert_coordinates != 1 or df.iloc[0]['geometry'].has_z:
            df['geometry'] = [transform(lambda x, y, z=None: (x * convert_coordinates,
                                                              y * convert_coordinates), g)
                              for g in df.geometry]

        # remove model offset from projected coordinates (llcorner = 0,0)
        if remove_offset:
            df['geometry'] = [translate(g,
                                        -1 * self.extent_proj[0],
                                        -1 * self.extent_proj[1]) for g in df.geometry]

        if simplify_patches > 0:
            df['geometry'] = [g.simplify(simplify_patches) for g in df.geometry]

        if 'Polygon' in df.iloc[0].geometry.type:
            print "building PatchCollection..."
            inds = []
            patches = []
            for i, g in df.geometry.iteritems():
                if g.type != 'MultiPolygon':
                    inds.append(i)
                    patches.append(PolygonPatch(g))
                else:
                    for part in g.geoms:
                        inds.append(i)
                        patches.append(PolygonPatch(part))

            collection = PatchCollection(patches, cmap=cmap,
                                         facecolor=fc, linewidth=lw, edgecolor=ec, alpha=alpha,
                                         )

        elif 'LineString' in df.geometry[0].type:
            print "building LineCollection..."
            inds = []
            lines = []
            for i, g in df.geometry.iteritems():
                if 'Multi' not in g.type:
                    x, y = g.xy
                    inds.append(i)
                    lines.append(zip(x, y))
                # plot each line in a multilinestring
                else:
                    for l in g:
                        x, y = l.xy
                        inds.append(i)
                        lines.append(zip(x, y))

            collection = LineCollection(lines, colors=ec, linewidths=lw, alpha=alpha, zorder=zorder, **kwargs)
            #lc.set_edgecolor(ec)
            #lc.set_alpha(alpha)
            #lc.set_lw(lw)

            # set the color scheme (could set line thickness by same proceedure)
            if fc in df.columns:
                colors = np.array([df[fc][ind] for ind in inds])
                collection.set_array(colors)

        else:
            print "plotting points..."
            x = np.array([g.x for g in df.geometry])
            y = np.array([g.y for g in df.geometry])

            collection = self.ax.scatter(x, y, s=s, c=fc, ec=ec, lw=lw, alpha=alpha, zorder=zorder, **kwargs)
            inds = range(len(x))

        self.layers[collection_name] = df
        self.collections[collection_name] = collection
        self.collection_inds[collection_name] = inds

        return collection
Exemple #29
0
init_t = math.atan(2.5)
r = math.sqrt(10**2 + 25**2)
thetas = [init_t, math.pi - init_t, math.pi + init_t, 2 * math.pi - init_t]


def gen_rect_pts(x, y, alpha):
    return [(x + r * math.cos(theta + alpha), y + r * math.sin(theta + alpha))
            for theta in thetas]


fig, ax = plt.subplots()
plt.ion()
plt.show()

for pt in [(-50, -50), (-50, 50), (50, 50), (50, -50)]:
    ax.plot(*pt)
ax.autoscale_view()
plt.draw()
plt.pause(0.1)

i = 0.
while i <= 2 * math.pi:
    print(math.degrees(i + init_t),
          ["(%.2f,%.2f)" % pt for pt in gen_rect_pts(10, 25, i)])
    ax.add_patch(PolygonPatch(Polygon(gen_rect_pts(10, 25, i))))
    i += math.pi / 64
    plt.draw()
    plt.pause(0.01)

plt.ioff()
plt.show()
Exemple #30
0
 def plot(self, ax):
     patch = PolygonPatch(self.getShape())
     ax.add_patch(patch)