Пример #1
0
def main(base_dir=DEF_DIR, base_pat=DEF_PAT, vmin=0, vmax=255):
    glob_pat = os.path.join(base_dir, base_pat)
    for nc_name in glob(glob_pat):
        nc_name = os.path.split(nc_name)[1]
        print "Drawing for NC name %s" % nc_name

        # Get the data and mask it
        nc = Dataset(nc_name, "r")
        data_var = nc.variables["image"]
        data_var.set_auto_maskandscale(False)
        data = data_var[:]
        data = data.astype(uint8) # How AWIPS reads it

        # Create a new figure everytime so things don't get shared
        plt.figure()

        # Plot the data
        print data.min(), data.max()
        plt.imshow(data, vmin=vmin, vmax=vmax)

        # Add a colorbar and force the colormap
        plt.colorbar()
        #plt.spectral()
        plt.bone()

        plt.savefig("plot_ncdata.%s.png" % nc_name)
        plt.close()
Пример #2
0
def plot_binary(arr, output_fn, dpi_to_use=None, vmin=None, vmax=None, fill_figure=False, full_res=False):
    if fill_figure:
        # dynamic dpi guess (6 inches high)
        full_res_dpi = int(arr.shape[0] / float(DEFAULT_FIG_SIZE[1]))
        figsize = (arr.shape[1] / float(full_res_dpi), arr.shape[0] / float(full_res_dpi))
        if full_res:
            dpi_to_use = dpi_to_use or full_res_dpi
        else:
            dpi_to_use = dpi_to_use or DEFAULT_DPI
        print("Figure size: {!r}".format(figsize))
        print("DPI: {}".format(dpi_to_use))
    else:
        dpi_to_use = dpi_to_use or DEFAULT_DPI
        figsize = None

    plt.figure(figsize=figsize)
    print("Minimum: %f | Maximum: %f" % (float(numpy.nanmin(arr)), float(numpy.nanmax(arr))))

    if fill_figure:
        plt.axes([0, 0, 1, 1])

    plt.imshow(arr, vmin=vmin, vmax=vmax)

    plt.bone()
    if not fill_figure:
        plt.colorbar()

    plt.savefig(output_fn, dpi=dpi_to_use)
    plt.close()
Пример #3
0
def visualize_array(image_data, label='data_figure'):
    """
    Produce a visual representation of the image_data matrix.

    Parameters
    ----------
    image_data : 2D array of floats
        The pixel values to make into an image.
    label : str
        The string label to affix to the image. It is used both
        to generate a figure number and as the title.
    """
    # Treat nan values like zeros for display purposes
    image_data = np.nan_to_num(np.copy(image_data))

    fig = plt.figure(str_to_int(label))
    # Diane made the brilliant suggestion to leave this plot in color.
    # It looks much prettier.
    plt.bone()
    img = plt.imshow(image_data)
    img.set_interpolation('nearest')
    plt.title(label)
    plt.xlabel('Max = {0:.3}, Min = {1:.3}'.format(np.max(image_data),
                                                   np.min(image_data)))
    fig.show()
    fig.canvas.draw()
Пример #4
0
def plot_binary_file(bf, fill_value=None, dpi=None, vmin=None, vmax=None):
    data = FBF(bf)
    img_fn = "plot_{}.png".format(data.stemname)

    if fill_value is not None:
        if numpy.isnan(fill_value):
            data = numpy.ma.masked_where(numpy.isfinite(data), data)
        else:
            data = numpy.ma.masked_where(data == fill_value, data)

    if LOG.getEffectiveLevel() <= logging.DEBUG:
        LOG.debug("Data Min: {}; Data Max: {}".format(numpy.min(data),
                                                      numpy.max(data)))

    plt.figure()

    if data.ndim == 1:
        plt.plot(data)
    else:
        plt.imshow(data, vmin=vmin, vmax=vmax)
        plt.bone()
        plt.colorbar()

    if dpi:
        plt.savefig(img_fn, dpi=dpi)
    else:
        plt.savefig(img_fn)

    plt.close()
    return img_fn
Пример #5
0
def NumofViews(data):
    colors = ['#addd8e', '#78c679', '#41ab5d', '#238443', '#005a32']  #run the query: # answers to questions
    #hack to get 0 point
    plt.bone()
    plt.figure(1, figsize=(8, 4))

    plots = []
    # alternative: draw a bar chart of first 100 values
    #+[sum(ys[249:])]
    for i in range(len(data)):
        plots.append(plt.loglog(data[i]['allxs'], data[i]['allys'], color=colors[i], linestyle='None', marker='.'))
        label = 'mode: %d' % data[i]['modex']
        plt.annotate(label, (data[i]['modex'], data[i]['modey']), xycoords='data', xytext=(5, 1),
                     textcoords='offset   points', arrowprops=dict(arrowstyle="->"))
    plt.title('Number of Views per Question (log-log)')
    plt.ylabel('Number of Questions')
    plt.xlabel('Number of Views')
    leg = plt.legend((plots[0][0], plots[1][0], plots[2][0], plots[3][0], plots[4][0]), (
        'Qs posted in last week', 'Qs posted in last month', 'Qs posted in last 6 months', 'Qs posted in last year',
        'All Questions'))
    for t in leg.get_texts():
        t.set_fontsize('x-small')  # the legend text fontsize
    plt.savefig(var.DIR_DATA + 'Plots/num_of_views.png')
    plt.ylim(ymin=0.8)
    plt.show()
Пример #6
0
def plot_binary_file(bf, fill_value=None, dpi=None, vmin=None, vmax=None):
    data = FBF(bf)
    img_fn = "plot_{}.png".format(data.stemname)

    if fill_value is not None:
        if numpy.isnan(fill_value):
            data = numpy.ma.masked_where(numpy.isfinite(data), data)
        else:
            data = numpy.ma.masked_where(data == fill_value, data)

    if LOG.getEffectiveLevel() <= logging.DEBUG:
        LOG.debug("Data Min: {}; Data Max: {}".format(numpy.min(data), numpy.max(data)))

    plt.figure()

    if data.ndim == 1:
        plt.plot(data)
    else:
        plt.imshow(data, vmin=vmin, vmax=vmax)
        plt.bone()
        plt.colorbar()

    if dpi:
        plt.savefig(img_fn, dpi=dpi)
    else:
        plt.savefig(img_fn)

    plt.close()
    return img_fn
Пример #7
0
def plot_irish(som, data):
    # Plotting the response for each pattern in the iris dataset
    plt.bone()
    plt.pcolor(som.distance_map().T)  # plotting the distance map as background
    plt.colorbar()

    target = np.genfromtxt('iris.csv', delimiter=',', usecols=(4), dtype=str)
    t = np.zeros(len(target), dtype=int)
    t[target == 'setosa'] = 0
    t[target == 'versicolor'] = 1
    t[target == 'virginica'] = 2

    # use different colors and markers for each label
    markers = ['o', 's', 'D']
    colors = ['r', 'g', 'b']
    for cnt, xx in enumerate(data):
        w = som.winner(xx)  # getting the winner
        # palce a marker on the winning position for the sample xx
        plt.plot(w[0] + .5,
                 w[1] + .5,
                 markers[t[cnt]],
                 markerfacecolor='None',
                 markeredgecolor=colors[t[cnt]],
                 markersize=12,
                 markeredgewidth=2)
    plt.axis([0, 10, 0, 10])
    plt.show()
Пример #8
0
def plot_binary(arr, output_fn, dpi_to_use=None, vmin=None, vmax=None, fill_figure=False, full_res=False):
    if fill_figure:
        # dynamic dpi guess (6 inches high)
        full_res_dpi = int(arr.shape[0] / float(DEFAULT_FIG_SIZE[1]))
        figsize = (arr.shape[1] / float(full_res_dpi), arr.shape[0] / float(full_res_dpi))
        if full_res:
            dpi_to_use = dpi_to_use or full_res_dpi
        else:
            dpi_to_use = dpi_to_use or DEFAULT_DPI
        print("Figure size: {!r}".format(figsize))
        print("DPI: {}".format(dpi_to_use))
    else:
        dpi_to_use = dpi_to_use or DEFAULT_DPI
        figsize = None

    plt.figure(figsize=figsize)
    print("Minimum: %f | Maximum: %f" % (numpy.nanmin(arr), numpy.nanmax(arr)))

    if fill_figure:
        plt.axes([0, 0, 1, 1])

    plt.imshow(arr, vmin=vmin, vmax=vmax)

    plt.bone()
    if not fill_figure:
        plt.colorbar()

    plt.savefig(output_fn, dpi=dpi_to_use)
    plt.close()
Пример #9
0
def visualize_array(image_data, label="data_figure"):
    """
    Produce a visual representation of the image_data matrix.

    Parameters
    ----------
    image_data : 2D array of floats
        The pixel values to make into an image.
    label : str
        The string label to affix to the image. It is used both
        to generate a figure number and as the title.
    """
    # Treat nan values like zeros for display purposes
    image_data = np.nan_to_num(np.copy(image_data))

    fig = plt.figure(str_to_int(label))
    # Diane made the brilliant suggestion to leave this plot in color.
    # It looks much prettier.
    plt.bone()
    img = plt.imshow(image_data)
    img.set_interpolation("nearest")
    plt.title(label)
    plt.xlabel("Max = {0:.3}, Min = {1:.3}".format(np.max(image_data), np.min(image_data)))
    fig.show()
    fig.canvas.draw()
Пример #10
0
def save_image(img, img_title, title):
    plt.bone()
    plt.clf()
    plt.axis('off')
    plt.figimage(img)
    dpi = 100
    plt.gcf().set_size_inches(
        (img.shape[1] / float(dpi), img.shape[0] / float(dpi)))
    plt.savefig("result/" + img_title + "_" + title + ".png", dpi=dpi)
Пример #11
0
def stim_show(images):
    '''
    Plots every image in images (using imshow)
    '''
    til = __tile_raster_images(images,
                    np.array([images.shape[1]**.5, images.shape[1]**.5], 'int'),
                    np.array([images.shape[0]**.5, images.shape[0]**.5], 'int'),
                    tile_spacing = (5,5))

    f = plt.imshow(til)
    plt.bone()
    plt.xticks([]), plt.yticks([])
    plt.show()
    return f
Пример #12
0
def stim_show(images, img_shape, tile_shape):
    '''
    Plots every image in images (using imshow)
    '''
    import matplotlib.pyplot as plt
    til = __tile_raster_images(images + .5,
                               img_shape,
                               tile_shape,
                               tile_spacing=(1, 1))

    f = plt.imshow(til, interpolation='nearest')
    plt.bone()
    plt.xticks([]), plt.yticks([])
    plt.show()
    return f
Пример #13
0
def main(fill=-999.0):
    W=Workspace('.')

    for fn in glob("result_*.real4.*.*"):
        print "Plotting for %s" % fn
        plt.figure()
        fbf_attr = fn.split(".")[0]
        result = getattr(W, fbf_attr)
        result = numpy.ma.masked_where(result == FILL, result)
        print result.min(),result.max()
        plt.imshow(result)
        plt.bone()
        plt.colorbar()
        plt.savefig("plot_result.%s.png" % fbf_attr)
        plt.close()
Пример #14
0
 def plot_map(self):
     #som_output_weights = self.map_som # SOM outputs
     som_distance_map = self.map_som.distance_map()  # distance map of SOM
     #print(som_distance_map)
     plt.figure()
     plt.bone()
     plt.pcolor(som_distance_map.T)
     #plt.pcolor(som_distance_map.T, cmap='bone_r')
     plt.colorbar()
     plt.title('fsom object with ' + str(self.x_n * self.y_n) +
               ' clusters and ' + str(self.nb_metaclusters) +
               ' metaclusters')
     plt.savefig('Resultats/4_Flowsom/Figure_1 - som ' + str(self.x_n) +
                 'x' + str(self.y_n) + '.png')
     plt.show
Пример #15
0
def plot_binary(data, title,
                fill_value=DEFAULT_FILL_VALUE,
                vmin=None, vmax=None):
    
    # TODO, there's probably a better way to show 3D data
    raw_data   = numpy.nansum(data, axis=0) if len(data.shape) > 2 else data
    
    # mask the data based on the fill value
    temp_mask   = numpy.isnan(raw_data) if fill_value is numpy.nan else raw_data == fill_value
    masked_data = numpy.ma.masked_where(temp_mask, raw_data)
    
    # plot the figure
    figure = plt.figure()
    axes   = figure.add_subplot(111)
    plt.imshow(masked_data, vmin=vmin, vmax=vmax)
    axes.set_title(title)
    plt.bone()
    plt.colorbar()
Пример #16
0
def plot_slice(slice_in, is_anns = False, num_anns = 4):
    
    slice_in = np.squeeze(slice_in)
    plt.figure()
    plt.set_cmap(plt.bone())
    if is_anns:
        plt.pcolormesh(slice_in, vmin = 0, vmax = num_anns - 1)
    else:
        plt.pcolormesh(slice_in)
    plt.show()
Пример #17
0
 def plot_meta_label_on_map(self):
     som_distance_map = self.map_som.distance_map()  # distance map of SOM
     plt.figure(figsize=(18.5, 10.5))
     plt.bone()
     plt.pcolor(som_distance_map.T)
     plt.colorbar()
     plt.title('fsom object ' + str(self.x_n * self.y_n) +
               ' clusters and ' + str(self.nb_metaclusters) +
               ' metaclusters')
     dictio = self.dict_meta_labels
     colors = [
         "r", "g", "b", "y", "c", (0, 0.1, 0.8), (1, 0.5, 0), (1, 1, 0.3),
         "m", (0.4, 0.6, 0)
     ]
     for w, meta_cell in dictio.items():
         samples = self.sample_by_pos_map[w]
         nb_sa = len(samples)
         winner = self.map_som.winner(
             samples[0]
         )  # make prediction, prediction = the closest entry location in the SOM
         c = self.map_class[
             winner]  # from the location info get cluster info
         plt.text(w[0] + .2,
                  w[1] + .2,
                  meta_cell,
                  color=colors[c],
                  fontsize=10)
         plt.text(w[0] + .5, w[1] + .7, nb_sa, color=colors[c], fontsize=12)
     cnt = self.data['category']
     col = []
     for m in cnt:
         col.append(colors[m])
     w1 = self.locationSOM_w1
     w2 = self.locationSOM_w2
     plt.scatter(w1, w2, s=200, c=col, marker='o')
     plt.axis([0, self.x_n, 0, self.y_n])
     plt.savefig('Resultats/4_Flowsom/Figure 3 Grid visualisation - som ' +
                 str(self.x_n) + 'x' + str(self.y_n) + ' metacluster.png')
     plt.show()
Пример #18
0
from minisom import MiniSom
from numpy import genfromtxt, array, linalg, zeros, mean, std, apply_along_axis, load

data = load('corrCoef.npy')

som = MiniSom(10, 10, 54, sigma=1.0, learning_rate=0.5)
som.random_weights_init(data)

print("Training")
som.train_random(data, 100)

print("\nReady!!!")

from matplotlib.pyplot import plot, axis, show, pcolor, colorbar, bone

bone()
pcolor(som.distance_map().T)
colorbar()

target = load('input.npy')[1]

markers = ['o', 's']
colors = ['r', 'g']

for cnt, xx in enumerate(data):
    w = som.winner(xx)
    plot(w[0] + .5,
         w[1] + .5,
         markers[target[cnt]],
         markerfacecolor='None',
         markeredgecolor=colors[target[cnt]],
Пример #19
0
X = data.iloc[:,:-1].values
y = data.iloc[:,-1].values

#Scaling the features
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range= (0,1))
X = sc.fit_transform(X)

#Imprting the Minisom Class
from minisom import MiniSom
ms = MiniSom(10,10, input_len= 15, sigma= 1.0, learning_rate= 0.5 )
ms.random_weights_init(X)
ms.train_random(X, num_iteration= 100)

#Visualising
plt.bone()
plt.pcolor(ms.distance_map().T)
plt.colorbar()
markers = ['o','s']
colors = ['r','g']
for i, x in enumerate(X):
    w = ms.winner(x)
    plt.plot(w[0]+ 0.5, w[1] + 0.5,
             marker = markers[y[i]],
             markeredgecolor = colors[y[i]],
             markerfacecolor = 'None',
             markersize = 10,
             markeredgewidth = 2)
plt.show()    

#finding the frauds
Пример #20
0
    def set_up_visualization(self, brain):
        # Prepare visualization.
        plt.bone()
        # fig : matplotlib figure
        #     The figure in which a visual representation of the results
        #     will be presented.
        # ax_curiosities,
        # ax_rewards,
        # ax_ocurrences : matplotlib axes
        #     The axes in which each of these 2D arrays will be rendered
        #     as images.
        plt.figure(num=73857, figsize=(9, 9))
        plt.clf()
        self.fig, ((self.ax_rewards, self.ax_curiosities),
                   (self.ax_activities,
                    self.ax_occurrences)) = (plt.subplots(2, 2, num=73857))

        def dress_axes(ax):
            plt.sca(ax)
            # patches.Rectangle((x, y), width, height)
            ax.add_patch(
                patches.Rectangle((-.5, brain.num_actions - .5),
                                  self.num_features,
                                  brain.num_sensors,
                                  facecolor='green',
                                  edgecolor='none',
                                  alpha=.16))
            ax.add_patch(
                patches.Rectangle((brain.num_actions - .5, -.5),
                                  brain.num_sensors,
                                  self.num_features,
                                  facecolor='green',
                                  edgecolor='none',
                                  alpha=.16))
            ax.plot([-.5, self.num_features - .5],
                    [brain.num_actions - .5, brain.num_actions - .5],
                    color='blue',
                    linewidth=.2)
            ax.plot([brain.num_actions - .5, brain.num_actions - .5],
                    [-.5, self.num_features - .5],
                    color='blue',
                    linewidth=.2)
            ax.plot([-.5, self.num_features - .5], [
                brain.num_sensors + brain.num_actions - .5,
                brain.num_sensors + brain.num_actions - .5
            ],
                    color='blue',
                    linewidth=.2)
            ax.plot([
                brain.num_sensors + brain.num_actions - .5,
                brain.num_sensors + brain.num_actions - .5
            ], [-.5, self.num_features - .5],
                    color='blue',
                    linewidth=.2)
            plt.xlim([-.5, self.num_features - .5])
            plt.ylim([-.5, self.num_features - .5])
            ax.invert_yaxis()

        dress_axes(self.ax_rewards)
        dress_axes(self.ax_curiosities)
        dress_axes(self.ax_activities)
        dress_axes(self.ax_occurrences)
Пример #21
0
def create_som(data,
               labels,
               one_hots,
               filename_load_weights,
               filename_save_weights,
               load_weights=False,
               num_iteration=100,
               plot_data=False,
               plot_labels=False,
               save_plot=False,
               plot_distance_map=False,
               show_activations=False,
               show_single_chars=False,
               filename_plots='unspecified.png'):
    assert len(data) == len(labels)

    size = int(np.ceil(np.sqrt(len(data))))
    input_len = len(data[0])
    # Initialization and training
    som = MiniSom(x=size,
                  y=size,
                  input_len=input_len,
                  model=rnn,
                  sigma=1.0,
                  learning_rate=0.5)
    if load_weights:
        som.load_weights(filename=filename_load_weights)
    else:
        som.random_weights_init(data)
        print("Training...")
        som.train_random(data, num_iteration=num_iteration)  # random training
        print("\n...ready!")
        som.save_weights(filename=filename_save_weights)

    print("beginn mapping vectors")

    # Plotting the response for each pattern in the data set
    if plot_distance_map:
        plt.bone()
        plt.pcolor(
            som.distance_map().T)  # plotting the distance map as background
        plt.colorbar()
    else:
        plt.figure(figsize=(size, size))

    for i, data_point in enumerate(data):
        w = som.winner(data_point)  # getting the winner
        if plot_data:
            # place a string of the vector on the winning position for the sample
            plt.text(x=w[0],
                     y=w[1] + np.random.rand() * 0.9,
                     s=str(data_point),
                     size='small',
                     color='r')

        if plot_labels:
            #place the string of the label on the winning position for the sample
            plt.text(x=w[0] + 0.75,
                     y=w[1] + np.random.rand() * 0.9,
                     s=labels[i],
                     size='small',
                     color='b')

    #add axis
    plt.axis([0, size, 0, size])

    #save if specified
    if save_plot:
        plt.savefig('../RNN/SOM_graphics/{}.png'.format(filename_plots))
    plt.show()

    if show_activations:
        for i in range(len(one_hots)):
            plt.bone()
            plt.pcolor(som.activation_map(
                one_hots[i]))  # plotting the distance map as background
            plt.colorbar()
            plt.title('vec_{}'.format(one_hots[i]))
            plt.show()

    if show_single_chars:
        unique_labels = np.unique(labels)
        for unique_label in unique_labels:
            #plt.figure(figsize=(size, size))
            plt.bone()
            plt.pcolor(som.distance_map().T
                       )  # plotting the distance map as background
            plt.colorbar()
            for i, data_point in enumerate(data):
                if unique_label == labels[i]:
                    w = som.winner(data_point)  # getting the winner
                    plt.text(x=w[0] + 0.75,
                             y=w[1] + np.random.rand() * 0.9,
                             s=labels[i],
                             size='small',
                             color='r')
                    #plot the vectors
                    plt.text(x=w[0],
                             y=w[1] + np.random.rand() * 0.9,
                             s=str(data_point),
                             size='small',
                             color='b')
            # add axis
            plt.axis([0, size, 0, size])
            plt.show()
Пример #22
0
def draw(t, ind):
    for i in range(ind.size):
        ax = plt.subplot(1, ind.size, i)
        ax.imshow(t[:, ind[i]].reshape(16, 16))
    plt.bone()
    plt.show()
Пример #23
0
for img_name in glob("image_*") + glob("prescale_DNB*"):
    print "Plotting for %s" % img_name

    # Get the data and mask it
    img_name = img_name.split(".")[0]
    img=getattr(W, img_name)
    discard = (img <= -999)
    data=ma.masked_array(img, discard)

    # Plot the data
    print data.min(),data.max()
    # Create a new figure everytime so things don't get shared
    if fit:
        fsize = (array(data.shape)/100.0)[::-1]
        plt.figure(figsize=fsize, dpi=100)
    else:
        plt.figure()
    plt.imshow(data)
    #plt.spectral()
    plt.bone()

    if fit:
        plt.subplots_adjust(left=0, top=1, bottom=0, right=1, wspace=0, hspace=0)
        plt.savefig("plot_%s.png" % img_name, dpi=100)
    else:
        # Add a colorbar and force the colormap
        plt.colorbar()
        plt.savefig("plot_%s.png" % img_name)

Пример #24
0
def get_database(filename, indent=0):
    """
    Go through all items in the dataset and print them with custom format
    Modelled after Dataset._pretty_str()
    """
    import pydicom
    import matplotlib.pyplot as plt

    dont_print = ['Pixel Data', 'File Meta Information Version']

    indent_string = "   " * indent
    next_indent_string = "   " * (indent + 1)

    for data_element in filename:
        if data_element.VR == "SQ":  # a sequence
            print(indent_string, data_element.name)
            for sequence_item in data_element.value:
                get_database(sequence_item, indent + 1)
                print(next_indent_string + "---------")
        else:
            if data_element.name in dont_print:
                print("""<item not printed -- in the "don't print" list>""")
            else:
                repr_value = repr(data_element.value)
                if len(repr_value) > 50:
                    repr_value = repr_value[:50] + "..."
                print("{0:s} {1:s} = {2:s}".format(indent_string,
                                                   data_element.name,
                                                   repr_value))

    # 2 ^ 11 bytes = 2048
    filename = "datasets/ImagensTC_Pulmao/8.dcm"
    dataset = pydicom.dcmread(filename, force=True)
    dataset.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
    # dataset.pixel_array

    # filename = get_testdata_files('MR_small.dcm')[0]
    # ds = pydicom.dcmread(filename)
    # myprint(ds)

    # Normal mode:
    print()
    print("Filename.........:", filename)
    print("Storage type.....:", dataset.SOPClassUID)
    print()

    pat_name = dataset.PatientName
    display_name = pat_name.family_name + ", " + pat_name.given_name
    print("Patient's name...:", display_name)
    print("Patient id.......:", dataset.PatientID)
    print("Modality.........:", dataset.Modality)
    print("Study Date.......:", dataset.StudyDate)
    # print("Bit Depth........:", dataset.pixel_array)

    if 'PixelData' in dataset:
        rows = int(dataset.Rows)
        cols = int(dataset.Columns)
        print("Image size.......: {rows:d} x {cols:d}, {size:d} bytes".format(
            rows=rows, cols=cols, size=len(dataset.PixelData)))
        if 'PixelSpacing' in dataset:
            print("Pixel spacing....:", dataset.PixelSpacing)

    # use .get() if not sure the item exists, and want a default value if missing
    print("Slice location...:", dataset.get('SliceLocation', "(missing)"))

    get_database(dataset)

    # plot the image using matplotlib
    plt.imshow(dataset.pixel_array, cmap=plt.bone())
    plt.show()
Пример #25
0
    def set_up_visualization(self, brain):
        """
        Initialize the visualization of the model.

        To make the visualization interpretable, there are some
        annotations and visual guides added.

        Parameters
        ----------
        brain : Brain
            The number of actions in the brain is referenced
            to customize the display.
        """
        # Prepare visualization.
        plt.bone()
        # fig : matplotlib figure
        #     The figure in which a visual representation of the results
        #     will be presented.
        # ax_curiosities,
        # ax_rewards,
        # ax_ocurrences : matplotlib axes
        #     The axes in which each of these 2D arrays will be rendered
        #     as images.
        plt.figure(num=73857, figsize=(9, 9))
        plt.clf()
        self.fig, ((self.ax_rewards, self.ax_curiosities),
                   (self.ax_activities,
                    self.ax_occurrences)) = (plt.subplots(2, 2, num=73857))

        def dress_axes(ax):
            """
            Decorate the axes appropriately with visual cues.
            """
            plt.sca(ax)
            ax.add_patch(
                patches.Rectangle((-.5, -.5),
                                  self.num_features,
                                  2.,
                                  facecolor='green',
                                  edgecolor='none',
                                  alpha=.16))
            ax.add_patch(
                patches.Rectangle((-.5, -.5),
                                  2.,
                                  self.num_features,
                                  facecolor='green',
                                  edgecolor='none',
                                  alpha=.16))
            ax.add_patch(
                patches.Rectangle((-.5, brain.num_actions + 2. - .5),
                                  self.num_features,
                                  brain.num_sensors,
                                  facecolor='green',
                                  edgecolor='none',
                                  alpha=.16))
            ax.add_patch(
                patches.Rectangle((brain.num_actions + 2. - .5, -.5),
                                  brain.num_sensors,
                                  self.num_features,
                                  facecolor='green',
                                  edgecolor='none',
                                  alpha=.16))
            ax.plot([-.5, self.num_features - .5], [2. - .5, 2. - .5],
                    color='blue',
                    linewidth=.2)
            ax.plot([2. - .5, 2. - .5], [-.5, self.num_features - .5],
                    color='blue',
                    linewidth=.2)
            ax.plot([-.5, self.num_features - .5],
                    [brain.num_actions + 2. - .5, brain.num_actions + 2. - .5],
                    color='blue',
                    linewidth=.2)
            ax.plot([brain.num_actions + 2. - .5, brain.num_actions + 2. - .5],
                    [-.5, self.num_features - .5],
                    color='blue',
                    linewidth=.2)
            ax.plot([-.5, self.num_features - .5], [
                brain.num_sensors + brain.num_actions + 2. - .5,
                brain.num_sensors + brain.num_actions + 2. - .5
            ],
                    color='blue',
                    linewidth=.2)
            ax.plot([
                brain.num_sensors + brain.num_actions + 2. - .5,
                brain.num_sensors + brain.num_actions + 2. - .5
            ], [-.5, self.num_features - .5],
                    color='blue',
                    linewidth=.2)
            plt.xlim([-.5, self.num_features - .5])
            plt.ylim([-.5, self.num_features - .5])
            ax.invert_yaxis()

        dress_axes(self.ax_rewards)
        dress_axes(self.ax_curiosities)
        dress_axes(self.ax_activities)
        dress_axes(self.ax_occurrences)
Пример #26
0
    pyplot.imshow( (true_values- linapprox_values).reshape(orders))
    pyplot.colorbar()


    pyplot.show()
    exit()

    pyplot.figure()




    minbound = delaunay.min_bound
    maxbound = delaunay.max_bound
    extent = [minbound[0],maxbound[0],minbound[1],maxbound[1]]
    pyplot.bone()
    pyplot.figure()
    pyplot.imshow( values, extent=extent, origin='lower' )
    pyplot.colorbar()
    pyplot.figure()
    pyplot.imshow( interp_values, extent=extent,origin='lower', interpolation='nearest' )
    pyplot.axes().set_aspect('equal')
    for el in triangles: #triangulation.get_elements():
        plot_triangle(el)
    pyplot.colorbar()
    pyplot.figure()
    pyplot.imshow( abs(interp_values - values), extent=extent,origin='lower' )
    pylab.colorbar()

    triangles = []
    for v in delaunay.vertices: