def generate_matrix_visualization(known_words, bookmark_words):

    m = []
    for i in range(0,100):
        m.append([])
        for j in range (0, 100):
            if (i*100+j) in bookmark_words:
                m[i].append(0.65)
            elif (i*100+j) in known_words:
                m[i].append(0.4)
            else:
                m[i].append(0.2)
    m.reverse()
	
    # we need this next line to scale the color scheme
    m[0][0]=0
    matrix = numpy.matrix(m)

	fig = plt.figure()
	ax = fig.add_subplot(1,1,1)
	ax.set_aspect('equal')
	plt.imshow(matrix, interpolation='none')
	plt.set_cmap('hot')
	plt.colorbar()
	plt.show()
def PlotMtxError(Corr_w):
    max_val = 1
    min_val = -0.1

    AvCorr = np.sum(Corr_w, axis=0)
    dCorr = Corr_w - AvCorr
    errCorr = np.log10(np.sqrt(np.einsum("i...,i...", dCorr, dCorr)) / np.absolute(AvCorr) / np.sqrt(Corr_w.shape[0]))
    # print errCorr.shape
    # print errCorr

    plt.rcParams.update({"font.size": 6, "font.weight": "bold"})
    for i in xrange(errCorr.shape[0]):
        plt.subplot(2, 7, i + 1)
        plt.title("SITE " + str(i + 1) + ":: \nHistogram of errors in corr. mtx.")
        plt.hist(errCorr[0, :, :].flatten(), 256, range=(min_val, max_val))
        plt.xlabel("log_10(sigma)")
        plt.ylabel("Count")

        plt.subplot(2, 7, i + 7 + 1)
        plt.imshow(errCorr[0, :, :], vmin=min_val, vmax=max_val)
        cbar = plt.colorbar(shrink=0.25, aspect=40)
        cbar.set_label("log_10(sigma)")
        plt.set_cmap("gist_yarg")
        plt.title("SITE " + str(i + 1) + ":: \nError in corr. matx. values")
        plt.xlabel("Site i")
        plt.ylabel("Site j")
    plt.show()
def display_data(x, **kwargs):
  plt.set_cmap('gray')
  nrows, ncols = x.shape
  example_width = int(kwargs.get('example_width', round(math.sqrt(ncols))))
  example_height = int(ncols / example_width)
  display_rows = int(math.floor(math.sqrt(nrows)))
  display_cols = int(math.ceil(nrows/display_rows))
  pad = 1
  display_array = -np.ones( (pad + display_rows *(example_height + pad),
                            pad + display_cols * (example_width + pad)) );
  curr_ex = 0;
  for j in range(0, display_rows):
    for i in range(0, display_cols):
      if (curr_ex >= nrows):
        break;
      max_val = np.max(np.abs(x[curr_ex, :]))
      x_splice_start = pad + j*(example_height + pad)
      y_splice_start = pad + i*(example_width + pad)
      display_array[x_splice_start:(x_splice_start+example_height),
                    y_splice_start:(y_splice_start+example_width)] = \
                    np.reshape(x[curr_ex,:], (example_height, example_width)) / max_val
      curr_ex += 1
    if (curr_ex >= nrows):
      break
  plt.imshow(display_array)
  plt.show()
Esempio n. 4
0
def histogram_plot():
    global image, extension, image_count, log_path, max_image_count, view_value, plot_number
    if (image.max() != 0):
        if (
                plot_number == 121
        ):  #because this function will be called two times in display_original()
            fig.clf()
        fig.add_subplot(plot_number)  #dynamically changing the grid plot
        im = plt.imshow(image, vmin=0, vmax=255)
        plt.set_cmap('gray')

        image_histogram = np.zeros(256)  #contains histogram of image
        #create the image histogram
        for i in range(image.shape[0]):
            for j in range(image.shape[1]):
                intensity_value = int(
                    abs(image[i][j])
                )  #abs() is taken in case of negative image intensities
                image_histogram[
                    intensity_value] = image_histogram[intensity_value] + 1
        fig.add_subplot(plot_number + 1)
        plt.stem(np.arange(256), image_histogram,
                 markerfmt=' ')  #plots a stem image of histogram

        canvas.draw()
        view_value = "100"  #set the callback so that the display image option is enabled
        var2.set(view_value)
    else:
        messagebox.showerror("Error", "Please load an image first.")
Esempio n. 5
0
def plot_decision_surface(axes, clusters, X, Y=None):
    import matplotlib.pylab as pylab
    import numpy as np

    def kmeans_predict(clusters, X):
        from ..core import distance
        dist_m = distance.minkowski_dist(clusters, X)
        print 'dist_m:', dist_m.shape
        pred = np.argmin(dist_m, axis=0)
        print 'pred:', pred.shape
        return pred

    # step size in the mesh
    h = (np.max(X, axis=0) - np.min(X, axis=0)) / 100.0
    # create a mesh to plot in
    x_min = np.min(X, axis=0) - 1
    x_max = np.max(X, axis=0) + 1
    xx, yy = np.meshgrid(np.arange(x_min[0], x_max[0], h[0]),
                         np.arange(x_min[1], x_max[1], h[1]))
    Z = kmeans_predict(clusters, np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    pylab.set_cmap(pylab.cm.Paired)
    pylab.axes(axes)
    pylab.contourf(xx, yy, Z, cmap=pylab.cm.Paired)
    pylab.xlim(np.min(xx), np.max(xx))
    pylab.ylim(np.min(yy), np.max(yy))
    #pylab.axis('off')

    # Plot also the training points
    if Y is not None:
        pylab.scatter(X[:,0], X[:,1], c=Y)
    else:
        pylab.scatter(X[:,0], X[:,1])
    pylab.scatter(clusters[:,0], clusters[:,1], s=200, marker='x', color='white')
Esempio n. 6
0
 def draw(self):
   plt.imshow(self._original_values.T, interpolation='none', origin='lower',
              extent=[self._origin[X],
                      self._origin[X] + self._values.shape[0] * self._resolution,
                      self._origin[Y],
                      self._origin[Y] + self._values.shape[1] * self._resolution])
   plt.set_cmap('gray_r')
Esempio n. 7
0
    def show_msk3D(self, what='amplitude'):
        """Show the amplitude/phase of the mask in 3D plot.
        
        :Args: 
            - what : string= (amplitude/phase) to choose what to plot.
        
        .. Note::
        This function needs matplotlib package
        
        :Returns:
            - none.
        """
        if what == 'amplitude':
            msk = np.abs(self.Msk)
        elif what == 'phase':
            msk = np.angle(self.Msk)
        else:
            print('"what" must be "amplitude" or "phase"')
            sys.exit(1)

        fig = plt.figure()
        ax = fig.gca(projection='3d')
        X, Y = np.meshgrid(self.grid_x,
                           self.grid_y)  #we create a meshgrid for the plot
        #surf = ax.plot_surface(X, Y, np.abs(msk2), rstride=1,cmap=cm.jet ,cstride=1, linewidth=0)
        surf = ax.plot_surface(X, Y, msk, rstride=1, cstride=1, linewidth=0)
        plt.set_cmap('hot')
Esempio n. 8
0
def setThreshold(fname, aviProps, bg, ths, morphDiameter):    
    cap = cv2.VideoCapture(fname)
    sPlot = [221,222,223,224]
    nFrames = aviProps[6]
    frames = np.random.random_integers(int(nFrames/2), nFrames, 4)
    fig = plt.figure()
    cmap = colormap.gray
    cmap.set_over('r')
    for f in np.arange(0,4):
        cap.set(1,frames[f])
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)      
        bgSubGray = subtractBg(gray, bg)        
        thsGray = applyThreshold(bgSubGray, ths)
        thsGray = erode(thsGray, morphDiameter)
        thsGray = dilate(thsGray, morphDiameter)
        gray[gray==255] = 254
        gray[thsGray==255] = 255
        cOm = ndimage.measurements.center_of_mass(thsGray)
        #if tFrame.sum()/255 < nestThreshold: cOm = nestPosition
        fig.add_subplot(sPlot[f])
        plt.imshow(gray, vmax=254)
        plt.set_cmap(cmap)
        plt.plot(cOm[1],cOm[0], 'o')
    cap.release()
    plt.show()
    return ths, morphDiameter
Esempio n. 9
0
def histogram_equalize():
    global image, extension, image_count, log_path, max_image_count, max_image_count
    if (image.max() != 0):
        image = fun.histeq_im(
            image)  #call the function with the current image in canvas

        ###
        #Some general steps being followed in a image processing functions:
        #(1)clear the canvas
        #(2)draw the image on the canvas
        #(3)increment the image count as this is a new image and store this new image based on image_count to log_folder
        #(4)increment max_image_count which will be used for redo and undo functionalities
        #(5)remove_files() will remove all the images with count greater than the current image_count in the log_folder.
        #this is required in case I have 5 images say, 1,2,3,4,5 I undo and go to 2. Then I do a processing task.
        #then the new processed image will be stored as 3, and 4,5 will be removed from log_folder.
        ###
        fig.clf()
        fig.add_subplot(111)
        im = plt.imshow(image, vmin=0, vmax=255)
        plt.set_cmap('gray')
        canvas.draw()

        max_image_count = image_count + 1
        image_count = image_count + 1
        var.set(image_count)

        #store the image in log_folder

        current_file = log_path + "\\" + str(image_count) + "." + str(
            extension)
        cv2.imwrite(current_file, image)
        remove_files()
    else:
        messagebox.showerror("Error", "Please load an image first.")
Esempio n. 10
0
def load_image():
    global image, script_path, log_path, image_count, extension, max_image_count, view_value
    script_path = os.path.dirname(os.path.realpath(__file__))
    log_path = script_path + "\log_folder"

    file_name = filedialog.askopenfilename(
    )  #opens up the file_system for user to select a file. returns file path
    #print(file_name) #prints the entire file path
    #print(os.path.basename(file_name)) #prints only the actual file name with extension

    if (not (file_name
             == "")):  #in case user clicked on cancel or cross button
        if os.path.exists(
                log_path
        ):  #if the log_folder already exists then delete it and create a new one
            shutil.rmtree(log_path, ignore_errors=True)  #remove the log_folder
            os.makedirs(log_path)
            #image_count=0
        else:
            os.makedirs(log_path)
            #image_count=0
        image_count = 0  #as the image was just loaded
        max_image_count = 0  #as no processing has yet happened on original image
        view_value = "000"  #initializing the values
        var.set(
            image_count
        )  #used to call the callback functions so as to set the proper visibility for the menu options
        var2.set(view_value)

        fig.clf()  #clear the current canvas
        fig.add_subplot(111)  #makes a 1x1 image plot
        #some validations in case a 'gif' file or some other non-image file was selected
        try:
            name, extension = os.path.basename(file_name).split(".")
            if (extension == "gif"):
                raise exception
            image = scipy.ndimage.imread(
                file_name, mode='L')  #read the image into an numpy.ndarray
            im = plt.imshow(
                image, vmin=0, vmax=255
            )  #vmin and vmax are required to specify the gray scales.
            plt.set_cmap('gray')  #setting the colormap
            canvas.draw()  #displaying the image on the canvas

            #increment the image_count and store the current image in the log_folder.
            #will be required for undo and redo operations.
            image_count = image_count + 1
            var.set(image_count)

            #save current image in log_folder as 1.extension eg:1.jpg or 1.png
            current_file = log_path + "\\" + str(image_count) + "." + str(
                extension)
            cv2.imwrite(
                current_file, image
            )  #cv2.imwrite() is better compared to Image.fromarray() as it doesn't manipulate the image.
            #selected cv2 for the file write after I found some images getting manipulated by the rescaling required for Image.fromarray().
        except Exception as e:
            messagebox.showerror(
                title="Can't identify file!!!!",
                message="This file format is currently not supported")
Esempio n. 11
0
def visualize_attention_map_per_token(image,
                                      tokens,
                                      attention_map,
                                      pixel_upscale,
                                      smooth_attention=True,
                                      sigma=None,
                                      **kwargs):
    """
    :param image: PIL image
    :param tokens: list of strings (each being a token)
    :param attention_map: (np.array) for each token an attention map over the image
    :param pixel_upscale: re-scale the KxK input attention_map by this amount (in pixels)
    :param smooth_attention: (opt, boolean) to smooth the displayed attention values
    :param sigma: (opt, float) control ammount of smoothing
    :param kwargs: common parameters for matplotlib {'figsize', 'fontsize'}
    :return: nothing
    """
    figsize = kwargs.pop('figsize', 20)
    fontsize = kwargs.pop('fontsize', 14)

    plt.figure(figsize=(figsize, figsize))
    n_tokens, h, w = attention_map.shape
    if n_tokens != len(tokens):
        raise ValueError('Each token is expected to have an attention map.')

    if h != w:
        warnings.warn('code has not been tested')

    new_im_size = [pixel_upscale * h, pixel_upscale * w]
    image = image.resize(new_im_size, Image.LANCZOS)

    for t in range(n_tokens):
        plt.subplot(np.ceil(n_tokens / 5.), 5, t + 1)
        plt.text(0,
                 1,
                 '%s' % (tokens[t]),
                 color='black',
                 backgroundcolor='white',
                 fontsize=fontsize)
        plt.imshow(image)
        current_alpha = attention_map[t][:]

        if smooth_attention:
            alpha = skimage.transform.pyramid_expand(current_alpha,
                                                     upscale=pixel_upscale,
                                                     sigma=sigma,
                                                     multichannel=False)
        else:
            alpha = skimage.transform.resize(current_alpha, new_im_size)

        if t == 0:
            plt.imshow(alpha, alpha=0)
        else:
            plt.imshow(alpha, alpha=0.8)

        plt.set_cmap(cm.Greys_r)
        plt.axis('off')
    plt.show()
Esempio n. 12
0
def ShowMatrix(X, title=''):
    plt.figure()
    plt.imshow(X, interpolation='nearest',vmax=5,vmin=0)
    plt.colorbar()
    plt.set_cmap('jet')
    plt.xlabel('profiles')
    plt.ylabel('features')
    plt.title(title)
    plt.show()
Esempio n. 13
0
def make_image(data, outputname, size=(1, 1), dpi=100):
    fig = plt.figure()
    fig.set_size_inches(size)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    plt.set_cmap('gray')
    ax.imshow(data, aspect='equal', interpolation='nearest')
    plt.savefig(outputname, dpi=dpi)
    plt.close()
Esempio n. 14
0
def sitk_show(img, title=None, margin=0.05, dpi=40, cmap="gray"): 
    nda = sitk.GetArrayFromImage(img)
    spacing = img.GetSpacing()
    figsize = (1 + margin) * nda.shape[0] / dpi, (1 + margin) * nda.shape[1] / dpi
    extent = (0, nda.shape[1]*spacing[1], nda.shape[0]*spacing[0], 0)
    fig = plt.figure(figsize=figsize, dpi=dpi)
    ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])
    plt.set_cmap(cmap) 
    ax.imshow(nda,extent=extent,interpolation=None)
    if title:
        plt.title(title)
Esempio n. 15
0
def undo_all():
    global image, extension, image_count, log_path
    image_count = 1  #set callback to affect the views accordingly
    var.set(image_count)

    first_file = log_path + "\\" + str(image_count) + "." + str(extension)
    image = scipy.ndimage.imread(first_file, mode='L')

    fig.clf()
    fig.add_subplot(111)
    im = plt.imshow(image, vmin=0, vmax=255)
    plt.set_cmap('gray')
    canvas.draw()
Esempio n. 16
0
def redo_all():
    global image, extension, image_count, log_path
    image_count = max_image_count
    var.set(image_count)

    last_file = log_path + "\\" + str(image_count) + "." + str(extension)
    image = scipy.ndimage.imread(last_file, mode='L')

    fig.clf()
    fig.add_subplot(111)
    im = plt.imshow(image, vmin=0, vmax=255)
    plt.set_cmap('gray')
    canvas.draw()
Esempio n. 17
0
def butterworth_sharpen():
    global image, extension, image_count, log_path, max_image_count, lab_5_data, lab_6_data, lab_7_data, error_flag_1, error_flag_2, error_flag_3, butter_width, butter_order, butter_a, popup_true
    if (image.max() != 0):
        #ask the user if he wishes to use the default parameter values
        answer = messagebox.askyesno(
            "Settings", "Do you want to use default settings?\n" +
            "width=3, order=2, a=0.5")
        if (answer == True):
            image = fun.butterworth_highpass_filter(image, 3, 2, 0.5)
            #general steps
            fig.clf()
            fig.add_subplot(111)
            im = plt.imshow(image, vmin=0, vmax=255)
            plt.set_cmap('gray')
            canvas.draw()

            max_image_count = image_count + 1
            image_count = image_count + 1
            var.set(image_count)

            #store the image in log_folder

            current_file = log_path + "\\" + str(image_count) + "." + str(
                extension)
            cv2.imwrite(current_file, image)
            remove_files()
        else:
            ###initialize the variables before calling popup
            lab_5_data.set("")
            lab_6_data.set("")
            lab_7_data.set("")

            error_flag_1 = 0
            error_flag_2 = 0
            error_flag_3 = 0

            butter_width = ""
            butter_order = ""
            butter_a = ""
            popup_true = 0
            ###
            popupmsg()
    else:
        messagebox.showerror("Error", "Please load an image first.")
Esempio n. 18
0
def diff_images(fname1, fname2, output="diff.png"):
    """
    Creates a file `output` that represents a diff of two input images
    `fname1` and `fname`. If these are .pdf, they will be first converted to .png.
    Example:
    >>> utils.diff_images("examples/test1.pdf", "examples/test3.pdf", output="diff.png")
    >>> os.system("ic diff.png")
    """
    import numpy as np
    import matplotlib.pylab as plt
    conversion_cmd = "gs -q -sDEVICE=pngalpha -o {outname} -sDEVICE=pngalpha -dUseCropBox -r{density} {inname}"
    # conversion_cmd = "convert -density {density} -trim {inname} -fuzz 1% {outname}"
    new_fnames = []
    for fname in [fname1, fname2]:
        if fname.rsplit(".", 1)[-1] == "pdf":
            fname_in = fname
            fname_out = fname.replace(".pdf", ".png")
            os.system(
                conversion_cmd.format(density=75,
                                      inname=fname_in,
                                      outname=fname_out))
            new_fnames.append(fname_out)
    if len(new_fnames) == 2: fname1, fname2 = new_fnames
    # img1 = plt.imread(fname1)[::2,::2] # downsample by factor of 2
    # img2 = plt.imread(fname2)[::2,::2]
    img1 = plt.imread(fname1)
    img2 = plt.imread(fname2)

    # Calculate the absolute difference on each channel separately
    error_r = np.fabs(np.subtract(img2[:, :, 0], img1[:, :, 0]))
    error_g = np.fabs(np.subtract(img2[:, :, 1], img1[:, :, 1]))
    error_b = np.fabs(np.subtract(img2[:, :, 2], img1[:, :, 2]))

    lum_img = np.sqrt(error_r * error_r + error_g + error_g +
                      error_b * error_b) / np.sqrt(3)

    # # # Calculate the maximum error for each pixel
    # lum_img = np.maximum(np.maximum(error_r, error_g), error_b)

    # plt.set_cmap('Spectral')
    plt.set_cmap('gray')
    plt.imsave(output, -lum_img)
Esempio n. 19
0
def processLyrics(lyrics, name):
	arr1 = lyrics.split()
	length = len(arr1)
	song = [[0 for x in range(length)] for y in range(length)]

	for i in range(length):
		for j in range(length):
			if arr1[i] == arr1[j]:
				song[i][j] = colorIntensity(arr1[i])
				song[j][i] = colorIntensity(arr1[i])

	fig, ax0 = plt.subplots(1)
	plt.set_cmap(colorspace)
	plt.gca().invert_yaxis()

	ax0.pcolor(song)
	ax0.set_title(name)
	fig.tight_layout()
	plt.savefig(dirname + '/graphs/' + name[:-4] + '.png')
	plt.close()
Esempio n. 20
0
def undo_last():
    global image, extension, image_count, log_path
    image_count = image_count - 1  #image_count always holds the count of my current image displayed in canvas
    var.set(
        image_count
    )  #set callback to change the views of options that are affected by image_count change accordingly

    if (image_count == 1):
        #image_count=image_count+1
        #messagebox.showwarning("Original image", "Can't undo further.")
        editmenu.entryconfigure('undo last', state="disabled")

    prev_file = log_path + "\\" + str(image_count) + "." + str(extension)
    image = scipy.ndimage.imread(prev_file, mode='L')

    fig.clf()
    fig.add_subplot(111)
    im = plt.imshow(image, vmin=0, vmax=255)
    plt.set_cmap('gray')
    canvas.draw()
Esempio n. 21
0
def plot_decision_surface(axes, clf, X, Y):
    import matplotlib.pylab as pylab
    import numpy as np
    # step size in the mesh
    h = (np.max(X, axis=0) - np.min(X, axis=0)) / 100.0
    # create a mesh to plot in
    x_min = np.min(X, axis=0) - 1
    x_max = np.max(X, axis=0) + 1
    xx, yy = np.meshgrid(np.arange(x_min[0], x_max[0], h[0]),
                         np.arange(x_min[1], x_max[1], h[1]))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    pylab.set_cmap(pylab.cm.Paired)
    pylab.axes(axes)
    pylab.contourf(xx, yy, Z, cmap=pylab.cm.Paired)
    #pylab.axis('off')

    # Plot also the training points
    pylab.scatter(X[:,0], X[:,1], c=Y)
Esempio n. 22
0
def fourier_phase():
    global image, extension, image_count, log_path, max_image_count, view_value, plot_number
    if (image.max() != 0):
        if (
                plot_number == 121
        ):  #because this function will be called two times in display_original()
            fig.clf()
        fig.add_subplot(plot_number)  #dynamically change the grid plot
        im = plt.imshow(image, vmin=0, vmax=255)
        plt.set_cmap('gray')

        phase_image = fun.find_fft_phase(image)
        fig.add_subplot(plot_number + 1)
        im = plt.imshow(phase_image, vmin=0, vmax=255)
        plt.set_cmap('gray')

        canvas.draw()
        view_value = "001"  #set the callback so that the display image option is enabled
        var2.set(view_value)
    else:
        messagebox.showerror("Error", "Please load an image first.")
Esempio n. 23
0
    def draw(self):
        plt.imshow(
            self._original_values.T,
            interpolation='none',
            origin='lower',
            extent=[
                self._origin[X],
                self._origin[X] + self._values.shape[0] * self._resolution,
                self._origin[Y],
                self._origin[Y] + self._values.shape[1] * self._resolution
            ])
        # # for debug
        # for i in range(self._values.shape[0]):
        #   for j in range(self._values.shape[1]):
        #     if np.random.rand() < 0.4:
        #       pos = self.get_position(i, j)
        #       if not self.is_free(pos):
        #         plt.scatter(pos[0], pos[1], s=3, marker='o', color='red')
        #   print(i)

        plt.set_cmap('gray_r')
Esempio n. 24
0
def plot_gmm(axes, classifier, clusters, X, Y=None):
    import matplotlib.pylab as pl
    import numpy as np

    def make_ellipses(gmm, ax, cm):
        global pca
        import matplotlib as mpl
        #for n, color in enumerate('rgb'):
        for n in xrange(gmm.means.shape[0]): 
            var = gmm.covars[n][np.identity(gmm.means.shape[1], dtype=bool)]
            v = pca.transform(var)
            #v, w = np.linalg.eigh(gmm.covars[n][:2, :2])
            #u = w[0] / np.linalg.norm(w[0])
            #angle = np.arctan(u[1] / u[0])
            #angle = 180 * angle / np.pi  # convert to degrees
            #v *= 9
            #v /= 10.0
            means = pca.transform(gmm.means[n, :])
            ell = mpl.patches.Ellipse(means, v[0], v[1], 0,
                                      color=cm(n), alpha=0.5)
            ell.set_clip_box(ax.bbox)
            ell.set_alpha(0.5)
            ax.add_artist(ell)

    cm = pl.cm.Paired
    pl.set_cmap(cm)

    h = pl.subplot(1, 1, 1)
    make_ellipses(classifier, h, cm)

    # Plot also the training points
    if Y is not None:
        pl.scatter(X[:,0], X[:,1], c=Y)
    else:
        pl.scatter(X[:,0], X[:,1])

    pl.xticks(())
    pl.yticks(())

    pl.scatter(clusters[:,0], clusters[:,1], s=200, marker='x', color='black')
Esempio n. 25
0
def gamma_correct():
    global image, extension, image_count, log_path, max_image_count, max_image_count
    if (image.max() != 0):
        #ask for a user defined gamma value
        gamma = simpledialog.askfloat("Input",
                                      "Enter gamma value:",
                                      parent=root,
                                      minvalue=0.0)
        if (
                gamma is not None
        ):  #None will be when user clicks cancel. in that case no processing is done.
            image_bkp = fun.gamma_im(image, gamma)
            if (
                    image_bkp is None
            ):  #If user enters a high value of gamma then can give exception. Function returns None in case of such exception
                messagebox.showerror("Error",
                                     "Please use a lower value of gamma.")
            else:
                image = image_bkp

                #general steps
                fig.clf()
                fig.add_subplot(111)
                im = plt.imshow(image, vmin=0, vmax=255)
                plt.set_cmap('gray')
                canvas.draw()

                max_image_count = image_count + 1
                image_count = image_count + 1
                var.set(image_count)

                #store the image in log_folder

                current_file = log_path + "\\" + str(image_count) + "." + str(
                    extension)
                cv2.imwrite(current_file, image)
                remove_files()
    else:
        messagebox.showerror("Error", "Please load an image first.")
Esempio n. 26
0
def log_transform():
    global image, extension, image_count, log_path, max_image_count
    if (image.max() != 0):
        image = fun.log_trans_im(image)
        #general steps
        fig.clf()
        fig.add_subplot(111)
        im = plt.imshow(image, vmin=0, vmax=255)
        plt.set_cmap('gray')
        canvas.draw()

        max_image_count = image_count + 1
        image_count = image_count + 1
        var.set(image_count)

        #store the image in log_folder

        current_file = log_path + "\\" + str(image_count) + "." + str(
            extension)
        cv2.imwrite(current_file, image)
        remove_files()
    else:
        messagebox.showerror("Error", "Please load an image first.")
def scaling_plot(df, zcol, title, zdas=None, xcol='numIsilonNodes', xlabel=None, ycol='numPhysicalComputeNodes', ylabel=None):
    if xlabel == None: xlabel = xcol
    if ylabel == None: ylabel = ycol
    
    x = df[xcol].values
    y = df[ycol].values
    z = df[zcol].values
    
    # Set up a regular grid of interpolation points
    xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100)
    xi, yi = np.meshgrid(xi, yi)
    
    # Interpolate
    zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='cubic')
    
    fig = plt.figure(title)
    fig.clf()
    plt.set_cmap(cm.jet)
    plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
            extent=[x.min(), x.max(), y.min(), y.max()], aspect='auto')
    # Draw circles on actual measurement points
    plt.scatter(x, y, c=z)
    plt.colorbar()
    CS = plt.contour(xi, yi, zi, colors='k')
    plt.clabel(CS, inline=1, fontsize=10, fmt='%1.0f')

    if zdas is not None:
        dasNodes = np.arange(df.numPhysicalComputeNodes.min(), 2 * df.numPhysicalComputeNodes.max() + 1)
        dasZ = zdas * dasNodes
        CS = plt.contour(xi, yi, zi, colors='k', linestyles='dashed', levels=dasZ)
        fmtdict = {x[1]: 'DAS ' + str(int(x[0])) for x in zip(dasNodes, dasZ)}
        plt.clabel(CS, inline=1, fontsize=10, fmt=fmtdict)
    
    plt.title(title)
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    plt.show()    
Esempio n. 28
0
def popup_return():
    global image, extension, image_count, log_path, max_image_count, lab_5_data, lab_6_data, lab_7_data, error_flag_1, error_flag_2, error_flag_3, butter_width, butter_order, butter_a, popup_true
    #print(butter_width)
    #print(butter_order)
    #print(butter_a)

    image = fun.butterworth_highpass_filter(image, butter_width, butter_order,
                                            butter_a)
    #general steps
    fig.clf()
    fig.add_subplot(111)
    im = plt.imshow(image, vmin=0, vmax=255)
    plt.set_cmap('gray')
    canvas.draw()

    max_image_count = image_count + 1
    image_count = image_count + 1
    var.set(image_count)

    #store the image in log_folder

    current_file = log_path + "\\" + str(image_count) + "." + str(extension)
    cv2.imwrite(current_file, image)
    remove_files()
Esempio n. 29
0
def main():
    hemi = 1
    prop = 0.5
    varthresh = 0
    savefig = 1

    # file i/o
    file_base = 'lgnROI{}_comVoxGroupCoords_'.format(hemi)
    analysis_extension = 'betaM-P_prop{}_varThresh{:0^3}'.format(
        int(prop*100), int(varthresh*1000))
    data_path = glob.glob(file_base + analysis_extension + '*')[0]

    # import lgn data
    data = sio.loadmat(data_path)
    X = data['voxCoords']
    Y = data['voxGroups']
    Y = np.squeeze(Y)

    colors = np.array([[220, 20, 60],[0, 0, 205]])
    colors = colors/255.0
    cols = np.zeros((np.size(Y),3))
    for c in np.arange(np.size(Y)):
        cols[c,] = colors[Y[c]-1,]

    # we create an instance of SVM and fit out data. We do not scale our
    # data since we want to plot the support vectors
    C = 1  # SVM regularization parameter
    lin_svc = svm.SVC(kernel='linear', C=C).fit(X, Y)
    rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, Y)
    poly3_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, Y)
    poly2_svc = svm.SVC(kernel='poly', degree=2, C=C).fit(X, Y)


    # create a mesh to plot in
    x_min, x_max = X[:, 0].min(), X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min(), X[:, 1].max() + 1
    z_min, z_max = X[:, 2].min(), X[:, 2].max() + 1

    # make 3 3D meshgrid matrices. 3rd dimension is the z (inplane slice) dimension
    xx, yy, zz = np.mgrid[x_min:x_max, y_min:y_max, z_min:z_max] # add :30j to make 30 equally spaced points

    # title for the plots
    titles = ['SVC with linear kernel',
              'SVC with RBF kernel',
              'SVC with polynomial (degree 3) kernel',
              'SVC with polynomial (degree 2) kernel']

    # set plot parameters
    """
    n_levels is the number of contour levels. eg. 1 draws 1 contour
    slice_dim is whether slices will be by y (coronal, slice_dime=1) 
              or z (axial, slice_dim=2)
    """
    n_levels = 1
    slice_dim = 1
    pl.set_cmap(pl.cm.RdBu)
    # turn interactive mode on, so that pl.show() won't wait for the figure to be closed before continuing
    # pl.ion()

    for i, clf in enumerate((lin_svc, rbf_svc, poly3_svc, poly2_svc)):
        # Plot the decision boundary. For that, we will asign a color to each
        # point in the mesh [x_min, m_max]x[y_min, y_max].
        fig = pl.figure()
        Z = clf.predict(np.c_[xx.ravel(), yy.ravel(), zz.ravel()])

        # Put the result into a color plot
        Z = Z.reshape(xx.shape)

        if slice_dim == 2:
            if i==0:
                print 'slicing axial'
            slices = np.unique(X[:,2])
            for j in np.arange(np.size(Z,2)):
                pl.subplot(2, 3, j + 1)   
                in_slice = X[:,2]==slices[j]
 
                # Plot the contour and the training points
                pl.contourf(xx[:,:,j], yy[:,:,j], Z[:,:,j], n_levels)
                pl.scatter(X[in_slice, 0], X[in_slice, 1], c=cols[in_slice,])
    
        elif slice_dim == 1:
            if i==0:
                print 'slicing coronal'
            slices = np.unique(X[:,1])
            for j in np.arange(np.size(Z,1)):
                pl.subplot(3, 4, j + 1)   
                in_slice = X[:,1]==slices[j]

                # Plot the contour and the training points
                pl.contourf(xx[:,j,:], zz[:,j,:], Z[:,j,:], n_levels)
                pl.scatter(X[in_slice, 0], X[in_slice, 2], c=cols[in_slice,]) 

        pl.suptitle(titles[i])
        pl.show()
        
        if i==0 and savefig:
            print 'saving fig'
            pl.savefig('figures/lgnROI{}MapCoronal_spatialSVMLin_{}_{:%Y%m%d}.png'.format(
            hemi, analysis_extension, datetime.datetime.today()))

    return lin_svc
Esempio n. 30
0
def vPrep(fname, saveDir, check=True):
    fileName = va.getFileName(fname)
    aviProps = va.getAVIinfo(fname)
    plt.ion()

    # fBackground frames
    # -----------------
    # Default values
    nFrames = 10

    bgOK = False
    bgFile = saveDir + "/bg.npy"
    if os.path.isfile(bgFile):
        print("Background file exists, loading...")
        bg = np.load(bgFile)
    else:
        print("Generating background with default settings...")
        bg = va.getBg(fname, aviProps, nFrames)
    if check:
        while not bgOK:
            plt.figure()
            plt.imshow(bg)
            plt.set_cmap('gray')
            plt.show()
            uDecision = raw_input("Background OK? [y]es; [n]o ")
            if uDecision == 'y':
                bgOK = True
            else:
                uframes = raw_input("Select number of frames ")
                bg = va.getBg(fname, aviProps, int(uframes))
    np.save(saveDir + 'bg', bg)
    print('Background file saved')

    # Threshold
    # --------------
    # Default values
    ths = 40
    morphDiameter = 10

    pmtsFileExists = False
    thsOK = False
    pmtsFile = saveDir + "/pmts.npy"
    if os.path.isfile(pmtsFile):
        print("Parameters file exists, loading...")
        pmtsFileExists = True
        filePmts = np.load(pmtsFile)
        ths, morphDiameter = va.setThreshold(fname, aviProps, bg,
                                             filePmts[0][0], filePmts[1][0])
    else:
        print("Generating threshold with default settings...")
        ths, morphDiameter = va.setThreshold(fname, aviProps, bg, ths,
                                             morphDiameter)
    if check:
        while not thsOK:
            uDecision = raw_input("Threshold OK? [y]es; [n]o ")
            if uDecision == 'y':
                thsOK = True
            else:
                while True:
                    try:
                        print "Current threshold is", ths
                        uths = int(raw_input("Select new threshold "))
                        print "Current diameter is", morphDiameter
                        umorph = int(
                            raw_input(
                                "Select new diameter to erode and dilate "))
                        break
                    except ValueError:
                        print("Invalid number, please try again ")
                ths, morphDiameter = va.setThreshold(fname, aviProps, bg, uths,
                                                     umorph)

    # Arena areas
    # --------------
    # Default values
    nestPos = [125, 220]
    nestArea = [(1, 320), (225, 320), (120, 125)]
    arenaCenter = [600, 244]
    foodArea = [(785, 360), (960, 360), (860, 185)]

    plt.ioff()
    arenaOk = False
    if pmtsFileExists:
        print("Using parameters file...")
        va.plotArena(aviProps, filePmts, bg)
        pmts = [[ths], [morphDiameter], filePmts[2], filePmts[3], filePmts[4],
                filePmts[5]]
    else:
        print("Generating arena with default settings...")
        pmts = [[ths], [morphDiameter], nestPos, nestArea, arenaCenter,
                foodArea]
        va.plotArena(aviProps, pmts, bg)
    if check:
        while not arenaOk:
            uDecision = raw_input("Arena OK? [y]es; [n]o ")
            if uDecision == 'y':
                arenaOk = True
            else:
                print("Select new arena ")
                points = va.setPoints(fname, aviProps, bg)
                pmts = [[ths], [morphDiameter], points[0], points[1],
                        points[2], points[3]]

    #print pmts[0], pmts[1]
    #fsaveName = saveDir + fileName.rstrip(".avi") + "_pmts"
    np.save(saveDir + 'pmts', pmts)
    print('Parameters file saved')
Esempio n. 31
0
import keras.backend as K
from keras.models import model_from_json
from keras import optimizers
import matplotlib.pylab as plt
import numpy as np
import theano.tensor.nnet.abstract_conv as absconv
import cv2
import os
from PIL import Image
from glob import glob
#import imp
#cmaps = imp.load_source('colormaps','/home/jmiller/Dropbox/cnn_stuff/colormap/colormaps.py')
# colorScale='plasma'
#plt.register_cmap(name=colorScale, cmap=cmaps.plasma)
plt.set_cmap('jet')

home = os.environ['HOME']


def get_img(img_path):
    # Load image
    print(img_path)
    original_image = cv2.imread(img_path)
    img = original_image
    if img.shape[0] != 256:
        img = cv2.resize(img, (256, 256), interpolation=cv2.INTER_AREA)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    X = img / 1.
    X = X.astype('float32')
    X = np.rollaxis(X, 2)
Esempio n. 32
0
def vPrep(fname, saveDir, check=True):
  fileName = va.getFileName(fname)
  aviProps = va.getAVIinfo(fname)
  plt.ion()

  # fBackground frames
  # -----------------
  # Default values
  nFrames = 10

  bgOK = False
  bgFile = saveDir + "/bg.npy"
  if os.path.isfile(bgFile):
    print("Background file exists, loading...")
    bg = np.load(bgFile)
  else:
    print("Generating background with default settings...")
    bg  = va.getBg(fname, aviProps, nFrames)
  if check:
    while not bgOK:
      plt.figure()
      plt.imshow(bg)
      plt.set_cmap('gray')
      plt.show()
      uDecision = raw_input("Background OK? [y]es; [n]o ")
      if uDecision=='y': 
          bgOK = True
      else:
          uframes = raw_input("Select number of frames ")
          bg  = va.getBg(fname, aviProps, int(uframes))
  np.save(saveDir + 'bg', bg)
  print('Background file saved')

  # Threshold
  # --------------
  # Default values
  ths = 40
  morphDiameter = 10

  pmtsFileExists = False
  thsOK = False
  pmtsFile = saveDir + "/pmts.npy"
  if os.path.isfile(pmtsFile):
    print("Parameters file exists, loading...")
    pmtsFileExists = True
    filePmts = np.load(pmtsFile)
    ths, morphDiameter = va.setThreshold(fname, aviProps, bg, filePmts[0][0], filePmts[1][0])
  else:
    print("Generating threshold with default settings...")
    ths, morphDiameter = va.setThreshold(fname, aviProps, bg, ths, morphDiameter)
  if check:
    while not thsOK:
      uDecision = raw_input("Threshold OK? [y]es; [n]o ")
      if uDecision=='y': 
          thsOK = True
      else:
          while True:
              try:
                  print "Current threshold is", ths
                  uths = int(raw_input("Select new threshold "))
                  print "Current diameter is", morphDiameter
                  umorph = int(raw_input("Select new diameter to erode and dilate "))
                  break
              except ValueError:
                  print("Invalid number, please try again ")
          ths, morphDiameter = va.setThreshold(fname, aviProps, bg, uths, umorph)

  # Arena areas
  # --------------
  # Default values
  nestPos = [125, 220]
  nestArea = [(1,320),(225,320),(120,125)]
  arenaCenter = [600,244]
  foodArea = [(785,360),(960,360),(860,185)]

  plt.ioff()
  arenaOk = False
  if pmtsFileExists:
    print("Using parameters file...")
    va.plotArena(aviProps, filePmts, bg)
    pmts = [[ths], [morphDiameter], filePmts[2], filePmts[3], filePmts[4], filePmts[5]]
  else:
    print("Generating arena with default settings...")
    pmts = [[ths], [morphDiameter], nestPos, nestArea, arenaCenter, foodArea]
    va.plotArena(aviProps, pmts, bg)
  if check:
    while not arenaOk:
      uDecision = raw_input("Arena OK? [y]es; [n]o ")
      if uDecision=='y':
          arenaOk = True
      else:
          print("Select new arena ")	
          points = va.setPoints(fname, aviProps, bg)
          pmts = [[ths], [morphDiameter], points[0], points[1], points[2], points[3]]

  #print pmts[0], pmts[1]
  #fsaveName = saveDir + fileName.rstrip(".avi") + "_pmts"
  np.save(saveDir + 'pmts', pmts)
  print('Parameters file saved')
Esempio n. 33
0
Y_for_lasso = (observedX[1:, :] - observedX[:-1, :]) / ddt

lasso = Lasso(alpha=0.01)

lasso.fit(X_for_lasso, Y_for_lasso)

plt.subplot(1, 2, 1)
plt.plot(time_idxs, observedX)
plt.legend([str(i + 1) for i in range(n)])

predicted = [i for e in lasso.coef_ for i in e]
W0_plus_flat = [i for e in W0_plus for i in e]

predicted_null = [
    abs(predicted[i]) for i, v in enumerate(W0_plus_flat) if v == 0
]
predicted_not_nul = [
    abs(predicted[i]) for i, v in enumerate(W0_plus_flat) if not v == 0
]

plt.subplot(1, 2, 2)
plt.set_cmap('bwr')
plt.plot(range(len(predicted_null)), predicted_null, 'o', color='#336688')
plt.plot(range(len(predicted_not_nul)),
         predicted_not_nul,
         'o',
         color='#FF9900')
plt.title('Difference')

plt.show()
Esempio n. 34
0
mnist_path = os.path.join(os.environ['PYDEEP_HOME'], 'demo',  'mnist', 'train-images-idx3-ubyte.npy')
data = np.load(mnist_path).astype('float') / 255
train = data
tp = NetTrainParams()
tp.maxepoch=200
tp.batchsize=100
tp.eta = scalar_schedule.ConstantSchedule(0.01)
tp.mu  = scalar_schedule.ConstantSchedule(0.5)
arch = [784, 100, 784]
lts=['Logistic', 'Linear']
regs = [NetReg() for lt in lts]
for reg in regs:
    reg.dropout=True
    reg.drop_rate = 0.5
    reg.max_constraint = True
    reg.max_unit_weight = 10
regs[0].drop_rate = 0.2
net = Net(arch, lts, regs)
train_sgd(net, train, train, tp)

Wimg = pydeep.utils.utils.tile_raster_images(net.layers[0].W.transpose(), (28,28), (10,10))

plt.figure(1)
plt.imshow(Wimg)
plt.set_cmap('gray')
plt.axis('off')
plt.show()






clf = LogisticRegression(penalty='l1',C=2)

clf.fit(X_for_lasso,Y_for_lasso)


plt.subplot(1,2,1)
plt.plot(time_idxs,observedX)
plt.legend([str(i+1) for i in range(n)])


predicted = [i for e in clf.coef_ for i in e]
W0_plus_flat = [i for e in W0_plus for i in e]

predicted_null = [abs(predicted[i]) for i,v in enumerate(W0_plus_flat) if v==0]
predicted_not_nul = [abs(predicted[i]) for i,v in enumerate(W0_plus_flat) if not v==0]


plt.subplot(1,2,2)
plt.set_cmap('bwr')
plt.plot(range(len(predicted_null)),predicted_null,'o',color='#336688')
plt.plot(range(len(predicted_not_nul)),predicted_not_nul,'o',color='#FF9900')
plt.title('Difference')



plt.show()
def example2():

	#----------------------------------------
	#The connection matrix as shown in Figure 1a of the paper
	#----------------------------------------
	A0 = [[0.0,0.7,0.32,0.0,0.0,0.04],[0.7,0.0,0.9,0.0,0.0,0.0],[0.845,0.91,0.75,0.11,0.0,0.0],[0.13,0.6,0.68,0.0,0.22,0.0],[0.69,0.0,0.0,0.0,0.0,0.0],[0.0,0.27,0.0,0.95,0.375,0.0]]

	#----------------------------------------
	#This is the original time series data Figure 2, note that the initial conditions are randomly generated (from a normal distribution) so some of the values may vary
	#----------------------------------------
	t = [0.0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0]
	x = [   [0.5688,0.4694,0.0119,0.3371,0.1622,0.7943],
		 	[0.4700,0.3889,0.0182,0.5690,0.2533,0.9345],
	 		[0.3890,0.3202,0.0205,0.7603,0.3307,1.0324],
			[0.3229,0.2629,0.0240,0.9173,0.3951,1.0819],
			[0.2689,0.2155,0.0297,1.0459,0.4483,1.0910],
			[0.2245,0.1766,0.0368,1.1508,0.4920,1.0744],
			[0.1880,0.1446,0.0444,1.2363,0.5278,1.0443],
			[0.1578,0.1184,0.0517,1.3058,0.5572,1.0085],
			[0.1327,0.0970,0.0585,1.3623,0.5813,0.9715],
			[0.1118,0.0794,0.0646,1.4081,0.6010,0.9358],
			[0.0944,0.0650,0.0699,1.4453,0.6171,0.9027],
			[0.0799,0.0532,0.0746,1.4753,0.6303,0.8726],
			[0.0677,0.0436,0.0786,1.4996,0.6411,0.8456],
			[0.0575,0.0357,0.0821,1.5192,0.6500,0.8219],
			[0.0490,0.0292,0.0850,1.5350,0.6572,0.8010],
			[0.0418,0.0239,0.0875,1.5478,0.6632,0.7829],
			[0.0358,0.0196,0.0896,1.5581,0.6680,0.7672],
			[0.0308,0.0160,0.0913,1.5664,0.6720,0.7536],
			[0.0266,0.0131,0.0928,1.5730,0.6753,0.7420],
			[0.0231,0.0107,0.0941,1.5784,0.6780,0.7320],
			[0.0201,0.0088,0.0951,1.5827,0.6801,0.7235] ]

	
	#Plot the time series by using
	
	import matplotlib.pylab as plt
	plt.plot(np.matrix(t).T,np.matrix(x))
	plt.xlabel('Time')
	plt.ylabel('Gene regulation')
	plt.savefig('example2_time_series.png')
	

	#----------------------------------------
	#the function for example 2 as shown in Eq.1 of the paper
	#----------------------------------------
	def f(x):
		return - x
	def h(x,i,k):
		if k < 3:
			return x**5 / (1.0+x**5)
		else:
			return 1.0 / (1.0+x**5)

	reconstructed_A = network_reconstruction(x,A0,f,h,R=10)

		
	#Visualize the original adjacency matrix and the predicted one and compare you can use
	
	import matplotlib.pylab as plt
	fig, axes = plt.subplots(nrows=1, ncols=3)


	plt.set_cmap('bwr')
	vmin,vmax = -1,1
	im = axes.flat[0].imshow(A0,interpolation='none', vmin=vmin, vmax=vmax)
	axes.flat[0].set_title('Original A')
	plt.set_cmap('bwr')
	im = axes.flat[1].imshow(reconstructed_A,interpolation='none', vmin=vmin, vmax=vmax)
	axes.flat[1].set_title('Reconstructed A')
	plt.set_cmap('bwr')
	im = axes.flat[2].imshow(np.abs(reconstructed_A-A0),interpolation='none', vmin=vmin, vmax=vmax)
	axes.flat[2].set_title('Difference')

	fig.subplots_adjust(right=0.8)
	cbar_ax = fig.add_axes([0.85, 0.35, 0.02, 0.3])
	fig.colorbar(im, cax=cbar_ax)
	plt.savefig('example2_adjacency_matrix.png')
Esempio n. 37
0
    def __init__(self, orbit=8020, debug=False, digitization_db=None, load=True,
        auto=True,
        vmin=-16.0, vmax=-11.0, mobile=False, figure_number=1, timeseries_frequency=0.3):

        global ais_tool_instance
        ais_tool_instance = super(AISTool, self).__init__()

        # A few basic parameters
        self.status = None
        self.current_ionogram = None
        self.debug = debug
        self.orbit = None
        self.browsing = False
        self.minimum_interaction_mode = False
        self._initial_digitization_db = digitization_db
        self._digitization_saved = False
        self.load = load

        self.auto = auto

        self.ionospheric_model = celsius.mars.Morgan2008ChapmanLayer()

        np.seterr(all='ignore')

        self.params = dict(auto_refine=False, substitute_fp=ais.ne_to_fp(4.))

        self._bad_keypress = False
        self._messages = []
        self._message_counter = 0
        plt.set_cmap('viridis')
        self.selected_plasma_lines = []
        self.selected_cyclotron_lines = []

        self.timeseries_frequency = timeseries_frequency

        self.vmin = vmin
        self.vmax = vmax

        mex.check_spice_furnsh()

        # Set up the figure
        # self.figure = plt.figure(figsize=(12, 6))
        figsize = (20, 12)
        if mobile:
            figsize = (17, 8)
        plt.close(figure_number)
        self.figure = plt.figure(figure_number, figsize=figsize, facecolor='0.6')
        g = mpl.gridspec.GridSpec(6, 2, width_ratios=[1,0.34],
            height_ratios=[0.001, 0.001, 7,5,2,16], wspace=0.16, hspace=0.1,
            left=0.05, right=0.95, bottom=0.08, top=0.95)

        # self.stat_ax = plt.subplot(g[0,:])
        # self.traj_ax = plt.subplot(g[1,:])
        self.tser_ax = plt.subplot(g[2,:])
        self.freq_ax = plt.subplot(g[3,:])
        self.ig_ax   = plt.subplot(g[5,0])
        self.ne_ax   = plt.subplot(g[5,1])
        self.cbar_ax = plt.gcf().add_axes([0.45,  0.04, 0.3, 0.01])

        # self.fp_local_figure_number = figure_number + 1
        # self.td_cyclotron_figure_number = figure_number + 2

        self.fp_local_figure_number = False
        self.td_cyclotron_figure_number = False

        self.stored_color = 'white'
        self.interactive_color = 'red'

        # All the connections get set up:
        self.cids = []
        self.cids.append(self.figure.canvas.mpl_connect('key_press_event',
                                            self.on_keypress))
        self.cids.append(self.figure.canvas.mpl_connect('button_press_event',
                                            self.on_click))
        self.cids.append(self.figure.canvas.mpl_connect('button_release_event',
                                            self.on_release))
        self.cids.append(self.figure.canvas.mpl_connect('motion_notify_event',
                                            self.on_move))
        self.cids.append(self.figure.canvas.mpl_connect('scroll_event',
                                            self.on_scroll))

        self.message("Initialized")

        plt.show()
        self.set_orbit(orbit)
        self.update()
Esempio n. 38
0
def main():
    hemi = 1
    prop = 0.5
    varthresh = 0
    savefig = 1

    # file i/o
    file_base = 'lgnROI{}_comVoxGroupCoords_'.format(hemi)
    analysis_extension = 'betaM-P_prop{}_varThresh{:0^3}'.format(
        int(prop * 100), int(varthresh * 1000))
    data_path = glob.glob(file_base + analysis_extension + '*')[0]

    # import lgn data
    data = sio.loadmat(data_path)
    X = data['voxCoords']
    Y = data['voxGroups']
    Y = np.squeeze(Y)

    colors = np.array([[220, 20, 60], [0, 0, 205]])
    colors = colors / 255.0
    cols = np.zeros((np.size(Y), 3))
    for c in np.arange(np.size(Y)):
        cols[c, ] = colors[Y[c] - 1, ]

    # we create an instance of SVM and fit out data. We do not scale our
    # data since we want to plot the support vectors
    C = 1  # SVM regularization parameter
    lin_svc = svm.SVC(kernel='linear', C=C).fit(X, Y)
    rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, Y)
    poly3_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, Y)
    poly2_svc = svm.SVC(kernel='poly', degree=2, C=C).fit(X, Y)

    # create a mesh to plot in
    x_min, x_max = X[:, 0].min(), X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min(), X[:, 1].max() + 1
    z_min, z_max = X[:, 2].min(), X[:, 2].max() + 1

    # make 3 3D meshgrid matrices. 3rd dimension is the z (inplane slice) dimension
    xx, yy, zz = np.mgrid[x_min:x_max, y_min:y_max, z_min:
                          z_max]  # add :30j to make 30 equally spaced points

    # title for the plots
    titles = [
        'SVC with linear kernel', 'SVC with RBF kernel',
        'SVC with polynomial (degree 3) kernel',
        'SVC with polynomial (degree 2) kernel'
    ]

    # set plot parameters
    """
    n_levels is the number of contour levels. eg. 1 draws 1 contour
    slice_dim is whether slices will be by y (coronal, slice_dime=1) 
              or z (axial, slice_dim=2)
    """
    n_levels = 1
    slice_dim = 1
    pl.set_cmap(pl.cm.RdBu)
    # turn interactive mode on, so that pl.show() won't wait for the figure to be closed before continuing
    # pl.ion()

    for i, clf in enumerate((lin_svc, rbf_svc, poly3_svc, poly2_svc)):
        # Plot the decision boundary. For that, we will asign a color to each
        # point in the mesh [x_min, m_max]x[y_min, y_max].
        fig = pl.figure()
        Z = clf.predict(np.c_[xx.ravel(), yy.ravel(), zz.ravel()])

        # Put the result into a color plot
        Z = Z.reshape(xx.shape)

        if slice_dim == 2:
            if i == 0:
                print 'slicing axial'
            slices = np.unique(X[:, 2])
            for j in np.arange(np.size(Z, 2)):
                pl.subplot(2, 3, j + 1)
                in_slice = X[:, 2] == slices[j]

                # Plot the contour and the training points
                pl.contourf(xx[:, :, j], yy[:, :, j], Z[:, :, j], n_levels)
                pl.scatter(X[in_slice, 0], X[in_slice, 1], c=cols[in_slice, ])

        elif slice_dim == 1:
            if i == 0:
                print 'slicing coronal'
            slices = np.unique(X[:, 1])
            for j in np.arange(np.size(Z, 1)):
                pl.subplot(3, 4, j + 1)
                in_slice = X[:, 1] == slices[j]

                # Plot the contour and the training points
                pl.contourf(xx[:, j, :], zz[:, j, :], Z[:, j, :], n_levels)
                pl.scatter(X[in_slice, 0], X[in_slice, 2], c=cols[in_slice, ])

        pl.suptitle(titles[i])
        pl.show()

        if i == 0 and savefig:
            print 'saving fig'
            pl.savefig(
                'figures/lgnROI{}MapCoronal_spatialSVMLin_{}_{:%Y%m%d}.png'.
                format(hemi, analysis_extension, datetime.datetime.today()))

    return lin_svc
Esempio n. 39
0
def main():

	rc('xtick', labelsize=24)
	rc('ytick', labelsize=24)
	rcParams['font.family'] = 'serif'
	rcParams['font.sans-serif'] = ['Times New Roman']
	rcParams['xtick.major.pad']='16'
	rcParams['ytick.major.pad']='16'

	folder = sys.argv[2]
	path = folder + "/output/Solution"
	
	with open(path, 'r') as f:
		odes = np.genfromtxt(f, skip_header=0)

	time = np.zeros(odes.shape[0],  dtype=np.float64)

	f = open(sys.argv[1], "r")
	subspec = []
	
	for line in f:
		subspec.append(line)
	f.close()
	
	subspecies = []
	for i in range(0, len(subspec)):
		string = subspec[i].split("\n")
		subspecies.append(int(string[0]))


	ode1 = np.transpose(odes)
	ode = ode1[1::][:]
	time = ode1[0][:]

	alphabet1 = sys.argv[3]
	alphabet = []

	if alphabet1 == "no":
		for i in range(0, len(subspec)):
			alphabet.append("X" + str(i))
	else:
		f = open(alphabet1, "r")
		string = []
		for line in f:
			string.append(line)
	f.close()
	alphabet = string[0].split("\t")

	verb = sys.argv[4]
	verbose = int(verb)
	if(verbose):
		print("\nPlotting solution....");
	
	plt.set_cmap('winter')
	cmap = plt.get_cmap()
	plt.figure(figsize=(16, 9))
	plt.ylabel('Molecular concentration', fontsize = 26)
	plt.xlabel('Time [s]', fontsize = 26)

	# colors = [0.0, 0.2, 0.4, 0.6]
	
	# for i in range(0, ode.shape[0]):
	# 	#s = alphabet[subspecies[i]]
	# 	s = "$X_" + str(i+1) + "$"
	# 	c = cmap(colors[i])
	# 	plt.plot(time, ode[i][:], color=c, linewidth = 2.0, label=s)

	# path = folder + "/image/all.pdf"
	# lg = plt.legend(loc = 1, numpoints=1, borderaxespad=0, fontsize = 22)
	# lg.draw_frame(False)
	# plt.savefig(path, bbox_inches = 'tight', additional_artists=lg, dpi=300)
	
	for i in range(0, ode.shape[0]):
		s = alphabet[subspecies[i]]
		path = folder + "/image/" + s + ".pdf"
		plt.figure(255)
		plt.figure(figsize=(25, 15))
		plt.figure(figsize=(16, 9))
		plt.ylabel('Molecular concentration', fontsize = 26)
		plt.xlabel('Time [s]', fontsize = 26)
		dim_y = np.arange(min(ode[i][:]), max(ode[i][:]))
		plt.plot(time, ode[i][:], 'b', linewidth = 2.0, label=s)
		#plt.savefig(path, bbox_inches = 'tight', additional_artists=plt.legend(loc = 0, numpoints=1, borderaxespad=0.5,  fontsize = 18), dpi=92)
		lg = plt.legend(loc = 0, numpoints=1, borderaxespad=0, fontsize = 22)
		lg.draw_frame(False)
		plt.savefig(path, bbox_inches = 'tight', additional_artists=lg, dpi=300)
		plt.close('all')
Esempio n. 40
0
""" 
Author: Nesar Ramachandra 

Plots .data files 

"""

#import matplotlib
#matplotlib.use('GTKAgg')   # On remote machine
import numpy as np
import matplotlib.pylab as plt
plt.set_cmap('Set1_r')
import sys
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("-i",
                    "--file",
                    dest="fileIn",
                    help="input .data file",
                    metavar="FILE")

#parser.add_argument

args = parser.parse_args()

print
print args.fileIn

pixData = np.fromfile(str(args.fileIn), dtype=np.float32)
Esempio n. 41
0
#  signal.  The higher carrier frequency (and subsequently doppler bandwidth)#
#  also results in a 14x increase in the number of synthetic aperture        #
#  samples required to perform the frequency mapping prescribed by Soumekh   #
#  as opposed to polar format mapping.                                       #
#                                                                            #
##############################################################################

from numpy import *
import numpy as np
import ritsar.signal as sig
from scipy.fftpack import *
from ritsar.signal import *
import matplotlib.pylab as plt
from scipy.interpolate import interp1d

plt.set_cmap(cm.Greys)

##########################################################
#   PULSED SPOTLIGHT SAR SIMULATION AND RECONSTRUCTION   #
##########################################################


cmap = cm.Greys_r
cj = 1j;
pi2 = 2 * pi;
#
c = 3e8;  # propagation speed
f0 = 185e6 / 2;  # baseband bandwidth is 2*f0
w0 = pi2 * f0;
fc = 10.0e9;  # carrier frequency
wc = pi2 * fc;
#  signal.  The higher carrier frequency (and subsequently doppler bandwidth)#
#  also results in a 14x increase in the number of synthetic aperture        #
#  samples required to perform the frequency mapping prescribed by Soumekh   #
#  as opposed to polar format mapping.                                       #
#                                                                            #
##############################################################################

from numpy import *
import numpy as np
import ritsar.signal as sig
from scipy.fftpack import *
from ritsar.signal import *
import matplotlib.pylab as plt
from scipy.interpolate import interp1d

plt.set_cmap(cm.Greys)

##########################################################
#   PULSED SPOTLIGHT SAR SIMULATION AND RECONSTRUCTION   #
##########################################################


cmap = cm.Greys_r
cj = 1j
pi2 = 2 * pi
#
c = 3e8
# propagation speed
f0 = 185e6 / 2
# baseband bandwidth is 2*f0
w0 = pi2 * f0
def sub_lba_dist(lists_action, lists_cmd, options):

    # Local Variables: plot_fontsize, lists_action, i, idx_write, save_figure, lba_size_set, stat_record, idx_read, section_name, X, y, x, plot_figure, lba_stat_array, options, Y, lists_cmd
    # Function calls: subplot, plot, lba_size_dist, set, gcf, figure, title, zlabel, isfield, findall, mesh, sub_lba_dist, colorbar, meshgrid, xlabel, ylabel, generate_ppt, saveas, isempty, find
    #% stat_record=sub_lba_dist(lists_action,lists_cmd,options)
    #% --> calcuate the size distribution
    #% inputs
    #%   lists_action: n samples x 2 array for arrival time and completion time;
    #%   lists_cmd: n samples x 3 for LBA, size, flags ( (0 write, 1 read))
    #%   access_type: 0 write, 1 read, 2 all
    #%   options: control parameters
    #%       lba_size_set: how many LBA range sets
    #%
    #% outputs
    #%   lba_stat_array: cells structure; LBA statistics for write/read/all
    #%
    #% contact [email protected] for questions

    if hasattr(options, 'plot_fontsize'):
        plot_fontsize = options.plot_fontsize
    else:
        plot_fontsize = 10

    if hasattr(options, 'save_figure'):
        save_figure = options.save_figure
    else:
        save_figure = 1

    if hasattr(options, 'plot_figure'):
        plot_figure = options.plot_figure
    else:
        plot_figure = 1

    if hasattr(options, 'lba_size_set'):
        lba_size_set = options.lba_size_set
    else:
        options.lba_size_set = 50

    plot_figure = options.plot_figure

    #%5: LBA vs time;
    if plot_figure == 1:
        idx_read = np.nonzero((lists_cmd[:, 2] == 1))
        idx_write = np.nonzero((lists_cmd[:, 2] == 0))
        plt.figure
        plt.subplot(2., 1., 1.)
        plt.plot(lists_action[(idx_read), 0],
                 lists_cmd[(idx_read), 0],
                 'r*',
                 markersize=1)
        plt.ylabel('LBA')
        plt.title('read')
        plt.subplot(2., 1., 2.)
        plt.plot(lists_action[(idx_write), 0],
                 lists_cmd[(idx_write), 0],
                 'b+',
                 markersize=1)
        plt.ylabel('LBA')
        plt.xlabel('time (s)')
        plt.title('write')
        plt.savefig('lba_all.eps')
        plt.savefig('lba_all.jpg')

    lba_stat_array = []
    for i in np.arange(3):

        print(i)
        stat_record = lba_size_dist2(lists_cmd, i, options)

        if plot_figure == 1:
            x = np.arange(1, 1025)
            y = stat_record.lba_size_idx
            if len(y) <= 1:
                continue
            fig = plt.figure()
            ax = Axes3D(fig)
            [X, Y] = plt.meshgrid(x, y)
            ax.plot_surface(X, Y, (stat_record.lba_size_dist))
            plt.set_cmap('hot')

            ax.set_ylabel('LBA Range')
            ax.set_xlabel('Request size')
            ax.set_zlabel('Frequency')

            if i == 0.:
                ax.set_title('LBA & Size Disribution - Write ')
            elif i == 1.:
                ax.set_title('LBA & Size Disribution - Read ')

            else:
                ax.set_title('LBA & Size Disribution - Combined ')

            # set((plt.gcf, '-property', 'FontSize'), 'FontSize', plot_fontsize)
            # plt.grid()
            if i == 1:
                plt.savefig('lba_size_freq_read.eps', format="eps")
                plt.savefig('lba_size_freq_read.jpg')
            elif i == 0:
                plt.savefig('lba_size_freq_write.eps', format="eps")
                plt.savefig('lba_size_freq_write.jpg')

            else:
                plt.savefig('lba_size_freq_com.eps', format="eps")
                plt.savefig('lba_size_freq_com.jpg')

            plt.show()

        lba_stat_array.append(stat_record)

#    if options.export_report:
#        options.section_name = 'LBA Distribution'
#        generate_ppt(options)

    return lba_stat_array
Esempio n. 44
0
#             old_ax = plt.gca()
#             plt.colorbar(cax=celsius.make_colorbar_cax(), ticks=[0,1,2], cmap=cmap)
#             plt.ylabel(r'log$_{10}$ Counts')
#             plt.sca(old_ax)
#
#
#
#






if __name__ == '__main__':
    plt.close('all')
    fig, ax = plt.subplots(2,1, sharex=True)

    start = mex.orbits[8000].periapsis - 2.5 * 3600
    finish = mex.orbits[8000].periapsis + 2.5 * 3600
    verbose = True

    plt.set_cmap(plt.cm.Spectral_r)
    plt.sca(ax[0])
    plot_aspera_els(start, finish, verbose=verbose)
    plt.sca(ax[1])
    plot_aspera_ima(start, finish, verbose=verbose)
    plt.vlines((start, finish), *plt.ylim())
    plt.xlim(start - 3600., finish + 3600.)
    plt.show()