Ejemplo n.º 1
0
def plot_scatter_ondem(lons_data,
                       lats_data,
                       val,
                       pathgg,
                       vname,
                       lonSource1=0,
                       latSource1=0,
                       lonSource2=0,
                       latSource2=0):
    verticalEx = 0.1
    ls = LightSource(azdeg=135, altdeg=30)

    lat_minimum = 19.31
    lat_maximum = 19.48
    lon_minimum = -155.40
    lon_maximum = -155.15

    lat_minimum_DEM = 19.31
    lat_maximum_DEM = 19.48
    lon_minimum_DEM = -155.40
    lon_maximum_DEM = -155.15
    ds = gdal.Open(path_data + 'dem_srtm.tif')
    data = ds.ReadAsArray()
    gt = ds.GetGeoTransform()
    cols = ds.RasterXSize
    rows = ds.RasterYSize
    minx = gt[0]
    miny = gt[3] + cols * gt[4] + rows * gt[5]
    maxx = gt[0] + cols * gt[1] + rows * gt[2]
    maxy = gt[3]
    lons = np.linspace(minx, maxx, cols)
    lats = np.linspace(miny, maxy, rows)
    lats = lats[::-1]
    #elats = lats[::-1]
    dem, lat_DEM, lon_DEM = crop_dem(data, lats, lons, lat_minimum_DEM,
                                     lat_maximum_DEM, lon_minimum_DEM,
                                     lon_maximum_DEM)  #Cropping the DEM
    rgb = ls.shade(dem,
                   cmap=plt.cm.gist_gray,
                   vert_exag=verticalEx,
                   blend_mode='overlay')
    '''
    Defining parameters for DEM plot
    NOTE: as the DEM is plotted with imshow (which is in pixel coordinates), the llclon... parameters 
    must correspond to the corner of the matrixm otherwise georeferencing and subsequent coordinate plot DO NOT WORK!!! 
    '''
    llclon = np.min(lon_DEM)
    llclat = np.min(lat_DEM)
    urclon = np.max(lon_DEM)
    urclat = np.max(lat_DEM)

    map = Basemap(projection='tmerc',
                  lat_0=(llclat + urclat) * 0.5,
                  lon_0=(llclon + urclon) * 0.5,
                  llcrnrlon=llclon,
                  llcrnrlat=llclat,
                  urcrnrlon=urclon,
                  urcrnrlat=urclat)
    lons_map, lats_map = map(lons_data, lats_data)

    im1 = map.imshow(rgb, origin='upper', rasterized=True)
    im2 = map.scatter(lons_map,
                      lats_map,
                      s=20,
                      c=val,
                      alpha=0.4,
                      cmap='jet',
                      vmin=-4,
                      vmax=0)
    if lonSource1:
        lonSource_map1, latSource_map1 = map(lonSource1, latSource1)
        im3 = map.scatter(lonSource_map1, latSource_map1, s=20, c='black')
    if lonSource2:
        lonSource_map2, latSource_map2 = map(lonSource2, latSource2)
        im3 = map.scatter(lonSource_map2, latSource_map2, s=20, c='black')
    cbar = map.colorbar(im2, shrink=0.2, alpha=1)
    cbar.set_label('LOS velocity [m/year]', fontsize=18)
    cbar.solids.set_rasterized(True)
    plt.savefig(pathgg + vname + '.pdf', dpi=300)
    plt.close('all')
Ejemplo n.º 2
0
 def __init__(self, sigma, fraction=0.5):
     self.gauss_filter = GaussianFilter(sigma, alpha=1)
     self.light_source = LightSource()
     self.fraction = fraction
Ejemplo n.º 3
0
        if (z[a][b] > maxz):
            maxz = z[a][b]
            maxx = a
            maxy = b

print(" Maxima = " + disp_string(0, maxx, maxy, maxz))

for i in range(n):
    rix[i] = random.randrange(0, 150)
    riy[i] = random.randrange(0, 150)
    vx[i] = x[rix[i]][0]
    vy[i] = y[0][riy[i]]
    vz[i] = z[rix[i]][riy[i]]
    vp[i] = aastr(6)

ls = LightSource(azdeg=20, altdeg=65)
rgb = ls.shade(z, plt.cm.RdYlBu)
plt.rc('font', size=8)
elevation = 25
edir = True
azimuth = 80
adir = True

while True:
    fig = plt.figure(1)
    ax = fig.gca(projection='3d')
    plt.hold(True)
    ax.grid(False)  # Hide grid lines
    ax.axis('off')  # OR #ax.set_xticks([])#ax.set_yticks([])#ax.set_zticks([])
    ax.view_init(elevation, azimuth)
    ax.dist = 5
Ejemplo n.º 4
0
def two_feature_analysis(data, regressor, feature1_ind, feature2_ind,
                         feature1_name, feature2_name, y_name,
                         xticks,yticks,zticks,cbar_ticks,ylabels,
                         cbar_label,
                         lon_ind=0, lat_ind=1, y_ind=-1, query_size=10,
                         lightsource_x=270, lightsource_y=45,
                         fig_size_x=10,fig_size_y=10,
                         elev=20,azmin=34,
                         x_axis_scale=1,
                         y_axis_scale=1,
                         z_axis_scale=1.4,
                         vmin=-4,vmax=2,
                         plot_name='3D_plot.pdf'
                         ):

    # set up variables
    X = data[:, :y_ind]
    log_thick = np.log(data[:, y_ind])

    # get feature column
    feature = X[:, [feature1_ind, feature2_ind]]

    # learn y just based on feature
    model = regressor.fit(feature, log_thick)
    print(('Polynomial feature names: {0}'.format(model.get_params()['poly'].get_feature_names())))
    print(('Polynomial coefficients: {0}'.format(model.get_params()['linear'].coef_)))

    # generate query sets
    fea1_min = np.min(feature[:, 0])
    fea1_max = np.max(feature[:, 0])
    fea1_query = np.linspace(fea1_min, fea1_max, query_size)[:, np.newaxis]
    fea2_min = np.min(feature[:, 1])
    fea2_max = np.max(feature[:, 1])
    fea2_query = np.linspace(fea2_min, fea2_max, query_size)[:, np.newaxis]

    # draw regression surface
    xeval, yeval = np.meshgrid(fea1_query, fea2_query)
    query = np.vstack((xeval.ravel(), yeval.ravel())).T
    fea_pred = model.predict(query)
    fea_pred_arr = fea_pred.reshape(query_size, query_size)
    
     # Values for thickness                          cmap=CMAP, lw=0.1, vmin=2, vmax=10)

    fig = plt.figure()
    #fig.set_size_inches((fig_size_x,fig_size_y))
    ax = fig.gca(projection='3d')

    # scale axes
    x_scale=x_axis_scale
    y_scale=y_axis_scale
    z_scale=z_axis_scale

    scale=np.diag([x_scale, y_scale, z_scale, 1.0])
    scale=scale*(1.0/scale.max())
    scale[3,3]=1.0

    def short_proj():
      return np.dot(Axes3D.get_proj(ax), scale)

    ax.get_proj = short_proj

    # add lightsource
    light = LightSource(lightsource_x, lightsource_y)
    illuminated_surface = light.shade(fea_pred_arr, cmap = plt.get_cmap(CMAP),blend_mode='soft')
    # make the plot surface
    surf = ax.plot_surface(xeval, yeval, fea_pred_arr, rstride=1, cstride=1,
                           cmap=CMAP, lw=0.1, vmin=vmin, vmax=vmax
                           )

    fig.tight_layout()
    # axis labels
    fs = 10
    lp = 15
    ax.set_xlabel(feature1_name,fontsize=fs,ha='center',labelpad=lp)
    ax.set_ylabel(feature2_name,fontsize=fs,ha='center',labelpad=lp)
    ax.set_zlabel(y_name,fontsize=fs,ha='center',va='baseline',labelpad=0)
    # axis ticks
    ax.set_xticks(xticks)
    ax.set_yticks(yticks)
    ax.set_zticks(zticks)
    # axis tick labels
    fs = 10
    ax.set_xticklabels(xticks,fontsize=fs)
    ax.set_yticklabels(ylabels,fontsize=fs)
    ax.set_zticklabels(zticks,fontsize=fs)
    ax.tick_params(axis='both', which='major', pad=5)
    ax.zaxis._axinfo['label']['space_factor'] = 2.8
    ax.tick_params(axis='z', which='major', pad=0)
    # axis space factors
    sf = 3
    ax.yaxis._axinfo['label']['space_factor'] = sf
    ax.xaxis._axinfo['label']['space_factor'] = sf
    ax.zaxis._axinfo['label']['space_factor'] = 0
    # color bar
    m = cm.ScalarMappable(cmap=surf.cmap, norm=surf.norm)
    m.set_array(fea_pred_arr)
    cbar = plt.colorbar(m, shrink=0.5, aspect=15, orientation='horizontal',pad=0.05)
    cbar.set_ticks(cbar_ticks)
    cbar.set_ticklabels(cbar_ticks)
    cbar.set_label(cbar_label)
    #cbar.ax.set_yticklabels(cbar_ticks,fontsize=fs)
    #cbar.ax.tick_params(labelsize=10) 
    #plt.title('Regression Surface')
    ax.view_init(elev=1.0*elev, azim=azmin)
    plt.savefig(plot_name,bbox_inches='tight',dpi=600,format='pdf')
Ejemplo n.º 5
0
    def createTopographicImage(self):
        try:
            # 緯度、経度をエディタから受け取るよ
            lat, lon = float(self.LatEdit.text()), float(self.LonEdit.text())
        except:
            # 緯度経度が入力されていなかったらエラーメッセージを表示するよ
            QMessageBox.information(
                self, "None file Error",
                "Can't create map. <br> Please Press lat and lon.",
                QMessageBox.Ok)
            return
        # 大きな画像いやだって人は下のコメントアウト外してね
        #elevs = self.elev(lat, lon)
        # ここの端の時の処理思いつかなかったよ;;
        calc_lon = 0.013
        calc_lat = 0.00833333333
        elevs1 = self.elev(lat, lon)
        elevs2 = self.elev(lat, lon + calc_lon)
        elevs3 = self.elev(lat + calc_lat, lon)
        elevs4 = self.elev(lat + calc_lat, lon + calc_lon)
        elevs = np.vstack((np.hstack(
            (elevs1, elevs2)), np.hstack((elevs3, elevs4))))
        # 配列の要素が全部nanだったときに怒られちゃったからここで例外処理をするよ
        warnings.simplefilter('error')
        try:
            # 配列の中のnanを同じ配列の中のnan以外で最小のものにするよ
            elevs[np.isnan(elevs)] = np.nanmin(elevs)
        except RuntimeWarning:
            # 配列の要素が全部nanだったときこっちの処理が動くよ
            elevs[np.isnan(elevs)] = -9999.0

        # 図を表示するときに使うよ
        fig, ax = plt.subplots()
        # 配列の反転だよ
        elevs = np.flipud(elevs)
        # azdeg: 光源の方位 0 ~ 360 altdeg: 光源の高度 0 ~ 90
        # 配列に色や影を追加するよ
        ls = LightSource(azdeg=180, altdeg=65)
        # カラーマップのデータを配列と組み合わせるよ
        color = ls.shade(elevs, cmap.rainbow)
        cs = ax.imshow(elevs, cmap.rainbow)
        ax.imshow(color)

        # 新しいラベルを作るよ
        make_axes = make_axes_locatable(ax)
        # 新しく作ったラベルの設定左から位置、ラベルの大きさ、パディングだよ
        cax = make_axes.append_axes("right", size="2%", pad=0.05)
        # 図に新しく作ったラベルを追加するよ
        fig.colorbar(cs, cax)

        # x軸y軸を消すよ
        ax.set_xticks([])
        ax.set_yticks([])

        # 画像の周りの余白をいじるよ
        fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9)

        # 画像をキャンバスに追加するよ
        canvas = FigureCanvas(fig)
        # キャンバスに描画するよ
        canvas.draw()

        # キャンバスの大きさを受け取るよ
        w, h = canvas.get_width_height()
        # キャンバスの画像をQImage型にするよ
        self.Image = QImage(canvas.buffer_rgba(), w, h, QImage.Format_ARGB32)
        # 地形図を表示するラベルに画像をセットするよ
        self.Canvas.setPixmap(QPixmap(self.Image))
Ejemplo n.º 6
0
    def draw_3d(self):
        """
        Draw various 3D plots
        """
        self.init_axes()

        bb = fb.fil[0]['ba'][0]
        aa = fb.fil[0]['ba'][1]

        zz = np.array(fb.fil[0]['zpk'][0])
        pp = np.array(fb.fil[0]['zpk'][1])

        wholeF = fb.fil[0]['freqSpecsRangeType'] != 'half'  # not used
        f_S = fb.fil[0]['f_S']
        N_FFT = params['N_FFT']

        alpha = self.diaAlpha.value() / 10.
        cmap = cm.get_cmap(str(self.cmbColormap.currentText()))
        # Number of Lines /step size for H(f) stride, mesh, contour3d:

        stride = 10 - self.diaHatch.value()
        NL = 3 * self.diaHatch.value() + 5

        surf_enabled = qget_cmb_box(self.cmbMode3D,
                                    data=False) in {'Surf', 'Contour'}
        self.cmbColormap.setEnabled(surf_enabled)
        self.chkColormap_r.setEnabled(surf_enabled)
        self.chkLighting.setEnabled(surf_enabled)
        self.chkColBar.setEnabled(surf_enabled)
        self.diaAlpha.setEnabled(surf_enabled or self.chkContour2D.isChecked())

        #cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
        #scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

        #-----------------------------------------------------------------------------
        # Calculate H(w) along the upper half of unity circle
        #-----------------------------------------------------------------------------

        [w, H] = sig.freqz(bb, aa, worN=N_FFT, whole=True)
        H = np.nan_to_num(H)  # replace nans and inf by finite numbers

        H_abs = abs(H)
        H_max = max(H_abs)
        H_min = min(H_abs)
        #f = w / (2 * pi) * f_S                  # translate w to absolute frequencies
        #F_min = f[np.argmin(H_abs)]

        plevel_rel = 1.05  # height of plotted pole position relative to zmax
        zlevel_rel = 0.1  # height of plotted zero position relative to zmax

        if self.chkLog.isChecked():  # logarithmic scale
            bottom = np.floor(max(self.zmin_dB, 20 * log10(H_min)) / 10) * 10
            top = self.zmax_dB
            top_bottom = top - bottom

            zlevel = bottom - top_bottom * zlevel_rel

            if self.cmbMode3D.currentText(
            ) == 'None':  # "Poleposition" for H(f) plot only
                plevel_top = 2 * bottom - zlevel  # height of displayed pole position
                plevel_btm = bottom
            else:
                plevel_top = top + top_bottom * (plevel_rel - 1)
                plevel_btm = top

        else:  # linear scale
            bottom = max(self.zmin, H_min)  # min. display value
            top = self.zmax  # max. display value
            top_bottom = top - bottom
            #   top = zmax_rel * H_max # calculate display top from max. of H(f)

            zlevel = bottom + top_bottom * zlevel_rel  # height of displayed zero position

            if self.cmbMode3D.currentText(
            ) == 'None':  # "Poleposition" for H(f) plot only
                #H_max = np.clip(max(H_abs), 0, self.zmax)
                # make height of displayed poles same to zeros
                plevel_top = bottom + top_bottom * zlevel_rel
                plevel_btm = bottom
            else:
                plevel_top = plevel_rel * top
                plevel_btm = top

        # calculate H(jw)| along the unity circle and |H(z)|, each clipped
        # between bottom and top
        H_UC = H_mag(bb,
                     aa,
                     self.xy_UC,
                     top,
                     H_min=bottom,
                     log=self.chkLog.isChecked())
        Hmag = H_mag(bb,
                     aa,
                     self.z,
                     top,
                     H_min=bottom,
                     log=self.chkLog.isChecked())

        #===============================================================
        ## plot Unit Circle (UC)
        #===============================================================
        if self.chkUC.isChecked():
            # Plot unit circle and marker at (1,0):
            self.ax3d.plot(self.xy_UC.real,
                           self.xy_UC.imag,
                           ones(len(self.xy_UC)) * bottom,
                           lw=2,
                           color='k')
            self.ax3d.plot([0.97, 1.03], [0, 0], [bottom, bottom],
                           lw=2,
                           color='k')

        #===============================================================
        ## plot ||H(f)| along unit circle as 3D-lineplot
        #===============================================================
        if self.chkHf.isChecked():
            self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, H_UC, alpha=0.5)
            # draw once more as dashed white line to improve visibility
            self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, H_UC, 'w--')

            if stride < 10:  # plot thin vertical line every stride points on the UC
                for k in range(len(self.xy_UC[::stride])):
                    self.ax3d.plot([
                        self.xy_UC.real[::stride][k],
                        self.xy_UC.real[::stride][k]
                    ], [
                        self.xy_UC.imag[::stride][k],
                        self.xy_UC.imag[::stride][k]
                    ], [
                        np.ones(len(self.xy_UC[::stride]))[k] * bottom,
                        H_UC[::stride][k]
                    ],
                                   linewidth=1,
                                   color=(0.5, 0.5, 0.5))

        #===============================================================
        ## plot Poles and Zeros
        #===============================================================
        if self.chkPZ.isChecked():

            PN_SIZE = 8  # size of P/N symbols

            # Plot zero markers at |H(z_i)| = zlevel with "stems":
            self.ax3d.plot(zz.real,
                           zz.imag,
                           ones(len(zz)) * zlevel,
                           'o',
                           markersize=PN_SIZE,
                           markeredgecolor='blue',
                           markeredgewidth=2.0,
                           markerfacecolor='none')
            for k in range(len(zz)):  # plot zero "stems"
                self.ax3d.plot([zz[k].real, zz[k].real],
                               [zz[k].imag, zz[k].imag], [bottom, zlevel],
                               linewidth=1,
                               color='b')

            # Plot the poles at |H(z_p)| = plevel with "stems":
            self.ax3d.plot(np.real(pp),
                           np.imag(pp),
                           plevel_top,
                           'x',
                           markersize=PN_SIZE,
                           markeredgewidth=2.0,
                           markeredgecolor='red')
            for k in range(len(pp)):  # plot pole "stems"
                self.ax3d.plot([pp[k].real, pp[k].real],
                               [pp[k].imag, pp[k].imag],
                               [plevel_btm, plevel_top],
                               linewidth=1,
                               color='r')

        #===============================================================
        ## 3D-Plots of |H(z)| clipped between |H(z)| = top
        #===============================================================

        m_cb = cm.ScalarMappable(
            cmap=cmap)  # normalized proxy object that is mappable
        m_cb.set_array(Hmag)  # for colorbar

        #---------------------------------------------------------------
        ## 3D-mesh plot
        #---------------------------------------------------------------
        if self.cmbMode3D.currentText() == 'Mesh':
            #    fig_mlab = mlab.figure(fgcolor=(0., 0., 0.), bgcolor=(1, 1, 1))
            #    self.ax3d.set_zlim(0,2)
            self.ax3d.plot_wireframe(self.x,
                                     self.y,
                                     Hmag,
                                     rstride=5,
                                     cstride=stride,
                                     linewidth=1,
                                     color='gray')

        #---------------------------------------------------------------
        ## 3D-surface plot
        #---------------------------------------------------------------
        # http://stackoverflow.com/questions/28232879/phong-shading-for-shiny-python-3d-surface-plots
        elif self.cmbMode3D.currentText() == 'Surf':
            if MLAB:
                ## Mayavi
                surf = mlab.surf(self.x,
                                 self.y,
                                 H_mag,
                                 colormap='RdYlBu',
                                 warp_scale='auto')
                # Change the visualization parameters.
                surf.actor.property.interpolation = 'phong'
                surf.actor.property.specular = 0.1
                surf.actor.property.specular_power = 5
                #                s = mlab.contour_surf(self.x, self.y, Hmag, contour_z=0)
                mlab.show()

            else:
                if self.chkLighting.isChecked():
                    ls = LightSource(azdeg=0,
                                     altdeg=65)  # Create light source object
                    rgb = ls.shade(
                        Hmag, cmap=cmap)  # Shade data, creating an rgb array
                    cmap_surf = None
                else:
                    rgb = None
                    cmap_surf = cmap

    #            s = self.ax3d.plot_surface(self.x, self.y, Hmag,
    #                    alpha=OPT_3D_ALPHA, rstride=1, cstride=1, cmap=cmap,
    #                    linewidth=0, antialiased=False, shade=True, facecolors = rgb)
    #            s.set_edgecolor('gray')
                s = self.ax3d.plot_surface(self.x,
                                           self.y,
                                           Hmag,
                                           alpha=alpha,
                                           rstride=1,
                                           cstride=1,
                                           linewidth=0,
                                           antialiased=False,
                                           facecolors=rgb,
                                           cmap=cmap_surf,
                                           shade=True)
                s.set_edgecolor(None)
        #---------------------------------------------------------------
        ## 3D-Contour plot
        #---------------------------------------------------------------
        elif self.cmbMode3D.currentText() == 'Contour':
            s = self.ax3d.contourf3D(self.x,
                                     self.y,
                                     Hmag,
                                     NL,
                                     alpha=alpha,
                                     cmap=cmap)

        #---------------------------------------------------------------
        ## 2D-Contour plot
        # TODO: 2D contour plots do not plot correctly together with 3D plots in
        #       current matplotlib 1.4.3 -> disable them for now
        # TODO: zdir = x / y delivers unexpected results -> rather plot max(H)
        #       along the other axis?
        # TODO: colormap is created depending on the zdir = 'z' contour plot
        #       -> set limits of (all) other plots manually?
        if self.chkContour2D.isChecked():
            #            self.ax3d.contourf(x, y, Hmag, 20, zdir='x', offset=xmin,
            #                         cmap=cmap, alpha = alpha)#, vmin = bottom)#, vmax = top, vmin = bottom)
            #            self.ax3d.contourf(x, y, Hmag, 20, zdir='y', offset=ymax,
            #                         cmap=cmap, alpha = alpha)#, vmin = bottom)#, vmax = top, vmin = bottom)
            s = self.ax3d.contourf(self.x,
                                   self.y,
                                   Hmag,
                                   NL,
                                   zdir='z',
                                   offset=bottom - (top - bottom) * 0.05,
                                   cmap=cmap,
                                   alpha=alpha)

        # plot colorbar for suitable plot modes
        if self.chkColBar.isChecked() and (self.chkContour2D.isChecked()
                                           or str(self.cmbMode3D.currentText())
                                           in {'Contour', 'Surf'}):
            self.colb = self.mplwidget.fig.colorbar(m_cb,
                                                    ax=self.ax3d,
                                                    shrink=0.8,
                                                    aspect=20,
                                                    pad=0.02,
                                                    fraction=0.08)

        #----------------------------------------------------------------------
        ## Set view limits and labels
        #----------------------------------------------------------------------
        if not self.mplwidget.mplToolbar.a_lk.isChecked():
            self.ax3d.set_xlim3d(self.xmin, self.xmax)
            self.ax3d.set_ylim3d(self.ymin, self.ymax)
            self.ax3d.set_zlim3d(bottom, top)
        else:
            self._restore_axes()

        self.ax3d.set_xlabel('Re')  #(fb.fil[0]['plt_fLabel'])
        self.ax3d.set_ylabel(
            'Im'
        )  #(r'$ \tau_g(\mathrm{e}^{\mathrm{j} \Omega}) / T_S \; \rightarrow $')
        #        self.ax3d.set_zlabel(r'$|H(z)|\; \rightarrow $')
        self.ax3d.set_title(
            r'3D-Plot of $|H(\mathrm{e}^{\mathrm{j} \Omega})|$ and $|H(z)|$')

        self.redraw()
Ejemplo n.º 7
0
topodat = m.transform_scalar(data, lons, lats, nx, ny)

print('Getting colormap...')
# get colormap
try:
    cptfile = '//Users//trev//Documents//DATA//GMT//cpt//wiki-2.0.cpt'
except:
    cptfile = '/nas/active/ops/community_safety/ehp/georisk_earthquake/hazard/DATA/cpt/wiki-2.0.cpt'

cmap, zvals = cpt2colormap(cptfile, 30)
cmap = remove_last_cmap_colour(cmap)

# make shading
print('Making map...')
ls = LightSource(azdeg=180, altdeg=5)
#norm = mpl.colors.Normalize(vmin=-8000/zscale, vmax=5000/zscale)
norm = mpl.colors.Normalize(vmin=-1000 / zscale, vmax=1900 / zscale)  #wiki

rgb = ls.shade(topodat.data, cmap=cmap, norm=norm)
im = m.imshow(rgb, alpha=1.0)

##########################################################################################
# add epicentres
##########################################################################################
# get colormap
cptfile = '//Users//trev//Documents//DATA//GMT//cpt//Paired_10.cpt'
ncols = 10
cmap, zvals = cpt2colormap(cptfile, ncols + 1)
cmap = remove_last_cmap_colour(cmap)
cs = (cmap(arange(ncols)))
Ejemplo n.º 8
0
def combine_signals(X_all,
                    Y_class,
                    Y_loc,
                    defo_m,
                    APS_topo_m,
                    APS_turb_m,
                    heading,
                    dem,
                    defo_source,
                    defo_sources,
                    loc_list,
                    outputs,
                    succesful_generate,
                    sar_speckle_strength=0.05):
    """ Given the synthetic outputs and labels (X and Y) and the parts of the synthetic data, combine into different formats and write to dictionary (X_all)
    Inputs:
        X_all | dict of masked arrays | keys are formats (e.g. uuu), then rank 4 masked array
        Y_class | rank 2 array | class labels, n x 1 (ie not one hot encoding)
        Y_loc | rank 2 array |  location of deformaiton, nx4 (xy location, xy width)
        defo_m | rank 2 array | deformation in metres, not masked
        APS_topo_m | rank 2 array | topographically correlated APS, incoherence and water masked out.  
        APS_turb_m | rank 2 array | tubulent APS, not masked
        heading | float | in degrees.  e.g. 192 or 012
        dem | rank 2 masked array | the  DEM.  Needed to make radar amplitude.  
        defo_source_n | int | 0 = no def, 1 = dyke, 2 = sill, 3 = Mogi.  No 0's should be passed to this as it makes no deformatio nsignals.  
        loc_list | list of tuples | xy of centre of location box, and xy width.  e.g [(186, 162), (69, 75)]
        outputs | list of strings | e.g. ['uuu', 'uud']
        succesful_generate | int | which number within a file we've generated so far
        sar_speckle_strength | float | strength (variance) of gaussain speckled noise added to SAR real and imaginary
    Returns:
        X_all | as above, but updated
        Y_class  | as above, but updated
        Y_loc  | as above, but updated
        succesful | boolean | True if no nans are present.  False if nans are
    History:
        2020/08/20 | MEG | Written from exisiting scripts.  
        2020/10/19 | MEG | Fix bug that nans_present was being returned, instead of succesful (and they are generally the opposite of each other)
    """
    import numpy as np
    import numpy.ma as ma
    from matplotlib.colors import LightSource  # used to make a synthetic Radar return.

    def normalise_m1_1(r2_array):
        """ Rescale a rank 2 array so that it lies within the range[-1, 1]
        """
        import numpy as np
        r2_array = r2_array - np.min(r2_array)
        r2_array = 2 * (r2_array / np.max(r2_array))
        r2_array -= 1
        return r2_array

    s1_wav = 0.056  # Sentinel-1 wavelength in m
    incidence = 30  # ditto - 30 roughly right for S1

    # 1 Create ph_all and classes and locations, depending on if we want deformation or not.
    if defo_source == 'no_def':
        ph_all = ((4 * np.pi) / s1_wav) * (
            APS_topo_m + APS_turb_m
        )  # comnbine the signals in m, then convert to rads
        Y_loc[succesful_generate, :] = np.array(
            [0, 0, 0, 0])  # 0 0 0 0 for no deformaiton
    else:
        ph_all = ((4 * np.pi) / s1_wav) * (
            APS_topo_m + APS_turb_m + defo_m
        )  # combine the signals in m, then convert to rads.  Here we include deformation.
        Y_loc[succesful_generate, :] = np.array(
            [loc_list[0][0], loc_list[0][1], loc_list[1][0],
             loc_list[1][1]])  # location of deformation
    Y_class[succesful_generate,
            0] = defo_sources.index(defo_source)  # write the label as a number
    ph_all_wrap = (ph_all + np.pi) % (2 * np.pi) - np.pi  # wrap

    #1 Genreate SAR amplitude
    look_az = heading - 90
    look_in = 90 - incidence  #
    ls = LightSource(azdeg=look_az, altdeg=look_in)
    sar_amplitude = normalise_m1_1(ls.hillshade(dem))  # in range [-1, 1]

    # make real and imaginary
    ifg_real = sar_amplitude * np.cos(ph_all_wrap)
    ifg_imaginary = sar_amplitude * np.sin(ph_all_wrap)
    ifg_real = ifg_real + sar_speckle_strength * np.random.randn(
        ifg_real.shape[0], ifg_real.shape[1])  # add noise to real
    ifg_imaginary = ifg_imaginary + sar_speckle_strength * np.random.randn(
        ifg_real.shape[0], ifg_real.shape[1])  # and imaginary

    # make things rank 4
    unwrapped = ma.expand_dims(ma.expand_dims(ph_all, axis=0), axis=3)
    dem = ma.expand_dims(ma.expand_dims(dem, axis=0), axis=3)
    ifg_real = ma.expand_dims(ma.expand_dims(ifg_real, axis=0), axis=3)
    ifg_imaginary = ma.expand_dims(ma.expand_dims(ifg_imaginary, axis=0),
                                   axis=3)
    wrapped = ma.expand_dims(ma.expand_dims(ph_all_wrap, axis=0), axis=3)

    # Check for Nans
    nans_present = False  #initiate
    for signal in [unwrapped, dem, ifg_real, ifg_imaginary, wrapped]:
        nans_present = np.logical_or(
            nans_present,
            np.max(np.isnan(signal).astype(int)).astype(bool)
        )  # check if nans in current signal, and update succesful.
    if nans_present:
        succesful = False
        print(f"| Failed due to Nans ", end='')
    else:
        succesful = True
        for output in outputs:
            if output == 'uuu':
                X_all[output][succesful_generate, ] = ma.concatenate(
                    (unwrapped, unwrapped, unwrapped), axis=3)  # uuu
            elif output == 'uud':
                X_all[output][succesful_generate, ] = ma.concatenate(
                    (unwrapped, unwrapped, dem), axis=3)  # uud
            elif output == 'rid':
                X_all[output][succesful_generate, ] = ma.concatenate(
                    (ifg_real, ifg_imaginary, dem), axis=3)  # rid
            elif output == 'www':
                X_all[output][succesful_generate, ] = ma.concatenate(
                    (wrapped, wrapped, wrapped), axis=3)  # www
            elif output == 'wwd':
                X_all[output][succesful_generate, ] = ma.concatenate(
                    (wrapped, wrapped, dem), axis=3)  #wwd
            else:
                raise Exception(
                    "Error in output format.  Should only be either 'uuu', 'uud', 'rid', 'www', or 'wwd'.  Exiting.  "
                )

    return X_all, Y_class, Y_loc, succesful
Ejemplo n.º 9
0
base_name = 'PNG/S03_interferences' # Le nom par défaut

i = 0                              # Initialisation du compteur
for t in np.arange(tmin,tmax,dt):  # On boucle sur le temps
    i += 1                         # Incrémentation du compteur
    print(t)                       # Un peu de feedback
    Z1 = source(X,Y,t,-pos,0)      # La première source
    Z2 = source(X,Y,t, pos,0,phi)  # et la seconde

    # Ouverture de la figure et définition des sous-figures
    plt.figure(figsize=(8,7.76)) 
    ax1= plt.subplot2grid((3,3),(0,0),colspan=2,rowspan=2)
    plt.title('Interferences a deux sources, $t={}$'.format(round(t,1)))
    plt.ylabel('$y$')
    if shading:
        ls = LightSource(azdeg=20,altdeg=65) # create light source object.
        rgb = ls.shade(Z1+Z2,plt.cm.copper)  # shade data, creating an rgb array.
        plt.imshow(rgb,extent=extent)
    else:
        plt.imshow(Z1+Z2,interpolation='bilinear',extent=extent,cmap='jet',vmin=vmin,vmax=vmax)

    # Pour visualiser les deux plans de coupes
    plt.plot([-ext,ext],[ycut,ycut],'--k') 
    plt.plot([xcut,xcut],[-ext,ext],'--k')    

    # La figure du bas
    ax2= plt.subplot2grid((3,3),(2,0),colspan=2,sharex=ax1)
    plt.xlabel('$x$')
    plt.ylabel('Intensite\nSection $y={}$'.format(ycut))
    plt.ylim((0,vmax**2))
    plt.plot(x,(source(x,ycut,t,-pos,0)+source(x,ycut,t,pos,0,phi))**2)
Ejemplo n.º 10
0
def grid_search_plot_two_parameter_curves(estimator,
                                          grid,
                                          X,
                                          y,
                                          scoring="accuracy",
                                          cv=10,
                                          rotation=False):
    grid_estimator = model_selection.GridSearchCV(estimator,
                                                  grid,
                                                  cv=cv,
                                                  scoring=scoring,
                                                  return_train_score=True)
    grid_estimator.fit(X, y)

    param1_name = list(grid.keys())[0]
    param1_range = grid.get(param1_name)
    param2_name = list(grid.keys())[1]
    param2_range = grid.get(param2_name)

    fig = plt.figure()
    ax = plt.axes(projection='3d')
    X, Y = np.meshgrid(param1_range, param2_range)

    Z = grid_estimator.cv_results_.get('mean_test_score').reshape(X.shape)
    ls = LightSource(azdeg=0, altdeg=65)
    rgb = ls.shade(Z, plt.cm.RdYlBu)
    ax.plot_surface(X,
                    Y,
                    Z,
                    rstride=1,
                    cstride=1,
                    linewidth=0,
                    alpha=None,
                    antialiased=False,
                    facecolors=rgb,
                    label="Cross-validation score")

    Z = grid_estimator.cv_results_.get('mean_train_score').reshape(X.shape)
    rgb = ls.shade(Z, plt.cm.RdYlBu)
    ax.plot_surface(X,
                    Y,
                    Z,
                    rstride=1,
                    cstride=1,
                    linewidth=0,
                    alpha=None,
                    antialiased=False,
                    facecolors=rgb,
                    label="Training score")

    ax.set_xlabel(param1_name)
    ax.set_ylabel(param2_name)
    ax.set_zlabel('performance')
    #plt.legend(loc="best")
    plt.tight_layout()

    if rotation:
        for angle in range(0, 360):
            ax.view_init(20, angle)
            plt.draw()
            plt.pause(.1)
Ejemplo n.º 11
0
        def OnDrawGraph(self, evt):

            # simple line plot
            if evt.GetId() == self.idLine:
                # clear previous plot
                self.pnlPlot.Clear()
                # acquire new axes
                ax = self.pnlPlot.AddSubPlot(111)

                x = np.linspace(0,10,500)
                dashes = [10,5,100,5]

                line1, = ax.plot(x, np.sin(x), '--', linewidth=2,
                        label='Dashes set retroactively')
                line1.set_dashes(dashes)

                line2, = ax.plot(x, -1 * np.sin(x), dashes=[30, 5, 10, 5],
                        label='Dashes set proactively')
                ax.legend(loc='lower right')

            # histogram
            elif evt.GetId() == self.idHist:
                # clear previous plot
                self.pnlPlot.Clear()
                # acquire new axes
                ax0 = self.pnlPlot.AddSubPlot(1,2,1)
                ax1 = self.pnlPlot.AddSubPlot(1,2,2)

                np.random.seed(0)
                mu = 200
                sigma = 25
                bins = [100, 150, 180, 195, 205, 220, 250, 300]
                x = np.random.normal(mu, sigma, size=100)

                ax0.hist(x, 20, normed=1, histtype='stepfilled', facecolor='g',
                        alpha=0.75)
                ax0.set_title('stepfilled')

                ax1.hist(x, bins, normed=1, histtype='bar', rwidth=0.8)
                ax1.set_title('unequal bins')

            # contour
            elif evt.GetId() == self.idCont:
                # clear previous plot
                self.pnlPlot.Clear()
                # acquire new axes
                ax = self.pnlPlot.AddSubPlot(111)
                # we need figure object
                fig = self.pnlPlot.GetFigure()

                Y,X = np.mgrid[-3:3:100j, -3:3:100j]
                U = -1 - X**2 + Y
                V = 1 + X - Y**2
                strm = ax.streamplot(X, Y, U, V, color=U, linewidth=2,
                        cmap=matplotlib.cm.autumn)
                fig.colorbar(strm.lines)

            elif evt.GetId() == self.idShade:
                # clear previous plot
                self.pnlPlot.Clear()
                # acquire new axes
                ax = self.pnlPlot.AddSubPlot(111)
                # we need figure object
                fig = self.pnlPlot.GetFigure()

                from matplotlib.colors import LightSource
                y,x = np.mgrid[-4:2:200j, -4:2:200j]
                z = 10 * np.cos(x**2 + y**2)

                cmap = matplotlib.cm.copper
                ls = LightSource(315, 45)
                rgb = ls.shade(z, cmap)

                ax.imshow(rgb, interpolation='bilinear')
                im = ax.imshow(z, cmap=cmap)
                im.remove()
                fig.colorbar(im)
                ax.set_title('Using a colorbar with a shaded plot',
                        size='x-large')

            # draw plot
            self.pnlPlot.Draw()
Ejemplo n.º 12
0
    def plot_inv2(self, projection='lambert', geopolygons=None, showfig=True, blon=1, blat=1, \
                 netcodelist=[], plotetopo=True, stacode=None):
        """Plot station map
        ==============================================================================
        Input Parameters:
        projection      - type of geographical projection
        geopolygons     - geological polygons for plotting
        blon, blat      - extending boundaries in longitude/latitude
        showfig         - show figure or not
        ==============================================================================
        """
        inv = self.inv
        m = self._get_basemap_plt(projection=projection,
                                  geopolygons=geopolygons,
                                  blon=blon,
                                  blat=blat)
        # m.etopo()
        if plotetopo:
            from netCDF4 import Dataset
            from matplotlib.colors import LightSource
            import pycpt
            # etopodata   = Dataset('/home/leon/station_map/grd_dir/ETOPO2v2g_f4.nc')
            # etopodata   = Dataset('/home/lili/data_marin/map_data/station_map/grd_dir/ETOPO1_Ice_g_gmt4.grd')
            # etopo       = etopodata.variables['z'][:]
            # lons        = etopodata.variables['x'][:]
            # lats        = etopodata.variables['y'][:]
            etopodata = Dataset('/home/lili/gebco_alaska2.nc')
            etopo = etopodata.variables['elevation'][:]
            lons = etopodata.variables['lon'][:]
            lons[lons > 180.] = lons[lons > 180.] - 360.
            lats = etopodata.variables['lat'][:]

            ind_lon = (lons <= -120.) * (lons >= -180.)
            ind_lat = (lats <= 75.) * (lats >= 55.)
            # etopo       = etopo[ind_lat, ind_lon]
            tetopo = etopo[ind_lat, :]
            etopo = tetopo[:, ind_lon]
            lons = lons[ind_lon]
            lats = lats[ind_lat]

            ls = LightSource(azdeg=315, altdeg=45)
            # nx          = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1
            # etopo,lons  = shiftgrid(180.,etopo,lons,start=False)
            # topodat,x,y = m.transform_scalar(etopo,lons,lats,nx,ny,returnxy=True)
            ny, nx = etopo.shape
            topodat, xtopo, ytopo = m.transform_scalar(etopo,
                                                       lons,
                                                       lats,
                                                       nx,
                                                       ny,
                                                       returnxy=True)
            m.imshow(ls.hillshade(topodat, vert_exag=1., dx=1., dy=1.),
                     cmap='gray')
            mycm1 = pycpt.load.gmtColormap(
                '/home/lili/data_marin/map_data/station_map/etopo1.cpt_land')
            mycm2 = pycpt.load.gmtColormap(
                '/home/lili/data_marin/map_data/station_map/bathy1.cpt')
            mycm2.set_over('w', 0)
            m.imshow(
                ls.shade(topodat,
                         cmap=mycm1,
                         vert_exag=1.,
                         dx=1.,
                         dy=1.,
                         vmin=0.,
                         vmax=8000.))
            m.imshow(
                ls.shade(topodat,
                         cmap=mycm2,
                         vert_exag=1.,
                         dx=1.,
                         dy=1.,
                         vmin=-11000.,
                         vmax=-0.5))
        inet = 0
        for network in inv:
            stalons = np.array([])
            stalats = np.array([])
            if len(netcodelist) != 0:
                if network.code not in netcodelist:
                    continue
            inet += 1
            for station in network:
                # if stacode != None:
                #     if station.code != stacode:
                #         continue
                # if station.code == 'DHY':
                # time            = obspy.UTCDateTime('20150101')
                # if station.end_date < time:
                #     continue
                # time            = obspy.UTCDateTime('20141231')
                # if station.start_date > time:
                #     continue
                # az, baz, dist   = geodist.inv(np.ones(lons_glims.size)*station.longitude, np.ones(lons_glims.size)*station.latitude,\
                #                                       lons_glims, lats_glims)
                # if dist.min() > 5000.:
                #     continue
                stalons = np.append(stalons, station.longitude)
                stalats = np.append(stalats, station.latitude)
            stax, stay = m(stalons, stalats)
            # if inet==1:
            #     m.plot(stax, stay, 'r^', mec='k', markersize=8, label = network.code)
            # if inet == 2:
            #     m.plot(stax, stay, 'b^', mec='k', markersize=8, label = network.code)
            # m.plot(stax, stay, 'r^', mec='k', markersize=20, label = network.code+'.'+stacode)
            #
            # m.plot(stax, stay, 'r^', markersize=15)
            labellst    = ['r^', 'b^', 'm^', 'c^', 'w^', \
                           'ro', 'bo', 'mo', 'co',  'wo', \
                              'rv', 'bv', 'mv', 'cv',  'wv', \
                              'rs', 'bs', 'ms', 'cs',  'ws', \
                              'rp', 'bp', 'mp', 'cp',  'wp']

            # # # m.plot(stax, stay, labellst[inet-1], mec='k', markersize=8, label = network.code)
            m.plot(stax, stay, 'k^', mec='k', markersize=8, label=network.code)
            # if inet<=10:
            #     m.plot(stax, stay, '^', mec='k', markersize=8, label = network.code)
            # elif inet > 10 and inet <=20:
            #     m.plot(stax, stay, 's', mec='k', markersize=8, label = network.code)
            # elif inet > 20:
            #     m.plot(stax, stay, 'v', mec='k', markersize=8, label = network.code)
        # plt.legend(numpoints=1, loc=1, fontsize=10)
        #######################################
        # xc, yc      = m(np.array([-140]), np.array([63]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = - 81.097
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #
        # xc, yc      = m(np.array([-146]), np.array([65]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = 75.8076
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #
        # xc, yc      = m(np.array([-153]), np.array([64]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = 53.1896
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #
        # xc, yc      = m(np.array([-156]), np.array([62]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = 32.1394
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #######################################

        def read_slab_contour(infname, depth):
            ctrlst = []
            lonlst = []
            latlst = []
            with open(infname, 'rb') as fio:
                newctr = False
                for line in fio.readlines():
                    if line.split()[0] is '>':
                        newctr = True
                        if len(lonlst) != 0:
                            ctrlst.append([lonlst, latlst])
                        lonlst = []
                        latlst = []
                        z = -float(line.split()[1])
                        if z == depth:
                            skipflag = False
                        else:
                            skipflag = True
                        continue
                    if skipflag:
                        continue
                    lonlst.append(float(line.split()[0]))
                    latlst.append(float(line.split()[1]))
            return ctrlst

        dlst = [40., 60., 80., 100.]
        # dlst    = [100.]

        # m.plot(xslb, yslb,  '--', lw = 3, color='white')

        ###
        arr = np.loadtxt('SlabE325.dat')
        lonslb = arr[:, 0]
        latslb = arr[:, 1]
        depthslb = -arr[:, 2]
        for depth in dlst:
            # index           = (depthslb > (depth - .05))*(depthslb < (depth + .05))
            index = (depthslb == depth)
            lonslb2 = lonslb[index]
            latslb2 = latslb[index]
            indsort = lonslb2.argsort()
            lonslb2 = lonslb2[indsort]
            latslb2 = latslb2[indsort]
            xslb, yslb = m(lonslb2, latslb2)
            # m.plot(xslb, yslb,  '-', lw = 5, color='black')
            m.plot(xslb, yslb, '-', lw=3, color='red')

        # xc, yc      = m(np.array([-140]), np.array([63]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')

        # xc, yc      = m(np.array([-146, -142]), np.array([58, 64]))
        # m.plot(xc, yc,'k', lw = 5, color='black')
        # m.plot(xc, yc,'k', lw = 3, color='white')
        #
        # xc, yc      = m(np.array([-147, -159]), np.array([56, 62]))
        # m.plot(xc, yc,'k', lw = 5, color='black')
        # m.plot(xc, yc,'k', lw = 3, color='white')
        # plot_fault_lines(m, 'AK_Faults.txt')
        #
        import shapefile
        shapefname = '/home/lili/data_marin/map_data/volcano_locs/SDE_GLB_VOLC.shp'
        shplst = shapefile.Reader(shapefname)
        for rec in shplst.records():
            lon_vol = rec[4]
            lat_vol = rec[3]
            xvol, yvol = m(lon_vol, lat_vol)
            m.plot(xvol, yvol, '^', mfc='white', mec='k', ms=10)
        #
        #############################
        yakutat_slb_dat = np.loadtxt('YAK_extent.txt')
        yatlons = yakutat_slb_dat[:, 0]
        yatlats = yakutat_slb_dat[:, 1]
        xyat, yyat = m(yatlons, yatlats)
        m.plot(xyat, yyat, '-', lw=5, color='black')
        m.plot(xyat, yyat, '-', lw=3, color='white')
        #############################
        plot_fault_lines(m, 'AK_Faults.txt', color='blue')

        xc, yc = m(np.array([-153]), np.array([66.1]))
        m.plot(xc,
               yc,
               's',
               ms=10,
               markeredgecolor='black',
               markerfacecolor='cyan')
        xc, yc = m(np.array([-138]), np.array([60.3]))
        m.plot(xc,
               yc,
               's',
               ms=10,
               markeredgecolor='black',
               markerfacecolor='cyan')

        xc, yc = m(np.array([-150]), np.array([62.]))
        m.plot(xc,
               yc,
               '*',
               ms=20,
               markeredgecolor='black',
               markerfacecolor='yellow')
        xc, yc = m(np.array([-151]), np.array([64.]))
        m.plot(xc,
               yc,
               '*',
               ms=20,
               markeredgecolor='black',
               markerfacecolor='yellow')

        if showfig:
            plt.savefig('alaska_sta.png')
            # plt.show()
        return
Ejemplo n.º 13
0
    def plot_topo(self, projection='lambert', geopolygons=None, showfig=True, blon=1, blat=1, \
                 netcodelist=[], plotetopo=True, stacode=None):
        """Plot station map
        ==============================================================================
        Input Parameters:
        projection      - type of geographical projection
        geopolygons     - geological polygons for plotting
        blon, blat      - extending boundaries in longitude/latitude
        showfig         - show figure or not
        ==============================================================================
        """
        # inv     = self.inv
        m = self._get_basemap_plt(projection=projection,
                                  geopolygons=geopolygons,
                                  blon=blon,
                                  blat=blat)
        # m.etopo()
        if plotetopo:
            from netCDF4 import Dataset
            from matplotlib.colors import LightSource
            import pycpt
            # # # etopodata   = Dataset('/home/leon/station_map/grd_dir/ETOPO2v2g_f4.nc')
            # # # etopo       = etopodata.variables['z'][:]
            # # # lons        = etopodata.variables['x'][:]
            # # # lats        = etopodata.variables['y'][:]
            etopodata = Dataset('/home/leon/GEBCO_2019.nc')
            etopo = etopodata.variables['elevation'][:]
            lons = etopodata.variables['lon'][:]
            lats = etopodata.variables['lat'][:]

            ind_lon = (lons <= -123.) * (lons >= -180.)
            ind_lat = (lats <= 75.) * (lats >= 55.)
            # etopo       = etopo[ind_lat, ind_lon]
            tetopo = etopo[ind_lat, :]
            etopo = tetopo[:, ind_lon]
            lons = lons[ind_lon]
            lats = lats[ind_lat]

            ls = LightSource(azdeg=315, altdeg=45)
            # nx          = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1

            # etopo,lons  = shiftgrid(180., etopo, lons, start=False)

            # topodat,x,y = m.transform_scalar(etopo,lons,lats,nx,ny,returnxy=True)
            ny, nx = etopo.shape
            topodat, xtopo, ytopo = m.transform_scalar(etopo,
                                                       lons,
                                                       lats,
                                                       nx,
                                                       ny,
                                                       returnxy=True)
            m.imshow(ls.hillshade(topodat, vert_exag=1., dx=1., dy=1.),
                     cmap='gray')
            mycm1 = pycpt.load.gmtColormap('/home/leon/station_map/etopo1.cpt')
            mycm2 = pycpt.load.gmtColormap('/home/leon/station_map/bathy1.cpt')
            mycm2.set_over('w', 0)
            m.imshow(
                ls.shade(topodat,
                         cmap=mycm1,
                         vert_exag=1.,
                         dx=1.,
                         dy=1.,
                         vmin=0,
                         vmax=8000))
            m.imshow(
                ls.shade(topodat,
                         cmap=mycm2,
                         vert_exag=1.,
                         dx=1.,
                         dy=1.,
                         vmin=-11000,
                         vmax=-0.5))

        #############################
        yakutat_slb_dat = np.loadtxt('YAK_extent.txt')
        yatlons = yakutat_slb_dat[:, 0]
        yatlats = yakutat_slb_dat[:, 1]
        xyat, yyat = m(yatlons, yatlats)
        m.plot(xyat, yyat, '-', lw=5, color='black')
        m.plot(xyat, yyat, '-', lw=3, color='white')
        #############################

        plot_fault_lines(m, 'AK_Faults.txt', color='black')

        # #
        def read_slab_contour(infname, depth):
            ctrlst = []
            lonlst = []
            latlst = []
            with open(infname, 'rb') as fio:
                newctr = False
                for line in fio.readlines():
                    if line.split()[0] is '>':
                        newctr = True
                        if len(lonlst) != 0:
                            ctrlst.append([lonlst, latlst])
                        lonlst = []
                        latlst = []
                        z = -float(line.split()[1])
                        if z == depth:
                            skipflag = False
                        else:
                            skipflag = True
                        continue
                    if skipflag:
                        continue
                    lonlst.append(float(line.split()[0]))
                    latlst.append(float(line.split()[1]))
            return ctrlst

        dlst = [40., 60., 80., 100.]
        # dlst    = [100.]

        # m.plot(xslb, yslb,  '--', lw = 3, color='white')
        #
        ####
        arr = np.loadtxt('SlabE325.dat')
        lonslb = arr[:, 0]
        latslb = arr[:, 1]
        depthslb = -arr[:, 2]
        for depth in dlst:
            # index           = (depthslb > (depth - .05))*(depthslb < (depth + .05))
            index = (depthslb == depth)
            lonslb2 = lonslb[index]
            latslb2 = latslb[index]
            indsort = lonslb2.argsort()
            lonslb2 = lonslb2[indsort]
            latslb2 = latslb2[indsort]
            xslb, yslb = m(lonslb2, latslb2)
            # m.plot(xslb, yslb,  '-', lw = 5, color='black')
            m.plot(xslb, yslb, '-', lw=3, color='red')

        #############################
        # for depth in dlst:
        #     slb_ctrlst      = read_slab_contour('alu_contours.in', depth=depth)
        #     for slbctr in slb_ctrlst:
        #         xslb, yslb  = m(np.array(slbctr[0])-360., np.array(slbctr[1]))
        #         m.plot(xslb, yslb,  '--', lw = 3, color='red')
        ###

        import shapefile
        shapefname = '/home/leon/volcano_locs/SDE_GLB_VOLC.shp'
        shplst = shapefile.Reader(shapefname)
        for rec in shplst.records():
            lon_vol = rec[4]
            lat_vol = rec[3]
            xvol, yvol = m(lon_vol, lat_vol)
            m.plot(xvol, yvol, '^', mfc='white', mec='k', ms=10)
        #
        #
        xc, yc = m(np.array([-156]), np.array([67.5]))
        m.plot(xc,
               yc,
               '*',
               ms=20,
               markeredgecolor='black',
               markerfacecolor='yellow')
        xc, yc = m(np.array([-153]), np.array([61.]))
        m.plot(xc,
               yc,
               '*',
               ms=20,
               markeredgecolor='black',
               markerfacecolor='yellow')
        xc, yc = m(np.array([-149]), np.array([64.5]))
        m.plot(xc,
               yc,
               '*',
               ms=20,
               markeredgecolor='black',
               markerfacecolor='yellow')
        xc, yc = m(np.array([-152]), np.array([60.]))
        m.plot(xc,
               yc,
               '*',
               ms=20,
               markeredgecolor='black',
               markerfacecolor='yellow')
        if showfig:
            plt.show()
        return
Ejemplo n.º 14
0
    def plot_inv(self, projection='merc', geopolygons=None, showfig=True, blon=1, blat=1, \
                 netcodelist=[], plotetopo=True, stacode=None):
        """Plot station map
        ==============================================================================
        Input Parameters:
        projection      - type of geographical projection
        geopolygons     - geological polygons for plotting
        blon, blat      - extending boundaries in longitude/latitude
        showfig         - show figure or not
        ==============================================================================
        """
        inv = self.inv
        m = self._get_basemap_plt(projection=projection,
                                  geopolygons=geopolygons,
                                  blon=blon,
                                  blat=blat)
        # m.etopo()
        if plotetopo:
            from netCDF4 import Dataset
            from matplotlib.colors import LightSource
            import pycpt
            etopodata = Dataset(
                '/home/leon/station_map/grd_dir/ETOPO1_Ice_g_gmt4.grd')
            etopo = etopodata.variables['z'][:]
            lons = etopodata.variables['x'][:]
            lats = etopodata.variables['y'][:]

            # # # etopodata   = Dataset('/home/leon/GEBCO_2019.nc')
            # # # etopo       = etopodata.variables['elevation'][:]
            # # # lons        = etopodata.variables['lon'][:]
            # # # lats        = etopodata.variables['lat'][:]

            ind_lon = (lons <= -122.) * (lons >= -180.)
            ind_lat = (lats <= 75.) * (lats >= 50.)
            # etopo       = etopo[ind_lat, ind_lon]
            tetopo = etopo[ind_lat, :]
            etopo = tetopo[:, ind_lon]
            lons = lons[ind_lon]
            lats = lats[ind_lat]
            ls = LightSource(azdeg=315, altdeg=45)
            # nx          = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1
            # etopo,lons  = shiftgrid(180.,etopo,lons,start=False)
            # topodat,x,y = m.transform_scalar(etopo,lons,lats,nx,ny,returnxy=True)
            ny, nx = etopo.shape
            topodat, xtopo, ytopo = m.transform_scalar(etopo,
                                                       lons,
                                                       lats,
                                                       nx,
                                                       ny,
                                                       returnxy=True)
            m.imshow(ls.hillshade(topodat, vert_exag=1., dx=1., dy=1.),
                     cmap='gray')
            mycm1 = pycpt.load.gmtColormap('/home/leon/station_map/etopo1.cpt')
            mycm2 = pycpt.load.gmtColormap('/home/leon/station_map/bathy1.cpt')
            mycm2.set_over('w', 0)
            m.imshow(
                ls.shade(topodat,
                         cmap=mycm1,
                         vert_exag=1.,
                         dx=1.,
                         dy=1.,
                         vmin=0,
                         vmax=8000))
            m.imshow(
                ls.shade(topodat,
                         cmap=mycm2,
                         vert_exag=1.,
                         dx=1.,
                         dy=1.,
                         vmin=-11000,
                         vmax=-0.5))

        # shapefname  = '/home/leon/geological_maps/qfaults'
        # m.readshapefile(shapefname, 'faultline', linewidth=2, color='red')
        # shapefname  = '/home/leon/AKgeol_web_shp/AKStategeolarc_generalized_WGS84'
        # m.readshapefile(shapefname, 'geolarc', linewidth=1, color='red')
        # shapefname  = '/home/leon/glims_db/glims_download_07183/glims_images'
        # m.readshapefile(shapefname, 'glims', linewidth=1, color='red')

        # import shapefile
        # shplst = shapefile.Reader("/home/leon/glims_db/glims_download_07183/glims_points.shp")
        # ishp    = 0
        # records = shplst.shapeRecords()
        # L       = len(records)
        # for shp in records:
        #     points      = shp.shape.points
        #     lon_glims   = []
        #     lat_glims   = []
        #     ishp        += 1
        #     print ishp, L
        #     for point in points:
        #         lon_glims.append(point[0])
        #         lat_glims.append(point[1])
        #     xglims, yglims      = m(lon_glims, lat_glims)
        #     m.plot(xglims, yglims,'-', ms = 15, markeredgecolor='grey', markerfacecolor='yellow')
        #######################3
        # glims_inarr = np.loadtxt('/home/leon/glims_db/glims_download_06652/glims_points.gmt')
        # lons_glims  = glims_inarr[:, 0]
        # lats_glims  = glims_inarr[:, 1]
        # xglims, yglims      = m(lons_glims, lats_glims)
        # m.plot(xglims, yglims,'o', ms = 2, markeredgecolor='cyan', markerfacecolor='cyan')
        #########################
        inet = 0
        for network in inv:
            stalons = np.array([])
            stalats = np.array([])
            if len(netcodelist) != 0:
                if network.code not in netcodelist:
                    continue
            inet += 1
            for station in network:
                # if stacode != None:
                #     if station.code != stacode:
                #         continue
                # if station.code == 'DHY':
                # time            = obspy.UTCDateTime('20150101')
                # if station.end_date < time:
                #     continue
                # time            = obspy.UTCDateTime('20141231')
                # if station.start_date > time:
                #     continue
                # az, baz, dist   = geodist.inv(np.ones(lons_glims.size)*station.longitude, np.ones(lons_glims.size)*station.latitude,\
                #                                       lons_glims, lats_glims)
                # if dist.min() > 5000.:
                #     continue
                stalons = np.append(stalons, station.longitude)
                stalats = np.append(stalats, station.latitude)
            stax, stay = m(stalons, stalats)
            # if inet==1:
            #     m.plot(stax, stay, 'r^', mec='k', markersize=8, label = network.code)
            # if inet == 2:
            #     m.plot(stax, stay, 'b^', mec='k', markersize=8, label = network.code)
            # m.plot(stax, stay, 'r^', mec='k', markersize=20, label = network.code+'.'+stacode)
            #
            # m.plot(stax, stay, 'r^', markersize=15)
            labellst    = ['r^', 'b^', 'm^', 'c^', 'w^', \
                           'ro', 'bo', 'mo', 'co',  'wo', \
                              'rv', 'bv', 'mv', 'cv',  'wv', \
                              'rs', 'bs', 'ms', 'cs',  'ws', \
                              'rp', 'bp', 'mp', 'cp',  'wp']
            # if network.code == 'TA':
            #     continue
            m.plot(stax,
                   stay,
                   labellst[inet - 1],
                   mec='k',
                   markersize=8,
                   label=network.code)
            # if inet<=10:
            #     m.plot(stax, stay, '^', mec='k', markersize=8, label = network.code)
            # elif inet > 10 and inet <=20:
            #     m.plot(stax, stay, 's', mec='k', markersize=8, label = network.code)
            # elif inet > 20:
            #     m.plot(stax, stay, 'v', mec='k', markersize=8, label = network.code)
        plt.legend(numpoints=1, loc=1, fontsize=10)
        #######################################
        # xc, yc      = m(np.array([-140]), np.array([63]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = - 81.097
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #
        # xc, yc      = m(np.array([-146]), np.array([65]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = 75.8076
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #
        # xc, yc      = m(np.array([-153]), np.array([64]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = 53.1896
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #
        # xc, yc      = m(np.array([-156]), np.array([62]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')
        # phi         = 32.1394
        # U       = np.sin(phi/180.*np.pi)
        # V       = np.cos(phi/180.*np.pi)
        # m.quiver(xc, yc, U, V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        # m.quiver(xc, yc, -U, -V, scale=10, width=.005, headaxislength=0, headlength=0, headwidth=0.5, color = 'b')
        #######################################

        # xc, yc      = m(np.array([-140]), np.array([63]))
        # m.plot(xc, yc,'*', ms = 15, markeredgecolor='black', markerfacecolor='yellow')

        # xc, yc      = m(np.array([-146, -142]), np.array([58, 64]))
        # m.plot(xc, yc,'k', lw = 5, color='black')
        # m.plot(xc, yc,'k', lw = 3, color='white')
        #
        # xc, yc      = m(np.array([-147, -159]), np.array([56, 62]))
        # m.plot(xc, yc,'k', lw = 5, color='black')
        # m.plot(xc, yc,'k', lw = 3, color='white')
        # plot_fault_lines(m, 'AK_Faults.txt')
        #
        # import shapefile
        # shapefname  = '/home/leon/volcano_locs/SDE_GLB_VOLC.shp'
        # shplst      = shapefile.Reader(shapefname)
        # for rec in shplst.records():
        #     lon_vol = rec[4]
        #     lat_vol = rec[3]
        #     xvol, yvol            = m(lon_vol, lat_vol)
        #     m.plot(xvol, yvol, '^', mfc='white', mec='k', ms=10)
        #
        #############################
        # yakutat_slb_dat     = np.loadtxt('YAK_extent.txt')
        # yatlons             = yakutat_slb_dat[:, 0]
        # yatlats             = yakutat_slb_dat[:, 1]
        # xyat, yyat          = m(yatlons, yatlats)
        # m.plot(xyat, yyat, '-', lw = 5, color='black')
        # m.plot(xyat, yyat, '-', lw = 3, color='white')
        #############################
        # plot_fault_lines(m, 'AK_Faults.txt', color='red')
        if showfig:
            plt.show()
        return
Ejemplo n.º 15
0
                (x_values_array[i], y_values_array[i], z_values_array[i]),
                axis=1))

    # Plotting the freeboundary edges of the 3-d Mesh
    for item in freeboundary_points:
        freeboundary_plot = ax1.plot(item[:, 0],
                                     item[:, 1],
                                     item[:, 2],
                                     c='black',
                                     linewidth=1,
                                     zorder=3)

    # create a light source

    # Z = jn(0,z)
    ls = LightSource(azdeg=315, altdeg=65)
    # Shade data, creating a rgb array
    rgb = ls.shade(final_col, cmap=newcmp)
    print('rgb\n', rgb.shape)
    # plt.imshow(rgb)

    # Trisurface 3-D Mesh Plot
    surf1 = ax1.plot_trisurf(
        x,
        y,
        z,
        triangles=t,
        linewidth=0.1,
        antialiased=True,
        # color='gray',
        cmap=newcmp,
Ejemplo n.º 16
0
fig = plt.figure()
ax = fig.gca(projection='3d')

import matplotlib.ticker as mticker


def log_tick_formatter(val, pos=None):
    return "{:.0e}".format(10**val)


ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))

ax.yaxis.set_ticks([0, 2, 4, 6])
##

light = LightSource(azdeg=-20, altdeg=60)
#green_surface = light.shade_rgb(rgb * green, grid_z)

illuminated_surface = light.shade(grid_z, cmap=cm.jet)
ax.plot_surface(grid_freq,
                grid_tps,
                grid_z,
                rstride=1,
                cstride=1,
                antialiased=False,
                facecolors=illuminated_surface)
#, cmap=cm.jet
#
plt.xlabel('\nfréquence (Hz)', linespacing=0.8)
plt.ylabel('\ntemps (s)', linespacing=0.8)
def animate_interactive(data,
                        t=None,
                        dim_order=(0, 1, 2),
                        fps=10.0,
                        title=None,
                        x_label='x',
                        y_label='y',
                        font_size=24,
                        color_bar=0,
                        colorbar_label=None,
                        sloppy=True,
                        fancy=False,
                        range_min=None,
                        range_max=None,
                        extent=[-1, 1, -1, 1],
                        shade=False,
                        azdeg=0,
                        altdeg=65,
                        arrows_x=None,
                        arrows_y=None,
                        arrows_res_x=10,
                        arrows_res_y=10,
                        arrows_pivot='mid',
                        arrows_width=0.002,
                        arrows_scale=5,
                        arrows_color='black',
                        plot_arrows_grid=False,
                        movie_file=None,
                        bitrate=1800,
                        keep_images=False,
                        figsize=(8, 7),
                        dpi=300,
                        **kwimshow):
    """
    Assemble a 2D animation from a 3D array.

    call signature::

    animate_interactive(data, t=None, dim_order=(0, 1, 2),
                        fps=10.0, title=None, x_label='x', y_label='y',
                        font_size=24, color_bar=0, colorbar_label=None,
                        sloppy=True, fancy=False,
                        range_min=None, range_max=None, extent=[-1, 1, -1, 1],
                        shade=False, azdeg=0, altdeg=65,
                        arrows_x=None, arrows_y=None, arrows_res_x=10, arrows_res_y=10,
                        arrows_pivot='mid', arrows_width=0.002, arrows_scale=5,
                        arrows_color='black', plot_arrows_grid=False,
                        movie_file=None, bitrate=1800, keep_images=False,
                        figsize=(8, 7), dpi=300,
                        **kwimshow)

    Assemble a 2D animation from a 3D array. *data* has to be a 3D array of
    shape [nt, nx, ny] and who's time index has the same dimension as *t*.
    The time index of *data* as well as its x and y indices can be changed
    via *dim_order*.

    Keyword arguments:

    *dim_order*:
      Ordering of the dimensions in the data array (t, x, y).

    *fps*:
      Frames per second of the animation.

    *title*:
      Title of the plot.

    *x_label*:
      Label of the x-axis.

    *y_label*:
      Label of the y-axis.

    *font_size*:
      Font size of the title, x and y label.
      The size of the x- and y-ticks is 0.5*font_size and the colorbar ticks'
      font size is 0.5*font_size.

    *color_bar*: [ 0 | 1 ]
      Determines how the colorbar changes:
      (0 - no cahnge; 1 - adapt extreme values).

    *colorbar_label*:
      Label of the color bar.

    *sloppy*: [ True | False ]
      If True the update of the plot lags one frame behind. This speeds up the
      plotting.

    *fancy*: [ True | False ]
      Use fancy font style.

    *range_min*, *range_max*:
      Range of the colortable.

    *extent*: [ None | (left, right, bottom, top) ]
      Limits for the axes (domain).

    *shade*: [ False | True ]
      If True plot a shaded relief instead of the usual colormap.
      Note that with this option cmap has to be specified like
      cmap = plt.cm.hot instead of cmap = 'hot'. Shading cannot
      be used with the color_bar = 0 option.

    *azdeg*, *altdeg*:
      Azimuth and altitude of the light source for the shading.

    *arrows_x*:
      Data containing the x-component of the arrows.

    *arrows_y*:
      Data containing the y-component of the arrows.

    *arrows_res_xY*:
      Plot every arrows_res_xY arrow in x and y.

    *arrows_pivot*: [ 'tail' | 'middle' | 'tip' ]
      The part of the arrow that is used as pivot point.

    *arrows_width*:
      Width of the arrows.

    *arrows_scale*:
      Scaling of the arrows.

    *arrows_color*:
      Color of the arrows.

    *plot_arrows_grid*: [ False | True ]
      If 'True' the grid where the arrows are aligned to is shown.

    *movie_file*: [ None | string ]
      The movie file where the animation should be saved to.
      If 'None' no movie file is written. Requires 'ffmpeg' to be installed.

    *bitrate*:
      Bitrate of the movie file. Set to higher value for higher quality.

    *keep_images*: [ False | True ]
      If 'True' the images for the movie creation are not deleted.

    *figsize*:
      Size of the figure in inches.

    *dpi*:
      Dots per inch of the frame.

    **kwimshow:
      Remaining arguments are identical to those of pylab.imshow. Refer to that help.
    """

    try:
        import thread
    except:
        import _thread as thread

    # We need to define these variables as globals, as they are being used
    # by various functions.

    global time_step, time_slider, pause
    global fig, axes, image, colorbar, arrows, manager, n_times, movie_files
    global rgb, plot_arrows

    if title is None:
        title = ''

    def plot_frame():
        """
        Plot the current frame.
        """

        global time_step, axes, colorbar, arrows, manager, rgb

        # Define the plot title.
        if not movie_file is None:
            axes.set_title(title + r'$\quad$' +
                           r'$t={0:.4e}$'.format(t[time_step]),
                           fontsize=font_size)

        # Update the image data.
        if not shade:
            image.set_data(data[time_step, :, :])
        else:
            image.set_data(rgb[time_step, :, :, :])

        # Update the colorbar.
        if color_bar == 0:
            pass
        if color_bar == 1:
            colorbar.set_clim(vmin=data[time_step, :, :].min(),
                              vmax=data[time_step, :, :].max())
            colorbar.draw_all()

        # Update the arrows data.
        if plot_arrows:
            arrows.set_UVC(
                U=arrows_x[time_step, ::arrows_res_x, ::arrows_res_y],
                V=arrows_y[time_step, ::arrows_res_x, ::arrows_res_y])

        if not sloppy or (not movie_file is None):
            manager.canvas.draw()

    def play(thread_name):
        """
        Play the movie.
        """

        import time
        global time_step, time_slider, pause, fig, axes, n_times, movie_files

        pause = False
        while (time_step < n_times) and (not pause):
            # Write the image files for the movie.
            if not movie_file is None:
                plot_frame()
                frame_name = '{0}{1:06}.png'.format(movie_file, time_step)
                fig.savefig(frame_name, dpi=dpi)
                movie_files.append(frame_name)
            else:
                time_start = time.clock()
                time_slider.set_val(t[time_step])
                # Wait for the next frame (fps).
                while (time.clock() - time_start < 1.0 / fps):
                    pass
            time_step += 1
        time_step -= 1

    def play_thread(event):
        """
        Call the play function as a separate thread (for GUI).
        """

        global pause

        if pause:
            try:
                thread.start_new_thread(play, ("play_thread", ))
            except:
                print("Error: unable to start play thread.")

    def pausing(event):
        global pause

        pause = True

    def reverse(event):
        global time_step, time_slider

        time_step -= 1
        if time_step < 0:
            time_step = 0
        # Plot the frame and update the time slider.
        time_slider.set_val(t[time_step])

    def forward(event):
        global time_step, time_slider

        time_step += 1
        if time_step > len(t) - 1:
            time_step = len(t) - 1
        # Plot the frame and update the time slider.
        time_slider.set_val(t[time_step])

    import numpy as np
    import pylab as plt

    pause = True
    plot_arrows = False

    # Check if the data has the right dimensions.
    if (data.ndim != 3 and data.ndim != 4):
        print("Error: data dimensions are invalid: {0} instead of 3.".format(
            data.ndim))
        return -1

    # Transpose the data according to dim_order.
    unordered_data = data
    data = np.transpose(unordered_data, dim_order)
    del (unordered_data)

    # Check if arrows should be plotted.
    if not (arrows_x is None) and not (arrows_y is None):
        if (isinstance(arrows_x, np.ndarray)
                and isinstance(arrows_y, np.ndarray)):
            if arrows_x.ndim == 3:
                # Transpose the data according to dim_order.
                unordered_data = arrows_x
                arrows_x = np.transpose(unordered_data, dim_order)
                del (unordered_data)
            if arrows_y.ndim == 3:
                # Transpose the data according to dim_order.
                unordered_data = arrows_y
                arrows_y = np.transpose(unordered_data, dim_order)
                unordered_data = []

                # Check if the dimensions of the arrow arrays match each other.
                if arrows_x.shape != arrows_y.shape:
                    print(
                        "Error: dimensions of arrowX do not match with dimensions of arrowY."
                    )
                    return -1
                else:
                    plot_arrows = True
        else:
            print("Warning: arrows_x and/or arrows_y are of invalid type.")

    # Check if time array has the right length.
    n_times = len(t)
    if n_times != data.shape[0]:
        print(
            "Error: length of time array does not match length of data array.")
        return -1
    if plot_arrows:
        if (n_times != arrows_x.shape[0]) or (n_times != arrows_y.shape[0]):
            print(
                "error: length of time array does not match length of arrows array."
            )
            return -1

    # Check if fps is positive.
    if fps < 0:
        print("Error: fps is not positive, fps = {0}.".format(fps))
        return -1

    # Determine the size of the data array.
    nX = data.shape[1]
    nY = data.shape[2]

    # Determine the minimum and maximum values of the data set.
    if not range_min:
        range_min = np.min(data)
    if not range_max:
        range_max = np.max(data)

    # Setup the plot.
    if fancy:
        plt.rc('text', usetex=True)
        plt.rc('font', family='arial')
    else:
        plt.rc('text', usetex=False)
        plt.rc('font', family='sans')
    if not movie_file is None:
        fig = plt.figure(figsize=figsize)
        axes = plt.axes([0.15, 0.1, .70, .85])
    else:
        fig = plt.figure(figsize=figsize)
        axes = plt.axes([0.1, 0.3, .80, .65])

    # Set up canvas of the plot.
    axes.set_title(title, fontsize=font_size)
    axes.set_xlabel(x_label, fontsize=font_size)
    axes.set_ylabel(y_label, fontsize=font_size)
    plt.xticks(fontsize=0.5 * font_size)
    plt.yticks(fontsize=0.5 * font_size)
    if shade:
        plane = np.zeros([nX, nY, 3])
    else:
        plane = np.zeros([nX, nY])

    # Apply shading.
    if shade:
        from matplotlib.colors import LightSource

        ls = LightSource(azdeg=azdeg, altdeg=altdeg)
        rgb = []
        # Shading can be only used with color_bar=1 or color_bar=2 at the moment.
        if color_bar == 0:
            color_bar = 1
        # Check if colormap is set, if not set it to 'copper'.
        if 'cmap' not in kwimshow.keys():
            kwimshow['cmap'] = plt.cm.copper
        for i in range(data.shape[0]):
            tmp = ls.shade(data[i, :, :], kwimshow['cmap'])
            rgb.append(tmp.tolist())
        rgb = np.array(rgb)
        del (tmp)

    # Calibrate the displayed colors for the data range.
    image = axes.imshow(plane,
                        vmin=range_min,
                        vmax=range_max,
                        origin='lower',
                        extent=extent,
                        **kwimshow)
    colorbar = fig.colorbar(image)
    colorbar.set_label(colorbar_label, fontsize=font_size, labelpad=10)

    # Change the font size of the colorbar's ytickslabels.
    cbytick_obj = plt.getp(colorbar.ax.axes, 'yticklabels')
    plt.setp(cbytick_obj, fontsize=0.5 * font_size)

    # Plot the arrows.
    if plot_arrows:
        # Prepare the mesh grid where the arrows will be drawn.
        arrow_grid = np.meshgrid(
            np.arange(
                extent[0], extent[1],
                float(extent[1] - extent[0]) * arrows_res_x /
                (data.shape[2] - 1)),
            np.arange(
                extent[2], extent[3],
                float(extent[3] - extent[2]) * arrows_res_y /
                (data.shape[1] - 1)))
        arrows = axes.quiver(arrow_grid[0],
                             arrow_grid[1],
                             arrows_x[0, ::arrows_res_x, ::arrows_res_y],
                             arrows_y[0, ::arrows_res_x, ::arrows_res_y],
                             units='width',
                             pivot=arrows_pivot,
                             width=arrows_width,
                             scale=arrows_scale,
                             color=arrows_color)
        # Plot the grid for the arrows.
        if plot_arrows_grid:
            axes.plot(arrow_grid[0], arrow_grid[1], 'k.')

    # For real-time image display.
    if (not sloppy) or (not movie_file is None):
        manager = plt.get_current_fig_manager()
        manager.show()

    time_step = 0
    if not movie_file is None:
        import os

        movie_files = []

        # Start the animation.
        play('no_thread')

        # Write the movie file.
        ffmpeg_command = "ffmpeg -r {0} -i {1}%6d.png -vcodec mpeg4 -b:v {2} -q:v 0 {3}.avi".format(
            fps, movie_file, bitrate, movie_file)
        os.system(ffmpeg_command)
        # Clean up the image files.
        if not keep_images:
            print("Cleaning up files.")
            for fname in movie_files:
                os.remove(fname)
    else:
        # Set up the gui.
        plt.ion()
        plt.subplots_adjust(bottom=0.2)

        #        axes_play = plt.axes([0.1, 0.05, 0.15, 0.05])
        #        button_play = plt.Button(axes_play, 'play', color='lightgoldenrodyellow',
        #                                 hovercolor='0.975')
        #        button_play.on_clicked(play_thread)

        #        axes_pause = plt.axes([0.3, 0.05, 0.15, 0.05])
        #        button_pause = plt.Button(axes_pause, 'pause', color='lightgoldenrodyellow',
        #                                  hovercolor='0.975')
        #        button_pause.on_clicked(pausing)

        #        axes_reverse = plt.axes([0.5, 0.05, 0.15, 0.05])
        axes_reverse = plt.axes([0.1, 0.05, 0.3, 0.05])
        button_reverse = plt.Button(axes_reverse,
                                    'reverse',
                                    color='lightgoldenrodyellow',
                                    hovercolor='0.975')
        button_reverse.on_clicked(reverse)

        #        axes_forward = plt.axes([0.7, 0.05, 0.15, 0.05])
        axes_forward = plt.axes([0.5, 0.05, 0.3, 0.05])
        button_forward = plt.Button(axes_forward,
                                    'forward',
                                    color='lightgoldenrodyellow',
                                    hovercolor='0.975')
        button_forward.on_clicked(forward)

        # Create the time slider.
        time_slider_axes = plt.axes([0.2, 0.12, 0.6, 0.03],
                                    facecolor='lightgoldenrodyellow')
        time_slider = plt.Slider(time_slider_axes,
                                 'time',
                                 t[0],
                                 t[-1],
                                 valinit=t[0])

        def update(val):
            global time_step
            # Find the closest time step to the slider time value.
            for i in range(len(t)):
                if t[i] < time_slider.val:
                    time_step = i
            if (time_step != len(t) - 1):
                if (t[time_step + 1] - time_slider.val) < (time_slider.val -
                                                           t[time_step]):
                    time_step += 1
            plot_frame()

        time_slider.on_changed(update)

        plt.show()

    print("done")

    #    return button_play, button_pause, button_reverse, button_forward
    return button_reverse, button_forward
Ejemplo n.º 18
0
parallels = np.arange(0., 80, 20.)
m.drawparallels(parallels, labels=[1, 0, 0, 1])
meridians = np.arange(10., 360., 30.)
m.drawmeridians(meridians, labels=[1, 0, 0, 1])
# add colorbar
#cb = m.colorbar(im,"right", size="5%", pad='2%')
ax.set_title('ETOPO5 Topography - Lambert Conformal Conic')
fig.savefig('etopo5.png')

# make a shaded relief plot.

# create new figure, axes instance.
fig = pp.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# attach new axes image to existing Basemap instance.
m.ax = ax
# create light source object.
from matplotlib.colors import LightSource

ls = LightSource(azdeg=90, altdeg=20)
# convert data to rgb array including shading from light source.
# (must specify color map)
rgb = ls.shade(topodat, cm.GMT_haxby)
im = m.imshow(rgb)
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawcountries()
m.drawstates()
ax.set_title('Shaded ETOPO5 Topography - Lambert Conformal Conic')
fig.savefig('etopo5_shaded.png')
Ejemplo n.º 19
0
    def plot_3d(image,
                ax,
                threshold=-300,
                alpha=0.1,
                face_color=[0.5, 0.5, 1],
                cut=None):
        p = image.transpose(2, 1, 0)

        if cut is not None:
            indices = np.array([[i, j, k] for i in range(p.shape[0])
                                for j in range(p.shape[1])
                                for k in range(p.shape[2])])
            print(indices.shape)

            x, y, z = cut
            remove = np.logical_and(indices[..., 0] > x, indices[..., 1] < y)
            print(remove)
            indices = indices[remove]
            print(indices)

            # p[indices] = threshold - 1
            p[x:, :y, :] = threshold - 1

        print('skimage .....')
        verts, faces, normals, values = measure.marching_cubes_lewiner(
            p, threshold)

        # print(verts, verts.shape)
        # print(faces, faces.shape)

        vert = verts[faces]

        # if cut is not None:
        #     x, y, z = cut
        #     print(vert.shape)
        #     print(vert[0])
        #     # vert[vert[0, ...] > x] = np.Na
        #     print(np.logical_or(vert[..., 0] < x, vert[..., 1] > y))
        #     selected = np.logical_or(vert[..., 0] < x, vert[..., 1] > y)
        #     vert = vert[selected]

        mesh = Poly3DCollection(vert, alpha=alpha)
        # mesh = Poly3DCollection(np.argwhere(p > threshold), alpha=1)
        ls = LightSource(azdeg=225.0, altdeg=45.0)
        normalsarray = np.array([
            np.array((np.sum(
                normals[face[:], 0] / 3), np.sum(normals[face[:], 1] / 3),
                      np.sum(normals[face[:], 2] / 3)) / np.sqrt(
                          np.sum(normals[face[:], 0] / 3)**2 +
                          np.sum(normals[face[:], 1] / 3)**2 +
                          np.sum(normals[face[:], 2] / 3)**2))
            for face in faces
        ])

        # min shade value
        min = np.min(ls.shade_normals(normalsarray, fraction=1.0))
        # max shade value
        max = np.max(ls.shade_normals(normalsarray, fraction=1.0))
        diff = max - min
        newMin = 0.3
        newMax = 0.95
        newdiff = newMax - newMin

        # Using a constant color, put in desired RGB values here.
        # np.array((255.0/255.0, 54.0/255.0, 57/255.0, 1.0))
        colourRGB = np.array((*face_color, 1.0))

        # The correct shading for shadows are now applied. Use the face normals and light orientation to generate a shading value and apply to the RGB colors for each face.
        rgbNew = np.array([
            colourRGB * (newMin + newdiff * ((shade - min) / diff))
            for shade in ls.shade_normals(normalsarray, fraction=1.0)
        ])

        # mesh.set_facecolor(face_color)
        mesh.set_facecolor(rgbNew)
        ax.add_collection3d(mesh)
        # ax.set_xlim(0, p.shape[0])
        ax.set_xlim(0, p.shape[0])
        ax.set_ylim(0, p.shape[1])
        ax.set_zlim(0, p.shape[2])
Ejemplo n.º 20
0
def plot_isosurface(init_elev, init_azim, output_fname):
    fig = plt.figure(figsize=(10, 8))
    ax = fig.add_subplot(111, projection=Axes3D.name)
    ax.view_init(init_elev, init_azim)

    lower_lim = -0.30
    upper_lim = +0.30

    tps_half = tps_preds_mat[:200, :, :]
    mask_half = mask_mat[:200, :, :]
    # Fancy indexing: `verts[faces]` to generate a collection of triangles
    verts, faces, normals, values = measure.marching_cubes(tps_half,
                                                           lower_lim,
                                                           mask=mask_half)
    mesh = Poly3DCollection(verts[faces], rasterized=rast)

    ls = LightSource(azdeg=225.0, altdeg=45.0)
    normalsarray = np.array([
        np.array(
            (np.sum(normals[face[:], 0] / 3), np.sum(normals[face[:], 1] / 3),
             np.sum(normals[face[:], 2] / 3)) / np.sqrt(
                 np.sum(normals[face[:], 0] / 3)**2 +
                 np.sum(normals[face[:], 1] / 3)**2 +
                 np.sum(normals[face[:], 2] / 3)**2)) for face in faces
    ])

    # Next this is more asthetic, but it prevents the shadows of the image being too dark. (linear interpolation to correct)
    min = np.min(ls.shade_normals(normalsarray,
                                  fraction=1.0))  # min shade value
    max = np.max(ls.shade_normals(normalsarray,
                                  fraction=1.0))  # max shade value
    diff = max - min
    newMin = 0.3
    newMax = 0.95
    newdiff = newMax - newMin

    # Using a constant color, put in desired RGB values here.
    colourRGB = np.array((0 / 255.0, 53.0 / 255.0, 107 / 255.0, 1.0))

    # The correct shading for shadows are now applied. Use the face normals and light orientation to generate a shading value and apply to the RGB colors for each face.
    rgbNew = np.array([
        colourRGB * (newMin + newdiff * ((shade - min) / diff))
        for shade in ls.shade_normals(normalsarray, fraction=1.0)
    ])

    # Apply color to face
    mesh.set_facecolor(rgbNew)

    ax.add_collection3d(mesh)

    verts, faces, normals, values = measure.marching_cubes(tps_half,
                                                           upper_lim,
                                                           mask=mask_half)
    mesh = Poly3DCollection(verts[faces], rasterized=rast)

    ls = LightSource(azdeg=225.0, altdeg=45.0)
    normalsarray = np.array([
        np.array(
            (np.sum(normals[face[:], 0] / 3), np.sum(normals[face[:], 1] / 3),
             np.sum(normals[face[:], 2] / 3)) / np.sqrt(
                 np.sum(normals[face[:], 0] / 3)**2 +
                 np.sum(normals[face[:], 1] / 3)**2 +
                 np.sum(normals[face[:], 2] / 3)**2)) for face in faces
    ])

    # Next this is more asthetic, but it prevents the shadows of the image being too dark. (linear interpolation to correct)
    min = np.min(ls.shade_normals(normalsarray,
                                  fraction=1.0))  # min shade value
    max = np.max(ls.shade_normals(normalsarray,
                                  fraction=1.0))  # max shade value
    diff = max - min
    newMin = 0.3
    newMax = 0.95
    newdiff = newMax - newMin

    # Using a constant color, put in desired RGB values here.
    colourRGB = np.array((255.0 / 255.0, 54.0 / 255.0, 57 / 255.0, 1.0))

    # The correct shading for shadows are now applied. Use the face normals and light orientation to generate a shading value and apply to the RGB colors for each face.
    rgbNew = np.array([
        colourRGB * (newMin + newdiff * ((shade - min) / diff))
        for shade in ls.shade_normals(normalsarray, fraction=1.0)
    ])

    # Apply color to face
    mesh.set_facecolor(rgbNew)

    ax.add_collection3d(mesh)

    ax.set_xlabel(r"Days since TC passage ($\tau$)")
    ax.set_ylabel(r"Cross-track angle, degrees ($d$)")
    ax.set_zlabel(r"Pressure, dbars ($z$)")
    ax.set_xlim(0, 200)
    ax.set_ylim(0, 100)
    ax.set_zlim(0, 20)

    ax.set_xticks([36, 91, 145, 199])
    ax.set_xticklabels([0, 3, 6, 9])
    ax.set_yticks([19, 50, 80])
    ax.set_yticklabels([-5, 0, 5])
    ax.set_zticks([0, 5, 10, 15, 19])
    ax.set_zticklabels([200, 150, 100, 50, 10])

    plt.savefig(
        output_fname,
        bbox_inches='tight',
        pad_inches=0,
        dpi=300,
    )
    return
Ejemplo n.º 21
0
def animate_interactive(data,
                        t=[],
                        dimOrder=(0, 1, 2),
                        fps=10.0,
                        title='',
                        xlabel='x',
                        ylabel='y',
                        fontsize=24,
                        cBar=0,
                        sloppy=True,
                        rangeMin=[],
                        rangeMax=[],
                        extent=[-1, 1, -1, 1],
                        shade=False,
                        azdeg=0,
                        altdeg=65,
                        arrowsX=np.array(0),
                        arrowsY=np.array(0),
                        arrowsRes=10,
                        arrowsPivot='mid',
                        arrowsWidth=0.002,
                        arrowsScale=5,
                        arrowsColor='black',
                        plotArrowsGrid=False,
                        movieFile='',
                        bitrate=1800,
                        keepImages=False,
                        figsize=(8, 7),
                        dpi=None,
                        **kwimshow):
    """
    Assemble a 2D animation from a 3D array.

    call signature::
    
      animate_interactive(data, t = [], dimOrder = (0,1,2),
                        fps = 10.0, title = '', xlabel = 'x', ylabel = 'y',
                        fontsize = 24, cBar = 0, sloppy = True,
                        rangeMin = [], rangeMax = [], extent = [-1,1,-1,1],
                        shade = False, azdeg = 0, altdeg = 65,
                        arrowsX = np.array(0), arrowsY = np.array(0), arrowsRes = 10,
                        arrowsPivot = 'mid', arrowsWidth = 0.002, arrowsScale = 5,
                        arrowsColor = 'black', plotArrowsGrid = False,
                        movieFile = '', bitrate = 1800, keepImages = False,
                        figsize = (8, 7), dpi = None,
                        **kwimshow)
    
    Assemble a 2D animation from a 3D array. *data* has to be a 3D array who's
    time index has the same dimension as *t*. The time index of *data* as well
    as its x and y indices can be changed via *dimOrder*.
    
    Keyword arguments:
    
      *dimOrder*: [ (i,j,k) ]
        Ordering of the dimensions in the data array (t,x,y).
        
     *fps*:
       Frames per second of the animation.
       
     *title*:
       Title of the plot.
       
     *xlabel*:
       Label of the x-axis.
       
     *ylabel*:
       Label of the y-axis.
       
     *fontsize*:
       Font size of the title, x and y label.
       The size of the x- and y-ticks is 0.7*fontsize and the colorbar ticks's
       font size is 0.5*fontsize.
       
     *cBar*: [ 0 | 1 | 2 ]
       Determines how the colorbar changes:
       (0 - no cahnge; 1 - keep extreme values constant; 2 - change extreme values).
     
     *sloppy*: [ True | False ]
       If True the update of the plot lags one frame behind. This speeds up the
       plotting.
     
     *rangeMin*, *rangeMax*:
       Range of the colortable.
       
     *extent*: [ None | scalars (left, right, bottom, top) ]
       Data limits for the axes. The default assigns zero-based row,
       column indices to the *x*, *y* centers of the pixels.
       
     *shade*: [ False | True ]
       If True plot a shaded relief plot instead of the usual colormap.
       Note that with this option cmap has to be specified like
       cmap = plt.cm.hot instead of cmap = 'hot'. Shading cannot
       be used with the cBar = 0 option.
     
     *azdeg*, *altdeg*:
       Azimuth and altitude of the light source for the shading.
       
     *arrowsX*:
       Data containing the x-component of the arrows.
       
     *arrowsy*:
       Data containing the y-component of the arrows.
       
     *arrowsRes*:
       Plot every arrowRes arrow.
       
     *arrowsPivot*: [ 'tail' | 'middle' | 'tip' ]
       The part of the arrow that is at the grid point; the arrow rotates
       about this point.
       
     *arrowsWidth*:
       Width of the arrows.
       
     *arrowsScale*:
       Scaling of the arrows.
       
     *arrowsColor*:
       Color of the arrows.
       
     *plotArrowsGrid*: [ False | True ]
       If 'True' the grid where the arrows are aligned to is shown.
     
     *movieFile*: [ None | string ]
       The movie file where the animation should be saved to.
       If 'None' no movie file is written. Requires 'mencoder' to be installed.
     
     *bitrate*:
       Bitrate of the movie file. Set to higher value for higher quality.
       
     *keepImages*: [ False | True ]
       If 'True' the images for the movie creation are not deleted.
     
     *figsize*:
       Size of the figure in inches.
      
     *dpi*:
       Dots per inch of the frame.
     
     **kwimshow:
       Remaining arguments are identical to those of pylab.imshow. Refer to that help.
    """

    import pylab as plt
    import time
    import os  # for making the movie
    import thread  # for GUI
    from matplotlib.colors import LightSource

    global tStep, sliderTime, pause

    # plot the current frame
    def plotFrame():
        global tStep, sliderTime

        if movieFile:
            ax.set_title(title + r'$\quad$' + r'$t={0}$'.format(t[tStep]),
                         fontsize=fontsize)

        if shade == False:
            image.set_data(data[tStep, :, :])
        else:
            image.set_data(rgb[tStep, :, :, :])

        if (cBar == 0):
            pass
        if (cBar == 1):
            colorbar.set_clim(vmin=data[tStep, :, :].min(),
                              vmax=data[tStep, :, :].max())
        if (cBar == 2):
            colorbar.set_clim(vmin=data[tStep, :, :].min(),
                              vmax=data[tStep, :, :].max())
            colorbar.update_bruteforce(data[tStep, :, :])

        if plotArrows:
            arrows.set_UVC(U=arrowsX[tStep, ::arrowsRes, ::arrowsRes],
                           V=arrowsY[tStep, ::arrowsRes, ::arrowsRes])

        if (sloppy == False) or (movieFile):
            manager.canvas.draw()

    # play the movie
    def play(threadName):
        global tStep, sliderTime, pause

        pause = False
        while (tStep < nT) & (pause == False):
            # write the image files for the movie
            if movieFile:
                plotFrame()
                frameName = movieFile + '%06d.png' % tStep
                fig.savefig(frameName, dpi=dpi)
                movieFiles.append(frameName)
            else:
                start = time.clock()
                # time slider
                sliderTime.set_val(t[tStep])
                # wait for the next frame (fps)
                while (time.clock() - start < 1.0 / fps):
                    pass  # do nothing
            tStep += 1
        tStep -= 1

    # call the play function as a separate thread (for GUI)
    def play_thread(event):
        global pause

        if pause == True:
            try:
                thread.start_new_thread(play, ("playThread", ))
            except:
                print "Error: unable to start play thread"

    def pausing(event):
        global pause

        pause = True

    def reverse(event):
        global tStep, sliderTime

        tStep -= 1
        if tStep < 0:
            tStep = 0
        # plot the frame and update the time slider
        sliderTime.set_val(t[tStep])

    def forward(event):
        global tStep, sliderTime

        tStep += 1
        if tStep > len(t) - 1:
            tStep = len(t) - 1
        # plot the frame and update the time slider
        sliderTime.set_val(t[tStep])

    pause = True
    plotArrows = False

    # check if the data has the right dimensions
    if (len(data.shape) != 3 and len(data.shape) != 4):
        print 'error: data dimensions are invalid: {0} instead of 3'.format(
            len(data.shape))
        return -1

    # transpose the data according to dimOrder
    unOrdered = data
    data = np.transpose(unOrdered, dimOrder)
    unOrdered = []

    # check if arrows should be plotted
    if len(arrowsX.shape) == 3:
        # transpose the data according to dimOrder
        unOrdered = arrowsX
        arrowsX = np.transpose(unOrdered, dimOrder)
        unOrdered = []
        if len(arrowsY.shape) == 3:
            # transpose the data according to dimOrder
            unOrdered = arrowsY
            arrowsY = np.transpose(unOrdered, dimOrder)
            unOrdered = []

            # check if the dimensions of the arrow arrays match each other
            if ((len(arrowsX[:, 0, 0]) != len(arrowsY[:, 0, 0]))
                    or (len(arrowsX[0, :, 0]) != len(arrowsY[0, :, 0]))
                    or (len(arrowsX[0, 0, :]) != len(arrowsY[0, 0, :]))):
                print 'error: dimensions of arrowX do not match with dimensions of arrowY'
                return -1
            else:
                plotArrows = True

    # check if time array has the right length
    nT = len(t)
    if (nT != len(data[:, 0, 0])):
        print 'error: length of time array doesn\'t match length of data array'
        return -1
        if plotArrows:
            if (nT != len(arrowsX[:, 0, 0]) or nT != len(arrowsX[:, 0, 0])):
                print 'error: length of time array doesn\'t match length of arrows array'
                return -1

    # check if fps is positive
    if (fps < 0.0):
        print 'error: fps is not positive, fps = {0}'.format(fps)
        return -1

    # determine the size of the array
    nX = len(data[0, :, 0])
    nY = len(data[0, 0, :])

    # determine the minimum and maximum values of the data set
    if not (rangeMin):
        rangeMin = np.min(data)
    if not (rangeMax):
        rangeMax = np.max(data)

    # setup the plot
    if movieFile:
        plt.rc("figure.subplot", bottom=0.15)
        plt.rc("figure.subplot", top=0.95)
        plt.rc("figure.subplot", right=0.95)
        plt.rc("figure.subplot", left=0.15)
        fig = plt.figure(figsize=figsize)
        ax = plt.axes([0.1, 0.1, .90, .85])
    else:
        plt.rc("figure.subplot", bottom=0.05)
        plt.rc("figure.subplot", top=0.95)
        plt.rc("figure.subplot", right=0.95)
        plt.rc("figure.subplot", left=0.15)
        fig = plt.figure(figsize=figsize)
        ax = plt.axes([0.1, 0.25, .85, .70])

    ax.set_title(title, fontsize=fontsize)
    ax.set_xlabel(xlabel, fontsize=fontsize)
    ax.set_ylabel(ylabel, fontsize=fontsize)
    plt.xticks(fontsize=0.7 * fontsize)
    plt.yticks(fontsize=0.7 * fontsize)
    if shade:
        plane = np.zeros((nX, nY, 3))
    else:
        plane = np.zeros((nX, nY))

    # apply shading if True
    if shade:
        ls = LightSource(azdeg=azdeg, altdeg=altdeg)
        rgb = []
        # shading can be only used with cBar = 1 or cBar = 2 at the moment
        if cBar == 0:
            cBar = 1
        # check if colormap is set, if not set it to 'copper'
        if kwimshow.has_key('cmap') == False:
            kwimshow['cmap'] = plt.cm.copper
        for i in range(len(data[:, 0, 0])):
            tmp = ls.shade(data[i, :, :], kwimshow['cmap'])
            rgb.append(tmp.tolist())
        rgb = np.array(rgb)
        tmp = []

    # calibrate the displayed colors for the data range
    image = ax.imshow(plane,
                      vmin=rangeMin,
                      vmax=rangeMax,
                      origin='lower',
                      extent=extent,
                      **kwimshow)
    colorbar = fig.colorbar(image)
    # change the font size of the colorbar's ytickslabels
    cbytick_obj = plt.getp(colorbar.ax.axes, 'yticklabels')
    plt.setp(cbytick_obj, fontsize=0.5 * fontsize)

    # plot the arrows
    # TODO: add some more options
    if plotArrows:
        # prepare the mash grid where the arrows will be drawn
        arrowGridX, arrowGridY = np.meshgrid(
            np.arange(
                extent[0], extent[1],
                float(extent[1] - extent[0]) * arrowsRes / len(data[0, :, 0])),
            np.arange(
                extent[2], extent[3],
                float(extent[3] - extent[2]) * arrowsRes / len(data[0, 0, :])))
        arrows = ax.quiver(arrowGridX,
                           arrowGridY,
                           arrowsX[0, ::arrowsRes, ::arrowsRes],
                           arrowsY[0, ::arrowsRes, ::arrowsRes],
                           units='width',
                           pivot=arrowsPivot,
                           width=arrowsWidth,
                           scale=arrowsScale,
                           color=arrowsColor)
        # plot the grid for the arrows
        if plotArrowsGrid == True:
            ax.plot(arrowGridX, arrowGridY, 'k.')

    # for real-time image display
    if (sloppy == False) or (movieFile):
        manager = plt.get_current_fig_manager()
        manager.show()

    tStep = 0
    if movieFile:
        movieFiles = []
        # start the animation
        play('noThread')

        # write the movie file
        mencodeCommand = "mencoder 'mf://" + movieFile + "*.png' -mf type=png:fps=" + np.str(
            fps) + " -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate=" + np.str(
                bitrate) + " -ffourcc MP4S -oac copy -o " + movieFile + ".mpg"
        os.system(mencodeCommand)
        # clean up the image files
        if (keepImages == False):
            print 'cleaning up files'
            for fname in movieFiles:
                os.remove(fname)

    else:
        # set up the gui
        plt.ion()

        axPlay = plt.axes([0.1, 0.05, 0.15, 0.05],
                          axisbg='lightgoldenrodyellow')
        buttonPlay = plt.Button(axPlay,
                                'play',
                                color='lightgoldenrodyellow',
                                hovercolor='0.975')
        buttonPlay.on_clicked(play_thread)
        axPause = plt.axes([0.3, 0.05, 0.15, 0.05],
                           axisbg='lightgoldenrodyellow')
        buttonPause = plt.Button(axPause,
                                 'pause',
                                 color='lightgoldenrodyellow',
                                 hovercolor='0.975')
        buttonPause.on_clicked(pausing)

        axReverse = plt.axes([0.5, 0.05, 0.15, 0.05],
                             axisbg='lightgoldenrodyellow')
        buttonReverse = plt.Button(axReverse,
                                   'reverse',
                                   color='lightgoldenrodyellow',
                                   hovercolor='0.975')
        buttonReverse.on_clicked(reverse)
        axForward = plt.axes([0.7, 0.05, 0.15, 0.05],
                             axisbg='lightgoldenrodyellow')
        buttonForward = plt.Button(axForward,
                                   'forward',
                                   color='lightgoldenrodyellow',
                                   hovercolor='0.975')
        buttonForward.on_clicked(forward)

        # create the time slider
        fig.subplots_adjust(bottom=0.2)
        sliderTimeAxes = plt.axes([0.2, 0.12, 0.6, 0.03],
                                  axisbg='lightgoldenrodyellow')
        sliderTime = plt.Slider(sliderTimeAxes,
                                'time',
                                t[0],
                                t[-1],
                                valinit=0.0)

        def update(val):
            global tStep
            # find the closest time step to the slider time value
            for i in range(len(t)):
                if t[i] < sliderTime.val:
                    tStep = i
            if (tStep != len(t) - 1):
                if (t[tStep + 1] - sliderTime.val) < (sliderTime.val -
                                                      t[tStep]):
                    tStep += 1
            plotFrame()

        sliderTime.on_changed(update)

        plt.show()

    print 'done'
Ejemplo n.º 22
0
# -*- coding: utf-8 -*-
"""
Created on Wed Jun  7 13:52:04 2017

@author: Jonas Lindemann
"""

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LightSource
import numpy as np

light = LightSource(90, 45)

N = 100
M = 100

x = np.linspace(-3.0, 3.0, M)
y = np.linspace(-3.0, 3.0, N)

X, Y = np.meshgrid(x, y)

Z = np.sin(0.5 * X * Y)

fig = plt.figure()
axes = fig.add_subplot(111, projection='3d')

plt.title(r"Konturplott $sin(x=\frac{pi}{2})$")

axes.plot_surface(X, Y, Z, cmap=plt.cm.plasma)
Ejemplo n.º 23
0
 def _shade_colors_lightsource(self, data, cmap, lightsource):
     if lightsource is None:
         lightsource = LightSource(azdeg=135, altdeg=55)
     return lightsource.shade(data, cmap)
Ejemplo n.º 24
0
 def _lightsource(self, frame):
     # Note: 180 degrees are subtracted because visualization in Sandbox is upside-down
     ls = LightSource(azdeg=self.azdeg - 180, altdeg=self.altdeg)
     cmap = plt.cm.copper
     rgb = ls.shade(frame, cmap=cmap, vert_exag=self.ve, blend_mode='hsv')
     return rgb, cmap
Ejemplo n.º 25
0
    etopo1 = Dataset(etopo1name, 'r')
    lons = etopo1.variables["lon"][:]
    lats = etopo1.variables["lat"][:]
    i_lon, = np.where((left <= lons) & (lons <= right))
    i_lat, = np.where((bottom <= lats) & (lats <= top))
    topo = etopo1.variables["z"][i_lat, i_lon]
    lons = lons[i_lon]
    lats = lats[i_lat]

    # transform to nx x ny regularly spaced native projection grid
    nx = int((m.xmax - m.xmin) / RES) + 1
    ny = int((m.ymax - m.ymin) / RES) + 1
    topo, x, y = m.transform_scalar(topo, lons, lats, nx, ny, returnxy=True)

    # create light source object.
    ls = LightSource(azdeg=100, altdeg=45)

    # convert data to rgb array including shading from light source.
    topom = np.ma.masked_where((topo < 0), topo)
    rgb = ls.shade(topom, cmap)
    rgb = ls.shade(topom, cm.gray_r)
    im = m.imshow(rgb)

    shelf = np.ma.masked_where((topom > 90), topo)
    im = m.imshow(shelf, cmap=cm.gray_r)

#----------------------------------------------------------------

extent = (left - dx / 2., right + dx / 2., bottom - dy / 2., top + dy / 2.)
# minimum values for colorbar. filter our nans which are in the grid
zmin = grid[np.where(np.isnan(grid) == False)].min()
Ejemplo n.º 26
0
def get_basemap(llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat, res, fig,
                useGEBCO):
    '''
    useGEBCO = True: use GEBCO data
    useGEBCO = False: use shadedrelief
    '''
    from mpl_toolkits.basemap import Basemap
    import matplotlib as mpl
    from matplotlib.colors import LightSource
    from netCDF4 import Dataset as NetCDFFile
    from os import getcwd

    cwd = getcwd()

    lon_0 = mean([llcrnrlon, urcrnrlon])
    lat_1 = percentile([llcrnrlat, urcrnrlat], 25)
    lat_2 = percentile([llcrnrlat, urcrnrlat], 75)

    plt.tick_params(labelsize=16)
    ax = fig.add_subplot(111)

    m = Basemap(projection='lcc',lat_1=lat_1,lat_2=lat_2,lon_0=lon_0,\
                llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat, \
                urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,\
                rsphere=6371200.,resolution=res,area_thresh=100.)

    # draw coastlines, state and country boundaries, edge of map.
    if useGEBCO == False:
        m.shadedrelief()

    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.drawparallels(arange(-90., 90., 1.),
                    labels=[1, 0, 0, 0],
                    fontsize=16,
                    dashes=[2, 2],
                    color='0.5',
                    linewidth=0.75)
    m.drawmeridians(arange(0., 360., 2.),
                    labels=[0, 0, 0, 1],
                    fontsize=16,
                    dashes=[2, 2],
                    color='0.5',
                    linewidth=0.75)
    #m.drawmapscale(144, -34.8, 146., -38.5, 400, fontsize = 16, barstyle='fancy', zorder=100)

    ##########################################################################################
    # plot gebco
    ##########################################################################################
    if useGEBCO == True:
        print 'Reading netCDF file...'
        if cwd.startswith('/nas'):
            nc = NetCDFFile(
                '//nas//gemd//ehp//georisk_earthquake//hazard//DATA//GEBCO//au_gebco.nc'
            )
            cptfile = '//nas//gemd//ehp//georisk_earthquake//hazard//DATA//cpt//mby_topo-bath.cpt'
            #cptfile = '//nas//gemd//ehp//georisk_earthquake//hazard//DATA//cpt//gray.cpt'
            #cptfile = '//nas//gemd//ehp//georisk_earthquake//hazard//DATA//cpt//mby_topo-bath_mod.cpt'
        else:
            nc = NetCDFFile(
                '//Users//tallen//Documents//DATA//GMT//GEBCO//Australia_30c.nc'
            )
            cptfile = '//Users//tallen//Documents//DATA//GMT//cpt//mby_topo-bath.cpt'
            cptfile = '//Users//trev//Documents//DATA//GMT//cpt//wiki-2.0.cpt'

        zscale = 20.  #gray
        zscale = 30.  #colour
        data = nc.variables['elevation'][:] / zscale
        lons = nc.variables['lon'][:]
        lats = nc.variables['lat'][:]

        # transform to metres
        nx = int((m.xmax - m.xmin) / 500.) + 1
        ny = int((m.ymax - m.ymin) / 500.) + 1

        topodat = m.transform_scalar(data, lons, lats, nx, ny)

        print 'Getting colormap...'
        # get colormap

        #cptfile = '//Users//tallen//Documents//DATA//GMT//cpt//gray.cpt'
        cmap, zvals = cpt2colormap(cptfile, 30)
        cmap = remove_last_cmap_colour(cmap)
        #cmap = remove_last_cmap_colour(cmap)

        # make shading
        print 'Making map...'
        ls = LightSource(azdeg=180, altdeg=5)
        #norm = mpl.colors.Normalize(vmin=-8000/zscale, vmax=5000/zscale)#myb
        norm = mpl.colors.Normalize(vmin=-1000 / zscale,
                                    vmax=1900 / zscale)  #wiki
        rgb = ls.shade(topodat, cmap=cmap, norm=norm)
        im = m.imshow(rgb)

    return m, ax
Ejemplo n.º 27
0
            if (i + j + k) % 2 == 0:
                colors.append("crimson")
            else:
                colors.append("limegreen")

for p, s, c in zip(positions, sizes, colors):
    plotCubeAt(pos=p, size=s, ax=ax, color=c, alpha=0.7)

ax.scatter(x[::2], y[::2], z[::2]+2.4, s=0.1, facecolor='w', alpha=0.7)

x = linspace(0, 2, 45)

for value in x:
    ax.scatter(x, 2.5, value, s=0.1, facecolor='w', alpha=0.9)

ls = LightSource(azdeg=155, altdeg=75)
# Shade data, creating an rgb array.
# rgb = ls.shade(z, plt.cm.RdYlBu)
ax.xaxis.pane.set_facecolor('grey')
ax.yaxis.pane.set_facecolor('grey')
ax.zaxis.pane.set_facecolor('grey')
ax.xaxis.pane.set_edgecolor('grey')
ax.yaxis.pane.set_edgecolor('grey')
ax.zaxis.pane.set_edgecolor('grey')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$z$')
ax.set_xlim(0, 2.5)
ax.set_ylim(0, 2.5)
ax.set_zlim(0, 2.5)
ax.grid(False)
Ejemplo n.º 28
0
green = white * np.array([0, 1, 0])
blue = white * np.array([0, 0, 1])

# Set view parameters for all subplots.
azimuth = 45
altitude = 60

# Create empty figure.
fig = plt.figure(figsize=(18, 12))

# -------------------------------------------------------------------------
# Generate first subplot.
# -------------------------------------------------------------------------
# Create a light source object for light from
# 0 degrees azimuth, 0 degrees elevation.
light = LightSource(0, 0)

# Generate face colors for a shaded surface using either
# a color map or the uniform rgb color specified above.

illuminated_surface = light.shade_rgb(red, Z)

# Create a subplot with 3d plotting capabilities.
# This command will fail if Axes3D was not imported.
ax = fig.add_subplot(2, 2, 1, projection='3d')
ax.view_init(altitude, azimuth)
ax.plot_surface(X,
                Y,
                Z,
                rstride=1,
                cstride=1,
Ejemplo n.º 29
0
# Load and format data
filename = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
with np.load(filename) as dem:
    z = dem['elevation']
    print(z)
    nrows, ncols = z.shape
    x = np.linspace(dem['xmin'], dem['xmax'], ncols)
    y = np.linspace(dem['ymin'], dem['ymax'], nrows)
    x, y = np.meshgrid(x, y)

region = np.s_[5:50, 5:50]
x, y, z = x[region], y[region], z[region]

# Set up plot
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))

ls = LightSource(270, 45)
# To use a custom hillshading mode, override the built-in shading and pass
# in the rgb colors of the shaded surface calculated from "shade".
rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
surf = ax.plot_surface(x,
                       y,
                       z,
                       rstride=1,
                       cstride=1,
                       facecolors=rgb,
                       linewidth=0,
                       antialiased=False,
                       shade=False)

plt.show()
Ejemplo n.º 30
0
def flux_tube(self, r=0.12, alpha=0, delta_r=0.03, delta_alpha=0.2, delta_phi=4*np.pi, ntheta=80, nphi=150, ntheta_fourier=20, nphi_tube=2000,
         savefig=None, show=True, **kwargs):
    '''
    Plot the flux tube at a specific alpha and psi
    with a volume of delta alpha, delta psi and delta phi.
    The variable alpha is the field-line label
    alpha=theta-q varphi with theta and varphi the poloidal
    and toroidal Boozer angles. Phi is the cylindrical
    toroidal angle and psi=Bbar r^2/2

    Args:
      r (float): radial location of the field-line
      alpha (float): field-line label for the field-line
      delta_r (float): radial length of the field-line
      delta_alpha (float): poloidal length of the field-line
      delta_phi (float): toroidal length of the field-line
      ntheta (int): Number of grid points to plot in the poloidal angle.
      nphi   (int): Number of grid points to plot in the toroidal angle.
      ntheta_fourier (int): Resolution in the Fourier transform to cylindrical coordinates
      nphi_tube (int): Resolution of the field-lines in the flux tube plot
      savefig (str): Filename prefix for the png files to save.
        Note that a suffix including ``.png`` will be appended.
        If ``None``, no figure files will be saved.
      show (bool): Whether or not to call the matplotlib/mayavi ``show()`` command.
    '''

    x_2D_plot, y_2D_plot, z_2D_plot, R_2D_plot = self.get_boundary(r=r, ntheta=ntheta, nphi=nphi, ntheta_fourier=ntheta_fourier)
    # Define the magnetic field modulus and create its theta,phi array
    # The norm instance will be used as the colormap for the surface
    theta1D = np.linspace(0, 2 * np.pi, ntheta)
    phi1D = np.linspace(0, 2 * np.pi, nphi)
    phi2D, theta2D = np.meshgrid(phi1D, theta1D)
    # Create a color map similar to viridis 
    Bmag = self.B_mag(r, theta2D, phi2D)
    norm = clr.Normalize(vmin=Bmag.min(), vmax=Bmag.max())
    cmap = cm.plasma
    # Add a light source so the surface looks brighter
    ls = LightSource(azdeg=0, altdeg=10)
    cmap_plot = ls.shade(Bmag, cmap, norm=norm)
    fig = plt.figure(constrained_layout=False, figsize=(5, 4))
    ax = plt.axes(projection='3d')
    # Set the default azimuthal angle of view in the 3D plot
    # QH stellarators look rotated in the phi direction when
    # azim_default = 0
    if self.helicity == 0:
        azim_default = 0
    else:
        azim_default = 45
    create_subplot(ax, x_2D_plot, y_2D_plot, z_2D_plot, cmap_plot, elev=35, azim=azim_default, alpha=0.08, dist=5, **kwargs)

    # Create the field line arrays
    fieldline_X, fieldline_Y, fieldline_Z = create_field_lines(self, [alpha], x_2D_plot, y_2D_plot, z_2D_plot, phimax=delta_phi, nphi=nphi_tube)
    fieldline_X_delta_alpha, fieldline_Y_delta_alpha, fieldline_Z_delta_alpha = create_field_lines(self, [alpha+delta_alpha], x_2D_plot, y_2D_plot, z_2D_plot, phimax=delta_phi, nphi=nphi_tube)

    x_2D_plot_delta_r, y_2D_plot_delta_r, z_2D_plot_delta_r, R_2D_plot_delta_r = self.get_boundary(r=r-delta_r, ntheta=ntheta, nphi=nphi, ntheta_fourier=ntheta_fourier)
    fieldline_X_delta_r, fieldline_Y_delta_r, fieldline_Z_delta_r = create_field_lines(self, [alpha], x_2D_plot_delta_r, y_2D_plot_delta_r, z_2D_plot_delta_r, phimax=delta_phi, nphi=nphi_tube)
    fieldline_X_delta_r_delta_alpha, fieldline_Y_delta_r_delta_alpha, fieldline_Z_delta_r_delta_alpha = create_field_lines(self, [alpha+delta_alpha], x_2D_plot_delta_r, y_2D_plot_delta_r, z_2D_plot_delta_r, phimax=delta_phi, nphi=nphi_tube)
    
    # Plot the flux tube
    for i in range(len(fieldline_X[0])):
        x_array = [fieldline_X[0][i],fieldline_X_delta_r[0][i],fieldline_X_delta_alpha[0][i],fieldline_X_delta_r_delta_alpha[0][i]]
        y_array = [fieldline_Y[0][i],fieldline_Y_delta_r[0][i],fieldline_Y_delta_alpha[0][i],fieldline_Y_delta_r_delta_alpha[0][i]]
        z_array = [fieldline_Z[0][i],fieldline_Z_delta_r[0][i],fieldline_Z_delta_alpha[0][i],fieldline_Z_delta_r_delta_alpha[0][i]]
        ax.plot(x_array, y_array, z_array, 'k-', linewidth=1, alpha=0.3)
    # Plot the field lines
    ax.plot(fieldline_X[0], fieldline_Y[0], fieldline_Z[0], 'k-', linewidth=1)
    ax.plot(fieldline_X_delta_r[0], fieldline_Y_delta_r[0], fieldline_Z_delta_r[0], 'k-', linewidth=1)
    ax.plot(fieldline_X_delta_alpha[0], fieldline_Y_delta_alpha[0], fieldline_Z_delta_alpha[0], 'k-', linewidth=1)
    ax.plot(fieldline_X_delta_r_delta_alpha[0], fieldline_Y_delta_r_delta_alpha[0], fieldline_Z_delta_r_delta_alpha[0], 'k-', linewidth=1)
    
    if savefig != None:
        fig.savefig(savefig + 'flux_tube.png')
    if show:
        # Show figures
        plt.show()