Ejemplo n.º 1
0
def forest(input_forest_raster,
           output_file="forest.png",
           borders=None,
           zoom=None,
           figsize=(11.69, 8.27),
           dpi=300, **kwargs):
    """Plot forest map.

    This function plots the forest map in green value 1 in raster.

    :param input_forest_raster: path to forest raster.
    :param output_file: name of the plot file.
    :param borders: vector file to be plotted.
    :param zoom: zoom to region (xmin, xmax, ymin, ymax).
    :param figsize: figure size in inches.
    :param dpi: resolution for output image.

    :return: a Matplotlib figure of the forest map.

    """

    # Load raster and band
    rasterR = gdal.Open(input_forest_raster)
    rasterB = rasterR.GetRasterBand(1)
    rasterND = rasterB.GetNoDataValue()
    gt = rasterR.GetGeoTransform()
    ncol = rasterR.RasterXSize
    nrow = rasterR.RasterYSize
    Xmin = gt[0]
    Xmax = gt[0] + gt[1] * ncol
    Ymin = gt[3] + gt[5] * nrow
    Ymax = gt[3]
    extent = [Xmin, Xmax, Ymin, Ymax]

    # Overviews
    if (rasterB.GetOverviewCount() == 0):
        # Build overviews
        print("Build overview")
        rasterR.BuildOverviews("nearest", [4, 8, 16, 32])

    # Get data from finest overview
    ov_band = rasterB.GetOverview(0)
    ov_arr = ov_band.ReadAsArray()
    ov_arr[ov_arr == rasterND] = 2

    # Dereference driver
    rasterB = None
    del(rasterR)

    # Colormap
    colors = []
    cmax = 255.0  # float for division
    colors.append((51 / cmax, 160 / cmax, 44 / cmax, 1))  # forest green
    colors.append((0, 0, 0, 0))  # transparent
    color_map = ListedColormap(colors)

    # Plot raster
    place = 111 if zoom is None else 121
    fig = plt.figure(figsize=figsize, dpi=dpi)
    ax1 = plt.subplot(place)
    ax1.set_frame_on(False)
    ax1.set_xticks([])
    ax1.set_yticks([])
    plt.imshow(ov_arr, cmap=color_map, extent=extent)
    if borders is not None:
        plot_layer(borders, symbol="k-", **kwargs)
    plt.axis("off")
    if zoom is not None:
        z = Rectangle(
            (zoom[0], zoom[2]),
            zoom[1] - zoom[0],
            zoom[3] - zoom[2],
            fill=False
        )
        ax1.add_patch(z)
        ax2 = plt.subplot(222)
        plt.imshow(ov_arr, cmap=color_map, extent=extent)
        plt.xlim(zoom[0], zoom[1])
        plt.ylim(zoom[2], zoom[3])
        ax2.set_xticks([])
        ax2.set_yticks([])

    # Save and return figure
    fig.tight_layout()
    fig.savefig(output_file, dpi="figure", bbox_inches="tight")
    return(fig)
Ejemplo n.º 2
0
		# 	continue

		rbox = np.array(y_pred[k, :4])
		pbox = np.array(y_pred[k, 4:8])

		tframe = box2frame(box=pbox, apoint=[0.5, 0.5])
		
		ax.annotate(classes[pclz], (tframe[0], tframe[1]), color='green', weight='bold',
			fontsize=8, ha='center', va='center')

		rframe = box2frame(box=rbox, apoint=[0, 0])
		tframe = box2frame(box=pbox, apoint=[0, 0])

		ax.add_patch(Rectangle(
			(rframe[0], rframe[1]), rframe[2], rframe[3],
			linewidth=1, 
			edgecolor='r',
			facecolor='none', 
			linestyle='-'))

		ax.add_patch(Rectangle(
			(tframe[0], tframe[1]), tframe[2], tframe[3],
			linewidth=1, 
			edgecolor='g',
			facecolor='none', 
			linestyle='-'))

	plt.show()



L = 2, 2.7, 3  # room dimensions
x0 = 1.2, 1.7, 1.5  # source position
max_order = 2  # maximum order of image sources
coeffs = .8, .8, .6, .6, .7, .7  # wall reflection coefficients
omega = 2 * np.pi * 1000  # angular frequency of monocromatic sound field
fs = 44100  # sample rate for boadband response
signal = ([1, 0, 0], fs)  # signal for broadband response

# get 2D mirror image sources and their strength
xs, wall_count = sfs.util.image_sources_for_box(x0[0:2], L[0:2], max_order)
source_strength = np.prod(coeffs[0:4]**wall_count, axis=1)
# plot mirror image sources
plt.figure()
plt.scatter(*xs.T, source_strength * 20)
plt.gca().add_patch(Rectangle((0, 0), L[0], L[1], fill=False))
plt.xlabel('x / m')
plt.ylabel('y / m')
plt.savefig('image_source_positions.png')

# compute monochromatic sound field
grid = sfs.util.xyz_grid([0, L[0]], [0, L[1]], 1.5, spacing=0.02)
P = sfs.mono.source.point_image_sources(omega,
                                        x0, [1, 0, 0],
                                        grid,
                                        L,
                                        max_order,
                                        coeffs=coeffs)
# plot monocromatic sound field
plt.figure()
sfs.plot.soundfield(P, grid, xnorm=[L[0] / 2, L[1] / 2, L[2] / 2])
Ejemplo n.º 4
0
    def cell_plot(self, i, analysis_tree, decorate=True, **kwargs):
        """
        plots the `Partition` for unit roi *i*.
        """
        if isinstance(i, str):
            label = i
            title = kwargs.pop("title", label)
        else:
            label = self.subset_label(i)
            title = kwargs.pop("title", self.roi_label(i))
        if "delaunay" not in kwargs:
            # anticipate future changes in `helper.tessellation.cell_plot`
            voronoi = kwargs.pop("voronoi", dict(centroid_style=None))
            kwargs["voronoi"] = voronoi
        if "aspect" not in kwargs:
            kwargs["aspect"] = "equal"
        plot_bb = decorate and self.overlaps(i)
        if True:  # plot_bb:
            kwargs["show"] = False
        #
        cell_plot(analysis_tree, label=label, title=title, **kwargs)
        #
        if decorate:
            if "axes" in kwargs:
                ax = kwargs["axes"]
            else:
                import matplotlib.pyplot as plt

                ax = plt.gca()
            _min, _max = self.bounding_box[i]
            x0, y0, x1, y1 = _min[0], _min[1], _max[0], _max[1]
            xl, yl = ax.get_xlim(), ax.get_ylim()
            xc, yc = 0.5 * (x0 + x1), 0.5 * (y0 + y1)
            if not plot_bb:
                x0, y0, x1, y1 = xl[0], yl[0], xl[1], yl[1]
            ax.plot(
                [x0, x1, np.nan, xc, xc],
                [yc, yc, np.nan, y0, y1],
                color="k",
                linestyle="--",
                alpha=1,
                linewidth=1,
            )
        if plot_bb:
            from matplotlib.collections import PatchCollection
            from matplotlib.patches import Rectangle

            masks = []
            if xl[0] < x0:
                masks.append(Rectangle((xl[0], yl[0]), x0 - xl[0], yl[1] - yl[0]))
            if x1 < xl[1]:
                masks.append(Rectangle((x1, yl[0]), xl[1] - x1, yl[1] - yl[0]))
            if yl[0] < y0:
                masks.append(Rectangle((x0, yl[0]), x1 - x0, y0 - yl[0]))
            if y1 < yl[1]:
                masks.append(Rectangle((x0, y1), x1 - x0, yl[1] - y1))
            pc = PatchCollection(masks, facecolor="k", alpha=0.1, edgecolor=None)
            ax.add_collection(pc)
            #
            ax.plot(
                [x0, x0, x1, x1, x0],
                [y0, y1, y1, y0, y0],
                color="k",
                linestyle="-",
                alpha=1,
                linewidth=1,
            )
            ax.set_xlim(xl)
            ax.set_ylim(yl)
Ejemplo n.º 5
0
    def __init__(self, transform, size, label, loc,
                 pad=0.1, borderpad=0.1, sep=2,
                 frameon=True, size_vertical=0, color='black',
                 label_top=False, fontproperties=None, fill_bar=None,
                 **kwargs):
        """
        Draw a horizontal scale bar with a center-aligned label underneath.

        Parameters
        ----------
        transform : `matplotlib.transforms.Transform`
            The transformation object for the coordinate system in use, i.e.,
            :attr:`matplotlib.axes.Axes.transData`.

        size : float
            Horizontal length of the size bar, given in coordinates of
            *transform*.

        label : str
            Label to display.

        loc : int
            Location of this size bar. Valid location codes are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4,
                'right'        : 5,
                'center left'  : 6,
                'center right' : 7,
                'lower center' : 8,
                'upper center' : 9,
                'center'       : 10

        pad : float, default: 0.1
            Padding around the label and size bar, in fraction of the font
            size.

        borderpad : float, default: 0.1
            Border padding, in fraction of the font size.

        sep : float, default: 2
            Separation between the label and the size bar, in points.

        frameon : bool, default: True
            If True, draw a box around the horizontal bar and label.

        size_vertical : float, default: 0
            Vertical length of the size bar, given in coordinates of
            *transform*.

        color : str, default: 'black'
            Color for the size bar and label.

        label_top : bool, default: False
            If True, the label will be over the size bar.

        fontproperties : `matplotlib.font_manager.FontProperties`, optional
            Font properties for the label text.

        fill_bar : bool, optional
            If True and if size_vertical is nonzero, the size bar will
            be filled in with the color specified by the size bar.
            Defaults to True if `size_vertical` is greater than
            zero and False otherwise.

        **kwargs
            Keyworded arguments to pass to
            :class:`matplotlib.offsetbox.AnchoredOffsetbox`.

        Attributes
        ----------
        size_bar : `matplotlib.offsetbox.AuxTransformBox`
            Container for the size bar.

        txt_label : `matplotlib.offsetbox.TextArea`
            Container for the label of the size bar.

        Notes
        -----
        If *prop* is passed as a keyworded argument, but *fontproperties* is
        not, then *prop* is be assumed to be the intended *fontproperties*.
        Using both *prop* and *fontproperties* is not supported.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> import nump as np
        >>> from mpl_toolkits.axes_grid1.anchored_artists import (
        ...     AnchoredSizeBar)
        >>> fig, ax = plt.subplots()
        >>> ax.imshow(np.random.random((10, 10)))
        >>> bar = AnchoredSizeBar(ax.transData, 3, '3 data units', 4)
        >>> ax.add_artist(bar)
        >>> fig.show()

        Using all the optional parameters

        >>> import matplotlib.font_manager as fm
        >>> fontprops = fm.FontProperties(size=14, family='monospace')
        >>> bar = AnchoredSizeBar(ax.transData, 3, '3 units', 4, pad=0.5,
        ...                       sep=5, borderpad=0.5, frameon=False,
        ...                       size_vertical=0.5, color='white',
        ...                       fontproperties=fontprops)
        """
        if fill_bar is None:
            fill_bar = size_vertical > 0

        self.size_bar = AuxTransformBox(transform)
        self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical,
                                           fill=fill_bar, facecolor=color,
                                           edgecolor=color))

        if fontproperties is None and 'prop' in kwargs:
            fontproperties = kwargs.pop('prop')

        if fontproperties is None:
            textprops = {'color': color}
        else:
            textprops = {'color': color, 'fontproperties': fontproperties}

        self.txt_label = TextArea(
            label,
            minimumdescent=False,
            textprops=textprops)

        if label_top:
            _box_children = [self.txt_label, self.size_bar]
        else:
            _box_children = [self.size_bar, self.txt_label]

        self._box = VPacker(children=_box_children,
                            align="center",
                            pad=0, sep=sep)

        AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                   child=self._box,
                                   prop=fontproperties,
                                   frameon=frameon, **kwargs)

# for plot
import matplotlib.pyplot as plt

plt.ion()
fig = plt.figure() #plt.figure(figsize=(20,7))
x = np.arange(n)
x2 = np.arange(naux)

ax1 = fig.add_subplot(3,1,1)
line1, = ax1.plot(x, np.zeros(n, dtype=np.float32), linestyle='None', marker='p', markersize=2)
ax1.set_xlim(0, nx)
ax1.set_ylim(-1.2, 1.2)
from matplotlib.patches import Rectangle
rect = Rectangle((spt1, -1.2), spt2-spt1, 2.4, facecolor='w', linestyle='dashed')
ax1.add_patch(rect)

ax2 = fig.add_subplot(3,1,2)
line2, = ax2.plot(x2, np.zeros(naux, dtype=np.float32), linestyle='None', marker='p', markersize=2)
ax2.set_xlim(0, naux)
ax2.set_ylim(-1.2, 1.2)

ax3 = fig.add_subplot(3,1,3)
line3, = ax3.plot(x2, np.zeros(naux, dtype=np.float32), linestyle='None', marker='p', markersize=2)
ax3.set_xlim(0, naux)
ax3.set_ylim(-1.2, 1.2)


# main loop
for tstep in xrange(tmax):
Ejemplo n.º 7
0
def multi_van_krevelen_plot(*formula_lists,
                            group_labels = [],
                            colours=[],
                            symbols=[], 
                            alphas = [],
                            edge_colours = [],
                            x_ratio = 'OC',
                            y_ratio = 'HC',
                            patch_classes = [],
                            patch_alpha = 0.3,
                            patch_colors = ['#762a83','#9970ab','#c2a5cf','#e7d4e8','#d9f0d3','#a6dba0','#5aae61','#1b7837'],
                            patch_text = True,
                            **kwargs):

    """ 
	Docstring for function PyKrev.multi_van_krevelen_plot
	====================
	This function takes multiple lists of molecula formula strings and plots a van Krevelen diagram. 
    
	Use
	----
	multi_van_krevelen_plot(*Y)
    
	Returns tuple containing figure and axes handles 
    
	Parameters
	----------
	*Y: multiple lists of molecular formula strings.
    
	group_labels: A list of strings corresponding to each formula_list in Y to be displayed in the legend. 
    
	colours: A list of strings providing marker colours corresponding to each formula_list in Y. 
	See: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html
    
	symbol: A list of scatter plot symbols to use corresponding to each formula_list in Y. 
	See: https://matplotlib.org/3.2.1/api/markers_api.html
    
	edge_colours: a list of strings providing marker edge colours corresponding to each formula_list in Y.
        
	alphas: list of floats providing transparency of the marker points corresponding to each formula_list in Y.
    x_ratio: element ratio to plot on x axis, given numerator denominator e.g. 'OC'
    y_ratio: element ratio to plot on y axis, given numerator denominator e.g. 'HC'

    patch_classes: a list of the compound classes boundaries (taken from formularity software) to overlay as patches, can include:
        'lipid-like'
        'carbohydrate-like'
        'unsaturated hydrocarbons'
        'condensed aromatics'
        'lignin-like'
        'tannin-like'
        'amino sugar-like'
        'protein-like'
    patch_alpha: the transparency of the compound class  (float between 0 and 1)
    patch_colors: hex values for the colors of each class in patch_classes 
    patch_text: boolean, include text labels on the compound class patches 
    
    
    **kwargs: other key word arguments to pass to plt.scatter()
      
    """ 
    if len(formula_lists) == 1: formula_lists = formula_lists[0] #this enables the user to pass a nested set of lists
    assert 'alpha' not in kwargs, 'provide a list of alpha values, alphas = ...'
    assert 'c' not in kwargs, 'provide a list of colour values, colours = ...'
    assert 'color' not in kwargs, 'provide a list of color values, colours = ...'
    assert 'marker' not in kwargs, 'provide a list of marker values, symbols = ...'
    assert 'edgecolors' not in kwargs, 'provide a list of edgecolors, edge_colours = ...'
    assert 'label' not in kwargs, 'provide a list of labels, group_labels = ...'
    
    #apply colour blind safe colors taken from https://colorbrewer2.org/ 
    cols = ['#7fc97f','#beaed4','#fdc086','#74add1','#fdae61','#abd9e9','#fee090','#e0f3f8','#ffffbf']
    sybls = ['o','X','s','D','+','1','^','v','8']
    
    
    if not group_labels: 
        group_labels = ['NA'] * len(formula_lists)
    if not colours:
        colours = [cols[i] for i in range(0,len(formula_lists))]
    if not symbols: 
        symbols = [sybls[i] for i in range(0,len(formula_lists))]
    if not alphas:
        alphas = [0.5] * len(formula_lists)
    if not edge_colours:
        edge_colours = ['None'] * len(formula_lists)
    
    assert len(formula_lists) == len(group_labels) == len(colours) == len(symbols) == len(alphas) == len(edge_colours), 'Input variables must all be the same length'

    i = 0 
    for formula_list in formula_lists: 

        x_axis = []
        y_axis = []

        ratio_list = element_ratios(formula_list, ratios = [x_ratio,y_ratio])

        for ratios in ratio_list:
                x_axis.append(ratios[x_ratio])
                y_axis.append(ratios[y_ratio])

        plt.scatter(x_axis, y_axis, alpha=alphas[i], edgecolors=edge_colours[i],c=colours[i], marker = symbols[i], label = group_labels[i], **kwargs)
        i += 1 
        
    #apply grid lines 
    plt.grid(True) 

    #add on chemical class patches
    #boundaries taken from formularity software
    assert len(patch_colors) >= len(patch_classes), "Provide at least as many colors as classes"
    cindx = 0 #index for the patch colours 
    if 'lipid-like' in patch_classes:
        plt.gca().add_patch(Rectangle((0.01,1.5),0.29,0.7,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.012,2.14,'Lipid',fontsize=11,alpha=1, color = 'k')
        cindx += 1 
    if 'carbohydrate-like' in patch_classes:
        plt.gca().add_patch(Rectangle((0.7,1.5),0.4,0.8,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.702,2.24,'Carbs',fontsize=11,alpha=1, color = 'k')
        cindx += 1 
    if 'unsaturated hydrocarbons' in patch_classes:
        plt.gca().add_patch(Rectangle((0.01,0.8),0.09,0.7,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.012,1.44,'Unsat HC',fontsize=11,alpha=1, color = 'k')
        cindx += 1
    if 'condensed aromatics' in patch_classes:
        plt.gca().add_patch(Rectangle((0.01,0.2),0.09,0.6,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.012,0.74,'Con HC',fontsize=11,alpha=1, color = 'k')
        cindx += 1 
    if 'lignin-like' in patch_classes:
        plt.gca().add_patch(Rectangle((0.1,0.8),0.6,0.8,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.102,1.54,'Lignin',fontsize=11,alpha=1, color = 'k')
        cindx += 1
    if 'tannin-like' in patch_classes:
        plt.gca().add_patch(Rectangle((0.7,0.8),0.5,0.8,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.702,1.54,'Tannin',fontsize=11,alpha=1, color = 'k')
        cindx += 1
    if 'amino sugar-like' in patch_classes:
        plt.gca().add_patch(Rectangle((0.6,1.5),0.1,0.7,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.602,2.14,'AminoSugar',fontsize=11,alpha=1, color = 'k')
        cindx += 1 
    if 'protein-like' in patch_classes:
        plt.gca().add_patch(Rectangle((0.3,1.5),0.3,0.8,linewidth=2,edgecolor =patch_colors[cindx],facecolor=patch_colors[cindx],alpha = patch_alpha))
        if patch_text: plt.text(0.302,2.24,'Protein',fontsize=11,alpha=1, color = 'k')
        cindx += 1
        
    #label axis
    plt.xlabel(f"Atomic ratio of {x_ratio[0]}/{x_ratio[1]}")
    plt.ylabel(f"Atomic ratio of {y_ratio[0]}/{y_ratio[1]}")
    
    fig = plt.gcf()
    ax = plt.gca()
    return fig,ax
maxBSReceives = 8

#maxX = 2 * maxDist * math.sin(60*(math.pi/180)) # == sqrt(3) * maxDist
maxX = 5 * maxDist * math.sin(60 * (math.pi / 180))
print "maxX ", maxX
#maxY = 2 * maxDist * math.sin(30*(math.pi/180)) # == maxdist
maxY = 5 * maxDist * math.sin(30 * (math.pi / 180))
print "maxY", maxY

# prepare graphics and add sink
if (graphics == 1):
    plt.ion()
    plt.figure()
    ax = plt.gcf().gca()

    ax.add_patch(Rectangle((0, 0), maxX, maxY, fill=None, alpha=1))

## Après optimisation du placement des bs

#On place juste les nodes sans créer de paquets virtuels (car ils dépendent de la position des bs)
for i in range(0, nrNodes):
    # myNode takes period (in ms), base station id packetlen (in Bytes)
    # 1000000 = 16 min
    node = myNode(i, avgSendTime, 20)
    node.placeNode(i)
    node.draw(i)
    nodes.append(node)

###MEAN SHIFT PART
original_X = node_positions
original_X = np.copy(original_X)
Ejemplo n.º 9
0
ax.set_ylim(0, pow(2, 16) - 1)
#ax.scatter(figsize=(12,12))

ax.scatter(x, y, facecolor='black', s=1, alpha=0.2)

print('Printing cells...')

for i, r in dfr.iterrows():
    cid = int(r['id'])

    if cid != -2:
        c = 'C{}'.format(cid)
        #print(c)
        rect = Rectangle((r['x'], r['y']),
                         r['s'],
                         r['s'],
                         edgecolor='gray',
                         facecolor=c,
                         alpha=0.25)
        ax.add_patch(rect)
    else:
        c = 'C{}'.format(cid)
        rect = Circle((r['x'], r['y']),
                      300,
                      edgecolor='red',
                      facecolor='None',
                      alpha=1)
        ax.add_patch(rect)

plt.show()

print('Done.')
Ejemplo n.º 10
0
def is_match(known_embedding, candidate_embedding):

    # calculate distance between embeddings
    score = cosine(known_embedding, candidate_embedding)

    return score


thresh = 0.35  #means looking for at least 65% similarity
print("Please note this machine only knows prashant")
group_array = plt.imread(group_photo)
plt.imshow(group_array)
for i in range(0, len(group_embedding)):
    pk_score = is_match(known_embedings[0], group_embedding[i])
    if pk_score < thresh:
        ax = plt.gca()
        x = face_coordinates[i][0]
        y = face_coordinates[i][1]
        width = face_coordinates[i][2]
        height = face_coordinates[i][3]

        rect = Rectangle((x, y), width, height, fill=False, color='red')
        ax.add_patch(rect)
        s = str((100 - pk_score * 100))
        ax.text(x, y, 'Prashant - ' + s, color='yellow')

plt.show()

model = VGGFace()
print(model.summary())
Ejemplo n.º 11
0
    def evolucionar(self,
                    iteraciones: int,
                    porcentaje_conv: float = 1.0,
                    retornar_gen=False):
        """
        Hace que la población evolucione, es decir, que se avance cierta cantidad de generaciones.

        Además del valor retornato, este método da las siguientes salidas:
        1.- Una gráfica donde se visualiza la evolución de la media, el mejor caso y el peor caso,
        de los valores de fitness, para todas las generaciones, antes de realizar la poda.
        2.- Una imagen donde se aprecia el escenario y el recorrido del mejor individuo de la última generación.

        :param iteraciones: Por cuántas generaciones se va a avanzar.
        :param porcentaje_conv: En qué porcentaje deben converger los mejores individuos de una generación,
        para cancelar el resto de las iteraciones.
        :param retornar_gen: (Opcional) Si es True, la cantidad de iteraciones que se llevaron a cabo y
        no se graficará nada.
        :return: La información del individuo más apto de la última generación.
        """
        if iteraciones < 1:
            raise ValueError('Valor de iteraciones erróneo.')
        elif not (0.0 < porcentaje_conv <= 1.0):
            raise ValueError(
                'El porcentaje de convergencia debe estar en el rango (0,1].')

        # Valores de fitness a graficar por cada iteración.
        minimos, maximos, promedios = [], [], []

        # Se guardan los datos estadísticos de la generación inicial.
        self.actualizar_salida_grafica(minimos, maximos, promedios)

        # Las generaciones avanzan.
        for i in range(1, iteraciones + 1):

            self.cruzar()  # 'mutar' es mandado a llamar por 'cruzar'.

            self.actualizar_salida_grafica(minimos, maximos, promedios)

            self.podar()

            # Se extraen los valores de fitness.
            fitnesses = [
                individuo.get_fitness() for individuo in self.poblacion
            ]
            ''' Si al menos, el porcentaje de individuos, especificado en 'porcentaje_conv',
                tienen el mejor valor de fitness (que no tenga ningún obstáculo/penalización);
                se considera que ya se ha convergido a la solución óptima,
                por lo que ya no es necesario seguir iterando. 
                Este chequeo se realiza, una vez, se haya llegado a la polbación máxima.'''
            if ((len(fitnesses) == self.tam_pob_max)
                    and (min(fitnesses) < self.penalizacion)
                    and ((fitnesses.count(min(fitnesses)) / len(fitnesses)) >=
                         porcentaje_conv)):
                break

            #print('Generación: {!s} - Población: {!s}'.format(i, len(fitnesses)))

        if retornar_gen:
            return i

        # El mejor individuo de la generación más reciente.
        mejor_ind = self.poblacion[-1]
        '''
            SE GRAFICAN LOS DATOS ESTADÍSTICOS DE LOS FITNESS.
        '''
        plt.clf()  # Se eliminan gráficas pasadas.
        # Se crea el arraglo con los valores del eje x.
        indices_iteraciones = np.arange(0, i + 1)
        # Se grafican los valores máximos, mínimos y los promedios.
        plt.plot(indices_iteraciones, maximos, lw=2, label='Peor caso')
        plt.plot(indices_iteraciones, minimos, lw=2, label='Mejor caso')
        plt.plot(indices_iteraciones, promedios, lw=2, label='Promedio')
        plt.legend()
        # Se agregan las etiquetas de los ejes y el título.
        plt.xlabel('Generación/Iteración')
        plt.ylabel('Fitness')
        plt.title('Evolución de los valores de fitness (antes de la poda)')
        # Se muestra una cuadrícula.
        plt.grid(True)
        '''
            SE GRAFICA EL ESCENARIO CON EL CAMINO DEL MEJOR INDIVIDUO DE LA ÚLTIMA GENERACIÓN.
        '''
        # Fenotipo del mejor individuo, el recorrido representado por él.
        fen_mejor_ind = mejor_ind.get_fenotipo()
        # Las coordenadas de los puntos, separadas por ejes.
        x_camino, y_camino = [], []
        for i in range(0, len(fen_mejor_ind), 2):
            x_camino.append(fen_mejor_ind[i])
            y_camino.append(fen_mejor_ind[i + 1])

        # Los obstáculos, como rectángulos, para ser graficados.
        rec_obstaculos = []
        for obst in self.escenario['obstaculos']:
            # Se guarda el obstáculo, como un rectángulo que puede ser graficado por Matplotlib.
            rec_obstaculos.append(
                Rectangle((obst['x'], obst['y']), obst['anchura'],
                          obst['altura']))
        fig, ax = plt.subplots()
        # Se grafican los obstáculos.
        pc = PatchCollection(rec_obstaculos, facecolor='black')
        ax.add_collection(pc)
        # Se grafica el camino del mejor individuo.
        ax.plot(x_camino, y_camino, marker='o')
        ax.plot(x_camino[0], y_camino[0], 'gX', label='Inicio')
        ax.plot(x_camino[-1], y_camino[-1], 'rX', label='Fin')
        # Se limitan los ejes.
        plt.xlim(0, self.escenario['tamano']['anchura'])
        plt.ylim(0, self.escenario['tamano']['altura'])
        # Se dibuja la cuadrícula.
        loc = plticker.MultipleLocator(base=1)
        ax.xaxis.set_major_locator(loc)
        ax.yaxis.set_major_locator(loc)
        # Se titula la gráfica.
        ax.set_title('Recorrido del mejor individuo de la última generación')
        # Se muestra la gráfica.
        plt.grid(True)
        plt.legend()
        plt.show()

        # Se devuelve la información del individuo más apto.
        return str(mejor_ind)
Ejemplo n.º 12
0
def plot_simulation(simulated,
                    camera_output,
                    fiber=0,
                    wavelength_min=None,
                    wavelength_max=None,
                    title=None,
                    min_electrons=2.5,
                    figsize=(11, 8.5),
                    label_size='medium'):
    """Plot simulation output tables for a single fiber.

    This function is normally called via :meth:`Simulator.plot` but is provided
    separately so that plots can be generated from results saved to a file.

    Use :meth:`show <matplotlib.pyplot.show` and :meth:`savefig
    <matplotlib.pyplot.savefig>` to show or save the resulting plot.

    See :doc:`/cmdline` for a sample plot.

    Requires that the matplotlib package is installed.

    Parameters
    ----------
    simulated : astropy.table.Table
        Simulation results on the high-resolution simulation wavelength grid.
    camera_output : list
        Lists of tables of per-camera simulation results tabulated on each
        camera's output pixel grid.
    fiber : int
        Fiber index to plot.
    wavelength_min : quantity or None
        Clip the plot below this wavelength, or show the full extent.
    wavelength_max : quantity or None
        Clip the plot above this wavelength, or show the full extent.
    title : str or None
        Descriptive title to use for the plot.
    min_electrons : float
        Minimum y-axis value for displaying numbers of detected electrons.
    figsize : tuple
        Tuple (width, height) specifying the figure size to use in inches.
        See :meth:`matplotlib.pyplot.subplots` for details.
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle

    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=figsize, sharex=True)
    if title is not None:
        ax1.set_title(title)

    waveunit = '{0:Generic}'.format(simulated['wavelength'].unit)
    fluxunit = '{0:Generic}'.format(simulated['source_flux'].unit)
    wave = simulated['wavelength'].data
    dwave = np.gradient(wave)

    # Validate the optional wavelength limits and convert to waveunit.
    def validate(name, limit):
        if limit is None:
            return limit
        try:
            return limit.to(waveunit).value
        except AttributeError:
            raise ValueError('Missing unit for {0}.'.format(name))
        except u.UnitConversionError:
            raise ValueError('Invalid unit for {0}.'.format(name))

    wavelength_min = validate('wavelength_min', wavelength_min)
    wavelength_max = validate('wavelength_max', wavelength_max)
    if wavelength_min and wavelength_max and wavelength_min >= wavelength_max:
        raise ValueError('Expected wavelength_min < wavelength_max.')

    # Create a helper function that returns a slice that limits the
    # wavelength array w (with units) to wavelenth_min <= w <= wavelength_max.
    # Returns None if all w < wavelength_min or all w > wavelength_max.
    def get_slice(w):
        assert np.all(np.diff(w) > 0)
        if wavelength_min is None:
            start = 0
        elif wavelength_min > w[-1]:
            return None
        else:
            start = np.where(w >= wavelength_min)[0][0]
        if wavelength_max is None:
            stop = len(w)
        elif wavelength_max < w[0]:
            return None
        else:
            stop = np.where(w <= wavelength_max)[0][-1] + 1
        return slice(start, stop)

    # Trim the full wavelength grid.
    waves = get_slice(wave)
    if waves is None:
        raise ValueError('Wavelength limits do not overlap simulation grid.')
    wave = wave[waves]
    dwave = dwave[waves]

    # Plot fluxes above the atmosphere and into the fiber.

    src_flux = simulated['source_flux'][waves, fiber]
    src_fiber_flux = simulated['source_fiber_flux'][waves, fiber]
    sky_fiber_flux = simulated['sky_fiber_flux'][waves, fiber]

    ymin, ymax = 0.1 * np.min(src_flux), 10. * np.max(src_flux)
    if ymin <= 0:
        # Need ymin > 0 for log scale.
        ymin = 1e-3 * ymax

    line, = ax1.plot(wave, src_flux, 'r-')
    ax1.fill_between(wave,
                     src_fiber_flux + sky_fiber_flux,
                     ymin,
                     color='b',
                     alpha=0.2,
                     lw=0)
    ax1.fill_between(wave, src_fiber_flux, ymin, color='r', alpha=0.2, lw=0)

    # This kludge is because the label arg to fill_between() does not
    # propagate to legend() in matplotlib < 1.5.
    sky_fill = Rectangle((0, 0), 1, 1, fc='b', alpha=0.2)
    src_fill = Rectangle((0, 0), 1, 1, fc='r', alpha=0.2)
    ax1.legend(
        (line, sky_fill, src_fill),
        ('Source above atmosphere', 'Sky into fiber', 'Source into fiber'),
        loc='best',
        fancybox=True,
        framealpha=0.5,
        ncol=3,
        fontsize=label_size)

    ax1.set_ylim(ymin, ymax)
    ax1.set_yscale('log')
    ax1.set_ylabel('Flux [{0}]'.format(fluxunit))

    # Plot numbers of photons into the fiber.

    nsky = simulated['num_sky_photons'][waves, fiber] / dwave
    nsrc = simulated['num_source_photons'][waves, fiber] / dwave
    nmax = np.max(nsrc)

    ax2.fill_between(wave,
                     nsky + nsrc,
                     1e-1 * nmax,
                     color='b',
                     alpha=0.2,
                     lw=0)
    ax2.fill_between(wave, nsrc, 1e-1 * nmax, color='r', alpha=0.2, lw=0)

    ax2.legend((sky_fill, src_fill), ('Sky into fiber', 'Source into fiber'),
               loc='best',
               fancybox=True,
               framealpha=0.5,
               ncol=2,
               fontsize=label_size)

    ax2.set_ylim(1e-1 * nmax, 10. * nmax)
    ax2.set_yscale('log')
    ax2.set_ylabel('Mean photons / {0}'.format(waveunit))
    ax2.set_xlim(wave[0], wave[-1])

    # Plot numbers of electrons detected by each CCD.

    for output in camera_output:

        cwave = output['wavelength'].data
        dwave = np.gradient(cwave)
        # Trim to requested wavelength range.
        waves = get_slice(cwave)
        if waves is None:
            # Skip any cameras outside the requested wavelength range.
            continue
        cwave = cwave[waves]
        dwave = dwave[waves]
        nsky = output['num_sky_electrons'][waves, fiber] / dwave
        nsrc = output['num_source_electrons'][waves, fiber] / dwave
        ndark = output['num_dark_electrons'][waves, fiber] / dwave
        read_noise = (output['read_noise_electrons'][waves, fiber] /
                      np.sqrt(dwave))
        total_noise = (np.sqrt(output['variance_electrons'][waves, fiber] /
                               dwave))
        nmax = max(nmax, np.max(nsrc))

        ax3.fill_between(cwave,
                         ndark + nsky + nsrc,
                         min_electrons,
                         color='b',
                         alpha=0.2,
                         lw=0)
        ax3.fill_between(cwave,
                         ndark + nsrc,
                         min_electrons,
                         color='r',
                         alpha=0.2,
                         lw=0)
        ax3.fill_between(cwave,
                         ndark,
                         min_electrons,
                         color='k',
                         alpha=0.2,
                         lw=0)
        ax3.scatter(cwave, total_noise, color='k', lw=0., s=0.5, alpha=0.5)
        line2, = ax3.plot(cwave, read_noise, color='k', ls='--', alpha=0.5)

    if camera_output:
        # This kludge is because the label arg to fill_between() does not
        # propagate to legend() in matplotlib < 1.5.
        line1, = ax3.plot([], [], 'k-')
        dark_fill = Rectangle((0, 0), 1, 1, fc='k', alpha=0.2)
        ax3.legend((sky_fill, src_fill, dark_fill, line1, line2),
                   ('Sky detected', 'Source detected', 'Dark current',
                    'RMS total noise', 'RMS read noise'),
                   loc='best',
                   fancybox=True,
                   framealpha=0.5,
                   ncol=5,
                   fontsize=label_size)

        ax3.set_ylim(min_electrons, 2e2 * min_electrons)
        ax3.set_yscale('log')
        ax3.set_ylabel('Mean electrons / {0}'.format(waveunit))
        ax3.set_xlim(wave[0], wave[-1])
        ax3.set_xlabel('Wavelength [{0}]'.format(waveunit))

    # Remove x-axis ticks on the upper panels.
    plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)

    fig.patch.set_facecolor('white')
    plt.tight_layout()
Ejemplo n.º 13
0
 def updatePlot(self, poles, cable, printPdf=False):
     scale = 1
     legendCol = 4
     fontSize = 12
     if printPdf:
         legendCol = 3
         scale = 0.5
         fontSize = 8
     
     # current Zoom
     xlim = self.axes.get_xlim()
     ylim = self.axes.get_ylim()
     
     self.axes.clear()
     self.__setupAxes()
     # Terrain
     self.axes.plot(self.xdata, self.terrain, color='#a1d1ab',
                    linewidth=3.5*scale, zorder=1)
     # Mark survey points when working with CSV height data
     if self.tPoints is not None:
         # Add markers for survey points
         for pointX, pointY, idx, notes in zip(self.tPoints['d'],
                                               self.tPoints['z'],
                                               self.tPoints['nr'],
                                               self.tPoints['notes']):
             self.axes.plot([pointX, pointX],
                            [pointY, pointY - 6 * self.labelBuffer * scale],
                            color='green', linewidth=1.5 * scale, zorder=2)
             labelText = f"{idx}"
             rot = 0
             ha = 'center'
             va = 'top'
             if notes:
                 labelText = f"{idx}{':' if notes else ''} {notes if len(notes) <= 25 else notes[:22] + '...'}"
                 # For less placement issues, labels are rotated 45°
                 rot = 55
                 ha = 'right'
                 va = 'center'
                 # Label rotation is switched if profile line inclines
                 if self.terrain[0] < self.terrain[-1]:
                     rot = 305
                     ha = 'left'
             self.axes.text(pointX, pointY - 7 * self.labelBuffer * scale,
                            labelText, ha=ha, va=va, fontsize=fontSize,
                            color='green', rotation=rot, rotation_mode='anchor')
     
     if not printPdf:
         # Well suited locations (peaks) for poles
         self.axes.scatter(self.peakLoc_x, self.peakLoc_y, marker='^',
                           color='#ffaa00', edgecolors='#496b48',
                           label=self.tr('Guenstige Gelaendeform'), zorder=3)
     # Cable lines
     self.axes.plot(cable['xaxis'], cable['empty'], color='#4D83B2',
                    linewidth=1.5*scale, label=self.tr('Leerseil'))
     self.axes.plot(cable['xaxis'], cable['load'], color='#FF4D44',
                    linewidth=1.5*scale, label=self.tr('Lastwegkurve nach Zweifel'))
     # Anchors
     if cable['anchorA']:
         self.axes.plot(cable['anchorA']['d'], cable['anchorA']['z'],
                        color='#a6a6a6', linewidth=1.5*scale)
     if cable['anchorE']:
         self.axes.plot(cable['anchorE']['d'], cable['anchorE']['z'],
                        color='#a6a6a6', linewidth=1.5*scale)
     # Ground clearance
     self.axes.plot(cable['groundclear_di'], cable['groundclear'],
                    color='#910000', linewidth=1*scale, linestyle=':',
                    label=self.tr('Min. Bodenabstand'))
     self.axes.plot(cable['groundclear_di'], cable['groundclear_under'],
                    color='#910000', linewidth=1*scale)
         
     # Poles
     [pole_d, pole_z, pole_h, pole_dtop, pole_ztop, pole_nr, poleType] = poles
     for i, d in enumerate(pole_d):
         self.axes.plot([pole_d[i], pole_dtop[i]], [pole_z[i], pole_ztop[i]],
                        color='#363432', linewidth=3.0*scale)
         if poleType[i] == 'crane':
             h = 3.5
             w = h * 1.8
             rect = Rectangle((pole_d[i] - w/2, pole_z[i]), w, h, ls='-',
                              lw=3.0*scale, facecolor='black', ec='black', zorder=5)
             self.axes.add_patch(rect)
     # Vertical guide lines
     if self.isZoomed:
         d = self.currentPole['d']
         z = self.currentPole['z']
         ztop = self.currentPole['ztop']
         self.axes.axvline(lw=1, ls='dotted', color='black', x=d)
         self.axes.axhline(lw=1, ls='dotted', color='black', y=z)
         self.axes.axhline(lw=1, ls='dotted', color='black', y=ztop)
     
     # Data limit of axis
     # self.setPlotLimits()
     # Add labels
     if not printPdf:
         self.placeLabels(pole_dtop, pole_ztop, pole_nr)
     # Legend
     self.axes.legend(loc='lower center', fontsize=fontSize,
                      bbox_to_anchor=(0.5, 0), ncol=legendCol)
     
     self.axes.set_xlim(xlim)
     self.axes.set_ylim(ylim)
     self.draw()
     # Set new plot extent as home extent (for home button)
     if not printPdf:
         self.tbar.update()
         self.tbar.push_current()
Ejemplo n.º 14
0
def draw_heatmap_obim(
        result_image_name,
        input_files,
        baseline_files,
        titles,
        small_delta,
        xcolticks=[],
        ycolticks=[],
):
    fig, axn = plt.subplots(2, len(input_files), sharey='row')

    file_mul = .32
    cbar_ax = fig.add_axes([ file_mul * len(input_files) + .11, 0.73, .03, .35])
    cbar_ax2 = fig.add_axes([ file_mul * len(input_files) + .11, 0.17, .03, .35])


    ticks_delta = [0.5, 1.5, 2.5, 3.5, 4.5]
    ticks_chunks = [0.5, 1.5, 2.5, 3.5, 4.5]
    deltas = [0, 2, 4, 8, 10] if small_delta else [10, 12, 14, 16, 18]
    chunks = ['$2^{5}$', '$2^{6}$', '$2^{7}$', '$2^{8}$', '$2^{9}$']

    max_t = 0
    min_t = 1000
    max_n = 0
    min_n = 1000
    for i, file in enumerate(input_files):
        (time_hmq, nodes_hmq) = find_avg_hmq(baseline_files[i])
        #print(time_div, nodes_div)
        (hm, hm_n) = obimheatmap2array(file, time_hmq, nodes_hmq, small_delta)
        max_t_id_i = 0
        max_t_id_j = 0
        max_t_local = 0
        for k in range(0, len(hm)):
            for j in range(0, len(hm[k])):
                val = hm[k][j]
                if val > max_t:
                    max_t = val
                if val > max_t_local:
                    max_t_local = val
                    max_t_id_i = k
                    max_t_id_j = j
                if val < min_t:
                    min_t = val
                if hm_n[k][j] > max_n:
                    max_n = hm_n[k][j]
                if hm_n[k][j] < min_n:
                    min_n = hm_n[k][j]
        cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#990000", "#ffff00", "#38761d"])
        cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#38761d", "#ffff00", "#990000"])


        print(titles[i] + ": {" + str(2 ** max_t_id_j) + ", " + str(2 **max_t_id_i) + "} " + str(hm[max_t_id_i][max_t_id_j]))
        fmt = lambda x,pos: '{:.2f}'.format(x)

        thm = sns.heatmap(hm, ax=axn[0][i], center=1, cmap=cmap,
                          vmin=min_t, vmax=max_t, annot=True, fmt=".1f",
                          linewidths=.7, square=True, cbar_ax=cbar_ax,
                          cbar_kws={
                              'format': FuncFormatter(fmt),
                              'label' : 'Speedup',
                              'ticks' : [min_t, *xcolticks, max_t]
                          }
                          )

        nhm = sns.heatmap(hm_n, ax=axn[1][i], center=1, cmap=cmap2,
                          vmin=min_n, vmax=max_n, annot=True, fmt=".1f",
                          linewidths=.7, square=True, cbar_ax=cbar_ax2,
                          cbar_kws={
                              'format': FuncFormatter(fmt),
                              'label' : 'Work Increase',
                              'ticks' : [min_n, *ycolticks, max_n]
                          }
                          )
        thm.xaxis.set_ticks_position('top')
        nhm.xaxis.set_ticks_position('top')

        thm.add_patch(Rectangle((max_t_id_j, max_t_id_i), 1, 1, fill=False, edgecolor='black', lw=1.2))
        nhm.add_patch(Rectangle((max_t_id_j, max_t_id_i), 1, 1, fill=False, edgecolor='black', lw=1.2))

        axn[0][i].set_xticks(ticks_chunks)
        axn[1][i].set_xticks(ticks_chunks)
        axn[0][i].set_xticklabels(chunks, rotation=30, fontsize=12)
        axn[1][i].set_xticklabels(chunks, rotation=30, fontsize=12)


        axn[0][i].set_yticks(ticks_delta)
        axn[1][i].set_yticks(ticks_delta)
        axn[0][i].set_yticklabels([str(d) for d in deltas])
        axn[1][i].set_yticklabels(deltas)

        fs = 13
        axn[0][i].set_xlabel('chunk size', fontsize=fs)
        axn[1][i].set_xlabel('chunk size', fontsize=fs)

    fig.axes[-1].yaxis.label.set_size(15)
    fig.axes[-2].yaxis.label.set_size(15)
    for i in range(0, len(input_files)):
        axn[0][i].set_title(titles[i], fontsize=13, pad=17)
    fig.tight_layout(rect=[0, 0, len(input_files) * file_mul + .1, 1.3])

    for ax in axn[0]:
        ax.set_yticklabels([str(d) for d in deltas])
    axn[0][0].set_ylabel('delta', fontsize=fs)
    axn[1][0].set_ylabel('delta', fontsize=fs)

    plt.show()
    fig.savefig(result_image_name + ".png", bbox_inches="tight", transparent=True)
        ax.set_ylabel("Number of Pixels")
        if nside == 64:
            ax.set_ylim([8e-1, 2e3])
        #else:
        #    ax.set_ylim([8e-1, 1.5e5])
        ax.set_yscale("symlog")
        xlms = ax.get_xlim()
        ylms = ax.get_ylim()

        # Legend options
        mpl.rcParams['legend.loc'] = 'best'

        dummyHandle = Rectangle((0, 0),
                                1,
                                1,
                                fc="w",
                                fill=False,
                                edgecolor='none',
                                linewidth=0)

        if args.plotFit:
            lg = ax.legend([A[2][0], expPlot, fitPlot, dummyHandle], [
                "Data", "Expectation", "Fit",
                "mean = %.3f $\pm$ %.3f \nwidth = %.3f $\pm$ %.3f" %
                (mean, meanerr, sigma, sigmaerr)
            ])
            fitParam = lg.get_texts()[3]
            fitParam.set_color('green')
            fitParam._fontproperties = lg.get_texts()[0]._fontproperties.copy()
            fitParam.set_size('medium')
        else:
from matplotlib.backends.backend_agg import FigureCanvasAgg

figsize = 4.25, 5 * 0.55
xlim = 0.0, 11.0
ylim = 0.5, 5.0
dx = figsize[0] / (xlim[1] - xlim[0])
dy = figsize[1] / (ylim[1] - ylim[0])
widths = 1, 2, 3, 4, 5, 6
w, h = 0.75 * 10 / len(widths), 0.5
figsize = w * dx, h * dy
dpi = 600

for width in widths:
    plt.rcParams["hatch.linewidth"] = width
    fig = plt.figure(figsize=figsize, dpi=dpi)
    ax = fig.add_axes([0, 0, 1, 1], xlim=[0, 1], ylim=[0, 1])
    ax.axis("off")
    canvas = FigureCanvasAgg(fig)
    rect = Rectangle((0, 0),
                     1,
                     1,
                     hatch="/",
                     facecolor="0.85",
                     edgecolor="0.00",
                     linewidth=0.0)
    ax.add_patch(rect)
    canvas.draw()
    image = np.frombuffer(canvas.tostring_rgb(), dtype="uint8")
    image = image.reshape(int(figsize[1] * dpi), int(figsize[0] * dpi), 3)
    imageio.imwrite("hatch-%d.png" % width, image)
Ejemplo n.º 17
0
    def draw_court(ax=None, color="blue", lw=1, outer_lines=False):

        if ax is None:
            ax = plt.gca()

        #Basketball Hoop
        hoop = Circle((0, 0),
                      radius=7.5,
                      linewidth=lw,
                      color=color,
                      fill=False)
        #backboard
        backboard = Rectangle((-30, -12.5), 60, 0, linewidth=lw, color=color)
        #the paiint
        #outer box
        outer_box = Rectangle((-80, -47.5),
                              160,
                              190,
                              linewidth=lw,
                              color=color,
                              fill=False)
        #inner box
        inner_box = Rectangle((-60, -47.5),
                              120,
                              190,
                              linewidth=lw,
                              color=color,
                              fill=False)
        #freethrow top arc
        top_free_throw = Arc((0, 142.5),
                             120,
                             120,
                             theta1=0,
                             theta2=180,
                             linewidth=lw,
                             color=color,
                             fill=False)
        #freethrow bottom arc
        bottom_free_throw = Arc((0, 142.5),
                                120,
                                120,
                                theta1=180,
                                theta2=0,
                                linewidth=lw,
                                color=color)
        #restricted zone
        restricted = Arc((0, 0),
                         80,
                         80,
                         theta1=0,
                         theta2=180,
                         linewidth=lw,
                         color=color)
        #three point line
        corner_three_a = Rectangle((-220, -47.5),
                                   0,
                                   140,
                                   linewidth=lw,
                                   color=color)
        corner_three_b = Rectangle((220, -47.5),
                                   0,
                                   140,
                                   linewidth=lw,
                                   color=color)
        three_arc = Arc((0, 0),
                        475,
                        475,
                        theta1=22,
                        theta2=158,
                        linewidth=lw,
                        color=color)
        #center court
        center_outer_arc = Arc((0, 422.5),
                               120,
                               120,
                               theta1=180,
                               theta2=0,
                               linewidth=lw,
                               color=color)
        center_inner_arc = Arc((0, 422.5),
                               40,
                               40,
                               theta1=180,
                               theta2=0,
                               linewidth=lw,
                               color=color)

        court_elements = [
            hoop, backboard, outer_box, inner_box, top_free_throw,
            bottom_free_throw, restricted, corner_three_a, corner_three_b,
            three_arc, center_outer_arc, center_inner_arc
        ]

        outer_lines = True
        if outer_lines:
            outer_lines = Rectangle((-250, -47.5),
                                    500,
                                    470,
                                    linewidth=lw,
                                    color=color,
                                    fill=False)
            court_elements.append(outer_lines)

        for element in court_elements:
            ax.add_patch(element)
Ejemplo n.º 18
0
        fig = plt.figure()
        ax = fig.add_subplot(111)

        plt_x = []
        plt_y = []
        for p in points_plants:
            plt_x.append(p["x"])
            plt_y.append(p["y"])

            # draw rect around radius
            r = int(p["radius"])
            ax.add_patch(
                Rectangle(
                    xy=(p["x"] - r, p["y"] - r),
                    width=r * 2,
                    height=r * 2,
                    linewidth=2,
                    color="g",
                    fill=False,
                ))
        ax.scatter(plt_x, plt_y, color=next(cycol), s=10)

        # Add rectangles using resulting points as center
        for p in points:
            ax.add_patch(
                # xy (bottom-left) uses coverage/2 area and offset for each axis to calc
                Rectangle(
                    xy=(
                        p["x"] - (cover["x"] / 2) + offset["x"],
                        p["y"] - (cover["y"] / 2) + offset["y"],
                    ),
                    width=cover["x"],
Ejemplo n.º 19
0
 def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
                    height, fontsize, trans):
     p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height)
     self.update_prop(p, orig_handle, legend)
     p.set_transform(trans)
     return [p]
Ejemplo n.º 20
0
 def AddListenPatch(self, start_t, end_t, center_frequency_hz,
                    bandwidth_hz):
     self.update_range(center_frequency_hz, bandwidth_hz)
     p = Rectangle((start_t, center_frequency_hz - (bandwidth_hz / 2)),
                   end_t - start_t, bandwidth_hz)
     self.rx_patches.append(p)
    def addItem(self, x, y, legend, shape, color, fill, overlay, z):
        xView = numpy.array(x, copy=False)
        yView = numpy.array(y, copy=False)

        if shape == "line":
            item = self.ax.plot(x,
                                y,
                                label=legend,
                                color=color,
                                linestyle='-',
                                marker=None)[0]

        elif shape == "hline":
            if hasattr(y, "__len__"):
                y = y[-1]
            item = self.ax.axhline(y, label=legend, color=color)

        elif shape == "vline":
            if hasattr(x, "__len__"):
                x = x[-1]
            item = self.ax.axvline(x, label=legend, color=color)

        elif shape == 'rectangle':
            xMin = numpy.nanmin(xView)
            xMax = numpy.nanmax(xView)
            yMin = numpy.nanmin(yView)
            yMax = numpy.nanmax(yView)
            w = xMax - xMin
            h = yMax - yMin
            item = Rectangle(xy=(xMin, yMin),
                             width=w,
                             height=h,
                             fill=False,
                             color=color)
            if fill:
                item.set_hatch('.')

            self.ax.add_patch(item)

        elif shape in ('polygon', 'polylines'):
            points = numpy.array((xView, yView)).T
            if shape == 'polygon':
                closed = True
            else:  # shape == 'polylines'
                closed = numpy.all(numpy.equal(points[0], points[-1]))
            item = Polygon(points,
                           closed=closed,
                           fill=False,
                           label=legend,
                           color=color)
            if fill and shape == 'polygon':
                item.set_hatch('/')

            self.ax.add_patch(item)

        else:
            raise NotImplementedError("Unsupported item shape %s" % shape)

        item.set_zorder(z)

        if overlay:
            item.set_animated(True)
            self._overlays.add(item)

        return item
Ejemplo n.º 22
0
 def AddRxCorrectCircle(self, start_t, end_t, center_frequency_hz,
                        bandwidth_hz):
     self.update_range(center_frequency_hz, bandwidth_hz)
     p = Rectangle((start_t, center_frequency_hz - (bandwidth_hz / 2)),
                   end_t - start_t, bandwidth_hz)
     self.tx_correct_patches.append(p)
Ejemplo n.º 23
0
def plot(figwidth, figheight, refseqtrack, LeftToRight, strand, depths, colors,
         shade, limits, bedtrack, start, stop, staggerbed, bigwignames,
         wig_df_list, shade_by_bed, output_folder, geneid, outputsuffix,
         outputformat, dpi, track_names, axis_off, legend, staticaxes, bedfile,
         bedtype, name, chrom, refseqid, annotate_bed, fontsize):

    ###### RUN TO PLOT! ######

    print "Figure will be saved as: %s%s%s.%s" % (output_folder, geneid,
                                                  outputsuffix, outputformat)

    # DON'T MODIFY
    # Note: Need to clean up
    tracks_to_use = range(len(track_names))
    wigtracks_to_use = range(len(bigwignames))
    seqtracks = len(tracks_to_use)
    bedtracks = int(bedtrack)
    wigtracks = len(wigtracks_to_use)
    num_of_tracks = len(tracks_to_use) + int(bedtrack) + len(
        wigtracks_to_use) + refseqtrack
    height_ratios = ([3] * seqtracks + ([0.4] * bedtracks) + [1] * wigtracks +
                     [1] * refseqtrack)
    if figwidth == 0:
        figwidth = (stop - start) / 110
    if limits == 'default':
        limits = [start, stop]

    myfont = {'size': fontsize}
    rc('font', **myfont)

    # Initialize Figure
    fig, ax = plt.subplots(1)
    fig.set_figwidth(figwidth)
    fig.set_figheight(figheight)

    gs = gridspec.GridSpec(seqtracks + bedtracks + wigtracks + refseqtrack,
                           1,
                           height_ratios=height_ratios)
    plotnumber = iter(range(len(height_ratios)))

    # check invert
    invert = False
    if LeftToRight and strand == "-":
        invert = True

    cur_axes = plt.gca()

    ymax = max(depths.max())
    # Build RNAseq Tracks
    cur_axes_rna = []
    for n in tracks_to_use:
        color = colors.next()
        plt.subplot(gs[plotnumber.next()])
        plt.plot(depths.loc[:, track_names[n]], color=color, linewidth=1)
        plt.fill_between(depths.index,
                         depths.loc[:, track_names[n]].tolist(),
                         color=shade.next(),
                         edgecolor='none')
        plt.xlim(limits)
        cur_axes_rna.append(plt.gca())
        cur_axes_rna[n].axes.get_xaxis().set_visible(False)
        cur_axes_rna[n].axes.get_yaxis().set_ticks(cur_axes_rna[n].get_ylim())
        if axis_off:
            cur_axes_rna[n].axes.axis("off")
        if invert:
            cur_axes_rna[n].invert_xaxis()
        plt.tick_params(labelsize=fontsize)
        if legend:
            red_patch = mpatches.Patch(color=color, label=track_names[n])
            plt.legend(handles=[red_patch], fontsize=fontsize)
        if not staticaxes:
            plt.ylim([0, ymax])

    # Build Bedtracks
    if bedtrack:
        plt.subplot(gs[plotnumber.next()])
        bedregions, bedlabels = graph_bed(bedfile,
                                          bedtype,
                                          name,
                                          chrom,
                                          start,
                                          stop,
                                          strand,
                                          stagger=staggerbed)
        cur_axes = plt.gca()
        cur_axes.axes.get_xaxis().set_visible(False)
        cur_axes.axes.get_yaxis().set_ticks([])
        if axis_off:
            cur_axes.axes.axis("off")
        if invert:
            cur_axes.invert_xaxis()
        plt.ylabel(name,
                   rotation=0,
                   horizontalalignment="right",
                   verticalalignment="center")
        plt.xlim(limits)
        if staggerbed:
            plt.ylim([-1, 2])

    # Build Bigwig Tracks
    if len(wigtracks_to_use) > 0:
        for n in wigtracks_to_use:
            plt.subplot(gs[plotnumber.next()])
            color = colors.next()
            wigdepths = graph_wig(wig_df_list[bigwignames[n]], name, chrom,
                                  start, stop)
            cur_axes = plt.gca()
            cur_axes.axes.get_xaxis().set_visible(False)
            cur_axes.axes.get_yaxis().set_ticks([])
            if axis_off:
                cur_axes.axes.axis("off")
            if invert:
                cur_axes.invert_xaxis()
            plt.fill_between(wigdepths.index,
                             wigdepths["expression"].tolist(),
                             color=color)
            plt.ylabel(bigwignames[n],
                       rotation=0,
                       horizontalalignment="right",
                       verticalalignment="center")
            # To get relative ylim.. has weird values.
            wig_ylim = [
                wig_df_list[bigwignames[n]]["expression"].min(),
                wig_df_list[bigwignames[n]]["expression"].max()
            ]
            # Try again with just -3:3
            wig_ylim = [-3, 3]
            plt.ylim(wig_ylim)
            plt.xlim(limits)

    # Build Refseq Track
    if refseqtrack:
        plt.subplot(gs[plotnumber.next()])
        graphRefseq(refseqid,
                    xlim=limits,
                    strand=strand,
                    LeftToRight=LeftToRight)
        plt.ylabel(chrom,
                   rotation=0,
                   horizontalalignment="right",
                   verticalalignment="center")
        cur_axes = plt.gca()

    if shade_by_bed:
        for b in bedregions:
            for n in tracks_to_use:
                # Rectangle(<start(xy)>,<width>,<height>)
                cur_axes_rna[n].add_patch(
                    Rectangle((b[0] - 10, 0),
                              20,
                              ymax,
                              facecolor="#e2e2e2",
                              edgecolor='none',
                              alpha=0.7))

    #cur_axes.axes.get_yaxis().set_visible(False)
    cur_axes.axes.get_yaxis().set_ticks([])
    plt.xlabel(geneid)
    plt.ylabel(chrom)
    if axis_off:
        cur_axes.axes.spines['top'].set_visible(False)
        cur_axes.axes.spines['right'].set_visible(False)
        cur_axes.axes.spines['bottom'].set_visible(False)
        cur_axes.axes.spines['left'].set_visible(False)
        plt.xticks(visible=False)

    if invert:
        cur_axes.invert_xaxis()

    if bedtrack:
        # Remove duplicate bed entries
        bedannotations = zip(bedlabels, bedregions)
        bedannotations.sort()
        bedannotations = list(i for i, _ in itertools.groupby(bedannotations))
        print "======\nRegions\n======"
        for label, x in bedannotations:
            print label, x
            if annotate_bed:
                plt.annotate(label,
                             xy=(np.mean(x), 0),
                             xytext=(0, -45),
                             textcoords='offset points',
                             ha='right',
                             va='top',
                             rotation=45,
                             bbox=dict(boxstyle='round,pad=0.5',
                                       fc='yellow',
                                       alpha=0.5),
                             arrowprops=dict(arrowstyle='-',
                                             connectionstyle='arc3,rad=0'))
    #plt.gca().invert_xaxis()
    #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=0.2)
    plt.savefig("%s%s%s.%s" %
                (output_folder, geneid, outputsuffix, outputformat),
                format=outputformat,
                bbox_inches='tight',
                dpi=dpi)
    return plt
Ejemplo n.º 24
0
             linestyle=linestyle,
             label=label,
             linewidth=3)

    print(key, perc_10, perc_50, perc_90)

superluminal_mu, superluminal_std = 0.30, 0.02
superluminal_mu = 180 - superluminal_mu * 360.0 / (2 * np.pi)
superluminal_std = superluminal_std * 360.0 / (2 * np.pi)
plt.plot([superluminal_mu, superluminal_mu], [0, 1],
         alpha=0.3,
         color='g',
         label='Superluminal')
rect1 = Rectangle((superluminal_mu - superluminal_std, 0),
                  2 * superluminal_std,
                  0.05,
                  alpha=0.8,
                  color='g')
rect2 = Rectangle((superluminal_mu - 2 * superluminal_std, 0),
                  4 * superluminal_std,
                  0.05,
                  alpha=0.5,
                  color='g')

gws_mu, gws_std = 152, 14
plt.plot([gws_mu, gws_mu], [0, 1], alpha=0.3, color='r', label='GW')
rect3 = Rectangle((gws_mu - gws_std, 0),
                  2 * gws_std,
                  0.05,
                  alpha=0.3,
                  color='r')
Ejemplo n.º 25
0
def plot_block(block, utc_offset=0):
    """Visualize time usage of one observation block.

    Parameters
    -------
    block : obsplanner.scheduler.ObsBlock
        Observing block that should be visualized.
    utc_offset : int, default=0
        UTC offset for the time zone the telescope is located in. Used to show
        the local time on the x-axis.

    Returns
    -------
    fig : matplotlib.figure.Figure
        The created figure.
    """

    linewidth = 1
    linestyle = '-'
    edgecolor = 'k'
    y = 1.2

    gridspec_kw = {'width_ratios': (5, 1), 'wspace': 0.2}
    fig, ax = plt.subplots(1, 2, figsize=(16, 9), gridspec_kw=gridspec_kw)

    # plot block:
    x = block.time_start.to_value('mjd')
    width = block.duration.to_value('d')
    rect = Rectangle((x, 0),
                     width,
                     y,
                     fill=False,
                     linewidth=linewidth,
                     linestyle=linestyle,
                     edgecolor=edgecolor)
    ax[0].add_patch(rect)

    # plot slew times:
    for i, slew in enumerate(block.get_slew_periods()):
        ax_add_slew(slew, ax[0])

    # plot observations:
    for i, obs in enumerate(block.get_observations()):
        ax_add_obs(obs, ax[0])

    # edit time axis:
    xmin = block.time_start.to_value('mjd') - 1. / 24
    xmax = block.time_stop.to_value('mjd') + 1. / 24
    ax[0].set_xlim(xmin, xmax)
    ax[0].xaxis.set_major_locator(MultipleLocator(1. / 12))
    #ax[0].tick_params(
    #        axis='y', which='both', left=False, right=False,
    #        labelleft=False)
    ax[0].set_yticks([0.15, 0.65, 1.1])
    ax[0].set_yticklabels(['Slew periods', 'Obs. periods', 'Obs. block'])
    ax[0].set_ylim(0, 1.5)
    locs = ax[0].get_xticks()
    time_utc = np.round(np.mod(locs, 1) * 24., 0)
    time_loc = time_utc + utc_offset
    labels = ['{0:.0f}\n{1:.0f}'.format(utc, loc) \
              for (utc, loc) in zip(time_utc, time_loc)]
    ax[0].set_xticklabels(labels)
    ax[0].text(-0.06,
               -0.03,
               'UTC',
               horizontalalignment='left',
               transform=ax[0].transAxes)
    ax[0].text(-0.06,
               -0.05,
               'UTC{0:+d}'.format(utc_offset),
               horizontalalignment='left',
               transform=ax[0].transAxes)
    label = block.time_start.value[:10]
    ax[0].set_xlabel(label)

    # bar plots:
    time_obs = block.time_obs.to_value('h')
    time_slew = block.time_slew.to_value('h')
    time_slew_idle = block.time_slew_idle.to_value('h')
    time_idle = block.time_idle.to_value('h')
    time_tot = block.duration.to_value('h')
    ax[1].bar([1, 2, 3, 4], [time_obs, time_slew, time_slew_idle, time_idle],
              color=['0.6', '0.7', '0.8', 'w'],
              linestyle=linestyle,
              linewidth=linewidth,
              edgecolor='k')
    offset = 0.01 * ax[1].get_ylim()[1]
    ratio_obs = time_obs / time_tot
    ratio_slew = time_slew / time_tot
    ratio_slew_idle = time_slew_idle / time_tot
    ratio_idle = time_idle / time_tot
    ax[1].text(1,
               time_obs + offset,
               '{0:0.1f} %'.format(ratio_obs * 100.),
               horizontalalignment='center')
    ax[1].text(2,
               time_slew + offset,
               '{0:0.1f} %'.format(ratio_slew * 100.),
               horizontalalignment='center')
    ax[1].text(3,
               time_slew_idle + offset,
               '{0:0.1f} %'.format(ratio_slew_idle * 100.),
               horizontalalignment='center')
    ax[1].text(4,
               time_idle + offset,
               '{0:0.1f} %'.format(ratio_idle * 100.),
               horizontalalignment='center')
    ax[1].set_ylabel('hours')
    labels = ['obs', 'slew\ntotal', 'slew\nidle', 'idle']
    ax[1].set_xticks([1, 2, 3, 4])
    ax[1].set_xticklabels(labels)
    plt.setp(ax[1].xaxis.get_majorticklabels(), rotation=45)

    return fig
Ejemplo n.º 26
0
                                                       pix_pad)).astype(int)
            hmi_index_y_new = np.around(hmi_index_y + (thisxyshift[1].value -
                                                       pix_pad)).astype(int)
            hmi_data = magnetic_flux_density_hmi_rot[
                hmi_index_y_new[0]:hmi_index_y_new[1],
                hmi_index_x_new[0]:hmi_index_x_new[1]]

            # Now use the FFT image shift routine for better precision and
            # create the final HMI cutout.
            xshift, yshift = get_image_shift(hmi_data, tmp_hinode_data)

            hmi_index_x_new += xshift
            hmi_index_y_new += yshift

            rect = Rectangle((hmi_xcoords[hmi_index_x_new[0]],hmi_ycoords[hmi_index_y_new[0]]), \
                              hmi_xcoords[hmi_index_x_new[1]]-hmi_xcoords[hmi_index_x_new[0]],  \
                              hmi_ycoords[hmi_index_y_new[1]]-hmi_ycoords[hmi_index_y_new[0]],  \
                              linewidth=1, edgecolor='r', facecolor='none')

            ax.add_patch(rect)
            # Plot the Hinode timestamp next to the rectangle
            #ax.text(hmi_index_x_new[0], hmi_index_y_new[1]+15, HOP_336_info[jj][3], fontsize=10, color='red')
            # Wasn't really legible, so put it at the top next to the title instead
            plt.gcf().text(0.68,
                           0.983,
                           'Hinode: ' + HOP_336_info[jj][3],
                           fontsize=12)

    fig.savefig(plot_directory + '{:06d}'.format(ii) + '.jpg',
                dpi=107,
                format='jpg',
                quality=95)
Ejemplo n.º 27
0
    def visualize(self,
                  file_name=None,
                  fig_size: (float, float) = (6.5, 6.5),
                  size_auv_path: float = 0.8,
                  size_max_radius: float = 0.3,
                  size_min_radius: float = 0.1,
                  tick_size: float = 14,
                  grid_width: float = 0.25,
                  size_arrow_h_width: float = 0.4,
                  size_arrow_h_length: float = 0.3,
                  size_arrow_width: float = 0.4,
                  color_obstacle: str = 'firebrick',
                  color_target: str = 'deepskyblue',
                  color_auv: str = 'darkorange',
                  color_auv_path: str = 'peachpuff',
                  visited_reward_opacity: float = 0.15) -> Figure:

        if (fig_size[0] <= 0 or fig_size[1] <= 0 or size_auv_path <= 0
                or size_max_radius <= 0 or size_arrow_h_width <= 0
                or size_arrow_h_length <= 0 or size_arrow_width <= 0
                or tick_size <= 0 or grid_width <= 0):
            raise ValueError("Size must be positive")
        max_reward = self._environment.max_reward
        title_font = {
            'fontname': 'Sans Serif',
            'size': '16',
            'color': 'black',
            'weight': 'bold'
        }
        z = {'auv_path': 1, 'target': 2, 'obstacle': 3, 'auv': 5}

        # Initialize the figure
        fig = plt.figure(figsize=fig_size)
        ax = fig.add_subplot(111)
        plt.hlines(y=range(self._environment.y_min,
                           self._environment.y_max + 1),
                   xmin=self._environment.x_min,
                   xmax=self._environment.x_max,
                   color='k',
                   linewidth=grid_width,
                   zorder=0)
        plt.vlines(x=range(self._environment.x_min,
                           self._environment.x_max + 1),
                   ymin=self._environment.y_min,
                   ymax=self._environment.y_max,
                   color='k',
                   linewidth=grid_width,
                   zorder=0)

        # Plot obstacles
        for i, j in self._environment.obstacles:
            ax.add_patch(
                Rectangle(xy=(i, j),
                          width=1,
                          height=1,
                          color=color_obstacle,
                          zorder=z['obstacle']))

        # Plot rewards
        for position, reward in self._environment.rewards.items():
            target_radius = ((reward / max_reward) *
                             (size_max_radius - size_min_radius) +
                             size_min_radius)
            centroid = (position[0] + 0.5, position[1] + 0.5)
            ax.add_patch(
                Circle(xy=centroid,
                       radius=target_radius,
                       color=color_target,
                       zorder=z['target'],
                       alpha=(visited_reward_opacity
                              if position in self.visited else 1.0)))

        # Plot agents
        for path in self._paths:
            x, y = path[-1]
            dx, dy = 0, 1
            if len(path) >= 2:
                x_p, y_p = path[-2]
                if x == x_p + 1 and y == y_p:
                    dx, dy = 1, 0
                elif x == x_p - 1 and y == y_p:
                    dx, dy = -1, 0
                elif x == x_p and y == y_p - 1:
                    dx, dy = 0, -1
            x += 0.5 * float(1 - dx)
            y += 0.5 * float(1 - dy)
            ax.add_patch(
                FancyArrow(x=x,
                           y=y,
                           dx=dx,
                           dy=dy,
                           fc=color_auv,
                           width=size_arrow_width,
                           head_width=size_arrow_h_width,
                           head_length=size_arrow_h_length,
                           zorder=z['auv'],
                           length_includes_head=True))

            # plot trajectories
            for i in range(1, len(path)):
                x, y = path[i]
                x_p, y_p = path[i - 1]
                ax.add_line(
                    Line2D(xdata=(x + 0.5, x_p + 0.5),
                           ydata=(y + 0.5, y_p + 0.5),
                           linewidth=size_auv_path * 10,
                           color=color_auv_path,
                           zorder=z['auv_path']))

        # Plotting
        plt.title('AUV Trajectory \n Accumulated Reward: ' + str(self.reward),
                  title_font)
        plt.xlabel('x', title_font)
        plt.ylabel('y', title_font)
        x_ticks = np.arange(self._environment.x_min,
                            self._environment.x_max + 1, 1)
        y_ticks = np.arange(self._environment.y_min,
                            self._environment.y_max + 1, 1)
        plt.xticks(x_ticks + 0.5, x_ticks.astype(int))
        plt.yticks(y_ticks + 0.5, y_ticks.astype(int))
        ax.tick_params(labelsize=tick_size)
        ax.grid(False)
        ax.axis('equal')
        ax.set_xlim(self._environment.x_min - 0.5,
                    self._environment.x_max + 1.5)
        ax.set_ylim(self._environment.y_min - 0.5,
                    self._environment.y_max + 1.5)

        # Save and display
        plt.show()
        if file_name is not None:
            plt.savefig(file_name)

        return fig
Ejemplo n.º 28
0
def rectangles(x,
               y,
               sw,
               sh=None,
               c='b',
               ax=None,
               vmin=None,
               vmax=None,
               **kwargs):
    """
    Make a scatter of squares plot of x vs y, where x and y are sequence 
    like objects of the same lengths. The size of sqares are in data scale.

    Parameters
    ----------
    x,y : scalar or array_like, shape (n, )
        Input data
    s : scalar or array_like, shape (n, ) 
        side of square in data scale (ie. in data unit)
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or
        RGBA sequence because that is indistinguishable from an array of
        values to be colormapped.  `c` can be a 2-D array in which the
        rows are RGB or RGBA, however.
    ax : Axes object, optional, default: None
        Parent axes of the plot. It uses gca() if not specified.
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.  (Note if you pass a `norm` instance, your
        settings for `vmin` and `vmax` will be ignored.)

    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`

    Other parameters
    ----------------
    kwargs : `~matplotlib.collections.Collection` properties
        eg. alpha, edgecolors, facecolors, linewidths, linestyles, norm, cmap

    Examples
    --------
    a = np.arange(11)
    squaress(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')

    License
    --------
    This code is under [The BSD 3-Clause License]
    (http://opensource.org/licenses/BSD-3-Clause)
    """
    #import matplotlib.colors as colors

    if ax is None:
        ax = mpl.gca()

    if isinstance(c, basestring):
        color = c  # ie. use colors.colorConverter.to_rgba_array(c)
    else:
        color = None  # use cmap, norm after collection is created
    kwargs.update(color=color)
    if sh is None:
        sh = sw
    x = x - sw / 2.  # offset as position specified is "lower left corner"
    y = y - sh / 2.
    if np.isscalar(x):
        patches = [
            Rectangle((x, y), sw, sh),
        ]
    elif np.isscalar(sw):
        patches = [Rectangle((x_, y_), sw, sh) for x_, y_ in zip(x, y)]
    else:
        patches = [
            Rectangle((x_, y_), sw_, sh_)
            for x_, y_, sw_, sh_ in zip(x, y, sw, sh)
        ]
    collection = PatchCollection(patches, **kwargs)

    if color is None:
        collection.set_array(np.asarray(c))
        if vmin is not None or vmax is not None:
            collection.set_clim(vmin, vmax)

    ax.add_collection(collection)
    ax.autoscale_view()
    return collection
Ejemplo n.º 29
0
def coordinates(filelist, **kwargs):
    """ Find all coordinates in a list of image files.

        Usage: fig = sims.coordinates([a.im, b.im], labels=['A', 'B'])

        For each image in the list, the stage coordinates and raster size are extracted.
        A box scaled to the rastersize is plotted for each image on a (X,Y) grid.
        A label for each file can be given. If it's omitted, the filename will be printed
        over the box, but no attempt is made to make the filename fit in the box.

        Returns a matplotlib figure instance.
    """
    labels = kwargs.pop('labels', filelist)

    patches = []
    x_min = None
    fig = mpl.figure()
    ax = fig.gca()

    for fn, lb in zip(filelist, labels):
        s = sims.SIMSOpener(fn)
        s.peek()
        s.read_header()
        s.close()

        # Remember!! In Cameca-land, X is up-down, Y is left-right. Fix here.
        x = s.header['sample y']
        y = s.header['sample x']

        if (x == 0 and y == 0):
            warnings.warn('Coordinates for file {} are 0,0.'.format(fn))

        if (('PrimaryBeam' in s.header.keys())
                and ('raster' in s.header['PrimaryBeam'].keys())):
            raster = s.header['PrimaryBeam']['raster']
        elif (('Image' in s.header.keys())
              and ('raster' in s.header['Image'].keys())):
            raster = s.header['Image']['raster'] / 1000
        else:
            warnings.warn('No raster size in header of file {}.'.format(fn))
            raster = 0

        # Text uses center of image coordinate, box uses lower left.
        ax.text(x, y, lb, ha='center', va='center', fontsize=8)

        x -= raster / 2
        y -= raster / 2

        # Update data limits, relim() used by autoview does not work with collections (yet)
        if not x_min:
            # first pass
            x_min = x
            x_max = x + raster
            y_min = y
            y_max = y + raster
        else:
            if x < x_min: x_min = x
            if x + raster > x_max: x_max = x + raster
            if y < y_min: y_min = y
            if y + raster > y_max: y_max = y + raster

        rect = Rectangle((x, y),
                         raster,
                         raster,
                         ec='black',
                         fc='white',
                         fill=False)
        patches.append(rect)

    collection = PatchCollection(patches, match_original=True)
    ax.add_collection(collection)

    # Set view limits
    x_span = x_max - x_min
    y_span = y_max - y_min
    # Remember!! In Cameca-land, X-axis (up-down) is positive downwards,
    # Y-axis (left-right) is positive going right.
    ax.set_xlim(x_min - 0.1 * x_span, x_max + 0.1 * x_span)
    ax.set_ylim(y_max + 0.1 * y_span, y_min - 0.1 * y_span)

    # Keep it square
    ax.set_aspect('equal', adjustable='datalim')
    ax.set_xlabel('Stage Y (μm)')
    ax.set_ylabel('Stage X (μm)')
    return fig
def sample_in_windows(drive_contour: np.ndarray, driven_contour: np.ndarray,
                      window_pairs: List[Tuple[Window_T, Window_T]], keep_count: int,
                      debugging_suite: ReportingSuite, k: int = 1, center_determine_function=center_of_window,
                      sampling_accuracy=1024, torque_weight=0.0, mismatch_penalty: float = 0.5) \
        -> List[Tuple[float, Window_T, Window_T, Polar_T, float, float]]:
    """
    find the best sample windows
    :param drive_contour: the drive contour
    :param driven_contour: the driven contour
    :param window_pairs: pair of windows
    :param keep_count: count of the windows to be kept
    :param debugging_suite: the debugging suite
    :param k: the k of the opposing gear
    :param center_determine_function: function to determine from window to center
    :param sampling_accuracy: number of samples when converting to polar contour
    :param torque_weight: weight of torque term
    :param mismatch_penalty: penalty for the extended d_driven not matching start and end (only for k>1)
    :return: list of (score, drive_window, driven_window, reconstructed_drive, max_phi, mismatch_penalty)
    """
    results = []
    path_prefix = debugging_suite.path_prefix  # store in a directory
    if debugging_suite.figure is not None:
        debugging_suite.figure.clear()  # clear the figure
        plt.figure(debugging_suite.figure.number)
        subplots = debugging_suite.figure.subplots(2, 2)
        update_polygon_subplots(drive_contour, driven_contour, subplots[0])
    else:
        subplots = None
    for index, (drive_window, driven_window) in enumerate(window_pairs):
        center_drive = center_determine_function(drive_window)
        center_driven = center_determine_function(driven_window)
        if not (Polygon(drive_contour).contains(Point(*center_drive)) and Polygon(driven_contour).contains(
                Point(*center_driven))):
            # not good windows
            continue
        # polar, dist, phi = compute_dual_gear(
        #     toExteriorPolarCoord(Point(*center_driven), driven_contour, sampling_accuracy), 1)
        # polar, dist, phi = compute_dual_gear(polar, 1)
        # d_phi = differentiate_function(pre_process(phi))
        # fig, splts = plt.subplots(2, 2, figsize=(9, 9))
        # splts[0][1].plot(*driven_contour.transpose())
        # splts[0][1].axis('equal')
        # splts[1][0].plot(np.linspace(0, 2 * math.pi, len(phi), endpoint=False), phi)
        # splts[1][1].plot(np.linspace(0, 2 * math.pi, len(d_phi), endpoint=False), d_phi, color='red')
        # plt.show() #checkpoint passed
        distance, d_drive, d_driven, dist_drive, dist_driven = \
            contour_distance(drive_contour, center_drive, driven_contour, center_driven, sampling_accuracy, k)
        # splts[1][1].plot(np.linspace(0, 2 * math.pi, len(d_driven), endpoint=False), d_driven, color='blue')
        # plt.show()
        reconstructed_drive = rebuild_polar(0.9, align_and_average(d_drive, d_driven, k=k))
        list_reconstructed_drive = list(reconstructed_drive)
        max_phi = max(differentiate_function(pre_process(compute_dual_gear(list_reconstructed_drive)[-1])))
        final_score = distance + torque_weight * max_phi
        m_penalty = None
        if k != 1:
            m_penalty = mismatch_penalty * abs(d_driven[0] - d_driven[-1])
            logger.info(f'{index} gear: mismatching start = {d_driven[0]}, end = {d_driven[-1]}, penalized {m_penalty}')
            final_score += m_penalty
        logging.info(f'{index} gear: plain score={distance}, max of phi\'={max_phi}')
        results.append((final_score, drive_window, driven_window, list_reconstructed_drive, max_phi, m_penalty))
        if subplots is not None:
            update_polygon_subplots(drive_contour, driven_contour, subplots[0])  # clear sample regions
            reconstructed_driven, plt_center_dist, plt_phi = compute_dual_gear(list_reconstructed_drive, k)
            reconstructed_drive_contour = toCartesianCoordAsNp(reconstructed_drive, 0, 0)
            reconstructed_driven_contour = toCartesianCoordAsNp(reconstructed_driven, 0, 0)
            update_polygon_subplots(reconstructed_drive_contour, reconstructed_driven_contour, subplots[1])
            min_x, max_x, min_y, max_y = drive_window
            sample_region = Rectangle((min_x, min_y), max_x - min_x, max_y - min_y, color='red', fill=False)
            subplots[0][0].add_patch(sample_region)
            min_x, max_x, min_y, max_y = driven_window
            sample_region = Rectangle((min_x, min_y), max_x - min_x, max_y - min_y, color='red', fill=False)
            subplots[0][1].add_patch(sample_region)
            subplots[0][0].scatter(*center_drive, 5)
            subplots[0][1].scatter(*center_driven, 5)
            subplots[1][0].scatter(0, 0, 5)
            subplots[1][1].scatter(0, 0, 5)
            plt.savefig(path_prefix + f'{index}.png')
            save_contour(path_prefix + f'{index}_drive.dat', reconstructed_drive_contour)
            save_contour(path_prefix + f'{index}_driven.dat', reconstructed_driven_contour)
            save_information(path_prefix + f'{index}.txt', center_drive, center_driven, final_score,
                             max_dphi_drive=max_phi, actual_distance=distance, mismatch_penalty=m_penalty)

            # get information about thee phi' functions
            original_figure = plt.gcf()
            figure, new_subplots = plt.subplots(2, 2, figsize=(16, 16))
            new_subplots[0][0].plot(np.linspace(0, 2 * math.pi, len(d_drive), endpoint=False), d_drive)
            new_subplots[0][0].axis([0, 2 * math.pi, 0, 2 * math.pi])
            new_subplots[0][1].plot(np.linspace(0, 2 * math.pi, len(d_driven), endpoint=False), d_driven)
            new_subplots[0][1].axis([0, 2 * math.pi, 0, 2 * math.pi])
            new_subplots[1][0].plot(np.linspace(0, 2 * math.pi, len(d_drive), endpoint=False),
                                    align_and_average(d_drive, d_driven, k=k))
            new_subplots[1][0].axis([0, 2 * math.pi, 0, 2 * math.pi])
            debugging_suite.plotter.draw_contours(
                path_prefix + f'drive_contour_{index}.png',
                [('carve_drive', drive_contour)],
                [center_drive])
            debugging_suite.plotter.draw_contours(
                path_prefix + f'driven_contour_{index}.png',
                [('carve_driven', driven_contour)],
                [center_driven])
            final_driven = np.array(
                psf_rotate(toCartesianCoordAsNp(reconstructed_driven, plt_center_dist, 0), plt_phi[0],
                           (plt_center_dist, 0)))
            debugging_suite.plotter.draw_contours(
                path_prefix + f'reconstructed_contour_{index}.png',
                [('carve_drive', reconstructed_drive_contour),
                 ('carve_driven', final_driven)],
                [(0, 0), (plt_center_dist, 0)])
            if k != 1:
                # then offset shall be 0
                new_subplots[1][1].plot(np.linspace(0, 2 * math.pi, len(d_drive), endpoint=False),
                                        extend_part(d_driven, 0, int(len(d_driven) / k), len(d_drive)))
                new_subplots[1][1].axis('equal')
            plt.axis('equal')
            plt.savefig(path_prefix + f'{index}_functions.png')
            plt.close()
            plt.figure(original_figure.number)
    results.sort(key=lambda dist, *_: dist)
    return results[:keep_count]