def GenerateGridCoordinates(self,Scanning_Direction_Mode,List_of_X_Points, List_of_Y_Points): ''' This function generate a grid of coordinates using SynaptiQs inputs ''' self.Scanning_Direction_Mode = Scanning_Direction_Mode if Scanning_Direction_Mode == 'X': Y, X = numpy.meshgrid(List_of_Y_Points, List_of_X_Points) elif Scanning_Direction_Mode == 'Y': X, Y = numpy.meshgrid(List_of_X_Points, List_of_Y_Points) self.Number_of_Turns= int(float(Mapping.Number_of_Turns.text())) self.Sorted_X_Coordinates=list(X.flatten()) self.Sorted_Y_Coordinates=list(Y.flatten()) self.Sorted_X_Coordinates_Full=self.Sorted_X_Coordinates*self.Number_of_Turns self.Sorted_Y_Coordinates_Full=self.Sorted_Y_Coordinates*self.Number_of_Turns self.Sorted_X_and_Y_Coordinates=zip(self.Sorted_X_Coordinates,self.Sorted_Y_Coordinates) self.Sorted_X_and_Y_Coordinates_Full=self.Sorted_X_and_Y_Coordinates*self.Number_of_Turns
def plotIsoFreqNStipper(ax,freq,array,flag,par='abs',colorbar=True,colorNorm='SymLog',cLevel=True,contour=True): indUniFreq = np.where(freq==array['freq']) x, y = array['x'][indUniFreq],array['y'][indUniFreq] if par == 'abs': cmap = plt.get_cmap('OrRd_r')#seismic') zPlot = np.abs(array[flag][indUniFreq]) if cLevel: level = np.logspace(-4,0,33) clevel = np.logspace(-4,0,5) else: level = np.linspace(zPlot.min(),zPlot.max(),100) clevel = np.linspace(zPlot.min(),zPlot.max(),10) if colorNorm=='SymLog': plotNorm = colors.LogNorm() else: plotNorm = colors.Normalize() elif par == 'real': cmap = plt.get_cmap('RdYlBu') zPlot = np.real(array[flag][indUniFreq]) if cLevel: level = np.concatenate((-np.logspace(0,-4,33),np.logspace(-4,0,33))) clevel = np.concatenate((-np.logspace(0,-4,5),np.logspace(-4,0,5))) else: level = np.linspace(zPlot.min(),zPlot.max(),100) clevel = np.linspace(zPlot.min(),zPlot.max(),10) if colorNorm=='SymLog': plotNorm = colors.SymLogNorm(1e-4,linscale=2) else: plotNorm = colors.Normalize() elif par == 'imag': cmap = plt.get_cmap('RdYlBu') zPlot = np.imag(array[flag][indUniFreq]) if cLevel: level = np.concatenate((-np.logspace(0,-4,33),np.logspace(-4,0,33))) clevel = np.concatenate((-np.logspace(0,-4,5),np.logspace(-4,0,5))) else: level = np.linspace(zPlot.min(),zPlot.max(),100) clevel = np.linspace(zPlot.min(),zPlot.max(),10) if colorNorm=='SymLog': plotNorm = colors.SymLogNorm(1e-4,linscale=2) else: plotNorm = colors.Normalize() if contour: cs = ax.tricontourf(x,y,zPlot,levels=level,cmap=cmap,norm=plotNorm)#,extend='both') else: uniX,uniY = np.unique(x),np.unique(y) X,Y = np.meshgrid(np.append(uniX-25,uniX[-1]+25),np.append(uniY-25,uniY[-1]+25)) cs = ax.pcolor(X,Y,np.reshape(zPlot,(len(uniY),len(uniX))),levels=level,cmap=cmap,norm=plotNorm,edgecolors='k', linewidths=0.5) if colorbar: plt.colorbar(cs,cax=ax.cax,ticks=clevel,format='%1.2e') ax.set_title(flag+' '+par,fontsize=8)
def plotIsoFreqNSimpedance( ax, freq, array, flag, par="abs", colorbar=True, colorNorm="SymLog", cLevel=True, contour=True, ): indUniFreq = np.where(freq == array["freq"]) x, y = array["x"][indUniFreq], array["y"][indUniFreq] if par == "abs": zPlot = np.abs(array[flag][indUniFreq]) cmap = plt.get_cmap("OrRd_r") # seismic') level = np.logspace(0, -5, 31) clevel = np.logspace(0, -4, 5) plotNorm = colors.LogNorm() elif par == "real": zPlot = np.real(array[flag][indUniFreq]) cmap = plt.get_cmap("RdYlBu") if cLevel: level = np.concatenate( (-np.logspace(0, -10, 31), np.logspace(-10, 0, 31))) clevel = np.concatenate( (-np.logspace(0, -8, 5), np.logspace(-8, 0, 5))) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) if colorNorm == "SymLog": plotNorm = colors.SymLogNorm(1e-10, linscale=2) else: plotNorm = colors.Normalize() elif par == "imag": zPlot = np.imag(array[flag][indUniFreq]) cmap = plt.get_cmap("RdYlBu") level = np.concatenate( (-np.logspace(0, -10, 31), np.logspace(-10, 0, 31))) clevel = np.concatenate((-np.logspace(0, -8, 5), np.logspace(-8, 0, 5))) plotNorm = colors.SymLogNorm(1e-10, linscale=2) if cLevel: level = np.concatenate( (-np.logspace(0, -10, 31), np.logspace(-10, 0, 31))) clevel = np.concatenate( (-np.logspace(0, -8, 5), np.logspace(-8, 0, 5))) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) if colorNorm == "SymLog": plotNorm = colors.SymLogNorm(1e-10, linscale=2) elif colorNorm == "Lin": plotNorm = colors.Normalize() if contour: cs = ax.tricontourf(x, y, zPlot, levels=level, cmap=cmap, norm=plotNorm) # ,extend='both') else: uniX, uniY = np.unique(x), np.unique(y) X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25), np.append(uniY - 25, uniY[-1] + 25)) cs = ax.pcolor(X, Y, np.reshape(zPlot, (len(uniY), len(uniX))), cmap=cmap, norm=plotNorm) if colorbar: plt.colorbar(cs, cax=ax.cax, ticks=clevel, format="%1.2e") ax.set_title(flag + " " + par, fontsize=8) return cs
def plotPsudoSectNSDiff( ax, sectDict, arrayList, flag, par="abs", colorbar=True, colorNorm="SymLog", cLevel=None, contour=True, mask=None, useLog=False, ): def sortInArr(arr): return np.sort(arr, order=["freq", "x", "y", "z"]) # Find the index for the slice indSect0 = np.where( sectDict.values()[0] == arrayList[0][sectDict.keys()[0]]) indSect1 = np.where( sectDict.values()[0] == arrayList[1][sectDict.keys()[0]]) # Extract and sort the mats arr0 = sortInArr(arrayList[0][indSect0]) arr1 = sortInArr(arrayList[1][indSect1]) # Define the plot axes if "x" in sectDict.keys()[0]: x0 = arr0["y"] x1 = arr1["y"] else: x0 = arr0["x"] x1 = arr1["x"] y0 = arr0["freq"] y1 = arr1["freq"] if par == "abs": if useLog: zPlot = (np.log10(np.abs(arr0[flag])) - np.log10(np.abs( arr1[flag]))) / np.log10(np.abs(arr1[flag])) else: zPlot = (np.abs(arr0[flag]) - np.abs(arr1[flag])) / np.abs( arr1[flag]) if mask: maskInd = np.logical_or( np.abs(arr0[flag]) < 1e-3, np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap("RdYlBu") # seismic) elif par == "ares": arF = 1 / (8 * np.pi**2 * 10**(-7)) if useLog: zPlot = (np.log10( (arF / arr0["freq"]) * np.abs(arr0[flag])**2) - np.log10( (arF / arr1["freq"]) * np.abs(arr1[flag])**2)) / np.log10( (arF / arr1["freq"]) * np.abs(arr1[flag])**2) else: zPlot = ((arF / arr0["freq"]) * np.abs(arr0[flag])**2 - (arF / arr1["freq"]) * np.abs(arr1[flag])**2) / ( (arF / arr1["freq"]) * np.abs(arr1[flag])**2) if mask: maskInd = np.logical_or( np.abs(arr0[flag]) < 1e-3, np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap("Spectral") # seismic) elif par == "aphs": if useLog: zPlot = (np.log10( np.arctan2(arr0[flag].imag, arr0[flag].real) * (180 / np.pi)) - np.log10( np.arctan2(arr1[flag].imag, arr1[flag].real) * (180 / np.pi))) / np.log10( np.arctan2(arr1[flag].imag, arr1[flag].real) * (180 / np.pi)) else: zPlot = (np.arctan2(arr0[flag].imag, arr0[flag].real) * (180 / np.pi) - np.arctan2(arr1[flag].imag, arr1[flag].real) * (180 / np.pi)) / ( np.arctan2(arr1[flag].imag, arr1[flag].real) * (180 / np.pi)) if mask: maskInd = np.logical_or( np.abs(arr0[flag]) < 1e-3, np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap("Spectral") # seismic) elif par == "real": if useLog: zPlot = (np.log10(arr0[flag].real) - np.log10(arr1[flag].real)) / np.log10(arr1[flag].real) else: zPlot = (arr0[flag].real - arr1[flag].real) / arr1[flag].real if mask: maskInd = np.logical_or(arr0[flag].real < 1e-3, arr1[flag].real < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap("Spectral") # ('Spectral') elif par == "imag": if useLog: zPlot = (np.log10(arr0[flag].imag) - np.log10(arr1[flag].imag)) / np.log10(arr1[flag].imag) else: zPlot = (arr0[flag].imag - arr1[flag].imag) / arr1[flag].imag if mask: maskInd = np.logical_or(arr0[flag].imag < 1e-3, arr1[flag].imag < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap("Spectral") # ('RdYlBu') if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = np.ceil(np.log10(np.abs(zPlot).max())) zMin = np.floor(np.log10(np.abs(zPlot).min())) if colorNorm == "SymLog": level = np.concatenate(( -np.logspace( zMax, zMin - 0.125, (zMax - zMin) * 8 + 1, endpoint=True), np.logspace(zMin - 0.125, zMax, (zMax - zMin) * 8 + 1, endpoint=True), )) clevel = np.concatenate(( -np.logspace(zMax, zMin, (zMax - zMin) * 1 + 1, endpoint=True), np.logspace(zMin, zMax, (zMax - zMin) * 1 + 1, endpoint=True), )) plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1) elif colorNorm == "Lin": if cLevel: level = np.arange(cLevel[0], cLevel[1] + 0.1, (cLevel[1] - cLevel[0]) / 50.0) clevel = np.arange(cLevel[0], cLevel[1] + 0.1, (cLevel[1] - cLevel[0]) / 10.0) else: level = np.arange(zPlot.min(), zPlot.max(), (zPlot.max() - zPlot.min()) / 50.0) clevel = np.arange(zPlot.min(), zPlot.max(), (zPlot.max() - zPlot.min()) / 10.0) plotNorm = colors.Normalize() elif colorNorm == "Log": level = np.logspace(zMin - 0.125, zMax, (zMax - zMin) * 8 + 1, endpoint=True) clevel = np.logspace(zMin, zMax, (zMax - zMin) * 2 + 1, endpoint=True) plotNorm = colors.LogNorm() if contour: cs = ax.tricontourf( x0, y0, zPlot * 100, levels=level * 100, cmap=cmap, norm=plotNorm, extend="both", ) # ,extend='both') else: uniX, uniY = np.unique(x0), np.unique(y0) X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25), np.append(uniY - 25, uniY[-1] + 25)) cs = ax.pcolor(X, Y, np.reshape(zPlot, (len(uniY), len(uniX))), cmap=cmap, norm=plotNorm) if colorbar: csB = plt.colorbar(cs, cax=ax.cax, ticks=clevel * 100, format="%1.2e") # csB.on_mappable_changed(cs) ax.set_title(flag + " " + par + " diff", fontsize=8) return cs, csB return cs, None
def plotPsudoSectNSimpedance( ax, sectDict, array, flag, par="abs", colorbar=True, colorNorm="None", cLevel=None, contour=True, ): indSect = np.where(sectDict.values()[0] == array[sectDict.keys()[0]]) # Define the plot axes if "x" in sectDict.keys()[0]: x = array["y"][indSect] else: x = array["x"][indSect] y = array["freq"][indSect] if par == "abs": zPlot = np.abs(array[flag][indSect]) cmap = plt.get_cmap("OrRd_r") # seismic') if cLevel: level = np.logspace(0, -5, 31, endpoint=True) clevel = np.logspace(0, -4, 5, endpoint=True) else: level = np.linspace(zPlot.min(), zPlot.max(), 100, endpoint=True) clevel = np.linspace(zPlot.min(), zPlot.max(), 10, endpoint=True) elif par == "ares": zPlot = np.abs(array[flag][indSect])**2 / (8 * np.pi**2 * 10**(-7) * array["freq"][indSect]) cmap = plt.get_cmap("RdYlBu") # seismic) if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = np.ceil(np.log10(np.abs(zPlot).max())) zMin = np.floor(np.log10(np.abs(zPlot).min())) level = np.logspace(zMin, zMax, (zMax - zMin) * 8 + 1, endpoint=True) clevel = np.logspace(zMin, zMax, (zMax - zMin) * 2 + 1, endpoint=True) plotNorm = colors.LogNorm() elif par == "aphs": zPlot = np.arctan2(array[flag][indSect].imag, array[flag][indSect].real) * (180 / np.pi) cmap = plt.get_cmap("RdYlBu") # seismic) if cLevel: zMax = cLevel[1] zMin = cLevel[0] else: zMax = np.ceil(zPlot).max() zMin = np.floor(zPlot).min() level = np.arange(zMin, zMax + 0.1, 1) clevel = np.arange(zMin, zMax + 0.1, 10) plotNorm = colors.Normalize() elif par == "real": zPlot = np.real(array[flag][indSect]) cmap = plt.get_cmap("Spectral") # ('RdYlBu') if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = np.ceil(np.log10(np.abs(zPlot).max())) zMin = np.floor(np.log10(np.abs(zPlot).min())) level = np.concatenate(( -np.logspace( zMax, zMin - 0.125, (zMax - zMin) * 8 + 1, endpoint=True), np.logspace(zMin - 0.125, zMax, (zMax - zMin) * 8 + 1, endpoint=True), )) clevel = np.concatenate(( -np.logspace(zMax, zMin, (zMax - zMin) * 1 + 1, endpoint=True), np.logspace(zMin, zMax, (zMax - zMin) * 1 + 1, endpoint=True), )) plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1) elif par == "imag": zPlot = np.imag(array[flag][indSect]) cmap = plt.get_cmap("Spectral") # ('RdYlBu') if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = np.ceil(np.log10(np.abs(zPlot).max())) zMin = np.floor(np.log10(np.abs(zPlot).min())) level = np.concatenate(( -np.logspace( zMax, zMin - 0.125, (zMax - zMin) * 8 + 1, endpoint=True), np.logspace(zMin - 0.125, zMax, (zMax - zMin) * 8 + 1, endpoint=True), )) clevel = np.concatenate(( -np.logspace(zMax, zMin, (zMax - zMin) * 1 + 1, endpoint=True), np.logspace(zMin, zMax, (zMax - zMin) * 1 + 1, endpoint=True), )) plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1) if colorNorm == "SymLog": plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1) elif colorNorm == "Lin": plotNorm = colors.Normalize() elif colorNorm == "Log": plotNorm = colors.LogNorm() if contour: cs = ax.tricontourf(x, y, zPlot, levels=level, cmap=cmap, norm=plotNorm) # ,extend='both') else: uniX, uniY = np.unique(x), np.unique(y) X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25), np.append(uniY - 25, uniY[-1] + 25)) cs = ax.pcolor(X, Y, np.reshape(zPlot, (len(uniY), len(uniX))), cmap=cmap, norm=plotNorm) if colorbar: csB = plt.colorbar(cs, cax=ax.cax, ticks=clevel, format="%1.2e") # csB.on_mappable_changed(cs) ax.set_title(flag + " " + par, fontsize=8) return cs, csB return cs, None
def cannyEdgeDetectorFilter(self, img, sigma=1, t_low=0.01, t_high=0.2): im = img.convert('L') img = np.array(im, dtype=float) # 1) Convolve gaussian kernel with gradient # gaussian kernel halfSize = 3 * sigma maskSize = 2 * halfSize + 1 mat = np.ones((maskSize, maskSize)) / (float)(2 * np.pi * (sigma**2)) xyRange = np.arange(-halfSize, halfSize + 1) xx, yy = np.meshgrid(xyRange, xyRange) x2y2 = (xx**2 + yy**2) exp_part = np.exp(-(x2y2 / (2.0 * (sigma**2)))) gSig = mat * exp_part gx, gy = self.drogEdgeDetectorFilter(gSig, ret_grad=True, pillow=False) # 2) Magnitude and Angles # apply kernels for Ix & Iy Ix = cv2.filter2D(img, -1, gx) Iy = cv2.filter2D(img, -1, gy) # compute magnitude mag = np.sqrt(Ix**2 + Iy**2) # normalize magnitude image normMag = my_Normalize(mag) # compute orientation of gradient orient = np.arctan2(Iy, Ix) # round elements of orient orientRows = orient.shape[0] orientCols = orient.shape[1] # 3) Non maximum suppression for i in range(0, orientRows): for j in range(0, orientCols): if normMag[i, j] > t_low: # case 0 if (orient[i, j] > (-np.pi / 8) and orient[i, j] <= (np.pi / 8)): orient[i, j] = 0 elif (orient[i, j] > (7 * np.pi / 8) and orient[i, j] <= np.pi): orient[i, j] = 0 elif (orient[i, j] >= -np.pi and orient[i, j] < (-7 * np.pi / 8)): orient[i, j] = 0 # case 1 elif (orient[i, j] > (np.pi / 8) and orient[i, j] <= (3 * np.pi / 8)): orient[i, j] = 3 elif (orient[i, j] >= (-7 * np.pi / 8) and orient[i, j] < (-5 * np.pi / 8)): orient[i, j] = 3 # case 2 elif (orient[i, j] > (3 * np.pi / 8) and orient[i, j] <= (5 * np.pi / 8)): orient[i, j] = 2 elif (orient[i, j] >= (-5 * np.pi / 4) and orient[i, j] < (-3 * np.pi / 8)): orient[i, j] = 2 # case 3 elif (orient[i, j] > (5 * np.pi / 8) and orient[i, j] <= (7 * np.pi / 8)): orient[i, j] = 1 elif (orient[i, j] >= (-3 * np.pi / 8) and orient[i, j] < (-np.pi / 8)): orient[i, j] = 1 mag = normMag mag_thin = np.zeros(mag.shape) for i in range(mag.shape[0] - 1): for j in range(mag.shape[1] - 1): if mag[i][j] < t_low: continue if orient[i][j] == 0: if mag[i][j] > mag[i][j - 1] and mag[i][j] >= mag[i][j + 1]: mag_thin[i][j] = mag[i][j] if orient[i][j] == 1: if mag[i][j] > mag[i - 1][j + 1] and mag[i][j] >= mag[ i + 1][j - 1]: mag_thin[i][j] = mag[i][j] if orient[i][j] == 2: if mag[i][j] > mag[i - 1][j] and mag[i][j] >= mag[i + 1][j]: mag_thin[i][j] = mag[i][j] if orient[i][j] == 3: if mag[i][j] > mag[i - 1][j - 1] and mag[i][j] >= mag[ i + 1][j + 1]: mag_thin[i][j] = mag[i][j] # 4) Thresholding and edge linking result_binary = np.zeros(mag_thin.shape) tHigh = t_high tLow = t_low # forward scan for i in range(0, mag_thin.shape[0] - 1): # rows for j in range(0, mag_thin.shape[1] - 1): # columns if mag_thin[i][j] >= tHigh: if mag_thin[i][j + 1] >= tLow: # right mag_thin[i][j + 1] = tHigh if mag_thin[i + 1][j + 1] >= tLow: # bottom right mag_thin[i + 1][j + 1] = tHigh if mag_thin[i + 1][j] >= tLow: # bottom mag_thin[i + 1][j] = tHigh if mag_thin[i + 1][j - 1] >= tLow: # bottom left mag_thin[i + 1][j - 1] = tHigh # backwards scan for i in range(mag_thin.shape[0] - 2, 0, -1): # rows for j in range(mag_thin.shape[1] - 2, 0, -1): # columns if mag_thin[i][j] >= tHigh: if mag_thin[i][j - 1] > tLow: # left mag_thin[i][j - 1] = tHigh if mag_thin[i - 1][j - 1]: # top left mag_thin[i - 1][j - 1] = tHigh if mag_thin[i - 1][j] > tLow: # top mag_thin[i - 1][j] = tHigh if mag_thin[i - 1][j + 1] > tLow: # top right mag_thin[i - 1][j + 1] = tHigh # fill in result_binary for i in range(0, mag_thin.shape[0] - 1): # rows for j in range(0, mag_thin.shape[1] - 1): # columns if mag_thin[i][j] >= tHigh: result_binary[i][j] = 255 # set to 255 for >= tHigh img = Image.fromarray(result_binary) return img
def rotate(self, img, angle, fill=0, resize=True): # Images have origin at the top left, so negate the angle. theta = angle * np.pi / 180 # Dimensions of source image. Note that scipy.misc.imread loads # images in row-major order, so src.shape gives (height, width). img = img.convert('RGB') src = np.array(img) red = src[:, :, 0] green = src[:, :, 1] blue = src[:, :, 2] sh, sw = src.shape[0], src.shape[1] ox, oy = sh / 2, sw / 2 # Rotated positions of the corners of the source image. cx, cy = self.rotate_coords([0, sw, sw, 0], [0, 0, sh, sh], theta, ox, oy) # Determine dimensions of destination image. dw, dh = (int(np.ceil(c.max() - c.min())) for c in (cx, cy)) # Coordinates of pixels in destination image. dx, dy = np.meshgrid(np.arange(dw), np.arange(dh)) # Corresponding coordinates in source image. Since we are # transforming dest-to-src here, the rotation is negated. sx, sy = self.rotate_coords(dx + cx.min(), dy + cy.min(), -theta, ox, oy) # Select nearest neighbour. sx, sy = sx.round().astype(int), sy.round().astype(int) # Mask for valid coordinates. mask = (0 <= sx) & (sx < sw) & (0 <= sy) & (sy < sh) # Create destination image. red_dest = np.empty(shape=(dh, dw), dtype=src.dtype) green_dest = np.empty(shape=(dh, dw), dtype=src.dtype) blue_dest = np.empty(shape=(dh, dw), dtype=src.dtype) # Copy valid coordinates from source image. red_dest[dy[mask], dx[mask]] = red[sy[mask], sx[mask]] green_dest[dy[mask], dx[mask]] = green[sy[mask], sx[mask]] blue_dest[dy[mask], dx[mask]] = blue[sy[mask], sx[mask]] # Fill invalid coordinates. red_dest[dy[~mask], dx[~mask]] = fill green_dest[dy[~mask], dx[~mask]] = fill blue_dest[dy[~mask], dx[~mask]] = fill src = np.resize(src, (dh, dw, 3)) src[:, :, 0] = red_dest src[:, :, 1] = green_dest src[:, :, 2] = blue_dest if not resize: new_src = np.array(img) new_src = imutils.rotate(new_src, angle) img = Image.fromarray(new_src.astype('uint8')) else: img = Image.fromarray(src.astype('uint8')) return img
def plotIsoFreqNStipper(ax, freq, array, flag, par='abs', colorbar=True, colorNorm='SymLog', cLevel=True, contour=True): indUniFreq = np.where(freq == array['freq']) x, y = array['x'][indUniFreq], array['y'][indUniFreq] if par == 'abs': cmap = plt.get_cmap('OrRd_r') #seismic') zPlot = np.abs(array[flag][indUniFreq]) if cLevel: level = np.logspace(-4, 0, 33) clevel = np.logspace(-4, 0, 5) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) if colorNorm == 'SymLog': plotNorm = colors.LogNorm() else: plotNorm = colors.Normalize() elif par == 'real': cmap = plt.get_cmap('RdYlBu') zPlot = np.real(array[flag][indUniFreq]) if cLevel: level = np.concatenate( (-np.logspace(0, -4, 33), np.logspace(-4, 0, 33))) clevel = np.concatenate( (-np.logspace(0, -4, 5), np.logspace(-4, 0, 5))) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) if colorNorm == 'SymLog': plotNorm = colors.SymLogNorm(1e-4, linscale=2) else: plotNorm = colors.Normalize() elif par == 'imag': cmap = plt.get_cmap('RdYlBu') zPlot = np.imag(array[flag][indUniFreq]) if cLevel: level = np.concatenate( (-np.logspace(0, -4, 33), np.logspace(-4, 0, 33))) clevel = np.concatenate( (-np.logspace(0, -4, 5), np.logspace(-4, 0, 5))) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) if colorNorm == 'SymLog': plotNorm = colors.SymLogNorm(1e-4, linscale=2) else: plotNorm = colors.Normalize() if contour: cs = ax.tricontourf(x, y, zPlot, levels=level, cmap=cmap, norm=plotNorm) #,extend='both') else: uniX, uniY = np.unique(x), np.unique(y) X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25), np.append(uniY - 25, uniY[-1] + 25)) cs = ax.pcolor(X, Y, np.reshape(zPlot, (len(uniY), len(uniX))), levels=level, cmap=cmap, norm=plotNorm, edgecolors='k', linewidths=0.5) if colorbar: plt.colorbar(cs, cax=ax.cax, ticks=clevel, format='%1.2e') ax.set_title(flag + ' ' + par, fontsize=8)
def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,colorNorm='SymLog',cLevel=None,contour=True,mask=None,useLog=False): def sortInArr(arr): return np.sort(arr,order=['freq','x','y','z']) # Find the index for the slice indSect0 = np.where(sectDict.values()[0]==arrayList[0][sectDict.keys()[0]]) indSect1 = np.where(sectDict.values()[0]==arrayList[1][sectDict.keys()[0]]) # Extract and sort the mats arr0 = sortInArr(arrayList[0][indSect0]) arr1 = sortInArr(arrayList[1][indSect1]) # Define the plot axes if 'x' in sectDict.keys()[0]: x0 = arr0['y'] x1 = arr1['y'] else: x0 = arr0['x'] x1 = arr1['x'] y0 = arr0['freq'] y1 = arr1['freq'] if par == 'abs': if useLog: zPlot = (np.log10(np.abs(arr0[flag])) - np.log10(np.abs(arr1[flag])))/np.log10(np.abs(arr1[flag])) else: zPlot = (np.abs(arr0[flag]) - np.abs(arr1[flag]))/np.abs(arr1[flag]) if mask: maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap('RdYlBu')#seismic) elif par == 'ares': arF = 1/(8*np.pi**2*10**(-7)) if useLog: zPlot = (np.log10((arF/arr0['freq'])*np.abs(arr0[flag])**2) - np.log10((arF/arr1['freq'])*np.abs(arr1[flag])**2))/np.log10((arF/arr1['freq'])*np.abs(arr1[flag])**2) else: zPlot = ((arF/arr0['freq'])*np.abs(arr0[flag])**2 - (arF/arr1['freq'])*np.abs(arr1[flag])**2)/((arF/arr1['freq'])*np.abs(arr1[flag])**2) if mask: maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap('Spectral')#seismic) elif par == 'aphs': if useLog: zPlot = (np.log10(np.arctan2(arr0[flag].imag,arr0[flag].real)*(180/np.pi)) - np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) )/np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) else: zPlot = ( np.arctan2(arr0[flag].imag,arr0[flag].real)*(180/np.pi) - np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi) )/(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) if mask: maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap('Spectral')#seismic) elif par == 'real': if useLog: zPlot = (np.log10(arr0[flag].real) - np.log10(arr1[flag].real))/np.log10(arr1[flag].real) else: zPlot = (arr0[flag].real - arr1[flag].real)/arr1[flag].real if mask: maskInd = np.logical_or(arr0[flag].real< 1e-3,arr1[flag].real < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap('Spectral') #('Spectral') elif par == 'imag': if useLog: zPlot = (np.log10(arr0[flag].imag) - np.log10(arr1[flag].imag))/np.log10(arr1[flag].imag) else: zPlot = (arr0[flag].imag - arr1[flag].imag)/arr1[flag].imag if mask: maskInd = np.logical_or(arr0[flag].imag< 1e-3,arr1[flag].imag < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap('Spectral') #('RdYlBu') if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = (np.ceil(np.log10(np.abs(zPlot).max()))) zMin = (np.floor(np.log10(np.abs(zPlot).min()))) if colorNorm=='SymLog': level = np.concatenate((-np.logspace(zMax,zMin-.125,(zMax-zMin)*8+1,endpoint=True),np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True))) clevel = np.concatenate((-np.logspace(zMax,zMin,(zMax-zMin)*1+1,endpoint=True),np.logspace(zMin,zMax,(zMax-zMin)*1+1,endpoint=True))) plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1) elif colorNorm=='Lin': if cLevel: level = np.arange(cLevel[0],cLevel[1]+.1,(cLevel[1] - cLevel[0])/50.) clevel = np.arange(cLevel[0],cLevel[1]+.1,(cLevel[1] - cLevel[0])/10.) else: level = np.arange(zPlot.min(),zPlot.max(),(zPlot.max() - zPlot.min())/50.) clevel = np.arange(zPlot.min(),zPlot.max(),(zPlot.max() - zPlot.min())/10.) plotNorm = colors.Normalize() elif colorNorm=='Log': level = np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True) clevel = np.logspace(zMin,zMax,(zMax-zMin)*2+1,endpoint=True) plotNorm = colors.LogNorm() if contour: cs = ax.tricontourf(x0,y0,zPlot*100,levels=level*100,cmap=cmap,norm=plotNorm,extend='both')#,extend='both') else: uniX,uniY = np.unique(x0),np.unique(y0) X,Y = np.meshgrid(np.append(uniX-25,uniX[-1]+25),np.append(uniY-25,uniY[-1]+25)) cs = ax.pcolor(X,Y,np.reshape(zPlot,(len(uniY),len(uniX))),cmap=cmap,norm=plotNorm) if colorbar: csB = plt.colorbar(cs,cax=ax.cax,ticks=clevel*100,format='%1.2e') # csB.on_mappable_changed(cs) ax.set_title(flag+' '+par + ' diff',fontsize=8) return cs, csB return cs,None
def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colorNorm='None',cLevel=None,contour=True): indSect = np.where(sectDict.values()[0]==array[sectDict.keys()[0]]) # Define the plot axes if 'x' in sectDict.keys()[0]: x = array['y'][indSect] else: x = array['x'][indSect] y = array['freq'][indSect] if par == 'abs': zPlot = np.abs(array[flag][indSect]) cmap = plt.get_cmap('OrRd_r')#seismic') if cLevel: level = np.logspace(0,-5,31,endpoint=True) clevel = np.logspace(0,-4,5,endpoint=True) else: level = np.linspace(zPlot.min(),zPlot.max(),100,endpoint=True) clevel = np.linspace(zPlot.min(),zPlot.max(),10,endpoint=True) elif par == 'ares': zPlot = np.abs(array[flag][indSect])**2/(8*np.pi**2*10**(-7)*array['freq'][indSect]) cmap = plt.get_cmap('RdYlBu')#seismic) if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = (np.ceil(np.log10(np.abs(zPlot).max()))) zMin = (np.floor(np.log10(np.abs(zPlot).min()))) level = np.logspace(zMin,zMax,(zMax-zMin)*8+1,endpoint=True) clevel = np.logspace(zMin,zMax,(zMax-zMin)*2+1,endpoint=True) plotNorm = colors.LogNorm() elif par == 'aphs': zPlot = np.arctan2(array[flag][indSect].imag,array[flag][indSect].real)*(180/np.pi) cmap = plt.get_cmap('RdYlBu')#seismic) if cLevel: zMax = cLevel[1] zMin = cLevel[0] else: zMax = (np.ceil(zPlot).max()) zMin = (np.floor(zPlot).min()) level = np.arange(zMin,zMax+.1,1) clevel = np.arange(zMin,zMax+.1,10) plotNorm = colors.Normalize() elif par == 'real': zPlot = np.real(array[flag][indSect]) cmap = plt.get_cmap('Spectral') #('RdYlBu') if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = (np.ceil(np.log10(np.abs(zPlot).max()))) zMin = (np.floor(np.log10(np.abs(zPlot).min()))) level = np.concatenate((-np.logspace(zMax,zMin-.125,(zMax-zMin)*8+1,endpoint=True),np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True))) clevel = np.concatenate((-np.logspace(zMax,zMin,(zMax-zMin)*1+1,endpoint=True),np.logspace(zMin,zMax,(zMax-zMin)*1+1,endpoint=True))) plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1) elif par == 'imag': zPlot = np.imag(array[flag][indSect]) cmap = plt.get_cmap('Spectral') #('RdYlBu') if cLevel: zMax = np.log10(cLevel[1]) zMin = np.log10(cLevel[0]) else: zMax = (np.ceil(np.log10(np.abs(zPlot).max()))) zMin = (np.floor(np.log10(np.abs(zPlot).min()))) level = np.concatenate((-np.logspace(zMax,zMin-.125,(zMax-zMin)*8+1,endpoint=True),np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True))) clevel = np.concatenate((-np.logspace(zMax,zMin,(zMax-zMin)*1+1,endpoint=True),np.logspace(zMin,zMax,(zMax-zMin)*1+1,endpoint=True))) plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1) if colorNorm=='SymLog': plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1) elif colorNorm=='Lin': plotNorm = colors.Normalize() elif colorNorm=='Log': plotNorm = colors.LogNorm() if contour: cs = ax.tricontourf(x,y,zPlot,levels=level,cmap=cmap,norm=plotNorm)#,extend='both') else: uniX,uniY = np.unique(x),np.unique(y) X,Y = np.meshgrid(np.append(uniX-25,uniX[-1]+25),np.append(uniY-25,uniY[-1]+25)) cs = ax.pcolor(X,Y,np.reshape(zPlot,(len(uniY),len(uniX))),cmap=cmap,norm=plotNorm) if colorbar: csB = plt.colorbar(cs,cax=ax.cax,ticks=clevel,format='%1.2e') # csB.on_mappable_changed(cs) ax.set_title(flag+' '+par,fontsize=8) return cs, csB return cs,None
v.append([0. for i in xrange (len(x))]) for i in xrange (1,len(x)-1): tmp=[0.] for j in range(1,len(y)-1): if i==len(x)/3 and len(y)/3<j<len(y)*2/3: tmp.append(1.) elif i==len(x)*2/3 and len(y)/3<j<len(y)*2/3: tmp.append(-1.) else: tmp.append(0.) tmp.append(0.) v.append(tmp) v.append([0. for i in xrange (len(x))]) while detv>end_detv: update_v() x, y = numpy.meshgrid(x, y) fig = pyplot.figure() ax = fig.gca(projection='3d') ax.set_title(r"Electric potential near two metal plates") ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax.set_zlabel(r'$V$') surf = ax.plot_surface(x, y, v, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) pyplot.show()
tmp = [0.] for j in range(1, len(Y) - 1): if i==len(X)/3 and len(Y)/3<j<len(Y)*2/3: tmp.append(1.) elif i==len(X)*2/3 and len(Y)/3<j<len(Y)*2/3: tmp.append(-1.) else: tmp.append(0.) tmp.append(0.) V.append(tmp) V.append([0. for i in xrange(len(X))]) while detV > end_detV: update_V() X, Y = numpy.meshgrid(X, Y) fig = pyplot.figure() ax = fig.gca(projection='3d') ax.set_title(r"Electric potential near two metal plates") ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax.set_zlabel(r'$V$') surf = ax.plot_surface(X, Y, V, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) pyplot.show()
import scipy.optimize as opt def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset): xo = float(xo) yo = float(yo) a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2) b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2) c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2) g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) + c*((y-yo)**2))) return g.ravel() # Create x and y indices x = np.linspace(0, 200, 201) y = np.linspace(0, 200, 201) x, y = np.meshgrid(x, y) #create data data = twoD_Gaussian((x, y), 3, 100, 100, 20, 40, 0, 10) # plot twoD_Gaussian data generated above plt.figure() plt.imshow(data.reshape(201, 201)) plt.colorbar() # add some noise to the data and try to fit the data generated beforehand initial_guess = (3,100,100,20,40,0,10) data_noisy = data + 0.2*np.random.normal(size=data.shape) popt, pcov = opt.curve_fit(twoD_Gaussian, (x, y), data_noisy, p0=initial_guess)