def plot_organism2(x1, y1, theta, fit, ax):
    # TODO: Could make color relaitive to the genetic parent to see agent clustering
    #            The border could be this and the inside could be fitness?
    #       Could also add a dotted or thin line to the food that the agent is
    #        currently persuing. This is like "vision"

    ##    plt.plot(x1, y1, marker=(3, 1, theta+33), markersize=11, color='darkslateblue', linestyle='None')
    ##    plt.plot(x1, y1, marker=(3, 1, theta+33), markersize=6, color='mediumslateblue', linestyle='None')
    ##
    plt.plot(x1,
             y1,
             marker=(3, 1, theta + 33),
             markersize=11,
             color=cm.hot(fit / 200),
             linestyle='None')
    plt.plot(x1,
             y1,
             marker=(3, 1, theta + 33),
             markersize=6,
             color='grey',
             linestyle='None')

    dir_len = 0.075

    x2 = cos(radians(theta)) * dir_len + x1
    y2 = sin(radians(theta)) * dir_len + y1
    ax.add_line(
        lines.Line2D([x1, x2], [y1, y2],
                     color=cm.hot(fit / 200),
                     linewidth=1,
                     zorder=10))

    pass
Exemplo n.º 2
0
    def get_heatmap(self, sensor_data):
        rgb_array = sensor_data['CenterRGB'].copy()
        image = Image.fromarray(rgb_array)
        transform = get_truncated_transform()
        input_image = transform(image)
        input_image.putalpha(255)  # add RGB + A dimension for composite

        mask_array = self.pilotnet.visual_mask.detach().squeeze().numpy().copy(
        )
        mask_array *= 30.0  # TODO: Hack to emphasize really light activations
        mask_array[mask_array < 0.2] = 0
        mask_image = Image.fromarray(np.uint8(cm.hot(mask_array) * 255))

        # return mask_image

        # Convert black pixels into transparent pixels
        datas = mask_image.getdata()
        newData = []
        for item in datas:
            if item[0] == 10 and item[1] == 0 and item[2] == 0:
                newData.append((255, 255, 255, 0))
            else:
                newData.append(item)
        mask_image.putdata(newData)

        return Image.alpha_composite(input_image, mask_image)
def plot_path(x, f, max_pts=500):
    """
    x: list of ndarray.
        All the points on the way to the result
    f: function.
        Function to be optimized
    """
    fig = figure()
    ax = fig.add_subplot(111, projection='3d')
    xs = []
    ys = []
    zs = []
    for k in range(len(x)):
        xs.append(x[k][0, 0])
        ys.append(x[k][1, 0])
        zs.append(f(x[k]))
    max_f = 1.0 * max(zs)
    min_f = 1.0 * min(zs)
    colors = []
    for idx in range(len(x)):
        color = cm.hot(1.0 - (zs[idx] - min_f) / (max_f - min_f))
        colors.append(color)
    ax.scatter(xs=xs, ys=ys, zs=zs, color=colors)
    show()
    return
Exemplo n.º 4
0
def add_masks_viz(ax,
                  masks,
                  bboxes_norm,
                  labels=None,
                  mask_alpha=0.6,
                  debug=False):
    if labels is None:
        labels = ["coco" for _ in bboxes_norm]
    detect2d.visualize_bboxes(
        ax,
        bboxes_norm,
        labels=labels,
        label_color="w",
        linewidth=2,
        color="c",
    )
    for mask in masks:
        if isinstance(mask, torch.Tensor):
            mask = mask.cpu().detach().numpy()
        base_mask = mask[:, :, np.newaxis].astype(np.float)
        base_mask = base_mask / base_mask.max()
        show_mask = np.concatenate(
            [
                # cm.YlGn(base_mask)[:, :, 0][:, :, :3],
                cm.hot(base_mask)[:, :, 0][:, :, :3],
                mask_alpha * (base_mask > 0).astype(np.float),
            ],
            2,
        )
        ax.imshow(show_mask)
Exemplo n.º 5
0
    def visualize_map(self, title, figure):
        map = self.stiffness
        self.stiffness[self.stiffness == 0] = self.min
        map = map - self.min
        map = map / np.max(map)
        map = map.reshape(int(np.sqrt(map.size)), int(np.sqrt(map.size)))
        im = PIL.Image.fromarray(np.uint8(cm.hot(map) * 255))
        cv_im = np.array(im)

        msg_frame = CvBridge().cv2_to_imgmsg(cv_im, 'rgba8')
        self.pub.publish(msg_frame)

        if self.visualize:
            plt.figure(figure)
            plt.clf()
            fig = plt.imshow(map, origin='lower', cmap=cm.hot)
            plt.title(title)
            plt.colorbar()
            if len(self.probedPoints) != 0:
                plt.scatter(self.probedPoints[:, 0], self.probedPoints[:, 1])
            # plt.xlim((0,int(np.sqrt(map.size))))
            # plt.ylim((0,int(np.sqrt(map.size))))
            # plt.tight_layout()
            # plt.show()
            plt.pause(0.01)
Exemplo n.º 6
0
    def visualize_map(self, title, figure, map=None, probed_points=None):
        if map is None:
            dense_grid = self.generateGrid(res=1)

            ymu = self.gp.predict(self.grid, return_std=False)
            ymu[ymu < 0] = 0
            map = ymu
        map = map.reshape(int(np.sqrt(map.size)), int(np.sqrt(map.size)))
        # map = map/np.max(map)

        im = PIL.Image.fromarray(np.uint8(cm.hot(map) * 255))
        cv_im = np.array(im)
        # cv_im = cv2.flip(cv_im,0)
        # embed()

        msg_frame = CvBridge().cv2_to_imgmsg(cv_im, 'rgba8')
        self.pub.publish(msg_frame)

        if self.visualize:
            plt.figure(figure)
            plt.clf()
            fig = plt.imshow(map, origin='upper', cmap=cm.hot)
            plt.title(title)
            plt.colorbar()
            if not (probed_points is None):
                plt.scatter(probed_points[:, 0], probed_points[:, 1])
            plt.xlim((0, int(np.sqrt(map.size))))
            plt.ylim((0, int(np.sqrt(map.size))))
            # plt.tight_layout()
            # plt.show()
            plt.pause(0.01)

        return msg_frame
Exemplo n.º 7
0
def display(pc, i):
    # 3D plotting of point cloud
    fig = plt.figure(i)
    ax = fig.gca(projection='3d')

    #ax.set_aspect('equal')
    X = pc[0]
    Y = pc[1]
    Z = pc[2]
    c = pc[3]
    """
	radius = np.sqrt(X**2 + Y**2 + Z**2)
	X = X[np.where(radius<20)]
	Y = Y[np.where(radius<20)]
	Z = Z[np.where(radius<20)]
	c = pc.points[3][np.where(radius<20)]
	print(radius)
	"""
    ax.scatter(X, Y, Z, s=1, c=cm.hot((c / 100)))

    max_range = np.array(
        [X.max() - X.min(),
         Y.max() - Y.min(),
         Z.max() - Z.min()]).max()
    Xb = 0.5 * max_range * np.mgrid[
        -1:2:2, -1:2:2, -1:2:2][0].flatten() + 0.5 * (X.max() + X.min())
    Yb = 0.5 * max_range * np.mgrid[
        -1:2:2, -1:2:2, -1:2:2][1].flatten() + 0.5 * (Y.max() + Y.min())
    Zb = 0.5 * max_range * np.mgrid[
        -1:2:2, -1:2:2, -1:2:2][2].flatten() + 0.5 * (Z.max() + Z.min())

    i = 0
    for xb, yb, zb in zip(Xb, Yb, Zb):
        i = i + 1
        ax.plot([xb], [yb], [zb], 'w')
Exemplo n.º 8
0
    def get_colors(self, qty):

        qty = np.power(qty / qty.max(), 1.0 / CONTRAST)

        if COLORMAP == 0:
            rgba = cm.gray(qty, alpha=ALPHA)
        elif COLORMAP == 1:
            rgba = cm.afmhot(qty, alpha=ALPHA)
        elif COLORMAP == 2:
            rgba = cm.hot(qty, alpha=ALPHA)
        elif COLORMAP == 3:
            rgba = cm.gist_heat(qty, alpha=ALPHA)
        elif COLORMAP == 4:
            rgba = cm.copper(qty, alpha=ALPHA)
        elif COLORMAP == 5:
            rgba = cm.gnuplot2(qty, alpha=ALPHA)
        elif COLORMAP == 6:
            rgba = cm.gnuplot(qty, alpha=ALPHA)
        elif COLORMAP == 7:
            rgba = cm.gist_stern(qty, alpha=ALPHA)
        elif COLORMAP == 8:
            rgba = cm.gist_earth(qty, alpha=ALPHA)
        elif COLORMAP == 9:
            rgba = cm.spectral(qty, alpha=ALPHA)

        return rgba
Exemplo n.º 9
0
def draw_output(im,
                rect_gt=None,
                rect_pred=None,
                hmap_pred=None,
                color_pred=None,
                color_gt=None):
    '''Modifies original image and returns an image that may be different.'''
    if color_pred is None:
        color_pred = COLOR_PRED
    if color_gt is None:
        color_gt = COLOR_GT

    draw = ImageDraw.Draw(im)
    if rect_gt is not None:
        rect_gt = _rect_to_int_list(_unnormalize_rect(rect_gt, im.size))
        draw.rectangle(rect_gt, outline=color_gt)
    if rect_pred is not None:
        rect_pred = _rect_to_int_list(_unnormalize_rect(rect_pred, im.size))
        draw.rectangle(rect_pred, outline=color_pred)
    del draw

    if hmap_pred is not None:
        assert len(hmap_pred.shape) == 3
        hmap_pred = Image.fromarray(cm.hot(hmap_pred[:, :, 0],
                                           bytes=True)).convert('RGB')
        # Caution: This does not resize with align_corners=True.
        if hmap_pred.size != im.size:  # i.e., OTB
            hmap_pred = hmap_pred.resize(im.size)
        im = Image.blend(im, hmap_pred, 0.5)
    return im
def get_cmap(group, age, scale=1):
    structure_vals, n = get_mean_value_per_structure(group, age, dat['structure_id'].unique())
    rgb_vals = structure_vals.copy()
    for key in structure_vals:
        rgb_vals[key] = tuple([255*i for i in cm.hot(structure_vals[key]*scale)[:3]])
        rgb_vals[0] = (0, 0, 0)
    return rgb_vals, n
Exemplo n.º 11
0
    def get_colors(self, qty):

        qty = np.power(qty / qty.max(), 1.0 / CONTRAST)

        if COLORMAP == 0:
            rgba = cm.gray(qty, alpha=ALPHA)
        elif COLORMAP == 1:
            rgba = cm.afmhot(qty, alpha=ALPHA)
        elif COLORMAP == 2:
            rgba = cm.hot(qty, alpha=ALPHA)
        elif COLORMAP == 3:
            rgba = cm.gist_heat(qty, alpha=ALPHA)
        elif COLORMAP == 4:
            rgba = cm.copper(qty, alpha=ALPHA)
        elif COLORMAP == 5:
            rgba = cm.gnuplot2(qty, alpha=ALPHA)
        elif COLORMAP == 6:
            rgba = cm.gnuplot(qty, alpha=ALPHA)
        elif COLORMAP == 7:
            rgba = cm.gist_stern(qty, alpha=ALPHA)
        elif COLORMAP == 8:
            rgba = cm.gist_earth(qty, alpha=ALPHA)
        elif COLORMAP == 9:
            rgba = cm.spectral(qty, alpha=ALPHA)

        return rgba
def manipulate_latent(model, data, args):
    print('-' * 30 + 'Begin: manipulate' + '-' * 30)
    x_test, y_test = data
    index = np.argmax(y_test, 1) == args.digit
    number = np.random.randint(low=0, high=sum(index) - 1)
    x, y = x_test[index][number], y_test[index][number]
    x, y = np.expand_dims(x, 0), np.expand_dims(y, 0)
    noise = np.zeros([1, 3, 16])
    x_recons = []
    for dim in range(16):
        for r in [
                -0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25
        ]:
            tmp = np.copy(noise)
            tmp[:, :, dim] = r
            x_recon = model.predict([x, y, tmp])
            x_recons.append(x_recon)

    x_recons = np.concatenate(x_recons)

    img = combine_images(x_recons, height=16)
    image = cm.hot(img) * 255
    Image.fromarray(image.astype(
        np.uint8)).save(args.save_dir + '/manipulate-%d.png' % args.digit)
    print('manipulated result saved to %s/manipulate-%d.png' %
          (args.save_dir, args.digit))
    print('-' * 30 + 'End: manipulate' + '-' * 30)
Exemplo n.º 13
0
    def visualize_map(self, title, figure, map=None, probed_points=None):
        if map is None:
            dense_grid=self.generateGrid(res=1)
            ymu = self.gp.predict(self.grid, return_std=False)
            ymu[ymu<0]=0
            map = ymu

        map=map.reshape(self.domain['L1'],self.domain['L2'])
        normalized_map = map/np.max(map)

        im = PIL.Image.fromarray(np.uint8(cm.hot(normalized_map)*255))
        cv_im=np.array(im)

        msg_frame = CvBridge().cv2_to_imgmsg(cv_im,'rgba8')
        self.pub.publish(msg_frame)
       
        if self.visualize:
            plt.figure(figure)
            plt.clf()
            fig=plt.imshow(normalized_map, origin='lower',cmap=cm.hot)
            plt.title(title)
            plt.colorbar()
            if not (probed_points is None):
                plt.scatter(probed_points[:,0],probed_points[:,1])
            # plt.xlim((0,100))
            # plt.ylim((0,100))
            # plt.tight_layout()
            # plt.show()
            filename = str(len(probed_points)).zfill(4)
            plt.savefig(filename + '.png')
            np.savetxt(filename + '.txt', self.estimated_map['mean'])
            plt.pause(0.01)

        return msg_frame
Exemplo n.º 14
0
def main():
    print("static uint32_t colormap[] = {")
    for i in range(256):
        l = i / 255
        c = cm.hot(l, 1, True)
        print("  0x{0:02x}{1:02x}{2:02x}".format(c[0], c[1], c[2]), end='')
        if (i != 255):
            print(",")
    print("\n};")
def test(model, data, args):

    time_date = datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
    filename = time_date + '_capsule_network' + '_batch_size=' + str(
        args.batch_size) + '_epochs=' + str(args.epochs) + '_ntr=' + str(
            x_train.shape[0]) + '_nch=' + str(x_train.shape[3])
    x_test, y_test = data
    y_pred, x_recon = model.predict(x_test, batch_size=100)
    print('-' * 30 + 'Begin: test' + '-' * 30)
    img = combine_images(
        np.concatenate([np.abs(x_test[:50]),
                        np.abs(x_recon[:50])]))
    image = cm.hot(img) * 255
    Image.fromarray(image.astype(np.uint8)).save(args.save_dir +
                                                 "/real_and_recon4.png")
    print('Reconstructed images are saved to %s/real_and_recon4.png' %
          args.save_dir)
    print('-' * 30 + 'End: test' + '-' * 30)

    predicted_classes = y_pred
    predicted_classes = np.asarray(predicted_classes)
    b = np.zeros_like(predicted_classes)
    b[np.arange(len(predicted_classes)), predicted_classes.argmax(1)] = 1
    predicted_classes = np.argmax(np.round(b), axis=1)
    b = np.zeros_like(y_test)
    b[np.arange(len(y_test)), y_test.argmax(1)] = 1
    y_test = np.argmax(np.round(b), axis=1)
    class_names = ['Unresolved', 'FRI', 'FRII']
    from sklearn.metrics import classification_report
    print(
        classification_report(y_test,
                              predicted_classes,
                              target_names=class_names,
                              digits=4))
    os.chdir(args.save_dir)
    filename1 = filename + '_classification_report.txt'
    f = open(filename1, 'w')
    f.write(
        classification_report(y_test,
                              predicted_classes,
                              target_names=class_names,
                              digits=4))

    f = open(filename1, 'w')
    f.write(
        classification_report(y_test,
                              predicted_classes,
                              target_names=class_names,
                              digits=4))

    ############# Architecture

    with open(filename + '_architecture.txt', 'w') as fh:
        model.summary(print_fn=lambda x: fh.write(x + '\n'))

    with open(filename + '_architecture.txt', 'w') as fh:
        model.summary(print_fn=lambda x: fh.write(x + '\n'))
Exemplo n.º 16
0
def write_images(output_dir, truth_path, color_img_path, visual_path,
                 maj_voted, strength_of_disagreement_img, equality_img):
    img_width = equality_img.shape[1]
    img_height = equality_img.shape[0]

    # Write already computed images
    cv2.imwrite(output_dir + '/majority_voted/' +
                Path(truth_path).name, maj_voted[:, :, 0])
    cv2.imwrite(output_dir + '/votes/' +
                Path(truth_path).name, maj_voted[:, :, 1])
    cv2.imwrite(output_dir + '/disagreement_strength/' +
                Path(truth_path).name, strength_of_disagreement_img)

    # Create image for direct visual inspection:
    pad_top = 40
    pad_middle = 10

    color_map = [i * (255 // 3) for i in range(4)]
    colorize = np.vectorize(lambda x: color_map[x])

    imgs = [equality_img * 255,
            colorize(maj_voted[:, :, 1]),
            colorize(np.multiply(np.invert(equality_img), maj_voted[:, :, 1])),
            colorize(maj_voted[:, :, 0])]

    img_captions = ['Majority vote == ground truth?',
                    'Number of Votes',
                    'Disagreement with ground truth',
                    'Majority-predicted classes']

    # Combine all four images on a single canvas with respective captions
    canvas = np.full(shape=(img_height + pad_top,
                            img_width * 5 + 4 * pad_middle),
                     fill_value=23, dtype=np.uint8)
    for j, (img, img_caption) in enumerate(zip(imgs, img_captions)):
        left = (img_width + pad_middle) * j
        right = (img_width + pad_middle) * j + img_width
        canvas[pad_top:, left:right] = img.astype(np.uint8)
        canvas = cv2.putText(img=canvas,
                             text=img_caption,
                             org=(left, pad_top - 10),
                             fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                             fontScale=0.4,
                             color=120,
                             thickness=1)
        if type(canvas) == cv2.UMat:
            canvas = cv2.UMat.get(canvas)

    canvas = cm.hot(canvas, bytes=True)[:, :, :3]
    canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)

    # Add color image
    left = (img_width + pad_middle) * 4
    right = (img_width + pad_middle) * 4 + img_width
    canvas[pad_top:, left:right] = cv2.imread(color_img_path)

    cv2.imwrite(visual_path, canvas)
Exemplo n.º 17
0
 def heatmap(self, activations, unit=None, mode='bilinear'):
     amin, amax = self.range_for(activations, unit)
     if unit is None:
         a = activations
     else:
         a = activations[unit]
     upsampler = self.upsampler_for(a)
     a = upsampler(a[None,None,...], mode=mode)[0,0].cpu()
     return PIL.Image.fromarray(
             (cm.hot((a - amin) / (1e-10 + amax - amin)) * 255
                 ).astype('uint8'))
 def __init__(self, parent):
     wx.Panel.__init__(self, parent)
     self.Bind(wx.EVT_PAINT, self.OnPaint)
     self.graph = np.zeros((SIZE,SIZE),np.float32)
     data = np.uint8(255*cm.hot(self.graph)[:,:,0:3])
     self.bmp = wx.BitmapFromBuffer(SIZE, SIZE, data)
     # create a buffer that can be used to store historical samples
     self.sample_buffer=np.zeros(NUM_WINDOWS*CHUNK,np.float32)
     self.sample_pos = 0 # start a first sample location
     self.graph_pos = 0 # which time line we are at
     self.in_setup = True
Exemplo n.º 19
0
    def color(self, n):
        n = self.color_clip(n)

        n = (n - self.color_range[0]) / float(
            self.color_range[1] - self.color_range[0])  # range to 0~1
        c = cm.hot(n)  # rgba tuple
        red = int(c[0] * 255) << 16 & 0xFF0000
        blue = int(c[1] * 255) << 8 & 0x00FF00
        green = int(c[2] * 255) & 0x0000FF
        rgb = 0x000000 | red | blue | green
        return rgb
 def __init__(self, parent):
     wx.Panel.__init__(self, parent)
     self.Bind(wx.EVT_PAINT, self.OnPaint)
     self.graph = np.zeros((SIZE,SIZE),np.float32)
     data = np.uint8(255*cm.hot(self.graph)[:,:,0:3])
     self.bmp = wx.BitmapFromBuffer(SIZE, SIZE, data)
     # create a buffer that can be used to store historical samples
     self.sample_buffer=np.zeros(NUM_WINDOWS*CHUNK,np.float32)
     self.sample_pos = 0 # start a first sample location
     self.sample_count = -1
     self.graph_pos = 0 # which time line we are at
     self.in_setup = True
Exemplo n.º 21
0
    def update(frame_number):
        # print frame_number
        x, y = gen.next()
        f.set_pos(xx + x, yy + y)
        # f.set_pos(frame_number,100)
        src = f.next()
        img.set_array(src)

        a, z = ld.get_value(copy(src))
        # print x,y, z
        img2.set_array(a)
        # print z, x, y
        xs.append(xx + x)
        ys.append(yy + y)
        line.set_data(xs, ys)
        scatter2.set_data([xx + x], [yy + y])

        ts.append(time.time() - st)
        # print z
        # z /= 3716625.0
        # z += 0.1 * random.random()
        # print x, y, z
        pattern.set_point(z, x, y)
        zs.append(z)
        # print ts
        # print zs
        tvint.set_data(ts, zs)
        ax4.set_ylim(min(zs) * 0.9, max(zs) * 1.1)

        tcs.append(f.time_constant)
        rcs.append(f.cradius)
        tc.set_data(ts, tcs)

        rs.set_data(ts, rcs)

        # >>>>>>>>>>>>>>>>>>>>>>>
        # add a plot that is the current points of the triangle
        # >>>>>>>>>>>>>>>>>>>>>>>
        xy = pattern._tri.xys()
        x, y, z = zip(*xy)
        # print x, y
        # cp.set_data(x, y)
        cp.set_offsets(zip(x, y))

        maz, miz = max(z), min(z)
        z = [(zi - miz) / (maz - miz) for zi in z]
        print z
        cp.set_facecolors([cm.hot(zi) for zi in z])
        # cp.set_edgecolors(z)
        if not pattern._tri.is_equilateral():
            print 'not eq'
Exemplo n.º 22
0
    def update(frame_number):
        # print frame_number
        x, y = gen.next()
        f.set_pos(xx + x, yy + y)
        # f.set_pos(frame_number,100)
        src = f.next()
        img.set_array(src)

        a, z = ld.get_value(copy(src))
        # print x,y, z
        img2.set_array(a)
        # print z, x, y
        xs.append(xx + x)
        ys.append(yy + y)
        line.set_data(xs, ys)
        scatter2.set_data([xx + x], [yy + y])

        ts.append(time.time() - st)
        # print z
        # z /= 3716625.0
        # z += 0.1 * random.random()
        # print x, y, z
        pattern.set_point(z, x, y)
        zs.append(z)
        # print ts
        # print zs
        tvint.set_data(ts, zs)
        ax4.set_ylim(min(zs) * 0.9, max(zs) * 1.1)

        tcs.append(f.time_constant)
        rcs.append(f.cradius)
        tc.set_data(ts, tcs)

        rs.set_data(ts, rcs)

        # >>>>>>>>>>>>>>>>>>>>>>>
        # add a plot that is the current points of the triangle
        # >>>>>>>>>>>>>>>>>>>>>>>
        xy = pattern._tri.xys()
        x, y, z = zip(*xy)
        # print x, y
        # cp.set_data(x, y)
        cp.set_offsets(zip(x, y))

        maz, miz = max(z), min(z)
        z = [(zi - miz) / (maz - miz) for zi in z]
        print z
        cp.set_facecolors([cm.hot(zi) for zi in z])
        # cp.set_edgecolors(z)
        if not pattern._tri.is_equilateral():
            print 'not eq'
Exemplo n.º 23
0
def animate_behav():
    with open("pickles/learnednet5.p", "rb") as p:
        dic = pickle.load(p)
    sim3 = dic["sim3"]
    m = dic["m"]
    f = dic["f"]
    net = sim3.network
    start_idx = 8500
    end_idx = 11250
    interval = 25
    query_start = (9500 - 8500) / 25
    query_end = (10250 - 8500) / 25
    f_pl = f[net.J_place_indices,
             start_idx:end_idx:interval]  # 9500-10250 query
    f_pl = np.flip(f_pl, axis=0)
    f_ep = f[net.J_episode_indices,
             start_idx:end_idx:interval]  # 9500-10250 query
    f_ep = np.flip(f_ep, axis=0)
    fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [1, 4]})
    camera = Camera(fig)
    f_colors = [cm.hot(i) for i in f_pl[:, 0]]
    my_circle = plt.Circle((0, 0), 0.7, color='white')
    axs[0].imshow(repmat(f_ep[:, 0], 5, 1), cmap='hot')
    axs[0].set_yticks([])
    axs[0].set_xticks([])
    axs[1].pie(x=np.ones(net.N_pl), colors=f_colors)
    axs[1].add_artist(my_circle)
    for i in range(f_pl.shape[1]):
        f_colors = [cm.hot(i) for i in f_pl[:, i]]
        axs[0].imshow(repmat(f_ep[:, i], 5, 1), cmap='hot')
        axs[1].pie(x=np.ones(net.N_pl), colors=f_colors)
        axs[1].add_artist(my_circle)
        camera.snap()
    Writer = ani.writers['ffmpeg']
    writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

    anim = camera.animate(interval=500, repeat_delay=3000, blit=True)
    anim.save('behav.mp4', writer=writer)
Exemplo n.º 24
0
def simpleTest():
    width = 50
    height = 100
    #points = np.array([
    #    [0.2, 0.3],
    #    [0.7, 0.5],
    #    [0.6,0.2],
    #    [0.3, 0.9],
    #    [0.8, 0.1]
    #])
    points = sampleRandomPoints(100, width, height)  #np.random.rand(20, 2)
    print("Points:")
    print(points)

    cells = bounded_voronoi(points, [0, width, 0, height])
    for i, cell in enumerate(cells):
        print("cell", i, "with point", cell.generator())
        print(cell.corner())

    # example density map
    density = np.zeros((width, height))
    for x in range(width):
        for y in range(height):
            density[x, y] = 1 - math.sqrt((x / width - 0.5)**2 +
                                          (y / height - 0.5)**2)

    # compute cell integrals
    cell_densities = [cell.integrate(density) for cell in cells]

    # plotting
    plt.figure(figsize=(20, 10))

    ax1 = plt.subplot(1, 2, 1)
    ax1.imshow(density, cmap=cm.hot)

    ax2 = plt.subplot(1, 2, 2)
    for cell, (d, _) in zip(cells, cell_densities):
        vertices = np.array(list(cell.corner()) + [cell.corner()[0]])
        ax2.fill(vertices[:, 0], vertices[:, 1], facecolor=cm.hot(d))
    ax2.plot([cell.generator()[0] for cell in cells],
             [cell.generator()[1] for cell in cells], 'b.')
    ax2.plot([d[1][0] for d in cell_densities],
             [d[1][1] for d in cell_densities], 'r.')
    for cell in cells:
        ax2.plot(cell.corner()[:, 0], cell.corner()[:, 1], 'go')
    for cell in cells:
        vertices = np.array(list(cell.corner()) + [cell.corner()[0]])
        ax2.plot(vertices[:, 0], vertices[:, 1], 'k-')
    #fig.show()
    plt.savefig("bounded_voronoi.png")
Exemplo n.º 25
0
def draw(L):
    X = range(len(L))
    Y = []
    for v in get_next(L, items):
        Y.append(v)

    offset = [0] * len(Y[0])
    plt.bar(X,
            Y[0],
            align='center',
            color=cm.hot(map(lambda c: c * 2.5, Y[0])))
    for p in zip(range(1, len(Y)), range(0, len(Y) - 1)):
        offset = [a + b for a, b in zip(Y[p[1]], offset)]
        plt.bar(X,
                Y[p[0]],
                bottom=offset,
                align='center',
                color=cm.hot(map(lambda c: c * 2.5, Y[p[0]])))


#    plt.savefig('bin_packing02.png', bbox_inches='tight')
    plt.gca().margins(0.1)
    plt.show()
Exemplo n.º 26
0
    def visualize(self, samples, costs):
        marker_array = vm.MarkerArray()

        for i, (sample, cost) in enumerate(zip(samples, costs)):
            if sample is None:
                continue

            origin = np.array([0., 0., 0.])
            angle = 0.
            for t in xrange(len(sample.get_U())):
                marker = vm.Marker()
                marker.id = i * len(sample.get_U()) + t
                marker.header.frame_id = '/map'
                marker.type = marker.ARROW
                marker.action = marker.ADD

                speed = sample.get_U(t=t, sub_control='cmd_vel')[0] / 5.
                steer = sample.get_U(t=t, sub_control='cmd_steer')[0]
                angle += (steer - 50.) / 100. * (np.pi / 2)
                new_origin = origin + [
                    speed * np.cos(angle), speed * np.sin(angle), 0.
                ]
                marker.points = [
                    gm.Point(*origin.tolist()),
                    gm.Point(*new_origin.tolist())
                ]
                origin = new_origin

                marker.lifetime = rospy.Duration()
                marker.scale.x = 0.05
                marker.scale.y = 0.1
                marker.scale.z = 0.1

                if cost == min(costs):
                    rgba = (0., 1., 0., 1.)
                    marker.scale.x *= 2
                    marker.scale.y *= 2
                    marker.scale.z *= 2
                else:
                    rgba = list(cm.hot(1 - cost))
                    rgba[-1] = 0.5
                marker.color.r, marker.color.g, marker.color.b, marker.color.a = rgba

                marker_array.markers.append(marker)

        # for id in xrange(marker.id+1, int(1e4)):
        #     marker_array.markers.append(vm.Marker(id=id, action=marker.DELETE))

        self.debug_cost_probcoll_pub.publish(marker_array)
Exemplo n.º 27
0
 def heatmap(self, activations, unit=None, mode='bilinear'):
     '''
     Produces a heatmap from the given activations.  The unit,
     if specified, is an index into the activations tensor,
     and is also used to dereference quantile ranges.
     '''
     amin, amax = self.range_for(activations, unit)
     if unit is None:
         a = activations
     else:
         a = activations[unit]
     upsampler = self.upsampler_for(a)
     a = upsampler(a[None, None, ...], mode=mode)[0, 0].cpu()
     return PIL.Image.fromarray((cm.hot(
         (a - amin) / (1e-10 + amax - amin)) * 255).astype('uint8'))
Exemplo n.º 28
0
    def _plot_distributions(self):
        prs, pgg = self._samples()
        to = self.template_objects
        x_axis_width = len(prs[0])
        bin_size = x_axis_width / (self.generalization_generator.range * 2)
        amp = 0.3

        # Scale the regularization samples bins to the [0, 1] interval
        prs = prs / np.amax(prs)
        prs = prs / 3

        # x-axis
        p_x = np.linspace(-self.generalization_generator.range,
                          self.generalization_generator.range, x_axis_width)

        f, ax = plt.subplots(1)

        # Draw the template objects at their position on the x axis
        for idx, mu in enumerate(to.mu):
            color = cm.hot(idx / 3 + 0.15)

            # Draw the regularization samples
            # label_regularization_samples = 'regularization samples ' + str(idx + 1)
            plt.bar(p_x, prs[idx], 0.5, color=color, alpha=0.6)

            # Draw the template objects at their position on the x axis
            to_x = np.zeros(np.shape(p_x))
            to_offset = ((self.generalization_generator.range + mu) * bin_size)
            to_x[int(to_offset)] = amp
            #label_template_objects = 'template object ' + str(idx + 1)
            label_template_objects = 'Object type ' + str(idx + 1)
            plt.bar(p_x, to_x, 1., color=color, label=label_template_objects)

            # Draw the generalization generated samples
            #label_generalization_samples = 'generalization generator ' + str(idx + 1)
            plt.plot(p_x, pgg[idx], color=color, linewidth=1.2)

        # Draw the figure
        plt.xlim([
            -self.generalization_generator.range,
            self.generalization_generator.range
        ])
        plt.ylim([0, 0.5])
        plt.title('Generative One-Shot Learning')
        plt.xlabel('Data values')
        plt.ylabel('Probability density')
        plt.legend()
        plt.show()
Exemplo n.º 29
0
def plot4d(inputarray, outname, xlabel='', ylabel='', zlabel='', project=1):

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    import numpy as np
    from pylab import cm

    fig = plt.figure(figsize=(8, 6), dpi=300)
    ax = fig.add_subplot(111, projection='3d')

    x, y, z, _ = inputarray.nonzero()
    c = inputarray.flatten()
    c = c[c != 0]

    # c=c/c.max()
    # c*=100
    s = c / c.min()
    from math import log10
    s = s + 0.01
    for i in range(len(s)):

        s[i]=log10(s[i])
        
    
    #sarr=c>0.06914700
    #sarr2=c<0.06914702
    #sarr=sarr&sarr2
    #s[sarr]=100
    #print(c)
        
    #colmap = cm.ScalarMappable(cmap=cm.hsv)
    #colmap.set_array(c)
    
    #s=s+1
    ax.scatter(x, z, y, c=cm.hot(c),s=s)
    
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_zlabel(zlabel)
    
    
    #fig.axes.get_xaxis().set_visible(False)
    #fig.axes.get_yaxis().set_visible(False)
    #fig.axes.get_zaxis().set_visible(False)
    if len(outname):
        fig.savefig(outname)
    return ax,plt,x,y,z,c
Exemplo n.º 30
0
def draw_pnt(data,header,output):
    #x = np.linspace(0,nrays,nrays)
    print "drawing"
    npoints = int(header["npoints"])
    date_begin_str = header["date_begin"]
    date_end_str = header["date_end"]
    time_begin_str = header["time_begin"]
    time_end_str = header["time_end"]

    o = ephem.Observer()
    o.lon = "37:37:48"

    t_begin = datetime.strptime(date_begin_str+" "+time_begin_str,"%d.%m.%Y %H:%M:%S") 

    msk = pytz.timezone("Europe/Moscow")
    t_begin.replace(tzinfo=msk)
    x = range(0,npoints)
    t_tuple = [t_begin+timedelta(seconds=i*3600*1.00/npoints) for i in x]
    s_t_tuple = []
    for t in t_tuple:
        o.date = datetime.utcfromtimestamp(float(t.strftime('%s')))
        s_t_tuple.append(datetime.strptime(str(o.sidereal_time()),"%H:%M:%S.%f"))

    
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twiny()

    plt.ylim([0,8000])

    ax2.plot(s_t_tuple,[0]*len(s_t_tuple),color = 'white',marker = '.',markersize = 0,lw = 0)
    for r in reversed(xrange(nrays)):
        c = cm.hot(r/76.,1)
        y = [(np.mean(data[i][r][0:6])+ 100*r) for i in x]
        ax1.plot(t_tuple,y,color = c,marker = '.',markersize = 0.1,lw = 0)

    
    ax2.grid(True)
    ax1.grid(True)
    ax1.set_xlabel("Moscow Time")
    ax2.set_xlabel("Star Time")
    fig.suptitle("BSA data from:" + date_begin_str)
    fig.autofmt_xdate()
    fig.set_size_inches(18.5,10.5)
    fig.savefig(output,dpi=300)

    plt.close(fig)
Exemplo n.º 31
0
def plot_walkers_traj(obs, traj_index='all'):
    """Plot the trajectory of all the individual walkers

    Arguments:
        obs_dict {dict} -- dictionary of observable

    Keyword Arguments:
        traj_index {str} -- all or index of a given walker (default: {'all'})

    Returns:
        float -- decorelation time
    """

    eloc = obs['local_energy']
    eloc = np.array(eloc).squeeze(-1)

    nstep, nwalkers = eloc.shape

    celoc = np.cumsum(eloc, axis=0).T
    celoc /= np.arange(1, nstep + 1)

    var_decor = np.sqrt(np.var(np.mean(celoc, axis=1)))
    print(var_decor)
    var = np.sqrt(np.var(celoc, axis=1) / (nstep - 1))
    print(var)

    Tc = (var_decor / var)**2

    if traj_index is not None:
        plt.subplot(1, 2, 1)

        if traj_index == 'all':

            plt.plot(eloc, 'o', alpha=1 / nwalkers, c='grey')
            cmap = cm.hot(np.linspace(0, 1, nwalkers))
            for i in range(nwalkers):
                plt.plot(celoc.T[:, i], color=cmap[i])
        else:
            plt.plot(eloc[traj_index, :], 'o', alpha=1 / nwalkers, c='grey')
            plt.plot(celoc.T[traj_index, :])
        plt.subplot(1, 2, 2)
        plt.hist(Tc)

    plt.show()

    return Tc
Exemplo n.º 32
0
def get_fused_output(ct, pet, mask, true_mask):
    pet = pet.astype('float32')
    pet = pet**(1/5)
    pet_img = cm.hot(pet)
    pet_img[..., -1] = pet
    
    mask_outline = get_outline(mask, [1, 0, 0])
    true_mask_outline = get_outline(true_mask, [0, 1, 0])
    
    fig, sub = plt.subplots(figsize=(5, 5))
    sub.axis('off')
    sub.imshow(ct, cmap='gray')
    sub.imshow(pet_img)
    sub.imshow(mask_outline)
    sub.imshow(true_mask_outline)
    
    return fig
Exemplo n.º 33
0
def bloch(ex_values, tlist, ops):
    """Plots expectation values of sx, sy and sz on the Bloch sphere.
    If one of these operators is not calculated, zeros are passed for that operator.
    
    Parameters:
    -----------
    ex_values : qutip.Result.expect or list
                expectation values per operator
    tlist : list, or numpy array
            times at which expectation values are evaluated
    ops : list
          operators of which the expectation values are found in ex_values
    
    Remark:
    -------
    Does not plot a color bar yet. The lines from the QuTiP tutorial (https://nbviewer.jupyter.org/github/qutip/qutip-notebooks/blob/master/examples/bloch_sphere_with_colorbar.ipynb), commented out down here, give an error which I have not been able to solve yet.
    """
    
    if 'sx' in ops:
        sx_exp = ex_values[ops.index('sx')]
    elif 'sx' not in ops:
        sx_exp = np.zeros(len(list(tlist)))
    if 'sy' in ops:
        sy_exp = ex_values[ops.index('sy')]
    elif 'sy' not in ops:
        sy_exp = np.zeros(len(list(tlist)))
    if 'sz' in ops:
        sz_exp = ex_values[ops.index('sz')]
    elif 'sz' not in ops:
        sz_exp = np.zeros(len(list(tlist)))
    
    b = Bloch()
    b.add_points([sx_exp, sy_exp, sz_exp], 'm')
    
    nrm = Normalize(-2,10)
    colors = cm.hot(nrm(tlist))
    b.point_color = list(colors)
    b.point_marker = ['o']
    # TODO: Plot color bar
#     left, bottom, width, height = [0.98, 0.05, 0.05, 0.9]
#     ax2 = b.fig.add_axes([left, bottom, width, height])
#     ColorbarBase(ax2, cmap=cm.hot, norm=nrm, orientation='vertical')
    b.show()
def fix_opacity_and_color_map(x, opacity_thresh=0.1, max_opacity=0.8):
    """"Given a 2d image, x, get rgbt values for each pixel and modify
    opacity values"""
    tmp = cm.hot(x)

    for i in xrange(tmp.shape[0]):
        for j in xrange(tmp.shape[1]):

            # XXXXXXXXXXXX
            tmp[i,j][0] *= 2
            tmp[i,j][1] *= 2
            tmp[i,j][2] *= 2

            # ############

            if x[i,j] > opacity_thresh:
                tmp[i,j][3] = max_opacity
            else:
                tmp[i,j][3] = max_opacity * x[i,j] / opacity_thresh
    return tmp
Exemplo n.º 35
0
def plot_one_histo(data, sequence, x_maximum):
    #x is a list
    a = np.arange(0.0, len(data))
    #pylab.hist(hist['Data'], bins=600, range=(0,600), histtype='step', align='mid', label=hist['Sequence']) 
    j=0
    y_maximum = 0
    for i in data:
        c = cm.hot(a[j]/(len(data)+1), 1)
        n, bins, patches = pylab.hist(i, bins=600, range=(0,600), histtype='step', label=str(sequence[j]), color=c)
        if max(n) > y_maximum:
            y_maximum = max(n)
        #pylab.title('Read Length Histogram  Barcode Sequence %s' % seq)
        j=j+1
    pylab.axis([0, x_maximum+100, 0, y_maximum+100])
    pylab.title("Read Length Histogram for Barcodes")
    pylab.legend(loc="upper right", ncol=1, labelspacing=0.01)
    pylab.xlabel('Read Length')
    pylab.ylabel('Count')
    pylab.savefig("ion_readLenHisto.png")
    pylab.grid(True)
def draw_circle(axes_handle, centers_x, centers_y, radii, scores=None):
    axes_handle.hold(True)
    n = 100 # number of samples for drawing circles
    if scores is None:
        colors = np.repeat(np.reshape([0, 0, 1], (1, 3)), 10, axis=0)
    else:
        (smin, smax) = (np.min(scores), np.max(scores))
        # create color map
        colors = cm.hot(np.arange(0, 256))
        colors = colors[63 : 192, 0:3]
        # use scores as indices into colormap    
        scores = np.int64(np.ceil(127. * ((scores - smin) / (smax - smin))))
        colors = colors[scores, :]
    
    # iterate over all circles that are passed
    for x, y, radius, color in zip(centers_x, centers_y, radii, colors):
        angles = np.arange(0, (2. - 2. / n) * pi, 1. / n)
        (xs, ys) = (radius * np.cos(angles) + x, radius * np.sin(angles) + y)
        axes_handle.plot(xs, ys, color=tuple(color), linewidth=2)
    fh.canvas.draw()
Exemplo n.º 37
0
def _cm_plot(data,headings,dates,ave_data,fig_num,colour_col,
             y_col,run_ave_points,n_plot_row,n_plot_col,n_plot_num):
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    depth = np.max(data[:,colour_col]) - np.min(data[:,colour_col])
    c_map = cm.hot(np.arange(256))
    
    Z = [[0,0],[0,0]]
    levels = range(int(np.min(data[:,colour_col])),
                    int(np.max(data[:,colour_col])),1)
    mappl = plt.contourf(Z,levels,cmap=cm.hot)      
   
    plt.figure(fig_num)   
 
    plt.subplot(n_plot_row,n_plot_col,n_plot_num)
    for i in range(len(data)):
        plot1 = plt.plot(dates[i],data[i,y_col])
        cm_point = np.floor(((np.max(data[:,colour_col]) - 
                data[i,colour_col]) / depth) * 255)
        plt.setp(plot1,linestyle = 'none',marker = '.')
        plt.setp(plot1,color = c_map[255 - cm_point,])
    

    plt.grid(True)
    plt.title('%s on %s'%(headings[colour_col],headings[y_col]))
    plt.ylabel('%s'%(headings[y_col]))
    plt.axis([min(dates),max(dates),min(data[:,y_col]),max(data[:,y_col])])
    plt.xticks(rotation = 90)
    ax = plt.gca()
    ax.xaxis.label.set_color([0.75,0.75,0.75])
    ax.tick_params(axis='x', colors=[0.75,0.75,0.75])
#    fig.patch.set_facecolor([1,0,0])
    ax.patch.set_facecolor([0.9,0.9,0.9])
    fig = plt.gcf()
    fig.subplots_adjust(top=0.95) 
    fig.subplots_adjust(bottom=0.12) 
    fig.subplots_adjust(left=0.08) 
    fig.subplots_adjust(right=0.97)
    plt.colorbar(mappl)
Exemplo n.º 38
0
 def drawcountry(self,
                 ax,
                 base_map,
                 iso2,
                 color,
                 alpha = 1):
     if iso2 not in self.countries:
         raise ValueError, "Where is that country ?"
     vertices = self.countries[iso2]
     shape = []
     for vertex in vertices:
         longs, lats = zip(*vertex)
         # conversion to plot coordinates
         x,y = base_map(longs, lats)
         shape.append(zip(x,y))
     lines = LineCollection(shape,antialiaseds=(1,))
     lines.set_facecolors(cm.hot(np.array([color,])))
     lines.set_edgecolors('white')
     lines.set_linewidth(0.5)
     lines.set_alpha(alpha)
     ax.add_collection(lines)
Exemplo n.º 39
0
Arquivo: logo.py Projeto: Jeff33/ptsa
def add_pizza():
    ax = fig.add_axes([0.025, 0.075, 0.3, 0.85], polar=True, resolution=50)

    ax.axesPatch.set_alpha(axalpha)
    ax.set_axisbelow(True)
    N = 8
    arc = 2. * np.pi
    theta = np.arange(0.0, arc, arc/N)
    radii = 10 * np.array([0.79, 0.81, 0.78, 0.77, 0.79, 0.78, 0.83, 0.78])
    width = np.pi / 4 * np.array([1.0]*N)
    theta = theta[1:]
    radii = radii[1:]
    width = width[1:]
    bars = ax.bar(theta, radii, width=width, bottom=0.0)
    for r, bar in zip(radii, bars):
        bar.set_facecolor(cm.hot(r/10.))
        bar.set_edgecolor('r')
        bar.set_alpha(0.6)

    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_visible(False)

    for line in ax.get_ygridlines() + ax.get_xgridlines():
        line.set_lw(0.8)
        line.set_alpha(0.9)
        line.set_ls('-')
        line.set_color('0.5')

    # add some veggie peperoni
    #theta = np.array([.08,.18,.32,.46,.54,.68,.77,.85,.96]) * np.pi * 2.0
    #radii = 10*np.array([.6,.38,.58,.5,.62,.42,.58,.67,.45])
    theta = np.array([.18,.32,.46,.54,.68,.77,.85,.96]) * np.pi * 2.0
    radii = 10*np.array([.38,.58,.5,.62,.42,.58,.67,.45])
    c = plt.scatter(theta,radii,c='r',s=7**2)
    c.set_alpha(0.75)

    ax.set_yticks(np.arange(1, 9, 2))
    ax.set_rmax(9)
Exemplo n.º 40
0
    def drawConfigurationGraphs(self, graphData, variable, keys=minimalDataKeys, normalize = True):
        data = [{k:v1 for k,v1 in v[1].items() if k in keys} for v in graphData]
        dataConfigs = [v[0] for v in graphData]
        maxVals = self.getMaxVals(data)
        #is the data a float (percent) or int (absolute value)
        isIntType = {k: isinstance(v, int) for k,v in data[0].items()}
        if normalize:
            relativeVals = [{k: (v*1.0/maxVals[k] if maxVals[k] != 0 else 0.0) if isIntType[k] else v for k,v in item.items()} for item in data]
        else:
            relativeVals = data

        N = len(keys)
        Ndata = len(data)
        Fdata = float(Ndata)
        ind = np.arange(N)
        width = 0.35
        # plot = plt.figure()
        fig, ax = plt.subplots()
        # fig, ax = plot.subplot()
        colors = [cm.hot(i/Fdata,1) for i in np.arange(len(data))]
        rects = []
        legends = ['{0}: {1}, unified: {2}'.format(variable, item[variable], item['unified']) for item in dataConfigs]
        i = 0
        for item in relativeVals:
            rects.append(ax.bar([idx*(Ndata+1)*width + i*width for idx in ind], [item[k] for k in keys], width, color=colors[i]))
            i = i+1
        ax.set_xticks([idx*width*(Ndata+1) + Ndata*width/2 for idx in ind])
        ax.set_xticklabels(keys, rotation=70)
        ax.set_ylabel('Normalized Values')
        ax.set_title('Performance by {0}'.format(variable))
        leg = ax.legend( (rects[i][0] for i in np.arange(Ndata)), legends, loc='center left',
                    bbox_to_anchor=(0.98, 0.5), ncol=1, fancybox=True, shadow=True, prop={'size':6})

        # plt.savefig(variable+'_in.png', bbox_extra_artists=[leg], bbox_inches='tight', figure=fig)

        return (fig, leg)
Exemplo n.º 41
0
    nest.Simulate(1600.0)

    # plot
    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)
    # get the neuron's membrane potential
    for i in range(num_neurons):
        dmm = nest.GetStatus(multimeter)[i]
        da_voltage = dmm["events"]["V_m"]
        voltage_precise[i] = da_voltage
        if i == num_neurons - 1:
            for j in range(num_neurons - 1):
                voltage_precise[j] -= da_voltage
        da_adapt = dmm["events"]["w"]
        da_syn = dmm["events"]["I_ex"]
        da_time = dmm["events"]["times"]
        ax1.plot(da_time, da_voltage, c=cm.hot(0.8 * i / float(num_neurons)), label=models[i])
        ax1.set_ylabel("Voltage (mV)")
        ax2.plot(da_time, da_adapt, c=cm.hot(0.8 * i / float(num_neurons)), label=models[i])
        ax2.set_ylabel("Current (pA)")
        ax3.plot(da_time, da_syn, c=cm.hot(0.8 * i / float(num_neurons)), label=models[i])
        ax3.set_xlabel("Time (ms)")
        ax3.set_ylabel("Conductance (nS)")

    plt.legend(loc=4)

    # ~ lst_di_param = [ nest.GetStatus(neuron)[0] for neuron in lst_neurons ]
    # ~ for di in lst_di_param:
    # ~ b_equal = True
    # ~ for key,val in lst_di_param[-1].iteritems():
    # ~ if key not in tpl_ignore:
    # ~ b_equal *= (val == di[key])
Exemplo n.º 42
0
def ellipse(data):
	x,y,a,b,theta,color = data
	R,G,B, _ = cm.hot(color)
	params = (x, y, a, b, theta, x, y, int(R*225), int(G*225), int(B*225))
	return '<ellipse cx="%f" cy="%f" rx="%f" ry="%f" transform="rotate(%f %f %f)" fill="#%02x%02x%02x"/>'%params
Exemplo n.º 43
0
    # Create array to calculate d(alpha)/dt to do coarse Euler integration.
    alphaDerivatives = np.zeros((3,))
    # Fill array with d(alpha)/dt values for each alphas.
    alphaDerivatives[:] = (a2-a1)/smallTstep
        
    # Find next alpha by an Euler step.
    nextAlpha = a2 + alphaDerivatives * bigTstep
    t += bigTstep
    
    # Lift back to the fine fine (theta) space to resume the fine integration.
    theta0 = np.dot(hermitePoly, nextAlpha)
    

## Plot the theta and alpha histories.
fig = plt.figure()
colors = cm.hot(np.linspace(0, 1, ncsteps))

ax = fig.add_subplot(2, 1, 1)
ax.set_xlabel('$\omega_i(t)$')
ax.set_ylabel(r'$\theta_i(t)$')  # The r'... (for "raw") is to prevent Python from interpreting \t as an escape code for a tab character.

bx = fig.add_subplot(2, 1, 2)
bx.set_xlabel('$t$')
bx.set_ylabel(r'$\alpha_k(t)$')

for i, c in zip(range(ncsteps), colors):
    ax.scatter(om, totalThetaHistory[:, i], color=c)
    ax.plot(om, totalThetaHistory[:, i], color='black')
    bx.scatter([times[i]]*nHermite, totalAlphaHistory[:, i], color=c)
    
# Draw lines through coarse points.
Exemplo n.º 44
0
def povray_making_movie(position) :

    X_size = 60

    # position == 0 ----> dermis
    # position == 1 ----> epidermis
    # position == 2 ----> top of basal membrane
    # position == 3 ----> bottom of basal membrane
    #position = 1

   
    if position == 0:
        open_file = 'states/indaderma_state_'
        open_file_pressure = 'pressure/indaderma_pressure.dat'
        write_file = '3D/indaderma_3D_'
        
    if position == 1:
        open_file = 'states/indaepidermis_state_'
        open_file_pressure = 'pressure/indaepidermis_pressure.dat'
        write_file = '3D/indaepidermis_3D_'
       
    if position == 2:
        open_file = 'states/top_basal_membrane_state_'
        open_file_pressure = 'pressure/top_basal_membrane_pressure.dat'
        write_file = '3D/top_basal_membrane_3D_'
        
    if position == 3:
        open_file = 'states/bottom_basal_membrane_state_'
        open_file_pressure = 'pressure/bottom_basal_membrane_pressure.dat'
        write_file = '3D/bottom_basal_membrane_3D_'
    


    filename_upload = open_file_pressure
    upload  = loadtxt(filename_upload)
    stress = empty((len(upload), 1))
    for i in range(0,len(upload)) :
        stress[i] = upload[i][1]
    
    max_number_of_cells = int(1 + upload[len(upload)-1][0])
    print 'max number of cells = ', max_number_of_cells

    for num_of_cell in range (0, max_number_of_cells):
        print 'num_of_cell = ', num_of_cell
        open_file_state = open_file + str(num_of_cell) +'.dat'
        with open(open_file_state,'r') as f:
            config, cells, links, ghosts, T = pickle.load(f)
        stress_partial = empty((num_of_cell + 1, 1))
        for i in range (0, num_of_cell+1) :
            stress_partial[i] = stress[(num_of_cell+1)*num_of_cell/2+i]
        print stress_partial
        if len(stress_partial)>1 :
            stress_partial = (stress_partial-stress_partial.min())/(stress_partial.max()-stress_partial.min())*0.9+0.1
        else :
            stress_partial[0] = 0.5
        col_array = []
        for i in range(0,len(stress_partial)) :
            rgb_color =  cm.hot(1-stress_partial[i],1.0)
            col_array.append(rgb_color)

        write_file_3D =  write_file +  str(num_of_cell) + '.txt'
        file_povray=open(write_file_3D,'w')
 
        numero_cancer = 0
        for cell in cells:
            if cell.type.name == 'tDermal':
                color = 'color LimeGreen'
            if cell.type.name == 'Epidermal':
                color = 'color MediumBlue'
            if cell.type.name == 'Basal':
                color = 'color Gray20'
            if cell.type.name == 'Corneum':
                color = 'color MediumVioletRed'
            if cell.type.name == 'Cancer':
                color = 'color <' + str(col_array[numero_cancer][0][0]) + ',' + str(col_array[numero_cancer][0][1]) + ',' +  str(col_array[numero_cancer][0][2]) + '>'
                numero_cancer = numero_cancer + 1
            s = 'sphere { <0, 0, 0>,' + str(cell.radius) + ' material {texture {pigment {' + color + '} finish { specular specularvalue roughness roughnessvalue reflection phongreflection }}}translate<' + str(cell.pos[0]) + ',' + str(cell.pos[1]) + ', 0.0 >}\n'
            file_povray.write(s)

        cutoff = X_size/2
        for link in links:
            if (link.two.pos[0]!=link.one.pos[0]) and (link.two.pos[1]!=link.one.pos[1]):
                d12 = link.one.pos-link.two.pos
                abs_d12 = norm(d12)
                if abs_d12 < cutoff :
                    color = 'color White'
                    s = 'cylinder { <' + str(link.one.pos[0]) + ',' + str(link.one.pos[1]) + ', 0.0 >,<' + str(link.two.pos[0]) + ',' + str(link.two.pos[1]) + ', 0.0 >,'  + str(0.1) + ' material {texture {pigment {' + color + '} finish { phong phongvalue_cyl phong_size phongsize_cyl reflection phongreflection_cyl}}}}\n'
                    file_povray.write(s)
        file_povray.close
Exemplo n.º 45
0
clusters = clusterator.predict(data)
result_df["cluster"] = clusters

# Color code by cluster, marker code by PHA flag
categories = np.unique(result_df["cluster"])
colors = np.linspace(0, 1, len(categories))
colordict = dict(zip(categories, colors))  
result_df["color"] = result_df["cluster"].apply(lambda x: colordict[x])

fig, ax = plt.subplots()
xv = 0
yv = 2
for c in colors:
    pha_df = result_df[(result_df["pha"] == True) & (result_df["color"] == c)]
    if not pha_df.empty:
        ax.scatter(pha_df[xv], pha_df[yv], marker='s', s=200, c=cm.hot(c))
        # uncomment to get the label for the PHA asteroid
        # for i, row in pha_df.iterrows():
        #     ax.annotate(df['neo_reference_id'][i], xy=row[[xv, yv]], textcoords='data')
        # pha_df.plot(kind='scatter', x=xv, y=yv, marker='x', markersize=20, color=cm.hot(c), ax=ax)

    non_pha_df = result_df[(result_df["pha"] == False) & (result_df["color"] == c)]
    if not non_pha_df.empty:
        ax.scatter(non_pha_df[xv], non_pha_df[yv], marker='o', c=cm.hot(c))
        # non_pha_df.plot(kind='scatter', x=xv, y=yv, marker='o', color=cm.hot(c), ax=ax)


# 2D
# fig, ax = plt.subplots()
# result_df[(result_df["pha"] == True)].plot(kind='scatter', x=1, y=2, marker='x', color='r', ax=ax)
# result_df[(result_df["pha"] == False)].plot(kind='scatter', x=1, y=2, marker='o', color='b', ax=ax)
Exemplo n.º 46
0
def draw_top_image(top):
    top_image = np.moveaxis(top, -1, 0)
    top_image = cm.hot(np.concatenate(top_image, axis=1))
    return cv2.cvtColor(top_image.astype(np.float32), cv2.COLOR_RGB2BGR)
Exemplo n.º 47
0
        nest.Connect(pn,(neuron[0],))

    nest.Simulate(1600.0)

    # plot

    plt.close("all")
    fig, (ax1, ax2) = plt.subplots(2,1,sharex=True)

    # get the neuron's membrane potential
    for i in range(num_models):
        dmm = nest.GetStatus(multimeter)[i]
        da_voltage = dmm["events"]["V_m"]
        da_adapt = dmm["events"][lst_record[i]]
        da_time = dmm["events"]["times"]
        ax1.plot(da_time,da_voltage,c=cm.hot(i/float(num_models)), label=models[i])
        ax1.set_ylabel('Voltage (mV)')
        ax2.plot(da_time,da_adapt,c=cm.hot(i/float(num_models)), label=models[i])
        ax2.set_xlabel('Time (ms)')
        ax2.set_ylabel(lst_ylabel[i])

    plt.legend(loc=4)


#-----------------------------------------------------------------------------#
# Compare network dynamics
#------------------------
#

if network:
    # time the simulations for each neural model and network size
Exemplo n.º 48
0
w_main = QtGui.QMainWindow()
w_cent = QtGui.QSplitter() #QtGui.QWidget()
w_main.setCentralWidget(w_cent)
#lay = QtGui.QHBoxLayout()
#w_cent.setLayout(lay)

# surface plot
w_surf = gl.GLViewWidget()
w_cent.addWidget(w_surf)
w_surf.setCameraPosition(distance=120)

verts = np.load('/home/duke/tvb-vert.npy')
faces = np.load('/home/duke/tvb-tri.npy')
nc = verts.shape[0]
colors = np.zeros((nc, 4))
colors = cm.hot(np.random.rand(nc))

m_data = gl.MeshData(vertexes=verts, faces=faces, vertexColors=colors)
m_surf = gl.GLMeshItem(meshdata=m_data)
#m_surf.setGLOptions('additive')
w_surf.addItem(m_surf)

# fake data
import h5py
h5 = h5py.File('/home/duke/surfspec.h5')
P = h5['all'][int(sys.argv[1])]
fs = np.r_[:P.shape[-1]*1.0]
lfs = np.log10(fs)

# line plots
split_lines = QtGui.QSplitter(QtCore.Qt.Vertical)
Exemplo n.º 49
0
def plot(data, graph_type, file_prefix, label_param):
	fig = plt.figure()
	ax = fig.add_subplot(111, projection='3d')

	if(graph_type == 1):#heatmap alfa beta vs accuracy rto vs rtt	
		title="Aproximacion Rtt vs Rto"
		ax.set_title(title)
		ancho_barra_x=([0.1]*len(data.alfas))
		ancho_barra_y=([0.1]*len(data.alfas))
		pos_inicial_z=([0]*len(data.alfas))
		#con el calculo loco de aca abajo, entre 0 y 1 los valores normalizados indican, mientras mas grande el valor, mas cerca RTT y RTO
		normalized_values = [1-(elem/float(max(data.diffsRttVsRTOProm))) for elem in data.diffsRttVsRTOProm]
		bar_colors_heat = [cm.hot(heat) for heat in normalized_values]
		ejex = "Alpha"
		ejey = "Beta"
		ejez = "Precision"
		ax.set_xlabel(ejex)
		ax.set_ylabel(ejey)
		ax.set_zlabel(ejez)
		#parametros:
		#pos_inicial_x, pos_inicial_y, pos_inicial_z, ancho_barra_x, ancho_barra_y, altura_barra_z, color=color_barras, alpha= transparencia entre 0 y 1
		ax.bar3d(data.alfas, data.betas, pos_inicial_z, ancho_barra_x, ancho_barra_y, normalized_values, color=bar_colors_heat, alpha=1)
		plt.suptitle(label_param)		

		plt.savefig(file_prefix + "_rtt_vs_rto.png")
		#plt.show()
		plt.close()

	if(graph_type == 2):
		title="Cant. Retransmisiones"
		ax.set_title(title)
		ancho_barra_x=([0.1]*len(data.alfas))
		ancho_barra_y=([0.1]*len(data.alfas))
		pos_inicial_z=([0]*len(data.alfas))
		#con el calculo loco de aca abajo, entre 0 y 1 los valores normalizados indican, mientras mas grande el valor, mas cerca RTT y RTO
		normalized_values = [(elem/float(max(data.retransmissions))) for elem in data.retransmissions]
		bar_colors_heat = [cm.hot(heat) for heat in normalized_values]		
		ejex = "Alpha"
		ejey = "Beta"
		ejez = "Cant. Retransmisiones"
		ax.set_xlabel(ejex)
		ax.set_ylabel(ejey)
		ax.set_zlabel(ejez)
		#parametros:
		#pos_inicial_x, pos_inicial_y, pos_inicial_z, ancho_barra_x, ancho_barra_y, altura_barra_z, color=color_barras, alpha= transparencia entre 0 y 1
		ax.bar3d(data.alfas, data.betas, pos_inicial_z, ancho_barra_x, ancho_barra_y, data.retransmissions, color=bar_colors_heat, alpha=1)
		plt.suptitle(label_param)

		plt.savefig(file_prefix + "_retransmisiones.png")
		#plt.show()
		plt.close()

	if(graph_type == 3):
		title="Rtx Timeout(RTO)"
		ax.set_title(title)
		ancho_barra_x=([0.1]*len(data.alfas))
		ancho_barra_y=([0.1]*len(data.alfas))
		pos_inicial_z=([0]*len(data.alfas))
		#con el calculo loco de aca abajo, entre 0 y 1 los valores normalizados indican, mientras mas grande el valor, mas cerca RTT y RTO
		normalized_values = [(elem/float(max(data.rtosProm))) for elem in data.rtosProm]
		bar_colors_heat = [cm.hot(heat) for heat in normalized_values]		
		ejex = "Alpha"
		ejey = "Beta"
		ejez = "RTO"
		ax.set_xlabel(ejex)
		ax.set_ylabel(ejey)
		ax.set_zlabel(ejez)
		#parametros:
		#pos_inicial_x, pos_inicial_y, pos_inicial_z, ancho_barra_x, ancho_barra_y, altura_barra_z, color=color_barras, alpha= transparencia entre 0 y 1
		ax.bar3d(data.alfas, data.betas, pos_inicial_z, ancho_barra_x, ancho_barra_y, data.rtosProm, color=bar_colors_heat, alpha=1)
		plt.suptitle(label_param)

		plt.savefig(file_prefix + "_rto.png")
		#plt.show()
		plt.close()

	if(graph_type == 4):#heatmap alfa beta vs accuracy rto vs rtt	
		title="Aproximacion Rtt vs Rto"
		ax.set_title(title)
		ancho_barra_x=([0.1]*len(data.delays))
		ancho_barra_y=([0.01]*len(data.pErrors))
		pos_inicial_z=([0]*len(data.delays))
		#con el calculo loco de aca abajo, entre 0 y 1 los valores normalizados indican, mientras mas grande el valor, mas cerca RTT y RTO
		normalized_values = [1-(elem/float(max(data.diffsRttVsRTOProm))) for elem in data.diffsRttVsRTOProm]
		bar_colors_heat = [cm.hot(heat) for heat in normalized_values]
		ejex = "Delay"
		ejey = "Probabilidad de Error"
		ejez = "Precision"
		ax.set_xlabel(ejex)
		ax.set_ylabel(ejey)
		ax.set_zlabel(ejez)
		#parametros:
		#pos_inicial_x, pos_inicial_y, pos_inicial_z, ancho_barra_x, ancho_barra_y, altura_barra_z, color=color_barras, alpha= transparencia entre 0 y 1
		ax.bar3d(data.delays, data.pErrors, pos_inicial_z, ancho_barra_x, ancho_barra_y, normalized_values, color=bar_colors_heat, alpha=1)
		plt.suptitle(label_param)		

		plt.savefig(file_prefix + "dp_rtt_vs_rto.png")
		#plt.show()
		plt.close()

	if(graph_type == 5):
		title="Cant. Retransmisiones"
		ax.set_title(title)
		ancho_barra_x=([0.1]*len(data.delays))
		ancho_barra_y=([0.01]*len(data.pErrors))
		pos_inicial_z=([0]*len(data.delays))
		#con el calculo loco de aca abajo, entre 0 y 1 los valores normalizados indican, mientras mas grande el valor, mas cerca RTT y RTO
		normalized_values = [(elem/float(max(data.retransmissions))) for elem in data.retransmissions]
		bar_colors_heat = [cm.hot(heat) for heat in normalized_values]		
		ejex = "Delay"
		ejey = "Probabildad de Error"
		ejez = "Cant. Retransmisiones"
		ax.set_xlabel(ejex)
		ax.set_ylabel(ejey)
		ax.set_zlabel(ejez)
		#parametros:
		#pos_inicial_x, pos_inicial_y, pos_inicial_z, ancho_barra_x, ancho_barra_y, altura_barra_z, color=color_barras, alpha= transparencia entre 0 y 1
		ax.bar3d(data.delays, data.pErrors, pos_inicial_z, ancho_barra_x, ancho_barra_y, data.retransmissions, color=bar_colors_heat, alpha=1)
		plt.suptitle(label_param)

		plt.savefig(file_prefix + "dp_retransmisiones.png")
		#plt.show()
		plt.close()

	if(graph_type == 6):
		title="Rtx Timeout(RTO)"
		ax.set_title(title)
		ancho_barra_x=([0.1]*len(data.delays))
		ancho_barra_y=([0.01]*len(data.pErrors))
		pos_inicial_z=([0]*len(data.delays))
		#con el calculo loco de aca abajo, entre 0 y 1 los valores normalizados indican, mientras mas grande el valor, mas cerca RTT y RTO
		normalized_values = [(elem/float(max(data.rtosProm))) for elem in data.rtosProm]
		bar_colors_heat = [cm.hot(heat) for heat in normalized_values]		
		ejex = "Delay"
		ejey = "Probabilidad de Error"
		ejez = "RTO"
		ax.set_xlabel(ejex)
		ax.set_ylabel(ejey)
		ax.set_zlabel(ejez)
		#parametros:
		#pos_inicial_x, pos_inicial_y, pos_inicial_z, ancho_barra_x, ancho_barra_y, altura_barra_z, color=color_barras, alpha= transparencia entre 0 y 1
		ax.bar3d(data.delays, data.pErrors, pos_inicial_z, ancho_barra_x, ancho_barra_y, data.rtosProm, color=bar_colors_heat, alpha=1)
		plt.suptitle(label_param)

		plt.savefig(file_prefix + "_rto.png")
		#plt.show()
		plt.close()		
Exemplo n.º 50
0
def plot_vector(ax,uv,x=0,y=0,color=0):
    return ax.quiver(x,y,uv[0],uv[1],cm.hot(color,1),angles='xy',scale_units='xy',scale=1)
	all_frequencies = np.array(all_frequencies_list)
	k = np.array(k)
	r = np.array(r)
	y_n = np.array(get_yn(all_frequencies))
	vars = [1.09, -1.02]
	#popt, pcov = curve_fit(function, x, y_n)
	#popt = leastsq(residual, vars, args = (y_n, k, r))
	solution = myleastsq(residual, vars, args = (y_n, k, r))
	rcParams['font.size'] = 16
	intercept = solution[0]
	slope  = solution[1]
	print intercept
	print slope
	fig = figure(count)
	ax = plt.axes([0.12, 0.10, 0.85, 0.85]) 
	p1 = plot(k_lists[0], freq_bin_1, marker= 'o', linestyle = 'None', color = cm.hot(.1))
	p2 = plot(k_lists[1], freq_bin_2, marker= 'o', linestyle = 'None', color = cm.hot(.2))
	p3 = plot(k_lists[2], freq_bin_3, marker= 'o', linestyle = 'None', color = cm.hot(.3))
	p4 = plot(k_lists[3], freq_bin_4, marker= 'o', linestyle = 'None', color = cm.hot(.4))
	p5 = plot(k_lists[4], freq_bin_5, marker= 'o', linestyle = 'None', color = cm.hot(.5))
	p6 = plot(k_lists[5], freq_bin_6, marker= 'o', linestyle = 'None', color = cm.hot(.6))
	p7 = plot(k_lists[6], freq_bin_7, marker= 'o', linestyle = 'None', color = cm.hot(.7))
	p8 = plot(k_lists[7], freq_bin_8, marker= 'o', linestyle = 'None', color = cm.hot(.8))
	p9 = plot(k_lists[8], freq_bin_9, marker= 'o', linestyle = 'None', color = cm.hot(.9))
	p10 = plot(k_lists[9], freq_bin_10, marker= 'o', linestyle = 'None', color = cm.hot(1))


	knew = arange(0,20,.1)
	r1 = RSA_midpoints[0]
	r2 = RSA_midpoints[1]
	r3 = RSA_midpoints[2]
Exemplo n.º 52
0
def SpectroPlot(data,nx=100,ny=100,ylabel='incidence angle',zlabel='Amplification',yscale='lin',cmap='rainbow'):
    import scipy.interpolate
    from matplotlib.colors import LogNorm
    from matplotlib.ticker import MaxNLocator
    
    if data['sensitivity']==False:
        raise IOError("Sensitivity calculation hasn't been performed! Please do so.")
    
    x = np.asarray(data['x'])
    y = np.asarray(data['y'])
    z = np.asarray(data['z'])

    xi,yi = np.logspace(np.log10(x.min()),np.log10(x.max()),nx), np.linspace(y.min(),y.max(),ny)
    xi,yi = np.meshgrid(xi,yi)
    
    # interpolation
    zi = scipy.interpolate.griddata((x,y),z,(xi,yi),method='linear')
    
    # plot the data
    f = plt.figure(figsize=(10.,5.),dpi=300)
    
    # plot velocity profile   
    a2= f.add_subplot(1,5,5)
    if type(data['hl'][0])==float:
        xmin = []
        xmax = []
        # plot vp
        if data['modeID']>=5:
            if type(data['vp'][0])==list:
                lvp = len(data['vp'][0])
                clistvp = cm.cool(np.arange(lvp))
                for i in range(len(data['vp'][0])):
                    vptemp = np.concatenate(([data['vp'][0][i]],data['vp'][1:]))
                    depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
                    
                    depth = [0.]
                    vp = [vptemp[0]/1000.]
                    for j in range(1,len(depthtemp)-1):
                        depth.append(depthtemp[j])
                        vp.append(vptemp[j-1]/1000.)
                        depth.append(depthtemp[j])
                        vp.append(vptemp[j]/1000.)   
                    depth.append(depth[-1]+0.1*depth[-1])
                    vp.append(vp[-1])                    
                    
                    a2.plot(vp,depth,color=clistvp[i])
                    xmax.append(np.max(vp))
            else:
                vptemp = data['vp']
                depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
                
                depth = [0.]
                vp = [vptemp[0]/1000.]
                for j in range(1,len(depthtemp)-1):
                    depth.append(depthtemp[j])
                    vp.append(vptemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vp.append(vptemp[j]/1000.)   
                depth.append(depth[-1]+0.1*depth[-1])
                vp.append(vp[-1])                
                
                a2.plot(vp,depth,color='b')
                xmax.append(np.max(vp))
        # plot vs
        if type(data['vs'][0])==list:
            lvs = len(data['vs'][0])
            clistvs = cm.hot(np.arange(lvs))
            for i in range(len(data['vs'][0])):
                vstemp = np.concatenate(([data['vs'][0][i]],data['vs'][1:]))
                depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
                
                depth = [0.]
                vs = [vstemp[0]/1000.]
                for j in range(1,len(depthtemp)-1):
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j]/1000.)   
                depth.append(depth[-1]+0.1*depth[-1])
                vs.append(vs[-1])                     
                
                a2.plot(vs,depth,color=clistvs[i])
                xmin.append(np.min(vs))
                xmax.append(np.max(vs))
        else:
            vstemp = data['vs']
            depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
            
            depth = [0.]
            vs = [vstemp[0]/1000.]
            for j in range(1,len(depthtemp)-1):
                depth.append(depthtemp[j])
                vs.append(vstemp[j-1]/1000.)
                depth.append(depthtemp[j])
                vs.append(vstemp[j]/1000.)   
            depth.append(depth[-1]+0.1*depth[-1])
            vs.append(vs[-1])             

            a2.plot(vs,depth,color='r')
            xmin.append(np.min(vs))
            xmax.append(np.max(vs))
        a2.set_xlim(np.min(xmin)-0.05,np.max(xmax)+0.05)
        a2.set_ylim(np.min(depth),np.max(depth))
    else:
        if data['modeID']>=5:
            ld = len(data['hl'][0])
            clistvp = cm.cool(np.arange(ld))
            clistvs = cm.hot(np.arange(ld))
            for i in range(len(data['hl'][0])):
                hl = np.concatenate(([data['hl'][0][i]],data['hl'][1:]))
                depthtemp = np.concatenate(([0.],np.cumsum(hl)))
                vptemp = data['vp']
                vstemp = data['vs']
                depth = [0.]
                vs = [vstemp[0]/1000.]
                vp = [vptemp[0]/1000.]
                for j in range(1,len(hl)):
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j-1]/1000.)
                    vp.append(vptemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j]/1000.)  
                    vp.append(vptemp[j]/1000.)   
                depth.append(depth[-1]+0.1*depth[-1])
                vs.append(vs[-1])
                vp.append(vp[-1])

                a2.plot(vp,depth,color=clistvp[i])
                a2.plot(vs,depth,color=clistvs[i])
                a2.set_xlim(np.min(vs)-0.05,np.max(vp)+0.05)
                a2.set_ylim(np.min(depth),np.max(depth))
        else:
            ld = len(data['hl'][0])
            clistvs = cm.hot(np.arange(ld))
            for i in range(len(data['hl'][0])):
                hl = np.concatenate(([data['hl'][0][i]],data['hl'][1:]))
                vstemp = data['vs']
                depthtemp = np.concatenate(([0.],np.cumsum(hl)))
                depth = [0.]
                vs =[vstemp[0]/1000.]
                for j in range(1,len(hl)):
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j]/1000.)     
                depth.append(depth[-1]+0.1*depth[-1])
                vs.append(vs[-1])
                a2.plot(vs,depth,color=clistvs[i])
                a2.set_xlim(np.min(vs)-0.05,np.max(vs)+0.05)
                a2.set_ylim(np.min(depth),np.max(depth))
    
    a2.invert_yaxis()
    a2.set_xlabel('Velocity (km/s)')
    a2.set_ylabel('Depth (m)')
    a2.set_title('Velocity profile')
    plt.xticks(rotation='vertical') 
    
    # plot data
    a = f.add_subplot(1,5,(1,4))
    #zi = np.log10(zi)
    #z = np.log10(z)
    
    am = a.imshow(zi, vmin=0.1, vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()],
             aspect = 'auto',norm=LogNorm())
    
    a.set_xlabel('Frequency (Hz)')
    a.set_ylabel(ylabel)
    a.set_xscale('log')
    if yscale=='log':
        print yscale
        a.set_yscale('log')
    a.minorticks_on()
    a.tick_params(axis='x', which='major', labelsize=11, labelcolor='k')
    a.tick_params(axis='x', which='minor', labelsize=10, labelcolor='grey')
    for axis in [a.xaxis]:
        axis.set_major_formatter(FuncFormatter(majortickformat))
        axis.set_minor_formatter(FuncFormatter(minortickformat))
    cb = plt.colorbar(am,label=zlabel)
    cb.locator = MaxNLocator(10)
#    cb.formatter = ScalarFormatter()
    cb.formatter = FuncFormatter(cbtickformat)
    cb.update_ticks()
    f.tight_layout()