Beispiel #1
0
def plot_decision_regions(X, y, classifier, resolution=0.02):
    # prepare marker and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot decision regions
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    # generate grid point
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    # translate features into array and predict
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    # translate result to grid point
    Z = Z.reshape(xx1.shape)
    # plot contour line of grid point
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)

    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # plot sample by each class
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx),
                    marker=markers[idx], label=cl)
def plotPredictions(clf):
    xx, yy = np.meshgrid(np.arange(0, 250000, 10), np.arange(10, 70, 0.5))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    plt.figure(figsize=(8, 6))
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)
    plt.scatter(X[:, 0], X[:, 1], c=y.astype(np.float))
    plt.show()
Beispiel #3
0
def plot_predictions(clf, axes):
    x0s = np.linspace(axes[0], axes[1], 100)
    x1s = np.linspace(axes[2], axes[3], 100)
    x0, x1 = np.meshgrid(x0s, x1s)
    X = np.c_[x0.ravel(), x1.ravel()]
    y_pred = clf.predict(X).reshape(x0.shape)
    y_decision = clf.decision_function(X).reshape(x0.shape)
    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
Beispiel #4
0
def plot_decision_boundary(model, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
    y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    # Predict the function value for the whole grid
    Z = model(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.ylabel('x2')
    plt.xlabel('x1')
    plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
    plt.show()
Beispiel #5
0
def get_contours(x,y,z,bounds):
    r"""
    points x and y with values z, with whole shape bounded by 
    a matplotlib.path bounds
    """

    grid_x, grid_y = np.mgrid[1.1*min(x):1.1*max(x):complex(0,10*len(x)j), 
                              1.1*min(y):1.1*max(y):complex(0,10*len(y))]

    grid_z = griddata(zip(x,y), z, (grid_x, grid_y), method='cubic')
    grid_x = grid_x.flatten(); grid_y = grid_y.flatten(); grid_z = grid_z.flatten()
    new_grid_x = []; new_grid_y = []; new_grid_z = []
    for i in xrange(len(grid_x)):
        if bounds.contains_point((grid_x[i], grid_y[i])):
            new_grid_x.append(grid_x[i])
            new_grid_y.append(grid_y[i])
            new_grid_z.append(grid_z[i])

    return contourf(grid_x, grid_y, grid_z)
Beispiel #6
0
# ### Visualisation

# In[15]:

X_set, Y_set = x_test, y_test
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('cyan', 'yellow', 'blue')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(Y_set)):
    plt.scatter(X_set[Y_set == j, 0],
                X_set[Y_set == j, 1],
                c=ListedColormap(('red', 'green', 'yellow'))(i),
                label=j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.legend()
plt.show()
Beispiel #7
0
print("x_test after scaling:\n", x_test)

print("y:\n", y)

print("y_train:\n", y_train)

print("y_test:\n", y_test)

X_set, y_set = x_train, y_train
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0],
                X_set[y_set == j, 1],
                c=ListedColormap(('red', 'green'))(i))
    plt.show()
Beispiel #8
0
def plot_lib(x_nodes,l,b,topo_in_file,bouger_in_file,geoid_in_file,FA_in_file,heatflux_in_file,anomaly,c,l_nodes,b_nodes,mat,max_depth,
  label_size,marker_size,anomaly_x,anomaly_y,anomaly_amount,anomaly_type,anomaly_compo,anomaly_color):
  #
  # Making string list of the observables file input
  #
  #data_list=[];data_list.extend([topo_in_file,bouger_in_file,FA_in_file,geoid_in_file,heatflux_in_file])
  #
  ## Figuring out what input files are given
  #name_len=[ len(data_list[k]) for k in range(len(data_list)) ];

  #for i in range(len(name_len)):
  #  if name_len[i] != 0 :
      # plot it

  #  else
  #    pass
  
  try:
    topo=np.loadtxt(topo_in_file)#f=np.loadtxt(self.digitized,comments=">")
    max_depth = -max_depth
    min_depth = max(topo[:,1]/1000)
  except Exception:
    max_depth = -400
    min_depth = 3
  # Initializing the figure
  #
  fig  = plt.figure()
  #gs = gridspec.GridSpec(6, 1, width_ratios=[3, 1]) 
  gs = gridspec.GridSpec(6, 1,height_ratios=[1,1,1,1,1,3])
  #
  # ploting the bodies geometry
  #
  ax1 = plt.subplot(gs[5]) #fig.add_subplot(616)
  for i in range(len(l_nodes)):
                ax1.plot(l_nodes[i],b_nodes[i],color='black',lw=1,marker=None)
                poly = Polygon(list(zip(l_nodes[i],b_nodes[i])),facecolor=c[i],label=mat[i], lw=1)
                ax1.add_patch(poly)
  for i in range(len(anomaly_x)):
    ax1.plot(anomaly_x[i],anomaly_y[i],color="green",lw=1,marker='o',markersize=4)
    poly = Polygon(list(zip(anomaly_x[i],anomaly_y[i])),facecolor=anomaly_color[i],label="anomaly", lw=1)
    l_text=min(anomaly_x[i])+ (max(anomaly_x[i])-min(anomaly_x[i]))/2
    b_text=min(anomaly_y[i])+ (max(anomaly_y[i])-min(anomaly_y[i]))/2
    ax1.add_patch(poly)
    ax1.text(l_text, b_text, str(int(i+1))+" "+str(anomaly_type[i])+" Material"
      +str(anomaly_compo[i])+""+str(anomaly_amount[i]), fontsize=8,fontstyle='italic',color='black',bbox=dict(facecolor='white', alpha=0.9))
  #ax1.plot(l[i][:],b[i][:],color='grey',linewidth=0.5)
  ax1.grid(True)
  ax1.tick_params(labelsize=10)
  plt.ylim((max_depth,min_depth))
  plt.title('Profile Geometry')
  plt.xlabel('Distance ($km$)')
  plt.ylabel('Depth ($km$)')
  #
  # plotting the topography
  # 
  ax2 = plt.subplot(gs[4])#fig.add_subplot(611)    
  # topography data
  f_out=open("topo_out.dat","r")
  data_out=f_out.readlines()
  try:
    f_in=open(topo_in_file,"r") #f_in=open("test_top.dat","r")#f_in=open("test_top.dat","r")
    data_in=f_in.readlines()
    f_in.close()
  except Exception:
    data_in=data_out
  profile_out=[]
  profile_in=[]
  if anomaly==1:
    topo_in=[]
    topo_error=[]
    topo_out_coupled=[]
    topo_out_uncoupled=[]
    f_out.close()
    ## storing data into local variables
    for i  in range(len(data_in)):
      try:
        data_temp=data_out[i].split()
      except IndexError:
        data_temp=[]
        pass
      try:
        profile_out.append(float(str(data_temp[0])))
        topo_out_coupled.append(float(str(data_temp[1])))
        topo_out_uncoupled.append(float(str(data_temp[2])))
      except ValueError:
        data_temp=[]
        pass
      try:
        data_temp=data_in[i].split()
      except IndexError:
        data_temp=[]
        pass
      try:
        profile_in.append(float(str(data_temp[0])))
        topo_in.append(float(str(data_temp[1])))
        try:
          topo_error.append(float(str(data_temp[2])))
        except:
          topo_error.append(0)
      except ValueError:
        data_temp=[]
        pass    
    plt.hold(True)
    ax2.errorbar(profile_in,topo_in,yerr=topo_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed')
    ax2.plot(profile_out,topo_out_coupled,'k-',label='Coupled' )
    ax2.plot(profile_out,topo_out_uncoupled, 'r-',label='Uncoupled')
    '''
    ax2_=ax2.twinx()
    diff=[]
    diff=np.subtract(topo_out_uncoupled,topo_in)
    ax2_.plot(profile_out,diff,color='g',label='Diff')
    ax2_.set_ylabel('Diff', color='g')
    ax2_.tick_params('y', colors='g')
    '''
    #ax2.plot(profile_in,topo_in, 'b-',label='Observed')
    ax2.grid(True)
    ax2.set_title('Elevation ')
    ax2.xaxis.set_ticklabels([])
    ax2.tick_params(labelsize=10)
    #plt.xlabel('Distance (Km)')
    plt.ylabel('Elevation ($m$)')
    plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best')
    #ax2.legend(handles, ['input','Computed-coupled','Computed-uncoupled'])
  else:
    topo_in=[]
    topo_error=[]
    topo_out=[]
    f_out.close()
    ## storing data into local variables
    for i  in range(len(data_in)):
      try:
        data_temp=data_out[i].split()
      except IndexError:
        pass
      try:
        profile_out.append(float(str(data_temp[0])))
        topo_out.append(float(str(data_temp[1])))
      except ValueError:
        passa
      try:
        data_temp=data_in[i].split()
      except IndexError:
        pass
      try:
        profile_in.append(float(str(data_temp[0])))
        topo_in.append(float(str(data_temp[1])))
        try:
          topo_error.append(float(str(data_temp[2])))
        except:
          topo_error.append(0)
      except ValueError:
        pass   
    #topo_misfit= (topo_in - topo_out)/len(topo_in)
    #print topo_misfit 
    plt.hold(True)
    #ax2.plot(profile_in,topo_in, 'b-',label='Observed')
    ax2.errorbar(profile_in,topo_in,yerr=topo_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed')    
    ax2.plot(profile_out,topo_out,'r-',label='Calculated')
    '''
    ax2_=ax2.twinx()
    diff=[]
    diff=np.subtract(topo_out,topo_in)
    ax2_.plot(profile_out,diff,color='g',label='Diff')
    ax2_.set_ylabel('Diff', color='g')
    ax2_.tick_params('y', colors='g')
    '''
    #ax2.fill(profile_in,topo_in+topo_error,zorder=10)
    ax2.grid(True)
    ax2.set_title('Elevation')
    ax2.xaxis.set_ticklabels([])
    ax2.tick_params(labelsize=10)
    #plt.xlabel('Distance (Km)')
    plt.ylabel('Elevation ($m$)')
    plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best')
  #  
  # bouguer data
  #
  f_out=open("bouguer_out.dat","r")
  data_out=f_out.readlines()
  try:
    f_in=open(bouger_in_file,"r") #f_in=open("test_bou.dat","r")
    data_in=f_in.readlines()
    f_in.close()
  except Exception:
    data_in=data_out
  profile_out=[]
  profile_in=[]
  boug_in=[]
  boug_out=[]
  boug_error=[]
  for i  in range(len(data_in)):
    try:
      data_temp=data_out[i].split()
    except IndexError:
      pass
    try:
      profile_out.append(float(str(data_temp[0])))
      boug_out.append(float(str(data_temp[1])))
    except ValueError:
      pass
    try:
      data_temp=data_in[i].split()
    except IndexError:
      pass
    try:
      profile_in.append(float(str(data_temp[0])))
      boug_in.append(float(str(data_temp[1])))
      try:
          boug_error.append(float(str(data_temp[2])))
      except:
          boug_error.append(0.0)
    except ValueError:
      pass  

  ax3 = plt.subplot(gs[3])#fig.add_subplot(612)
  plt.hold(True)
  #ax3.plot(profile_in,boug_in, 'b-')
  ax3.errorbar(profile_in,boug_in,yerr=boug_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed')
  ax3.plot(profile_out,boug_out,'r-',label='Calculated')
  '''
  ax3_=ax3.twinx()
  diff=[]
  diff=np.subtract(boug_out,boug_in[range(len(boug_out))])
  ax3_.plot(profile_out,diff,color='g',label='Diff')
  ax3_.set_ylabel('Diff', color='g')
  ax3_.tick_params('y', colors='g')
  '''
  ax3.grid(True)
  ax3.set_title('Bouguer')
  ax3.xaxis.set_ticklabels([])
  ax3.tick_params(labelsize=10)
  #plt.xlabel('Distance (Km)')
  plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best')
  plt.ylabel('Bouguer ($mGal$)')
  f_out.close()
  
  #
  # geoid data
  #
  f_out=open("geoid_out.dat","r")
  data_out=f_out.readlines()
  try:
    f_in=open(geoid_in_file,"r")#f_in=open("test_geo.dat","r")
    data_in=f_in.readlines()
    f_in.close()
  except Exception:
    data_in=data_out
  profile_out=[]
  profile_in=[]
  geoid_in=[]
  geoid_out=[]
  geoid_error=[]
  for i  in range(len(data_in)):
    try:
      data_temp=data_out[i].split()
    except IndexError:
      pass
    try:
      profile_out.append(float(str(data_temp[0])))
      geoid_out.append(float(str(data_temp[1])))
    except ValueError:
      pass
    try:
      data_temp=data_in[i].split()
    except IndexError:
      pass
    try:
      profile_in.append(float(str(data_temp[0])))
      geoid_in.append(float(str(data_temp[1])))
      try:
        geoid_error.append(float(str(data_temp[2])))
      except IndexError:
        geoid_error.append(0.0)        
    except ValueError:
      pass  
  #geoid_in=np.loadtxt(geoid_in_file)
  ax4 = plt.subplot(gs[2])#fig.add_subplot(614)
  plt.hold(True)
  ax4.plot(profile_in,geoid_in, 'b-')
  ax4.errorbar(profile_in,geoid_in,yerr=geoid_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed')
  '''
  ax4_=ax4.twinx()
  diff=[]
  diff=np.subtract(geoid_out,geoid_in[range(len(geoid_out))])
  ax4_.plot(profile_out,diff,color='g',label='Diff')
  ax4_.set_ylabel('Diff', color='g')
  ax4_.tick_params('y', colors='g')
  '''
  #test=[]
  #test=smoothListGaussian(geoid_in,degree=1)
  #ax4.plot(profile_in[0:len(test)],test,fmt='o-',markersize=marker_size,color='black',label='Observed--9')
  '''
  try:
    ax4.errorbar(geoid_in[:,0],geoid_in[:,1],yerr=geoid_in[:,2],fmt='o-',markersize=marker_size,ecolor='b',label='8')
    plt.hold(True)
  except Exception:
    pass
  try:
    ax4.errorbar(geoid_in[:,0],geoid_in[:,3],yerr=geoid_in[:,4],fmt='o-',markersize=marker_size,ecolor='k',label='9')
    plt.hold(True)
  except Exception:
    pass
  try:
    ax4.errorbar(geoid_in[:,0],geoid_in[:,5],yerr=geoid_in[:,6],fmt='o-',markersize=marker_size,ecolor='m',label='10')
    plt.hold(True)
  except Exception:
    pass
  '''
  plt.hold(True)
  ax4.plot(profile_out,geoid_out,'r-', label='Calculated')
  ax4.grid(True)
  ax4.set_title('Geoid')
  ax4.xaxis.set_ticklabels([])
  ax4.tick_params(labelsize=10)
  plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best')
  #plt.xlabel('Distance (Km)')
  plt.ylabel('Geoid ($m$)')
  f_out.close()
  #
  # heat flux data
  #
  f_out=open("SHF_out.dat","r")
  data_out=f_out.readlines()
  f_out.close()
  try:
    f_in=open(heatflux_in_file,"r")#f_in=open("fluxout.dat","r")
    data_in=f_in.readlines()
    f_in.close()
  except Exception:
    data_in=data_out
  profile_out=[]
  profile_in=[]
  flux_in=[]
  flux_out=[]
  flux_error=[]
  for i  in range(len(data_out)):
    try:
      data_temp=data_out[i].split()
    except IndexError:
      pass
    try:
      profile_out.append(float(str(data_temp[0])))
      flux_out.append(float(str(data_temp[1])))
    except ValueError:
      pass
    try:
      data_temp=data_in[i].split()
    except IndexError:
      pass
  for i  in range(len(data_in)):
    try:
      data_temp=data_in[i].split()
    except IndexError:
      pass
    try:
      profile_in.append(float(str(data_temp[0])))
      flux_in.append(float(str(data_temp[1])))
      try:
        flux_error.append(float(str(data_temp[2])))
      except IndexError:
        flux_error.append(0.0)
    except ValueError:
      pass
    try:
      data_temp=data_in[i].split()
    except IndexError:
      pass  
  

  ax5 = plt.subplot(gs[0])#fig.add_subplot(615)
  plt.hold(True)
  ax5.errorbar(profile_in,flux_in,yerr=flux_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed')
  ax5.plot(profile_out,flux_out,'r-',label='Calculated')
  ax5.grid(True)
  ax5.set_title('Heat Flux')
  ax5.xaxis.set_ticklabels([])
  ax5.tick_params(labelsize=10)
  #plt.xlabel('Distance (Km)')
  plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best')
  plt.ylabel('Heat-flux ($mW/m^2$)')

  #plt.tight_layout()

  #plt.tight_layout()  
  #
  # FA data
  #
  f_out=open("FA_out.dat","r")
  data_out=f_out.readlines()
  f_out.close()
  try:
    f_in=open(FA_in_file,"r")#f_in=open("fluxout.dat","r")
    data_in=f_in.readlines()
    f_in.close()
  except Exception:
    data_in=data_out
  profile_out=[]
  profile_in=[]
  FA_in=[]
  FA_out=[]
  FA_error=[]
  for i  in range(len(data_in)):
    try:
      data_temp=data_out[i].split()
    except IndexError:
      pass
    try:
      profile_out.append(float(str(data_temp[0])))
      FA_out.append(float(str(data_temp[1])))
    except ValueError:
      pass
    try:
      data_temp=data_in[i].split()
    except IndexError:
      pass
    try:
      profile_in.append(float(str(data_temp[0])))
      FA_in.append(float(str(data_temp[1])))
      try:
        FA_error.append(float(str(data_temp[2])))
      except IndexError:
        FA_error.append(0.0)
    except ValueError:
      pass  
  ax6 = plt.subplot(gs[1])#fig.add_subplot(613)
  plt.hold(True)
  #ax6.plot(profile_in,FA_in, 'b-')
  ax6.errorbar(profile_in,FA_in,yerr=FA_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed')
  ax6.plot(profile_out,FA_out,'r-',label='Calculated')
  '''
  ax6_=ax6.twinx()
  diff=[]
  diff=np.subtract(FA_out,FA_in[range(len(FA_out))])
  ax6_.plot(profile_out,diff,color='g',label='Diff')
  ax6_.set_ylabel('Diff', color='g')
  ax6_.tick_params('y', colors='g')
  '''
  ax6.grid(True)
  ax6.set_title('Free-Air')
  ax6.xaxis.set_ticklabels([])
  ax6.tick_params(labelsize=10)
  plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best')
  #plt.xlabel('Distance (Km)')
  plt.ylabel('FA (mGal)')
  #plt.tight_layout()

  multi = MultiCursor(fig.canvas,(ax1,ax2,ax3,ax4,ax5,ax6), color='r', lw=1)


  ##############33 temperature profile plotting
  gs_ = gridspec.GridSpec(4, 1)
  #fig_out = plt.figure()
  fig_out  = plt.figure()
  #ax_temp = fig_out.add_subplot(411)
  ax_temp =plt.subplot(gs_[0]) #fig_out.add_subplot(411)
  f=open("tempout.dat","r")
  data_out=f.readlines()
  temp_x=[]
  temp_y=[]
  temp_z=[]
  for i  in range(2,len(data_out)):
    data_temp=data_out[i].split()
    temp_x.append(float(str(data_temp[0])))
    temp_y.append(float(str(data_temp[1])))
    temp_z.append(float(str(data_temp[2])))
  xlist=[]
  ylist = np.array(temp_y[0:96])
  z =temp_z #np.array(temp_z)
  Z=[]
  temp=0
  for i in range(0,x_nodes):
    tmp = []
    xlist.append(temp_x[temp])
    for j in range(0,96):
      tmp.append(z[temp])
      temp=temp+1
    Z.append(tmp)
  X,Y = np.meshgrid(ylist, xlist)   
  levels = np.linspace(0, 50, 1600)
  
  
  for i in range(len(l)):
    ax_temp.plot(l[i][:],b[i][:],color='grey',linewidth=2)
  levels =[300,500,600,1000,1200,1300,1450,1550,1650]
  CS3 = plt.contourf(Y, X, Z, levels,extend='both',cmap=plt.cm.get_cmap('coolwarm',20))
  CS3.cmap.set_under('white')
  CS3.cmap.set_over('black')
  #levels = np.arange(min(temp_z), max(temp_z)+100, 100)
  CS4 = plt.contour(Y, X, Z, levels,linewidths=0.2,linestyles='dashed',colors='black')
  plt.clabel(CS4,inline=5,inline_spacing=10,fontsize=10,fontstyles='arial',fontweight='bold',fmt='%1.0f',colors='black')
  plt.colorbar(CS3,label='$^oC$')
  plt.title('Temperature',fontsize=10, fontweight='bold')
  """
  cp = plt.contourf(Y,X,Z)
  plt.colorbar(cp)
  #cpc=plt.contour(Y,X,Z,levels) # predefinrd number of contour
  CS = plt.contour(Y, X, Z, 30 ,linewidths=0.5,colors='grey') # automatice number of contours
  plt.clabel(CS,inline=1,inline_spacing=0,fontsize=12,fmt='%1.0f',colors='black')
  #plt.clabel(CS, inline=1, fontsize=10,color="black") # contour line labels
  """
  #plt.title('Temperature profile')
  #plt.xlabel('Distance ($km$)')
  plt.tick_params(labelsize=10)
  plt.ylabel('Depth ($km$)')

  ##############33 density profile plotting
  f=open("dens_node2.dat","r")
  data_out=f.readlines()
  temp_x=[]
  temp_y=[]
  temp_z=[]
  for i  in range(len(data_out)):
    data_temp=data_out[i].split()
    temp_x.append(float(str(data_temp[0])))
    temp_y.append(float(str(data_temp[1])))
    temp_z.append(float(str(data_temp[2])))
  xlist=[]
  ylist = np.array(temp_y[0:95])
  z =temp_z #np.array(temp_z)
  Z=[]
  temp=0
  for i in range(0,x_nodes):
    tmp = []
    xlist.append(temp_x[temp])
    for j in range(0,95):
      tmp.append(z[temp])
      temp=temp+1
    Z.append(tmp)
  X,Y = np.meshgrid(ylist, xlist)   
  levels = np.linspace(0, 50, 1600)
  
  #ax_dens = fig_out.add_subplot(412)
  ax_dens =plt.subplot(gs_[1])
  for i in range(len(l)):
    ax_dens.plot(l[i][:],b[i][:],color='grey',linewidth=2)
  levels = np.arange(2800, 3800, 50)
  #levels = np.arange(3000, 3800, 20)
  CS3 = plt.contourf(Y, X, Z, levels,extend='both',cmap=plt.cm.get_cmap('rainbow',20),origin=origin)
  CS3.cmap.set_under('white')
  CS3.cmap.set_over('black')
  levels = np.arange(3000, 3800, 50)
  CS4 = plt.contour(Y, X, Z,levels,linewidths=0.2,linestyles='dashed',colors='grey')
  plt.clabel(CS4,inline=True,inline_spacing=2,fontsize=10,fontstyles='arial',fontweight='normal',fmt='%1.0f',colors='black')
  plt.colorbar(CS3,label='$kg/m^3$')
  plt.title('Density',fontsize=10, fontweight='bold')
  plt.tick_params(labelsize=10)
  """  
  cp = plt.contourf(Y,X,Z)
  plt.colorbar(cp)3
  #cpc=plt.contour(Y,X,Z,levels) # predefinrd number of contour
  CS = plt.contour(Y, X, Z, 30 ,linewidths=0.5,colors='grey') # automatice number of contours
  plt.clabel(CS,inline=1,inline_spacing=0,fontsize=12,fmt='%1.0f',colors='black')
  #plt.clabel(CS, inline=1, fontsize=10,color="black") # contour line labels
  """
  #plt.title('Density profile')
  #plt.xlabel('Distance ($km$)')
  plt.ylabel('Depth ($km$)')
 

  ##############33 Vp profile plotting
  #f=open("velatten.dat","r")
  f=open("velocities.dat","r")
  data_out=f.readlines()
  temp_x=[]
  temp_y=[]
  temp_z_vp=[]
  temp_z_vs=[]
  for i  in range(len(data_out)):
    data_temp=data_out[i].split()
    temp_x.append(float(str(data_temp[0])))
    temp_y.append(float(str(data_temp[1])))
    temp_z_vp.append(float(str(data_temp[2])))
    temp_z_vs.append(float(str(data_temp[3])))
  xlist=[]
  ylist = np.array(temp_y[0:95])
  z_vp =temp_z_vp #np.array(temp_z)
  z_vs =temp_z_vs
  Z_vp=[]
  Z_vs=[]
  temp=0
  for i in range(0,x_nodes):
    tmp1 = []
    tmp2 = []
    xlist.append(temp_x[temp+1])
    for j in range(0,95):
      tmp1.append(z_vp[temp])
      tmp2.append(z_vs[temp])
      temp=temp+1
    Z_vp.append(tmp1)
    Z_vs.append(tmp2)
  X,Y = np.meshgrid(ylist, xlist)   
  levels = np.linspace(0, 50, 1600)
  
  #ax_vp = fig_out.add_subplot(413)
  ax_vp =plt.subplot(gs_[2])
  for i in range(len(l)):
    ax_vp.plot(l[i][:],b[i][:],color='grey',linewidth=2)
  levels = np.arange(7.2, 8.8, 0.01)
  CS3 = plt.contourf(Y, X, Z_vp, levels,extend='both',cmap=plt.cm.get_cmap('RdYlBu',20),origin=origin)
  #CS3 = plt.contourf(Y, X, Z_vp, levels,extend='both',cmap=cmap,origin=origin)
  CS3.cmap.set_under('white')
  CS3.cmap.set_over('black')
  levels = np.arange(7.7, 8.8, 0.05)
  CS4 = plt.contour(Y, X, Z_vp, levels,linewidths=0.2,linestyles='dashed',colors='black')
  plt.clabel(CS4,inline=5,inline_spacing=10,fontsize=10,fmt='%1.1f',colors='black')
  plt.colorbar(CS3,label='$km/s$')
  plt.tick_params(labelsize=10)
  plt.title('P wave velocity',fontsize=10, fontweight='bold')
  #plt.xlabel('Distance ($km$)')
  plt.ylabel('Depth ($km$)') 


  #ax_vs = fig_out.add_subplot(414)
  ax_vs =plt.subplot(gs_[3])


  for i in range(len(l)):
    ax_vs.plot(l[i][:],b[i][:],color='grey',linewidth=2)
  levels = np.arange(4.2, 4.8, 0.01)
  #CS3 = plt.contourf(Y, X, Z_vs, levels,extend='both')
  CS3 = plt.contourf(Y, X, Z_vs, levels,extend='both',cmap=plt.cm.get_cmap('RdYlBu',20),origin=origin)
  CS3.cmap.set_under('white')
  CS3.cmap.set_over('black')
  #levels = np.arange(4.1, 4.8, 0.05)
  levels = np.arange(4.3, 5.1, 0.05)
  CS4 = plt.contour(Y, X, Z_vs, levels,linewidths=0.2,linestyles='dashed',colors='black')
  plt.clabel(CS4,inline=5,inline_spacing=10,fontsize=10,fmt='%1.1f',colors='black')
  plt.colorbar(CS3,label='$km/s$')
  plt.title('S wave velocity',fontsize=10, fontweight='bold')
  plt.xlabel('Distance ($km$)')
  plt.ylabel('Depth ($km$)')
  plt.tick_params(labelsize=10)
  #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
  #plt.tight_layout()
  savefig('Temp_Dens_velocities.png', dpi=300) 
  

  ###########################3
  ### calculating the misfit
  
  
  #boug_misfit= (bouger_in - bouguer_out)/len(bouger_in)
  #print boug_misfit
  #geoid_misfit=(geoid_in - geoid_out )/len(geoid_in)
  #print geoid_misfit

  ##################
  plt.show()
Beispiel #9
0
x1_min, x1_max = X_combined[:, 0].min() - 1, X_combined[:, 0].max() + 1
x2_min, x2_max = X_combined[:, 1].min() - 1, X_combined[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution))
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                       np.arange(x2_min, x2_max, resolution))
xx1
xx2
xx1.ravel()
Z = tree.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z
xx1.shape
xx1
Z
Z.shape
Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
import matplotlib.pyplot as plt
import matplotlib.pyplot
y_combined = np.vstack((y_train[:, np.newaxis], y_test[:, np.newaxis]))
tree = DecisionTreeClassifier(criterion='entropy', max_depth=4,
                              random_state=0).fit(X_train, y_train)
test_idx = range(105, 150)
resolution = 0.01
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')

cmap = mpl.colors.ListedColormap(colors[:len(np.unique(y_combined))])
x1_min, x1_max = X_combined[:, 0].min() - 1, X_combined[:, 0].max() + 1
x2_min, x2_max = X_combined[:, 1].min() - 1, X_combined[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                       np.arange(x2_min, x2_max, resolution))
Beispiel #10
0
fig1 = plb.figure()
q = analyze.readGrid(sgrid=True)
xx = q.x[:]
yy = q.y[:]
zz = q.z[:]
#qq = np.meshgrid(xx, yy, zz, indexing='ij')
#xc = qq[0]
#yc = qq[1]
#zc = qq[2]
#x1 = xc[:,:,0]
#y1 = yc[:,:,0]
#z1 = zc[:,:,0]
#z2 = np.pi/2 - y1
data = analyze.readData(ddens=True, binary=False)
v = data.rhodust[0, :, :, 0]
c = plb.contourf(zz / natconst.pc, xx / natconst.pc,
                 (data.rhodust[0, :, :, 0]), 290)
#plb.xlabel('r [au]')
#plb.axis([-500000, 500000, -250000, 250000])
#plb.ylabel(r' [au]')
#plb.xscale('log')
#plb.yscale('log')
cb = plb.colorbar(c)
cb.set_label(r'$\log_{10}{\rho}$', rotation=270.)

# View a 2-D slice of the 3-D array of the setup
#
#fig2 = plt.figure()
#q = analyze.readGrid(sgrid = True)
#v = analyze.readData(ddens=True,  binary=False)
#ax   = fig2.add_subplot(111, projection='3d')
#ax.plot_wireframe((y1), (x1), (v), rstride=1, cstride=1)
lr_b = 0
lr_w = 0
# Iterations
for i in range(iteration):

    b_grad = 0.0
    w_grad = 0.0
    for n in range(len(x_data)):
        b_grad = b_grad - 2.0 * (y_data[n] - b - w * x_data[n]) * 1.0
        w_grad = w_grad - 2.0 * (y_data[n] - b - w * x_data[n]) * x_data[n]

    lr_b = lr_b + b_grad**2
    lr_w = lr_w + w_grad**2

    # Update parameters
    b = b - lr / np.sqrt(lr_b) * b_grad
    w = w - lr / np.sqrt(lr_w) * w_grad

    # Store parameters for plotting
    b_history.append(b)
    w_history.append(w)

#plot the figure
plt.contourf(x, y, z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))
plt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange')
plt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')
plt.xlim(-200, -100)
plt.ylim(-5, 5)
plt.xlabel(r'$b$', fontsize=16)
plt.ylabel(r'$w$', fontsize=16)
plt.show()
Beispiel #12
0
def create_figure_surface(figid, aspect, xx, yy, cmin, cmax, levels, slices, v3d):
    ''' creates a plot of the surface of a tracer data
    Parameters
    ----------
    figid : int  
            id of figure
    aspect: float
            aspect ratio of figure
    xx    : array 
            scale of x axis
    yy    : array 
            scale of y axis     
    cmin,cmax : array
                minimum and maxminm of the color range
    levels : array
            range of contourlines
    slices : array
            location of slices
    v3d    : vector data in geometry format
    Returns
    -------
    plot :  of surface data
    '''
    # prepare matplotlib
    import matplotlib
    matplotlib.rc("font",**{"family":"sans-serif"})
    matplotlib.rc("text", usetex=True)
    #matplotlib.use("PDF")
    import matplotlib.pyplot as plt
    # basemap
    from mpl_toolkits.basemap import Basemap
    # numpy
    import numpy as np

    # data
    vv = v3d[0,:,:,0]
    # shift
    vv = np.roll(vv, 64, axis=1)

    # plot surface
    plt.figure(figid)
    # colormap
    cmap = plt.cm.bone_r
    # contour fill
    p1 = plt.contourf(xx, yy, vv, cmap=cmap, levels=levels, origin="lower")#, hold="on")
    plt.clim(cmin, cmax)
    # contour lines
    p2 = plt.contour(xx, yy, vv, levels=levels, linewidths = (1,), colors="k")#, hold="on")
    plt.clabel(p2, fmt = "%2.1f", colors = "k", fontsize = 14)
    #plt.colorbar(p2,shrink=0.8, extend='both')
    # slices
    #s1 = xx[np.mod(slices[0]+64, 128)]
    #s2 = xx[np.mod(slices[1]+64, 128)]
    #s3 = xx[np.mod(slices[2]+64, 128)]
#    print s1, s2, s3
    #plt.vlines([s1, s2, s3], -90, 90, color='k', linestyles='--')
    # set aspect ratio of axes
    plt.gca().set_aspect(aspect)

    # basemap
    m = Basemap(projection="cyl")
    m.drawcoastlines(linewidth = 0.5)

    # xticks
    plt.xticks(range(-180, 181, 45), range(-180, 181, 45))
    plt.xlim([-180, 180])
    plt.xlabel("Longitude [degrees]", labelpad=8)
    # yticks
    plt.yticks(range(-90, 91, 30), range(-90, 91, 30))
    plt.ylim([-90, 90])
    plt.ylabel("Latitude [degrees]")


    # write to file
    plt.savefig("solution-surface", bbox_inches="tight")
    plt.show()
Beispiel #13
0
def Plot2DBoundary(DTrain, LTrain, DTest, LTest):
    # The dots are training samples (img not drawn), and the pics are testing samples (images drawn)
    # Play around with the K values. This is very controlled dataset so it should be able to get perfect classification on testing entries
    # Play with the K for isomap, play with the K for neighbors.

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title('Transformed Boundary, Image Space -> 2D')

    padding = 0.1  # Zoom out
    resolution = 1  # Don't get too detailed; smaller values (finer rez) will take longer to compute
    colors = ['blue', 'green', 'orange', 'red']

    # ------

    # Calculate the boundaries of the mesh grid. The mesh grid is
    # a standard grid (think graph paper), where each point will be
    # sent to the classifier (KNeighbors) to predict what class it
    # belongs to. This is why KNeighbors has to be trained against
    # 2D data, so we can produce this countour. Once we have the
    # label for each point on the grid, we can color it appropriately
    # and plot it.
    x_min, x_max = DTrain[:, 0].min(), DTrain[:, 0].max()
    y_min, y_max = DTrain[:, 1].min(), DTrain[:, 1].max()
    x_range = x_max - x_min
    y_range = y_max - y_min
    x_min -= x_range * padding
    y_min -= y_range * padding
    x_max += x_range * padding
    y_max += y_range * padding

    # Using the boundaries, actually make the 2D Grid Matrix:
    xx, yy = np.meshgrid(np.arange(x_min, x_max, resolution),
                         np.arange(y_min, y_max, resolution))

    # What class does the classifier say about each spot on the chart?
    # The values stored in the matrix are the predictions of the model
    # at said location:
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    # Plot the mesh grid as a filled contour plot:
    plt.contourf(xx, yy, Z, cmap=plt.cm.terrain, z=-100)

    # ------

    # When plotting the testing images, used to validate if the algorithm
    # is functioning correctly, size them as 5% of the overall chart size
    x_size = x_range * 0.05
    y_size = y_range * 0.05

    # First, plot the images in your TEST dataset
    img_num = 0
    for index in LTest.index:
        # DTest is a regular NDArray, so you'll iterate over that 1 at a time.
        x0, y0 = DTest[img_num, 0] - x_size / 2., DTest[img_num,
                                                        1] - y_size / 2.
        x1, y1 = DTest[img_num, 0] + x_size / 2., DTest[img_num,
                                                        1] + y_size / 2.

        # DTest = our images isomap-transformed into 2D. But we still want
        # to plot the original image, so we look to the original, untouched
        # dataset (at index) to get the pixels:
        img = df.iloc[index, :].reshape(num_pixels, num_pixels)
        ax.imshow(img,
                  aspect='auto',
                  cmap=plt.cm.gray,
                  interpolation='nearest',
                  zorder=100000,
                  extent=(x0, x1, y0, y1),
                  alpha=0.8)
        img_num += 1

    # Plot your TRAINING points as well... as points rather than as images
    for label in range(len(np.unique(LTrain))):
        indices = np.where(LTrain == label)
        ax.scatter(DTrain[indices, 0],
                   DTrain[indices, 1],
                   c=colors[label],
                   alpha=0.8,
                   marker='o')

    # Plot
    plt.show()
Beispiel #14
0
# Creating boundary on Gaussian NB
import numpy as np
import matplotlib as plt
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1],
              [3, 2]])  #collection of features
Y = np.array([1, 1, 1, 2, 2,
              2])  #class or label to which feature belongs to (responses)
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()  #instance of Gaussian NB model
clf.fit(X, Y)  #training of model
x = [-1, -2, -3, 1, 2, 3]
y = [-1, -1, -2, 1, 1, 2]
h = .02

#create a mesh to plot in
x_min = X[:, 0].min() - 1
x_max = X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm)
plt.show()