Beispiel #1
0
    def plotEllipse(self,barotropic=False,k=0,con='M2',scale=1e4,subsample=4,\
            xlims=None,ylims=None,cbarpos=[0.15, 0.15, 0.03, 0.3],**kwargs):
        """
        Plots tidal ellipses on a map
        """
        from matplotlib.collections import EllipseCollection
        
        plt.ioff()
        fig = plt.gcf()
        ax = fig.gca()
        
        iicon = findCon(con,self.frqnames)
        
        if self.clim==None:
            self.clim=[]
            self.clim.append(np.min(self.Amp))
            self.clim.append(np.max(self.Amp))
        if xlims==None or ylims==None:
            xlims=self.xlims 
            ylims=self.ylims

        ell = self.getEllipse(barotropic=barotropic,k=k,con=con)
            
        # Create the ellipse collection
        indices = range(0,self.Nc,subsample)
        widths = [ell[0][ii]*scale for ii in indices]
        heights = [ell[1][ii]*scale for ii in indices]
        angles = [ell[2][ii]*180.0/np.pi for ii in indices]
        #angles = [ell[2][ii] for ii in indices]
        offsets = [(self.xv[ii],self.yv[ii]) for ii in indices]

        
        collection = EllipseCollection(widths,heights,angles,units='xy',\
            offsets=offsets, transOffset=ax.transData,**kwargs)
        
        z=ell[0][indices]
        collection.set_array(np.array(z))
        collection.set_clim(vmin=self.clim[0],vmax=self.clim[1])
        collection.set_edgecolors(collection.to_rgba(np.array(z))) 
        
        ax.set_aspect('equal')
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)

        titlestr='%s - Semi-major Ellipse Amplitude'%(self.frqnames[iicon])
        plt.title(titlestr)
        
        ax.add_collection(collection)
        # Add a decent looking colorbar
        if not cbarpos==None:
            cbaxes = fig.add_axes(cbarpos) 
            cb = fig.colorbar(collection,cax = cbaxes,orientation='vertical')  
            cb.ax.set_title('[m s$^{-1}$]')
    
        plt.sca(ax)
        
        #axcb = fig.colorbar(collection)
        
        return collection
x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)

XY = np.column_stack((X.ravel(), Y.ravel()))

ww = X / 10.0
hh = Y / 15.0
aa = X * 9


fig, ax = plt.subplots()

ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,
                       transOffset=ax.transData)
ec.set_array((X + Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()

#############################################################################
#
# ------------
#
# References
# """"""""""
#
Beispiel #3
0
    rotations.append(INC)
    # Save the semi-major axis for the colouring the ellipses.
    sema.append(SEMA)
      
# Now plot the M2 results.
rcParams['mathtext.default'] = 'regular'  # sensible font for LaTeX text

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, aspect='equal')

# Make an EllipseCollection.
ellipses = EllipseCollection(widths, heights, rotations, 
                             offsets=xy,
                             units='xy',
                             transOffset=ax.transData)
ellipses.set_array(np.asarray(sema))

# Add coastlines
m.drawmapboundary(zorder=0)
m.drawcoastlines(zorder=1)
m.fillcontinents(zorder=0, color='0.6')
m.drawparallels(parallels, labels=[1, 0, 0, 0], linewidth=0)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], linewidth=0)

# Add ellipses coloured by the semi-major axis magnitude.
ax.add_collection(ellipses)
ellipses.set_linewidth(0)
ellipses.set_cmap(cm.viridis)
ellipses.set_zorder=200
    
# Add a nice colour bar.
homey = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))

ww = X / 10.0
ww[:] = 1.0
hh = Y / 15.0
hh[:] = 0.333
aa = X * 9
#aa[:] = -50.0

fig, ax = plt.subplots()

myalpha = ww
myalpha[:] = 0.5
ec = EllipseCollection(ww,
                       hh,
                       aa,
                       units='x',
                       alpha=0.1,
                       offsets=homey,
                       transOffset=ax.transData)
simon = (X + Y).ravel()
ec.set_array(simon)
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()
XY = np.column_stack((X.ravel(), Y.ravel()))

ww = X / 10.0
hh = Y / 15.0
aa = X * 9

fig, ax = plt.subplots()

ec = EllipseCollection(ww,
                       hh,
                       aa,
                       units='x',
                       offsets=XY,
                       offset_transform=ax.transData)
ec.set_array((X + Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()

#############################################################################
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
Beispiel #6
0
XY = np.column_stack(
    (X.ravel(), Y.ravel()))  # Sets co-ordinates for ellipses centers

fig, ax = plt.subplots()  # Creates figure environment
ax.set_facecolor('white')  # Background colour

if H > 0:  # Loop for selecting colour based on averaged handedness H
    ec = EllipseCollection(w,
                           h,
                           np.rad2deg(Psi),
                           units='xy',
                           offsets=XY,
                           transOffset=ax.transData,
                           cmap='Reds',
                           facecolors='none')
    ec.set_array(S0.ravel())  # Scales ellipse colour to intensity (i.e. S0)
elif H < 0:
    ec = EllipseCollection(w,
                           h,
                           np.rad2deg(Psi),
                           units='xy',
                           offsets=XY,
                           transOffset=ax.transData,
                           cmap='Blues',
                           facecolors='none')
    ec.set_array(S0.ravel())
else:
    ec = EllipseCollection(w,
                           h,
                           np.rad2deg(Psi),
                           units='xy',
Beispiel #7
0
def plot_people(ifig,
                dom,
                people,
                contacts,
                U,
                colors,
                time=-1,
                axis=None,
                plot_people=True,
                plot_contacts=True,
                plot_velocities=True,
                plot_paths=False,
                paths=None,
                plot_sensors=False,
                sensors=[],
                savefig=False,
                filename='fig.png',
                cmap='winter'):
    """
    This function draws spheres for the individuals, \
    lines for the active contacts and arrows for the \
    (desired or real) velocities.

    Parameters
    ----------
    ifig: int
        figure number
    dom: Domain
        contains everything for managing the domain
    people: numpy array
        people coordinates and radius : x,y,r
    contacts: numpy array
        all the contacts : i,j,dij,eij_x,eij_y
    U: numpy array
        people velocities
    colors: numpy array
        scalar field used to define people colors
    time: float
        time in seconds
    axis: numpy array
        matplotlib axis : [xmin, xmax, ymin, ymax]
    plot_people: boolean
        draws spheres for people if true
    plot_paths: boolean
        draws people paths if true
    paths: numpy array
        coordinates of the people paths
    plot_sensors: boolean
        draws sensor lines if true
    sensors: numpy array
        sensor line coordinates (see also the sensor function below)
    savefig: boolean
        writes the figure as a png file if true
    filename: string
        png filename used to write the figure
    cmap: string
        matplotlib colormap name
    """
    fig = plt.figure(ifig)
    plt.clf()
    ax1 = fig.add_subplot(111)
    # Domain
    ax1.imshow(dom.image,
               interpolation='nearest',
               extent=[dom.xmin, dom.xmax, dom.ymin, dom.ymax],
               origin='lower')
    if (plot_people):
        # People
        #offsets = list(zip(people[:,:2])) ## for older versions of matplotlib...
        offsets = people[:, :2]
        ec = EllipseCollection(widths=2 * people[:, 2],
                               heights=2 * people[:, 2],
                               angles=0,
                               units='xy',
                               cmap=plt.get_cmap(cmap),
                               offsets=offsets,
                               transOffset=ax1.transData)
        ec.set_array(colors)
        ax1.add_collection(ec)
    if (plot_contacts):
        # Contacts
        Nc = contacts.shape[0]
        if (Nc > 0):
            for ic in sp.arange(Nc):
                i = sp.int64(contacts[ic, 0])
                j = sp.int64(contacts[ic, 1])
                if (j != -1):
                    line = Line2D([people[i, 0], people[j, 0]],
                                  [people[i, 1], people[j, 1]],
                                  lw=1.,
                                  alpha=0.6,
                                  color='k')
                else:
                    line = Line2D([
                        people[i, 0], people[i, 0] -
                        (people[i, 2] + contacts[ic, 2]) * contacts[ic, 3]
                    ], [
                        people[i, 1], people[i, 1] -
                        (people[i, 2] + contacts[ic, 2]) * contacts[ic, 4]
                    ],
                                  lw=1.,
                                  alpha=0.6,
                                  color='k')
                ax1.add_line(line)
    if (plot_velocities):
        # Velocities
        Np = people.shape[0]
        for ip in sp.arange(Np):
            arrow = Arrow(people[ip, 0],
                          people[ip, 1],
                          U[ip, 0],
                          U[ip, 1],
                          width=0.3)
            ax1.add_patch(arrow)
    if ((plot_paths) and (paths is not None)):
        mpaths = sp.ma.masked_values(paths, 1e99)
        pathlines = []
        for id in sp.arange(paths.shape[0]):
            pathlines.append(sp.swapaxes(mpaths[id, :, :], 0, 1))
        pathlinecoll = LineCollection(pathlines,
                                      linewidths=0.5,
                                      linestyle="solid",
                                      cmap=plt.get_cmap(cmap))
        pathlinecoll.set_array(colors)
        ax1.add_collection(pathlinecoll)
    if (plot_sensors):
        # Sensors
        for ss in sensors:
            line = Line2D([ss[0], ss[2]], [ss[1], ss[3]],
                          lw=1.,
                          alpha=0.6,
                          color='g')
            ax1.add_line(line)
    if (axis):
        ax1.set_xlim(axis[0], axis[1])
        ax1.set_ylim(axis[2], axis[3])
    ax1.set_xticks([])
    ax1.set_yticks([])
    ax1.axis('off')
    if (time >= 0):
        ax1.set_title('time = {:.2F}'.format(time) + ' s')
    fig.canvas.draw()
    if (savefig):
        fig.savefig(filename, dpi=600, bbox_inches='tight', pad_inches=0)
Beispiel #8
0
def graph(locator, parameters, method, samples):
    """

    :param locator: locator class
    :param parameters: list of output parameters to analyse
    :param method: 'morris' or 'sobol' methods
    :param samples: number of samples to calculate
    :return: .pdf file per output_parameter stored in locator.get_sensitivity_plots_file()

    """
    if method is 'sobol':
        result = ['ST', 'ST_conf', 'S1']
    else:
        result = ['mu_star', 'sigma', 'mu_star_conf']

    for parameter in parameters:
        pdf = PdfPages(locator.get_sensitivity_plots_file(parameter))

        # read the mustar of morris analysis
        data_mu = pd.read_excel(
            locator.get_sensitivity_output(method, samples),
            (parameter + result[0]))
        data_sigma = pd.read_excel(
            locator.get_sensitivity_output(method, samples),
            (parameter + result[1]))
        var_names = data_mu.columns.values

        # normalize data to maximum value
        data_mu[var_names] = data_mu[var_names].div(
            data_mu[var_names].max(axis=1), axis=0)
        data_sigma[var_names] = data_sigma[var_names].div(
            data_sigma[var_names].max(axis=1), axis=0)
        # get x_names and y_names
        # columns
        x_names = data_mu.columns.tolist()
        # rows
        y_names = ['config ' + str(i) for i in list(data_mu.index + 1)]

        # get counter (integer to create the graph)
        x = range(len(x_names))
        y = range(len(y_names))

        X, Y = np.meshgrid(x, y)
        XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
        ww = data_mu.values.tolist()
        hh = data_sigma.values.tolist()
        aa = X * 0

        fig, ax = plt.subplots(dpi=150,
                               figsize=(len(x_names) + 2, len(y_names) + 2))  #
        ec = EllipseCollection(ww,
                               hh,
                               aa,
                               units='x',
                               offsets=XY,
                               transOffset=ax.transData,
                               cmap='Blues')
        ec.set_array(np.array(ww).ravel())
        ec.set_alpha(0.8)
        ax.add_collection(ec)
        ax.autoscale_view()
        plt.xticks(np.arange(-1, max(x) + 1, 1.0))
        plt.yticks(np.arange(-1, max(y) + 1, 1.0))
        ax.set_xlabel('variables [-]')
        ax.set_ylabel('configurations [-]')
        ax.set_xticklabels([""] + x_names)
        ax.set_yticklabels([""] + y_names)
        cbar = plt.colorbar(ec)
        cbar.set_label(result[0])
        plt.title('GRAPH OF ' + parameter + ' PARAMETER',
                  fontsize=14,
                  fontstyle='italic',
                  fontweight='bold')
        pdf.savefig()
        plt.close()
        plt.clf()
        pdf.close()
homey = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))

ww = X/10.0
ww[:] = 1.0
hh = Y/15.0
hh[:] = 0.333
aa = X*9
#aa[:] = -50.0

fig, ax = plt.subplots()

myalpha = ww
myalpha[:] = 0.5
ec = EllipseCollection(
                        ww,
                        hh,
                        aa,
                        units='x',
                        alpha = 0.1, 
                        offsets=homey,
                        transOffset=ax.transData)
simon = (X+Y).ravel()
ec.set_array(simon)
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()
Beispiel #10
0
def display_matrices(ax, grid, texture, scale=None, col=None):
    """Display on a matplotlib axis an ellipse representing a symmetric matrix at each grid element. Each axis of the ellipse corresponds to an eigenvalue and is oriented along its eigenvector. An axis corresponding to a positive eigenvalue is drawn. A 'coffee bean' has a negative eigenvalue smaller in absolute value than its positive eigenvalue. A 'capsule' has a negative eigenvalue larger in absolute value than its positive eigenvalue. A circle is when the two eigenvalues are equal in absolute value."""
    XY = grid.mesh()
    mask = grid.mask()
    #convert the texture back to an array of matrices
    mat = tri2square(texture)
    #compute egenvalues and eigenvectors of texture for each cell of the grid
    evalues, evectors = np.linalg.eigh(mat)
    #width and height are the larger and smaller eigenvalues respectively
    ww = evalues[..., 1][mask]
    hh = evalues[..., 0][mask]
    #angle is given by the angle of the larger eigenvector
    aa = np.rad2deg(np.arctan2(evectors[..., 1, 1], evectors[..., 0, 1]))[mask]
    #sum of the eigenvalues (trace of the matrix)
    trace = ww + hh  #np.where(np.abs(ww)>np.abs(hh), ww, hh)#ww*hh
    #color
    #if col is None:
    #    if trace.ptp()>0:
    #        col = plt.cm.viridis((trace.ravel() - trace.min())/trace.ptp())
    #    else:
    #        col = plt.cm.viridis(np.ones_like(trace))

    if scale is None:
        #scale = 1
        ellipse_areas = np.pi * np.abs(np.prod(evalues, axis=-1))
        rarea = ellipse_areas / grid.areas()
        scale = np.nanpercentile(np.sqrt(rarea[mask]), 90)
        if scale == 0:
            scale = np.nanmax(np.sqrt(rarea[mask]))
            if scale == 0:
                raise ValueError("All matrices are null")
        scale = 1 / scale

    #show ellipses
    ec = EllipseCollection(
        ww * scale,
        hh * scale,
        aa,
        units='xy',
        offsets=XY,
        transOffset=ax.transData,
        edgecolors=col,
        facecolors='none',
    )
    #major and minor axes (only for positive eigenvalues)
    xyps = scale * np.transpose(
        evectors * np.maximum(0, evalues)[..., None, :],
        (0, 1, 3, 2))[mask].reshape(2 * len(ww), 2) * 0.5
    ma = LineCollection([[-xyp, xyp] for xyp in xyps],
                        offsets=np.repeat(XY, 2, axis=0),
                        color=(0.5, 0.5, 0.5))
    if col is None:
        if trace.ptp() > 0:
            ec.set_array(trace)
            ma.set_array(trace[mask.ravel()])
    else:
        ec.set_edgecolors(col)
        ma.set_edgecolors(col)
    ax.add_collection(ec)
    ax.add_collection(ma)
    return ec
def graph(locator, parameters, method, samples):
    """

    :param locator: locator class
    :param parameters: list of output parameters to analyse
    :param method: 'morris' or 'sobol' methods
    :param samples: number of samples to calculate
    :return: .pdf file per output_parameter stored in locator.get_sensitivity_plots_file()

    """
    if method is 'sobol':
        result = ['ST', 'conf', 'S1']
    else:
        result = ['mu_star', 'sigma', 'mu_star_conf']

    for parameter in parameters:
        pdf = PdfPages(locator.get_sensitivity_plots_file(parameter))

        # read the mustar of morris analysis
        data_mu = pd.read_excel(locator.get_sensitivity_output(method, samples), (parameter + result[0]))
        data_sigma = pd.read_excel(locator.get_sensitivity_output(method, samples), (parameter + result[1]))
        var_names = data_mu.columns.values

        # normalize data to maximum value
        data_mu[var_names] = data_mu[var_names].div(data_mu[var_names].max(axis=1), axis=0)
        data_sigma[var_names] = data_sigma[var_names].div(data_sigma[var_names].max(axis=1), axis=0)
        # get x_names and y_names
        # columns
        x_names = data_mu.columns.tolist()
        # rows
        y_names = ['config '+str(i) for i in list(data_mu.index+1)]

        # get counter (integer to create the graph)
        x = range(len(x_names))
        y = range(len (y_names))

        X, Y = np.meshgrid(x,y)
        XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
        ww = data_mu.values.tolist()
        hh = data_sigma.values.tolist()
        aa = X*0

        fig, ax = plt.subplots(dpi=150, figsize=(len(x_names)+2, len(y_names)+2)) #
        ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY, transOffset=ax.transData, cmap='Blues')
        ec.set_array(np.array(ww).ravel())
        ec.set_alpha(0.8)
        ax.add_collection(ec)
        ax.autoscale_view()
        plt.xticks(np.arange(-1, max(x) + 1, 1.0))
        plt.yticks(np.arange(-1, max(y) + 1, 1.0))
        ax.set_xlabel('variables [-]')
        ax.set_ylabel('configurations [-]')
        ax.set_xticklabels([""]+x_names)
        ax.set_yticklabels([""]+y_names)
        cbar = plt.colorbar(ec)
        cbar.set_label(result[0])
        plt.title('GRAPH OF '+parameter+' PARAMETER', fontsize=14, fontstyle='italic', fontweight='bold')
        pdf.savefig()
        plt.close()
        plt.clf()
        pdf.close()
Beispiel #12
0
    def TransDisplay(self,
                     data,
                     A_or_B,
                     major_axis=20,
                     minor_axis=6,
                     angle=None,
                     cbar_label='',
                     colorbar_lim=None,
                     max_color_range=True,
                     combine_colorbar=False):
        """This function creates a color plot of data, for probe A_or_B. The
        feed horns are represented using ellipses of size major_axis &
        minor_axis, rotated by angle.  If angle is None, uses self.angle_file;
        if that's also None, throws error. data must be a correctly organized
        array. The plot is drawn on succeeding figures. The graph is labeled
        title, and the colour bar is labeled cbar_label. colorbar_lim and
        max_color_range explained in draw_ellipses docs.  combine_colorbar is
        only relevant if multiple sets of ellipses are being plotted on the
        same figure. In that case, only 1 colorbar is shown if
        combine_colorbar=True, and one colorbar is shown for each set of data
        if it is False. Returns the EllipseCollection."""
        if A_or_B == 'A':
            x = self.beam_centers_Ax
            y = self.beam_centers_Ay
        elif A_or_B == 'B':
            x = self.beam_centers_Bx
            y = self.beam_centers_By
        else:
            print "I'm sorry that you do not understand that " + A_or_B
            + " is not A and is not B!"
            return
        major_axes = np.ones(len(x)) * major_axis
        minor_axes = np.ones(len(x)) * minor_axis
        if angle != None:
            angles = np.ones(len(x)) * angle
        #  print angles
        else:
            angles = self.get_angles(A_or_B)
            if len(angles) != len(x):
                raise Exception("Angles file is invalid!")
        XY = np.hstack((x[:, np.newaxis], y[:, np.newaxis]))
        if combine_colorbar and self.curr_ellipses != None:
            plt.gcf().clear()
            ax = plt.subplot(1, 1, 1)
            #Make a new collection, containing all previous data plus new data
            old_majors = self.curr_ellipses._widths * 2
            old_minors = self.curr_ellipses._heights * 2
            #old_angles in radians, convert to degrees
            old_angles = self.curr_ellipses._angles * 180 / np.pi
            old_offsets = self.curr_ellipses._offsets
            old_data = self.curr_ellipses.get_array()
            combined_majors = np.hstack([old_majors, major_axes])
            combined_minors = np.hstack([old_minors, minor_axes])
            combined_angles = np.hstack([old_angles, angles])
            combined_data = np.hstack([old_data, data])
            combined_offsets = np.vstack([old_offsets, XY])
            new_ec = EllipseCollection(combined_majors,
                                       combined_minors,
                                       combined_angles,
                                       offsets=combined_offsets,
                                       transOffset=ax.transData)
            new_ec.set_array(combined_data)
            ec = new_ec
        else:
            ax = plt.subplot(1, 1, 1)
            ec = EllipseCollection(major_axes,
                                   minor_axes,
                                   angles,
                                   offsets=XY,
                                   transOffset=ax.transData)
            ec.set_array(data)

        self.curr_ellipses = ec
        ax.add_collection(ec)
        ax.autoscale_view()
        cbar = plt.colorbar(ec)
        if colorbar_lim != None:
            cbar.set_clim(colorbar_lim)
            if max_color_range == True:
                norm = mpl.colors.Normalize(vmin=colorbar_lim[0],
                                            vmax=colorbar_lim[1])
                cbar = mpl.colorbar.ColorbarBase(cbar.ax, norm=norm)
        ec.color_bar = cbar
        cbar.set_label(cbar_label)
        return ec