def barras(sin_repetidas, senders, recievers): senders_hosts = get_host_lista(senders) recievers_hosts = get_host_lista(recievers) todas_hosts = get_host_lista(sin_repetidas) todas_hosts = list(set(todas_hosts)) todas_hosts.sort() cant_ips = len(todas_hosts) count_senders = [senders_hosts.count(ip) for ip in todas_hosts] count_recievers = [recievers_hosts.count(ip) for ip in todas_hosts] fig, ax = plt.subplots() index = np.arange(cant_ips) bar_width = 0.3 opacity = 0.4 rects1 = plt.bar(index, count_senders, bar_width, alpha=opacity, color='b', label='Emisores') rects2 = plt.bar(index + bar_width, count_recievers, bar_width, alpha=opacity, color='g', label='Receptores') plt.xlabel('IPs (ultimos 8 bits)') plt.ylabel('Cantidad de paquetes') plt.xticks(index + bar_width, todas_hosts) plt.legend() plt.tight_layout() plt.show()
def Pre_Fit(self): #Last computation of the data, before fitting Y=eval(str(self.Data_Wave.currentText())) if self.Data_Wave_Axes.currentText() == 'None': X=numpy.arange(len(eval(str(self.Data_Wave.currentText())))) timescale=1. else: X=eval(str(self.Data_Wave_Axes.currentText())) timescale=abs(X[1]-X[0]) Bounds=[] for i in range(10): Bounds.append([self.MinGuess[i],self.MaxGuess[i]]) print 'bounds',Bounds try: self.Fit(Y,X=X,function=str(self.List_of_Functions.currentText()).lower(),Guess=self.param_list,StartX=self.range[0],EndX=self.range[1],Show_Guess=False,Figure=None,Rendering=True,Color='r',Bounds=Bounds) except ValueError: msgBox = QtGui.QMessageBox() msgBox.setText( """ <b>Fitting Error</b> <p>You should try others initial parameters """) msgBox.exec_()
def showwave(self): #将波形数据转换成数组 #需要根据声道数和量化单位,将读取的二进制数据转换为一个可以计算的数组 wave_data = numpy.fromstring(self.wavedata, dtype=numpy.short) wave_data.shape = -1, 2 wave_data = wave_data.T wave_data1 = numpy.fromstring(self.wavedata1, dtype=numpy.short) wave_data1.shape = -1, 2 wave_data1 = wave_data1.T print(self.nframes, len(self.wavedata)) time = numpy.arange(0, self.nframes) * (1.0 / self.RATE) len_time = int(len(time) / 2) * 2 print(len_time) time = time[0:len_time] #绘制波形 pylab.subplot(221) print(len(time), len(wave_data[0])) pylab.plot(time, wave_data[0]) pylab.subplot(222) pylab.plot(time, wave_data[1], c="r") pylab.subplot(223) pylab.plot(time, wave_data1[0]) pylab.subplot(224) pylab.plot(time, wave_data1[1], c="r") pylab.xlabel("time") pylab.show()
def Pre_Fit(self): #Last computation of the data, before fitting Y = eval(str(self.Data_Wave.currentText())) if self.Data_Wave_Axes.currentText() == 'None': X = numpy.arange(len(eval(str(self.Data_Wave.currentText())))) timescale = 1. else: X = eval(str(self.Data_Wave_Axes.currentText())) timescale = abs(X[1] - X[0]) Bounds = [] for i in range(10): Bounds.append([self.MinGuess[i], self.MaxGuess[i]]) print 'bounds', Bounds try: self.Fit(Y, X=X, function=str( self.List_of_Functions.currentText()).lower(), Guess=self.param_list, StartX=self.range[0], EndX=self.range[1], Show_Guess=False, Figure=None, Rendering=True, Color='r', Bounds=Bounds) except ValueError: msgBox = QtGui.QMessageBox() msgBox.setText(""" <b>Fitting Error</b> <p>You should try others initial parameters """) msgBox.exec_()
def idft(row): row = np.asarray(row, dtype=float) N = row.shape[0] n = np.arange(N) k = n.reshape((N, 1)) M = np.exp(2j * np.pi * k * n / N) return np.dot(M, row) / N
def Process(self, Source, Min, Max, N, Size, Destination, Internal=False, Rendering=True): """ display the histogram """ #NaNs must be removed before histogram #Source = Source[~numpy.isnan(Source)] #Making the histogram if Internal == True: self.Show_Hist.canvas.axes.clear() self.n, self.bins, patches = self.Show_Hist.canvas.axes.hist( eval(str(Source)), bins=numpy.arange(Min, Max + Size, Size), facecolor='green', alpha=0.5) self.bin_centres = (self.bins[:-1] + self.bins[1:]) / 2 figure = None self.Show_Hist.canvas.draw() else: figure = pyplot.figure() self.n, self.bins, patches = pyplot.hist(eval(str(Source)), bins=numpy.arange( Min, Max + Size, Size), facecolor='green', alpha=0.5) self.bin_centres = (self.bins[:-1] + self.bins[1:]) / 2 if Rendering == True: pyplot.show() Infos.Add_Array(Arrays=["Histogram.n", "Histogram.bin_centres"]) #setattr(self,Destination,self.n) return self.n, self.bins, self.bin_centres, figure
def plot_SpikeSlab(parameterized, fignum=None, ax=None, colors=None, side_by_side=True): """ Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given create a figure with fignum and plot in there colors: colors of different latent space dimensions input_dim """ if ax is None: if side_by_side: fig = pb.figure(num=fignum, figsize=(16, min(12, (2 * parameterized.mean.shape[1])))) else: fig = pb.figure(num=fignum, figsize=(8, min(12, (2 * parameterized.mean.shape[1])))) if colors is None: from ..Tango import mediumList from itertools import cycle colors = cycle(mediumList) pb.clf() else: colors = iter(colors) plots = [] means, variances, gamma = parameterized.mean, parameterized.variance, parameterized.binary_prob x = np.arange(means.shape[0]) for i in range(means.shape[1]): if side_by_side: sub1 = (means.shape[1],2,2*i+1) sub2 = (means.shape[1],2,2*i+2) else: sub1 = (means.shape[1]*2,1,2*i+1) sub2 = (means.shape[1]*2,1,2*i+2) # mean and variance plot a = fig.add_subplot(*sub1) a.plot(means, c='k', alpha=.3) plots.extend(a.plot(x, means.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i))) a.fill_between(x, means.T[i] - 2 * np.sqrt(variances.T[i]), means.T[i] + 2 * np.sqrt(variances.T[i]), facecolor=plots[-1].get_color(), alpha=.3) a.legend(borderaxespad=0.) a.set_xlim(x.min(), x.max()) if i < means.shape[1] - 1: a.set_xticklabels('') # binary prob plot a = fig.add_subplot(*sub2) a.bar(x,gamma[:,i],bottom=0.,linewidth=1.,width=1.0,align='center') a.set_xlim(x.min(), x.max()) a.set_ylim([0.,1.]) pb.draw() fig.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95)) return fig
def plot_SpikeSlab(parameterized, fignum=None, ax=None, colors=None, side_by_side=True): """ Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given create a figure with fignum and plot in there colors: colors of different latent space dimensions input_dim """ if ax is None: if side_by_side: fig = pb.figure(num=fignum, figsize=(16, min(12, (2 * parameterized.mean.shape[1])))) else: fig = pb.figure(num=fignum, figsize=(8, min(12, (2 * parameterized.mean.shape[1])))) if colors is None: colors = pb.gca()._get_lines.color_cycle pb.clf() else: colors = iter(colors) plots = [] means, variances, gamma = parameterized.mean, parameterized.variance, parameterized.binary_prob x = np.arange(means.shape[0]) for i in range(means.shape[1]): if side_by_side: sub1 = (means.shape[1],2,2*i+1) sub2 = (means.shape[1],2,2*i+2) else: sub1 = (means.shape[1]*2,1,2*i+1) sub2 = (means.shape[1]*2,1,2*i+2) # mean and variance plot a = fig.add_subplot(*sub1) a.plot(means, c='k', alpha=.3) plots.extend(a.plot(x, means.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i))) a.fill_between(x, means.T[i] - 2 * np.sqrt(variances.T[i]), means.T[i] + 2 * np.sqrt(variances.T[i]), facecolor=plots[-1].get_color(), alpha=.3) a.legend(borderaxespad=0.) a.set_xlim(x.min(), x.max()) if i < means.shape[1] - 1: a.set_xticklabels('') # binary prob plot a = fig.add_subplot(*sub2) a.bar(x,gamma[:,i],bottom=0.,linewidth=0,width=1.0,align='center') a.set_xlim(x.min(), x.max()) a.set_ylim([0.,1.]) pb.draw() fig.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95)) return fig
def render(): x = np.arange(0, np.pi * 3, .1) y = np.sin(x) fig = plt.figure() plt.plot(x, y) fig.show() svg_io = StringIO.StringIO() fig.savefig(svg_io, format='svg') svg_io.seek(0) # rewind the data return send_file(svg_io, mimetype='image/svg+xml')
def plot(parameterized, fignum=None, ax=None, colors=None, figsize=(12, 6)): """ Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given create a figure with fignum and plot in there colors: colors of different latent space dimensions input_dim """ if ax is None: fig = pb.figure(num=fignum, figsize=figsize) if colors is None: from ..Tango import mediumList from itertools import cycle colors = cycle(mediumList) pb.clf() else: colors = iter(colors) lines = [] fills = [] bg_lines = [] means, variances = parameterized.mean.values, parameterized.variance.values x = np.arange(means.shape[0]) for i in range(means.shape[1]): if ax is None: a = fig.add_subplot(means.shape[1], 1, i + 1) elif isinstance(ax, (tuple, list)): a = ax[i] else: raise ValueError("Need one ax per latent dimension input_dim") bg_lines.append(a.plot(means, c='k', alpha=.3)) lines.extend( a.plot(x, means.T[i], c=next(colors), label=r"$\mathbf{{X_{{{}}}}}$".format(i))) fills.append( a.fill_between(x, means.T[i] - 2 * np.sqrt(variances.T[i]), means.T[i] + 2 * np.sqrt(variances.T[i]), facecolor=lines[-1].get_color(), alpha=.3)) a.legend(borderaxespad=0.) a.set_xlim(x.min(), x.max()) if i < means.shape[1] - 1: a.set_xticklabels('') pb.draw() a.figure.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95)) return dict(lines=lines, fills=fills, bg_lines=bg_lines)
def ifft(row): N = row.shape[0] if N % 2 > 0: raise ValueError("size of x must be a power of 2") elif N <= 2: # this cutoff should be optimized return dft(row) else: X_even = ifft(row[::2]) X_odd = ifft(row[1::2]) factor = np.exp(2j * np.pi * np.arange(N) / N) concatenated = np.concatenate([ X_even + factor[:N // 2] * X_odd, X_even + factor[N // 2:] * X_odd ]) return concatenated
def image_response(input): import matplotlib import matplotlib.pyplot as plt import io from matplotlib import numpy as np x = np.arange(0, np.pi * 3, .1) y = np.sin(x) fig = plt.figure() plt.plot(x, y) imgdata = io.StringIO() fig.savefig(imgdata, format='svg') return imgdata.getvalue()
def image_response(input): import matplotlib import matplotlib.pyplot as plt import io from matplotlib import numpy as np x = np.arange(0,np.pi*3,.1) y = np.sin(x) fig = plt.figure() plt.plot(x,y) imgdata = io.StringIO() fig.savefig(imgdata, format='svg') return imgdata.getvalue()
def image_response(input): import matplotlib import matplotlib.pyplot as plt import io from matplotlib import numpy as np import base64 x = np.arange(0, np.pi * 3, .1) y = np.sin(x) fig = plt.figure() plt.plot(x, y) imgdata = io.StringIO() fig.savefig(imgdata, format='svg') return """<img src='data:image/svg+xml;charset=utf-8,%s'>""" % imgdata.getvalue( )
def image_response(input): import matplotlib import matplotlib.pyplot as plt import io from matplotlib import numpy as np import base64 x = np.arange(0,np.pi*3,.1) y = np.sin(x) fig = plt.figure() plt.plot(x,y) imgdata = io.StringIO() fig.savefig(imgdata, format='svg') return """<img src='data:image/svg+xml;charset=utf-8,%s'>""" % imgdata.getvalue()
def plot(parameterized, fignum=None, ax=None, colors=None, figsize=(12, 6)): """ Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given create a figure with fignum and plot in there colors: colors of different latent space dimensions input_dim """ if ax is None: fig = pb.figure(num=fignum, figsize=figsize) if colors is None: colors = pb.gca()._get_lines.color_cycle pb.clf() else: colors = iter(colors) lines = [] fills = [] bg_lines = [] means, variances = parameterized.mean.values, parameterized.variance.values x = np.arange(means.shape[0]) for i in range(means.shape[1]): if ax is None: a = fig.add_subplot(means.shape[1], 1, i + 1) elif isinstance(ax, (tuple, list)): a = ax[i] else: raise ValueError("Need one ax per latent dimension input_dim") bg_lines.append(a.plot(means, c='k', alpha=.3)) lines.extend(a.plot(x, means.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i))) fills.append(a.fill_between(x, means.T[i] - 2 * np.sqrt(variances.T[i]), means.T[i] + 2 * np.sqrt(variances.T[i]), facecolor=lines[-1].get_color(), alpha=.3)) a.legend(borderaxespad=0.) a.set_xlim(x.min(), x.max()) if i < means.shape[1] - 1: a.set_xticklabels('') pb.draw() a.figure.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95)) return dict(lines=lines, fills=fills, bg_lines=bg_lines)
def barras(ips_count, filename, field_name="", field_description=""): if len(ips_count) > 10: hosts = get_host_list(ips_count.keys()) else: hosts = list(ips_count.keys()) cant_ips = len(hosts) fig, ax = plt.subplots() index = np.arange(cant_ips) bar_width = 0.3 opacity = 0.4 rects1 = plt.bar(index, ips_count.values(), bar_width, alpha=opacity, color='b', label=field_description) plt.xlabel('IPs') plt.ylabel('Cantidad' if 'Tamaño' not in field_description else 'Bytes') plt.xticks(index + bar_width, hosts) plt.tight_layout() plt.legend(framealpha=0.5) plt.savefig(str("imgs/" + filename + "-" + field_name + ".png"))
def comparewave(self, wavedata, wavedata1): #将波形数据转换成数组 #需要根据声道数和量化单位,将读取的二进制数据转换为一个可以计算的数组 wave_data = numpy.fromstring(wavedata, dtype=numpy.short) wave_data1 = numpy.fromstring(wavedata1, dtype=numpy.short) wave_datac = wave_data - wave_data1 wave_data.shape = -1, 2 wave_data = wave_data.T wave_data1 = numpy.fromstring(wavedata1, dtype=numpy.short) wave_data1.shape = -1, 2 wave_data1 = wave_data1.T time = numpy.arange(0, self.nframes) * (1.0 / self.RATE) len_time = int(len(time) / 2) * 2 print(len_time) time = time[0:len_time] #绘制波形 pylab.subplot(221) pylab.plot(time, wave_data1[0], c="g") pylab.subplot(222) pylab.plot(time, wave_data1[1], c="y") pylab.subplot(221) pylab.plot(time, wave_data[0]) pylab.subplot(222) pylab.plot(time, wave_data[1], c="r") pylab.subplot(223) pylab.plot(time, wave_data[0] - wave_data[1]) pylab.subplot(224) pylab.plot(time, wave_data[0] - wave_data1[0], c="r") self.savewave("filec.wav", wave_datac) pylab.xlabel("time") pylab.show()
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 initialize(self, image, customize=True, xlim=None, ylim=None, xlabel='', ylabel='', log=True, vmin=None, vmax=None, maxresolution=1280, **kwargs): '''Display one image, give user a chance to zoom in, and leave everything set for populating with later images.''' if customize | (xlim is None )| (ylim is None): self.xlim = [0, image.shape[1]] self.ylim = [0, image.shape[0]] else: self.xlim = xlim self.ylim = ylim zoomed = image[self.ylim[0]:self.ylim[1], self.xlim[0]:self.xlim[1]] # create the figure, using xlim and ylim to determine the scale of the figure plt.ion() # create an empty dictionary to store the axes objects self.ax = {} # calculate aspect ratio (y/x) self.ysize, self.xsize = self.ylim[1] - self.ylim[0], self.xlim[1] - self.xlim[0] aspect = np.float(self.ysize)/self.xsize # set up the geometry of the plotting figure, including the desired resolution, histograms, and space for labels scale = 7.5 dpi = maxresolution/np.maximum(scale, scale*aspect) margin = 0.07 histheight = 0.1 inflate = 2*margin + histheight +1 self.figure = plt.figure(figsize=(scale*inflate, scale*aspect*inflate), dpi=dpi) gs = plt.matplotlib.gridspec.GridSpec(2,2,width_ratios=[1,histheight], height_ratios=[histheight, 1], top=1-margin, bottom=margin, left=margin, right=1-margin, hspace=0, wspace=0) # define panes for the image, as well as summed x and y histogram plots self.ax['image'] = plt.subplot(gs[1,0]) self.ax['xhist'] = plt.subplot(gs[0,0], sharex=self.ax['image'] ) self.ax['yhist'] = plt.subplot(gs[1,1], sharey=self.ax['image'] ) self.ax['navigator'] = plt.subplot(gs[0,1]) # clear the axes labels for k in self.ax.keys(): plt.setp(self.ax[k].get_xticklabels(), visible=False) plt.setp(self.ax[k].get_yticklabels(), visible=False) # set default image display keywords self.imagekw = dict(cmap='gray',interpolation='nearest',extent=[0, self.xsize, 0, self.ysize], aspect='equal') # replace any of these, as defined through the input keywords for k in kwargs.keys(): self.imagekw[k] = kwargs[k] #if customize: # self.imagekw['aspect'] = 'auto' # set the default line plotting keywords self.linekw = dict(color='black', linewidth=1, alpha=0.5) # make sure the min and max values for the color scale are set if vmin is None: vmin = np.min(image) if vmax is None: vmax = np.max(image) self.vmin, self.vmax = vmin, vmax # keep track of whether we're using a log scale self.log = log # calculate summed histograms xhist = np.sum(zoomed, 0) yhist = np.sum(zoomed, 1) # readjust things if a log scale is set if self.log: zoomedtoplot = logify(zoomed) imagetoplot = logify(image) self.imagekw['vmin'] = np.log(np.maximum(vmin, 1)) self.imagekw['vmax'] = np.log(vmax) else: zoomedtoplot = zoomed imagetoplot = image self.imagekw['vmin'] = vmin self.imagekw['vmax'] = vmax # keep the navigator like the image, but adjust its extent back to the regular self.navigatorkw = self.imagekw.copy() self.navigatorkw['extent'] = [0,image.shape[1], 0, image.shape[0]] # keep track of the data that goes into each plot self.current = {} # plot the histograms, once zoomed in self.current['xhist'] = self.ax['xhist'].plot(np.arange(len(xhist)), xhist, **self.linekw)[0] self.current['yhist'] = self.ax['yhist'].plot(yhist, np.arange(len(yhist)), **self.linekw)[0] self.ax['xhist'].set_xlim(0, zoomed.shape[1]-1) self.ax['xhist'].set_ylim(vmin*zoomed.shape[0], vmax*zoomed.shape[0]) self.ax['yhist'].set_xlim(vmin*zoomed.shape[1], vmax*zoomed.shape[1]) self.ax['xhist'].set_yscale('log') self.ax['yhist'].set_xscale('log') self.ax['yhist'].set_ylim(0, zoomed.shape[0]-1) # plot the (zoomed) image self.current['image'] = self.ax['image'].imshow(zoomedtoplot, **self.imagekw) self.current['navigator'] = self.ax['navigator'].imshow(imagetoplot, **self.navigatorkw) self.current['rectangle'] = self.ax['navigator'].add_patch(plt.matplotlib.patches.Rectangle((self.xlim[0], self.ylim[0]), self.xlim[1] - self.xlim[0], self.ylim[1]-self.ylim[0], edgecolor='red', facecolor='none', alpha=0.5, linewidth=5)) self.speak('created new image and plots') if customize: self.name = self.input('Please zoom to desired limits, enter a label to identify this window, and press return:') xlim, ylim = np.array(self.ax['image'].get_xlim()), np.array(self.ax['image'].get_ylim()) xlim[0] = np.maximum(xlim[0], 0) ylim[0] = np.maximum(ylim[0], 0) xlim[1] = np.minimum(xlim[1], self.xsize) ylim[1] = np.minimum(ylim[1], self.ysize) self.initialize(image, customize=False, xlim=xlim, ylim=ylim, log=log, vmin=vmin, vmax=vmax, maxresolution=maxresolution, **kwargs) self.speak('the display has been fully initialized -- ready for new plots!')
temp_list4 = [] temp_list5 = [] for j in range(test_times): temp_list1.append(Lottery_simul().calcu_possi(i)) temp_list2.append(Lottery_simul().calcu_multi_possi(i)) temp_list3.append(Lottery_simul().calcu_refer_possi(i)) temp_list4.append(Lottery_simul().calcu_multi_times(i)) temp_list5.append(Lottery_simul().calcu_refer_times(i)) possibility.append(np.mean(temp_list1)) multi_possibility.append(np.mean(temp_list2)) refer_possibility.append(np.mean(temp_list3)) multi_times.append(np.mean(temp_list4)) refer_times.append(np.mean(temp_list5)) plt.figure(figsize=(8, 6), dpi=80, num=1) X = np.arange(1, max_times, 10) plt.plot(X, possibility, color='black', label='next time possibility') plt.plot(X, multi_possibility, label='simulating possibility') plt.plot(X, refer_possibility, color='blue', label='referencing possibility') plt.ylim(0, 0.05) plt.legend(loc='upper left') plt.savefig('1.png') plt.figure(figsize=(8, 6), dpi=80, num=2) X = np.arange(1, max_times, 10) plt.plot(X, multi_times, color='black', label='simulatiing winning record') plt.plot(X, refer_times, color='blue', label='referencing winning record') plt.legend(loc='upper left')
def draw_single_cluster_plot(plotFilePath, dots): # print "# creating data from dots" X = [] Y = [] for x, y in dots: X.append(float(x)) Y.append(float(y)) nullfmt = NullFormatter() # no labels # print "# definitions for the axes" left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] # print "start with a rectangular Figure" plt.figure(1, figsize=(8, 8)) axScatter = plt.axes(rect_scatter) axHistx = plt.axes(rect_histx) axHisty = plt.axes(rect_histy) # print "# no labels" axHistx.xaxis.set_major_formatter(nullfmt) axHisty.yaxis.set_major_formatter(nullfmt) # print "# the scatter plot:" # axScatter.scatter(X, Y) axScatter.plot(X, Y, '.') # print "# now determine nice limits by hand:" # binwidth = 0.25 # nbBins = 60 # print " -1" # xymax = np.max( [np.max(np.fabs(X)), np.max(np.fabs(Y))] ) # xymin = np.min( [np.min(np.fabs(X)), np.min(np.fabs(Y))] ) # xmax = np.max(X); ymax = np.max(Y) # xmin = np.min(X); ymin = np.min(Y) # taille fixe sur les histo xmin = 0 xmax = 40000 ymin = 0 ymax = 100 # print xymax,xymin # print " -2" # lim = ( int(xymax/binwidth) + 1) * binwidth # print " -3" # axScatter.set_xlim( (-lim, lim) ) # axScatter.set_ylim( (-lim, lim) ) axScatter.set_xlim((xmin * .9, xmax * 1.1)) axScatter.set_ylim((ymin * .9, ymax * 1.1)) # print " -4" # bins = np.arange(-lim, lim + binwidth, binwidth) binwidth = (xmax * 1.1 - xmin * .9) / nbBins xBins = np.arange(xmin * .9, xmax * 1.1 + binwidth, binwidth) binwidth = (ymax * 1.1 - ymin * .9) / nbBins yBins = np.arange(ymin * .9, ymax * 1.1 + binwidth, binwidth) # print " -5" axHistx.hist(X, bins=xBins) # print " -6" axHisty.hist(Y, bins=yBins, orientation='horizontal') # print "making histograms" axHistx.set_xlim(axScatter.get_xlim()) axHisty.set_ylim(axScatter.get_ylim()) # print "# save plot" plt.savefig(plotFilePath) plt.clf()
import math from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import pyplot from matplotlib import numpy X = numpy.arange(-1, 1, 0.05) Y = numpy.arange(-1, 1, 0.05) V = [] detV = 10000 end_detV = 1e-5 * len(X) def update_V(): global detV detV = 0 for i in xrange(1, len(X) - 1): for j in xrange(1, len(Y) - 1): if (i==len(X)/3 or i==len(X)*2/3) and len(Y)/3<j<len(Y)*2/3: continue tmp = (V[i-1][j] + V[i+1][j] + V[i][j-1] + V[i][j+1]) / 4 detV += numpy.abs(tmp - V[i][j]) V[i][j] = tmp # initialize V V.append([0. for i in xrange(len(X))]) for i in xrange(1, len(X) - 1): tmp = [0.]
def plotIsoFreqNSDiff( ax, freq, arrayList, flag, par="abs", colorbar=True, cLevel=True, mask=None, contourLine=True, useLog=False, ): indUniFreq0 = np.where(freq == arrayList[0]["freq"]) indUniFreq1 = np.where(freq == arrayList[1]["freq"]) seicmap = plt.get_cmap("RdYlBu") # seismic') x, y = arrayList[0]["x"][indUniFreq0], arrayList[0]["y"][indUniFreq0] if par == "abs": if useLog: zPlot = (np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1])) ) / np.log10(np.abs(arrayList[1][flag][indUniFreq1])) else: zPlot = (np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1])) / np.abs( arrayList[1][flag][indUniFreq1]) if mask: maskInd = np.logical_or( np.abs(arrayList[0][flag][indUniFreq0]) < 1e-3, np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3, ) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask if cLevel: level = np.arange(-200, 201, 10) clevel = np.arange(-200, 201, 25) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) elif par == "real": if useLog: zPlot = ( np.log10(np.real(arrayList[0][flag][indUniFreq0])) - np.log10(np.real(arrayList[1][flag][indUniFreq1]))) / np.log10( np.abs((np.real(arrayList[1][flag][indUniFreq1])))) else: zPlot = (np.real(arrayList[0][flag][indUniFreq0]) - np.real(arrayList[1][flag][indUniFreq1])) / np.abs( (np.real(arrayList[1][flag][indUniFreq1]))) if mask: maskInd = np.logical_or( np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3, np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3, ) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask if cLevel: level = np.arange(-200, 201, 10) clevel = np.arange(-200, 201, 25) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) elif par == "imag": if useLog: zPlot = ( np.log10(np.imag(arrayList[0][flag][indUniFreq0])) - np.log10(np.imag(arrayList[1][flag][indUniFreq1]))) / np.log10( np.abs((np.imag(arrayList[1][flag][indUniFreq1])))) else: zPlot = (np.imag(arrayList[0][flag][indUniFreq0]) - np.imag(arrayList[1][flag][indUniFreq1])) / np.abs( (np.imag(arrayList[1][flag][indUniFreq1]))) if mask: maskInd = np.logical_or( np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3, np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3, ) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask if cLevel: level = np.arange(-200, 201, 10) clevel = np.arange(-200, 201, 25) else: level = np.linspace(zPlot.min(), zPlot.max(), 100) clevel = np.linspace(zPlot.min(), zPlot.max(), 10) cs = ax.tricontourf( x, y, zPlot * 100, levels=level * 100, cmap=seicmap, extend="both") # ,norm=colors.SymLogNorm(1e-2,linscale=2)) if contourLine: csl = ax.tricontour(x, y, zPlot * 100, levels=clevel * 100, colors="k") plt.clabel(csl, fontsize=7, inline=1, fmt="%1.1e", inline_spacing=10) if colorbar: cb = plt.colorbar(cs, cax=ax.cax, ticks=clevel * 100, format="%1.1e") for t in cb.ax.get_yticklabels(): t.set_rotation(60) t.set_fontsize(8) ax.set_title(flag + " " + par, fontsize=8)
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 Update_Graph(self, sender): sender = str(sender) if 'Button_Min' in sender: value = eval(sender).text() pos = int(sender[-1]) try: self.MinGuess[pos] = float(value) except ValueError: self.MinGuess[pos] = None pass if 'Button_Max' in sender: value = eval(sender).text() pos = int(sender[-1]) try: self.MaxGuess[pos] = float(value) except ValueError: self.MaxGuess[pos] = None pass elif 'Button_Guess' in sender: value = eval(sender).text() pos = int(sender[-1]) try: self.param_list[pos] = float(value) except ValueError: self.param_list[pos] = None pass elif 'Display_' in sender: value = eval(sender).text() pos = int(sender[-1]) try: self.display_range[pos] = float(value) except ValueError: self.display_range[pos] = 1.0 pass elif 'Range' in sender: value = eval(sender).text() pos = int(sender[-1]) try: self.range[pos] = float(value) except ValueError: self.range[pos] = 1.0 pass else: pass #fitting function is set function = eval('self.' + str(self.List_of_Functions.currentText()).lower()) #Graph is cleared self.Fit_Example.canvas.axes.clear() timescale = 1. if str(self.Data_Wave.currentText()) != 'None': y = numpy.array(eval(str(self.Data_Wave.currentText()))) if str(self.Data_Wave_Axes.currentText()) == 'None': x = numpy.arange(len(y)) else: try: x = numpy.array( eval(str(self.Data_Wave_Axes.currentText()))) except SyntaxError: #should be corrected x = numpy.arange(len(y)) timescale = abs(x[1] - x[0]) A, = self.Fit_Example.canvas.axes.plot(x, y, 'g') else: print 'No Data Wave defined (yet)' return Bounds = [] for i in range(10): Bounds.append([self.MinGuess[i], self.MaxGuess[i]]) fit = self.Fit(x, X=x, function=str( self.List_of_Functions.currentText()).lower(), Guess=self.param_list, StartX=self.range[0], EndX=self.range[1], Number_of_points=len(x), Rendering=False, Bounds=Bounds, Model=True) B, = self.Fit_Example.canvas.axes.plot(x, fit, 'r') #The fitting guess self.Fit_Example.canvas.axes.legend([A, B], ["Data", "Model"], loc='best', fancybox=True) self.Fit_Example.canvas.axes.axvspan(self.range[0], self.range[1], -2000, 2000, color='r', alpha=0.1) if self.fixed_range.checkState() == 2: self.Fit_Example.canvas.axes.set_xbound(self.display_range[0], self.display_range[1]) self.Fit_Example.canvas.axes.set_ybound(self.display_range[2], self.display_range[3]) else: self.Display_Range_0.setText( str(self.Fit_Example.canvas.axes.get_xbound()[0])) self.Display_Range_1.setText( str(self.Fit_Example.canvas.axes.get_xbound()[1])) self.Display_Range_2.setText( str(self.Fit_Example.canvas.axes.get_ybound()[0])) self.Display_Range_3.setText( str(self.Fit_Example.canvas.axes.get_ybound()[1])) self.display_range[0] = self.Fit_Example.canvas.axes.get_xbound( )[0] self.display_range[1] = self.Fit_Example.canvas.axes.get_xbound( )[1] self.display_range[2] = self.Fit_Example.canvas.axes.get_ybound( )[0] self.display_range[3] = self.Fit_Example.canvas.axes.get_ybound( )[1] self.Fit_Example.canvas.draw()
def plot_2D_and_histos(plotFilePath,dots,tag): idx=getTagIndex(tag) color=getTagColor(tag) print "# creating data from dots" X=[];Y=[] for d in dots : X.append(d[idx]);Y.append(d[-1]) nullfmt = NullFormatter() # no labels print "# definitions for the axes" left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] print "start with a rectangular Figure" plt.figure(1, figsize=(8,8)) axScatter = plt.axes(rect_scatter) axHistx = plt.axes(rect_histx) axHisty = plt.axes(rect_histy) print "# no labels" axHistx.xaxis.set_major_formatter(nullfmt) axHisty.yaxis.set_major_formatter(nullfmt) print "# the scatter plot:" # axScatter.scatter(X, Y) axScatter.plot(X, Y,'.',color=color) print "# now determine nice limits by hand:" # binwidth = 0.25 # nbBins = 60 # print " -1" # xymax = np.max( [np.max(np.fabs(X)), np.max(np.fabs(Y))] ) # xymin = np.min( [np.min(np.fabs(X)), np.min(np.fabs(Y))] ) xmax = np.max(X); ymax = np.max(Y) xmin = np.min(X); ymin = np.min(Y) # print xymax,xymin # print " -2" # lim = ( int(xymax/binwidth) + 1) * binwidth # print " -3" # axScatter.set_xlim( (-lim, lim) ) # axScatter.set_ylim( (-lim, lim) ) axScatter.set_xlim( (xmin*.9, xmax*1.1) ) axScatter.set_ylim( (ymin*.9, ymax*1.1) ) # print " -4" # bins = np.arange(-lim, lim + binwidth, binwidth) binwidth = (xmax*1.1-xmin*.9) / nbBins xBins = np.arange(xmin*.9,xmax*1.1 + binwidth, binwidth) binwidth = (ymax*1.1-ymin*.9) / nbBins yBins = np.arange(ymin*.9,ymax*1.1 + binwidth, binwidth) # print " -5" axHistx.hist(X, bins=xBins, color = color) # print " -6" axHisty.hist(Y, bins=yBins, orientation='horizontal') print "making histograms" axHistx.set_xlim( axScatter.get_xlim() ) axHisty.set_ylim( axScatter.get_ylim() ) print "# save plot" plt.savefig(plotFilePath) plt.clf()
import math from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import pyplot from matplotlib import numpy x=numpy.arange(-1,1,0.05) y=numpy.arange(-1,1,0.05) v=[] detv=10000 end_detv=1e-5*len(x) def update_v(): global detv detv=0 for i in xrange(1,len(x),-1): for j in xrange(1,len(y),-1): if (i==len(x)/3or i==len(x)*2/3) and len(y)/3<j<len(y)*2/3: continue tmp=(v[i-1][j]+v[i+1][j]+v[i][j-1]+v[i][j+1])/4 detv+=numpy.abs(tmp-v[i][j]) v[i][j]=tmp 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:
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+.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
def Helper(self): #Global Widget self.all = QtGui.QWidget() self.all.setMinimumSize(900,500) self.all.setWindowTitle("Fitting Tools") #Fitting preview self.Fit_Example = MyMplWidget(parent=self.all,No_Toolbar=False) self.Fit_Example.setMinimumSize(600,600) self.Fit_Example.setWindowTitle("Display") plot=self.line_init(numpy.arange(1000)*0.001) self.Fit_Example.canvas.axes.plot(numpy.arange(1000)*0.001,plot,'r') self.hbox=QtGui.QHBoxLayout() self.vbox=QtGui.QVBoxLayout() #Box1 The fitting Functions self.List_of_Functions = QtGui.QComboBox() self.List_of_Functions.setMinimumSize(600,40) self.List_of_Functions.addItems(self.List) self.vbox.addWidget(self.List_of_Functions) QtCore.QObject.connect(self.List_of_Functions, QtCore.SIGNAL("currentIndexChanged(int)"),self.Fitting_Parameters) #Box2 Select the DataWave & XScale self.ListYWaves() #self.ListXWaves() QtCore.QObject.connect(self.Data_Wave, QtCore.SIGNAL('currentIndexChanged(int)'),self.ListXWaves)#lambda sender="self.Button_1": self.Update_Graph(sender)) #just to refresh the display QtCore.QObject.connect(self.Data_Wave_Axes, QtCore.SIGNAL('currentIndexChanged(int)'),self.Optimize_Range) #just to refresh the display self.vbox.addWidget(self.Data_Wave) self.vbox.addWidget(self.Data_Wave_Axes) RangeHbox=QtGui.QHBoxLayout() self.Range = QtGui.QWidget() Label2 = QtGui.QLabel(self.Range) Label2.setText('<b>Fitting Range (in pts)</b>') Label2.setGeometry(40,0, 100, 25) for k,l in enumerate(["X_Start","X_End","Points"]): eval(compile("self.RangeLabel_"+str(k)+"= QtGui.QLabel(self.Range)",'<string>','exec')) eval(compile("self.RangeLabel_"+str(k)+".setGeometry(10,int(k*30)+30, 100, 25)",'<string>','exec')) eval(compile("self.RangeLabel_"+str(k)+".setText('"+l+"')",'<string>','exec')) eval(compile("self.Range_"+str(k)+"= QtGui.QLineEdit(self.Range)",'<string>','exec')) eval(compile("self.Range_"+str(k)+".setGeometry(50,int(k*30)+30, 100, 25)",'<string>','exec')) eval(compile("self.Range_"+str(k)+".setText('"+str(self.range[k])+"')",'<string>','exec')) current2=eval("self.Range_"+str(k)) QtCore.QObject.connect(current2, QtCore.SIGNAL('editingFinished()'),lambda sender="self.Range_"+str(k): self.Update_Graph(sender)) RangeHbox.addWidget(self.Range) self.Display_Range = QtGui.QWidget() Label3 = QtGui.QLabel(self.Display_Range) Label3.setText('<b>Display Range (in Units)</b>') Label3.setGeometry(40,0, 100, 25) for k,l in enumerate(["X_Start","X_End","Y_Start","Y_End"]): eval(compile("self.Display_RangeLabel_"+str(k)+"= QtGui.QLabel(self.Display_Range)",'<string>','exec')) eval(compile("self.Display_RangeLabel_"+str(k)+".setGeometry(10,int(k*30)+30, 100, 25)",'<string>','exec')) eval(compile("self.Display_RangeLabel_"+str(k)+".setText('"+l+"')",'<string>','exec')) eval(compile("self.Display_Range_"+str(k)+"= QtGui.QLineEdit(self.Display_Range)",'<string>','exec')) eval(compile("self.Display_Range_"+str(k)+".setGeometry(50,int(k*30)+30, 100, 25)",'<string>','exec')) eval(compile("self.Display_Range_"+str(k)+".setText('"+str(self.display_range[k])+"')",'<string>','exec')) eval(compile("self.Display_Range_"+str(k)+".setEnabled(False)",'<string>','exec')) current3=eval("self.Display_Range_"+str(k)) QtCore.QObject.connect(current3, QtCore.SIGNAL('editingFinished()'),lambda sender="self.Display_Range_"+str(k): self.Update_Graph(sender)) self.fixed_range=QtGui.QCheckBox(self.Display_Range) self.fixed_range.setText('Fixed display range') self.fixed_range.setGeometry(10,int((k+1)*30)+30, 150, 25) self.fixed_range.setCheckState(0) QtCore.QObject.connect(self.fixed_range, QtCore.SIGNAL('stateChanged(int)'), self.Update_Fields_State) #just to refresh the display RangeHbox.addWidget(self.Display_Range) self.vbox.addLayout(RangeHbox) self.Fitting_Parameters() self.fit_the_data = QtGui.QPushButton() self.fit_the_data.setText('Fit !') QtCore.QObject.connect(self.fit_the_data, QtCore.SIGNAL('clicked()'),self.Pre_Fit) #just to refresh the display self.vbox.addWidget(self.fit_the_data) self.hbox.addLayout(self.vbox) self.hbox.addWidget(self.Fit_Example) self.all.setLayout(self.hbox) self.all.show()
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 Update_Graph(self,sender): sender=str(sender) if 'Button_Min' in sender: value=eval(sender).text() pos=int(sender[-1]) try: self.MinGuess[pos]=float(value) except ValueError: self.MinGuess[pos]=None pass if 'Button_Max' in sender: value=eval(sender).text() pos=int(sender[-1]) try: self.MaxGuess[pos]=float(value) except ValueError: self.MaxGuess[pos]=None pass elif 'Button_Guess' in sender: value=eval(sender).text() pos=int(sender[-1]) try: self.param_list[pos]=float(value) except ValueError: self.param_list[pos]=None pass elif 'Display_' in sender: value=eval(sender).text() pos=int(sender[-1]) try: self.display_range[pos]=float(value) except ValueError: self.display_range[pos]=1.0 pass elif 'Range' in sender: value=eval(sender).text() pos=int(sender[-1]) try: self.range[pos]=float(value) except ValueError: self.range[pos]=1.0 pass else: pass #fitting function is set function=eval('self.'+str(self.List_of_Functions.currentText()).lower()) #Graph is cleared self.Fit_Example.canvas.axes.clear() timescale=1. if str(self.Data_Wave.currentText()) != 'None': y=numpy.array(eval(str(self.Data_Wave.currentText()))) if str(self.Data_Wave_Axes.currentText()) == 'None': x=numpy.arange(len(y)) else: try: x=numpy.array(eval(str(self.Data_Wave_Axes.currentText()))) except SyntaxError: #should be corrected x=numpy.arange(len(y)) timescale=abs(x[1]-x[0]) A,=self.Fit_Example.canvas.axes.plot(x,y,'g') else: print 'No Data Wave defined (yet)' return Bounds=[] for i in range(10): Bounds.append([self.MinGuess[i],self.MaxGuess[i]]) fit=self.Fit(x,X=x,function=str(self.List_of_Functions.currentText()).lower(),Guess=self.param_list,StartX=self.range[0],EndX=self.range[1],Number_of_points=len(x),Rendering = False,Bounds=Bounds,Model=True) B,=self.Fit_Example.canvas.axes.plot(x,fit,'r') #The fitting guess self.Fit_Example.canvas.axes.legend([A,B], ["Data", "Model"], loc='best',fancybox=True) self.Fit_Example.canvas.axes.axvspan(self.range[0], self.range[1], -2000, 2000,color='r',alpha=0.1) if self.fixed_range.checkState()==2: self.Fit_Example.canvas.axes.set_xbound(self.display_range[0],self.display_range[1]) self.Fit_Example.canvas.axes.set_ybound(self.display_range[2],self.display_range[3]) else: self.Display_Range_0.setText(str(self.Fit_Example.canvas.axes.get_xbound()[0])) self.Display_Range_1.setText(str(self.Fit_Example.canvas.axes.get_xbound()[1])) self.Display_Range_2.setText(str(self.Fit_Example.canvas.axes.get_ybound()[0])) self.Display_Range_3.setText(str(self.Fit_Example.canvas.axes.get_ybound()[1])) self.display_range[0]=self.Fit_Example.canvas.axes.get_xbound()[0] self.display_range[1]=self.Fit_Example.canvas.axes.get_xbound()[1] self.display_range[2]=self.Fit_Example.canvas.axes.get_ybound()[0] self.display_range[3]=self.Fit_Example.canvas.axes.get_ybound()[1] self.Fit_Example.canvas.draw()
def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True,mask=None,contourLine=True,useLog=False): indUniFreq0 = np.where(freq==arrayList[0]['freq']) indUniFreq1 = np.where(freq==arrayList[1]['freq']) seicmap = plt.get_cmap('RdYlBu')#seismic') x, y = arrayList[0]['x'][indUniFreq0],arrayList[0]['y'][indUniFreq0] if par == 'abs': if useLog: zPlot = (np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs(arrayList[1][flag][indUniFreq1])) else: zPlot = (np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1]))/np.abs(arrayList[1][flag][indUniFreq1]) if mask: maskInd = np.logical_or(np.abs(arrayList[0][flag][indUniFreq0])< 1e-3,np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask if cLevel: level = np.arange(-200,201,10) clevel = np.arange(-200,201,25) else: level = np.linspace(zPlot.min(),zPlot.max(),100) clevel = np.linspace(zPlot.min(),zPlot.max(),10) elif par == 'real': if useLog: zPlot = (np.log10(np.real(arrayList[0][flag][indUniFreq0])) -np.log10(np.real(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.real(arrayList[1][flag][indUniFreq1])))) else: zPlot = (np.real(arrayList[0][flag][indUniFreq0]) -np.real(arrayList[1][flag][indUniFreq1]))/np.abs((np.real(arrayList[1][flag][indUniFreq1]))) if mask: maskInd = np.logical_or(np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask if cLevel: level = np.arange(-200,201,10) clevel = np.arange(-200,201,25) else: level = np.linspace(zPlot.min(),zPlot.max(),100) clevel = np.linspace(zPlot.min(),zPlot.max(),10) elif par == 'imag': if useLog: zPlot = (np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -np.log10(np.imag(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.imag(arrayList[1][flag][indUniFreq1])))) else: zPlot = (np.imag(arrayList[0][flag][indUniFreq0]) -np.imag(arrayList[1][flag][indUniFreq1]))/np.abs((np.imag(arrayList[1][flag][indUniFreq1]))) if mask: maskInd = np.logical_or(np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask if cLevel: level = np.arange(-200,201,10) clevel = np.arange(-200,201,25) else: level = np.linspace(zPlot.min(),zPlot.max(),100) clevel = np.linspace(zPlot.min(),zPlot.max(),10) cs = ax.tricontourf(x,y,zPlot*100,levels=level*100,cmap=seicmap,extend='both') #,norm=colors.SymLogNorm(1e-2,linscale=2)) if contourLine: csl = ax.tricontour(x,y,zPlot*100,levels=clevel*100,colors='k') plt.clabel(csl, fontsize=7, inline=1,fmt='%1.1e',inline_spacing=10) if colorbar: cb = plt.colorbar(cs,cax=ax.cax,ticks=clevel*100,format='%1.1e') for t in cb.ax.get_yticklabels(): t.set_rotation(60) t.set_fontsize(8) ax.set_title(flag+' '+par,fontsize=8)
def Helper(self): #Global Widget self.all = QtGui.QWidget() self.all.setMinimumSize(900, 500) self.all.setWindowTitle("Fitting Tools") #Fitting preview self.Fit_Example = MyMplWidget(parent=self.all, No_Toolbar=False) self.Fit_Example.setMinimumSize(600, 600) self.Fit_Example.setWindowTitle("Display") plot = self.line_init(numpy.arange(1000) * 0.001) self.Fit_Example.canvas.axes.plot( numpy.arange(1000) * 0.001, plot, 'r') self.hbox = QtGui.QHBoxLayout() self.vbox = QtGui.QVBoxLayout() #Box1 The fitting Functions self.List_of_Functions = QtGui.QComboBox() self.List_of_Functions.setMinimumSize(600, 40) self.List_of_Functions.addItems(self.List) self.vbox.addWidget(self.List_of_Functions) QtCore.QObject.connect(self.List_of_Functions, QtCore.SIGNAL("currentIndexChanged(int)"), self.Fitting_Parameters) #Box2 Select the DataWave & XScale self.ListYWaves() #self.ListXWaves() QtCore.QObject.connect( self.Data_Wave, QtCore.SIGNAL('currentIndexChanged(int)'), self.ListXWaves ) #lambda sender="self.Button_1": self.Update_Graph(sender)) #just to refresh the display QtCore.QObject.connect( self.Data_Wave_Axes, QtCore.SIGNAL('currentIndexChanged(int)'), self.Optimize_Range) #just to refresh the display self.vbox.addWidget(self.Data_Wave) self.vbox.addWidget(self.Data_Wave_Axes) RangeHbox = QtGui.QHBoxLayout() self.Range = QtGui.QWidget() Label2 = QtGui.QLabel(self.Range) Label2.setText('<b>Fitting Range (in pts)</b>') Label2.setGeometry(40, 0, 100, 25) for k, l in enumerate(["X_Start", "X_End", "Points"]): eval( compile( "self.RangeLabel_" + str(k) + "= QtGui.QLabel(self.Range)", '<string>', 'exec')) eval( compile( "self.RangeLabel_" + str(k) + ".setGeometry(10,int(k*30)+30, 100, 25)", '<string>', 'exec')) eval( compile("self.RangeLabel_" + str(k) + ".setText('" + l + "')", '<string>', 'exec')) eval( compile( "self.Range_" + str(k) + "= QtGui.QLineEdit(self.Range)", '<string>', 'exec')) eval( compile( "self.Range_" + str(k) + ".setGeometry(50,int(k*30)+30, 100, 25)", '<string>', 'exec')) eval( compile( "self.Range_" + str(k) + ".setText('" + str(self.range[k]) + "')", '<string>', 'exec')) current2 = eval("self.Range_" + str(k)) QtCore.QObject.connect(current2, QtCore.SIGNAL('editingFinished()'), lambda sender="self.Range_" + str(k): self. Update_Graph(sender)) RangeHbox.addWidget(self.Range) self.Display_Range = QtGui.QWidget() Label3 = QtGui.QLabel(self.Display_Range) Label3.setText('<b>Display Range (in Units)</b>') Label3.setGeometry(40, 0, 100, 25) for k, l in enumerate(["X_Start", "X_End", "Y_Start", "Y_End"]): eval( compile( "self.Display_RangeLabel_" + str(k) + "= QtGui.QLabel(self.Display_Range)", '<string>', 'exec')) eval( compile( "self.Display_RangeLabel_" + str(k) + ".setGeometry(10,int(k*30)+30, 100, 25)", '<string>', 'exec')) eval( compile( "self.Display_RangeLabel_" + str(k) + ".setText('" + l + "')", '<string>', 'exec')) eval( compile( "self.Display_Range_" + str(k) + "= QtGui.QLineEdit(self.Display_Range)", '<string>', 'exec')) eval( compile( "self.Display_Range_" + str(k) + ".setGeometry(50,int(k*30)+30, 100, 25)", '<string>', 'exec')) eval( compile( "self.Display_Range_" + str(k) + ".setText('" + str(self.display_range[k]) + "')", '<string>', 'exec')) eval( compile("self.Display_Range_" + str(k) + ".setEnabled(False)", '<string>', 'exec')) current3 = eval("self.Display_Range_" + str(k)) QtCore.QObject.connect(current3, QtCore.SIGNAL('editingFinished()'), lambda sender="self.Display_Range_" + str( k): self.Update_Graph(sender)) self.fixed_range = QtGui.QCheckBox(self.Display_Range) self.fixed_range.setText('Fixed display range') self.fixed_range.setGeometry(10, int((k + 1) * 30) + 30, 150, 25) self.fixed_range.setCheckState(0) QtCore.QObject.connect( self.fixed_range, QtCore.SIGNAL('stateChanged(int)'), self.Update_Fields_State) #just to refresh the display RangeHbox.addWidget(self.Display_Range) self.vbox.addLayout(RangeHbox) self.Fitting_Parameters() self.fit_the_data = QtGui.QPushButton() self.fit_the_data.setText('Fit !') QtCore.QObject.connect(self.fit_the_data, QtCore.SIGNAL('clicked()'), self.Pre_Fit) #just to refresh the display self.vbox.addWidget(self.fit_the_data) self.hbox.addLayout(self.vbox) self.hbox.addWidget(self.Fit_Example) self.all.setLayout(self.hbox) self.all.show()
def graf2(): arr_time = list() arr_value = list() wins = list() plt.rc('axes', grid=True) #plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) fillcolor = 'darkgoldenrod' monthsFmt = DateFormatter("%d %b %y %H:%M:%S") with open(r".\report\test_online_main_page.txt", 'r', encoding='utf-8') as f: arr = [x.strip().split(';') for x in f] count = len(arr) for x in arr: #if x[4]=='1': # arr_time = [datetime.strptime(x[0], '%y/%m/%d %H:%M:%S') for x in arr[1:]] # arr_value = [x[1] for x in arr[1:]] arr_time.append(datetime.strptime(x[0], '%y/%m/%d %H:%M:%S').strftime('%d/%m/%y')) # '%y/%m/%d %H:%M:%S' arr_value.append(x[1]) #wins.append(1) x = list(range(1, len(arr_time) + 1)) plt.grid() plt.xlabel('Сборки') plt.ylabel('Время (мс)') plt.xticks(np.arange(1, len(arr_value) + 1, 1.0)) plt.margins(0.2) plt.subplots_adjust(bottom=0.35) plt.xticks(x, arr_time, rotation=55) fig, ax = plt.subplots() #ax.stackplot(x, y1, y2, y3) plt.plot(x, arr_value, 'b', x, arr_value, 'o')# plt.show() fig = plt.figure(facecolor='white') #fig.autofmt_xdate(bottom=0.2, rotation=45, ha='right') ax = fig.add_subplot(121) plt.title(r'$\sin(x)$') # ax.plot_date(arr_time, arr_value, 'o-') plt.xticks(range(1, len(arr_value)),arr_time, rotation=45) # 'vertical' plt.plot(arr_time,arr_value, 'o') # plt.xlabel(r"$time$", fontsize=14) # plt.ylabel(r"$timetest$", fontsize=14) #plt.setp(arr_time, rotation=45, fontsize=8) # hour = HourLocator(range(1,25), interval=4) # day = DayLocator(range(1,32), interval=1) # formatter = DateFormatter('%m/%d/%y')#:%S%H:%M # ax.xaxis.set_major_locator(day) # ax.xaxis.set_major_formatter(formatter) # labels = 'Wins', 'Los' # wins_ = wins # sizes = [15, 30]#, 45, 10 # colors = ['yellowgreen', 'gold'] #, 'lightskyblue', 'lightcoral' # explode = (0.1, 0.1) #, 0.1, 0.1 only "explode" the 2nd slice (i.e. 'Hogs') # # ax2 = fig.add_subplot(122) # ax2.pie(sizes, explode=explode, labels=labels, colors=colors, # autopct='%1.1f%%', shadow=True, startangle=90) # plt.title(r'$\cos(x)$') # ax2.plot_date(arr_time, arr_value) # hour = HourLocator(range(1,25), interval=4) # formatter = DateFormatter('%m/%d/%y')#%H:%M:%S # ax2.xaxis.set_major_locator(hour) # ax2.xaxis.set_major_formatter(formatter) plt.show()