Exemplo n.º 1
0
def plot_linreg_internal(alpha, E_batch, mu_P, S_P, n, sigma):
    """
	Plots the points of linreg and the line too.
	"""

    S_P1 = S_P(alpha, E_batch)  # cov matrix
    mu_P1 = mu_P(alpha, E_batch, S_P1)  # mean vector
    X, Y = E_batch  # unwrap
    fig, ax = plt.subplots(figsize=graph_size)
    ax.ticklabel_format(useOffset=False, style='plain')
    # Hide the right and top spines
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    # Only show ticks on the left and bottom spines
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')

    a = .5

    x_grid = np.linspace(np.min(X), np.max(X), num=100)[:, None]
    Phi_X = np.hstack((np.ones((x_grid.shape[0], 1)), x_grid))

    stdev_pred = np.sqrt(np.sum(np.dot(Phi_X, S_P1) * Phi_X, 1)[:, None])
    upper_bound = Phi_X @ mu_P1 + stdev_pred
    lower_bound = Phi_X @ mu_P1 - stdev_pred

    stdev_pred1 = np.sqrt(
        np.sum(np.dot(Phi_X, S_P1) * Phi_X, 1)[:, None] + sigma)
    upper_bound1 = Phi_X @ mu_P1 + stdev_pred1
    lower_bound1 = Phi_X @ mu_P1 - stdev_pred1

    a = .2

    plt.fill_between(np.squeeze(x_grid[:, 0]),
                     np.squeeze(lower_bound1),
                     np.squeeze(upper_bound1),
                     color=cm.autumn(.5),
                     alpha=a,
                     label='Std dev of predictions')

    plt.plot(x_grid,
             Phi_X @ mu_P1,
             '-',
             color=cm.autumn(1),
             label='Mean of predictions')

    plt.plot(X[:, 1], Y, 'xk', label='Observations')
    #plt.ylim(2 * np.min(Y), 2 * np.max(Y))
    plt.legend()
Exemplo n.º 2
0
    def region2rgba(rg, region_id, alpha=0.5):
        """
        Paints out the region outline selected via region_ID and converts the resulting 2D array slice to RGBA.

        Other than overlay2RGBA() and bg2RGBA(), this method takes a 2D array
        as input instead of a 3D array. That is because it is not useful to preprocess the
        entire 3D region outline layer, which would have to be redone every time the cross hair
        is pointing at another region.

        :param rg: The 2D region  relevance map.
        :param region_id: the region to plot
        :param alpha: the transparency
        :return: The resulting RGBA array.
        :rtype: numpy.ndarray
        """

        rgcopy = np.copy(rg)
        if region_id != 0:
            rgcopy[rgcopy != region_id] = 0
            rgcopy[rgcopy == region_id] = 1
        else:  # crosshair on background
            rgcopy[True] = 0
        alpha_mask = np.copy(rgcopy)
        alpha_mask[alpha_mask == 1] = alpha
        img = np.uint8(cm.autumn(rgcopy) * 255)
        img[:, :, 3] = np.uint8(alpha_mask * 255)
        ret = img.view("uint32").reshape(
            img.shape[:2])  # convert to 2D array of uint32
        return ret
Exemplo n.º 3
0
def _counter_post_per_thread(Thread_list, Post_list, group_n):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for th_i in range(1, len(Thread_list) + 1):
        thread = Thread_list[th_i]
        print(" title", thread.title, th_i)
        x_times, y_nums = _extract_time(thread.pi_list, Post_list)
        if len(x_times) == 0:
            print("     this thread has not post from users.")
            continue
        if group_n == "ALPHA":
            ax.plot(x_times, y_nums, label=th_i, color=cm.spring((th_i - 1) / len(Thread_list)))
        elif group_n == "BRAVO":
            ax.plot(x_times, y_nums, label=th_i, color=cm.summer((th_i - 1) / len(Thread_list)))
        elif group_n == "CHARLIE":
            ax.plot(x_times, y_nums, label=th_i, color=cm.autumn((th_i - 1) / len(Thread_list)))
        else:
            ax.plot(x_times, y_nums, label=th_i, color=cm.winter((th_i - 1) / len(Thread_list)))

    minutes = mdates.MinuteLocator(interval=5)  # 5分間隔で描画
    timeFmt = mdates.DateFormatter('%H:%M')  # x軸の時刻表示フォーマットの設定
    ax.xaxis.set_major_locator(minutes)  # 上記の条件をグラフに設定
    ax.xaxis.set_major_formatter(timeFmt)  # 上記の条件をグラフに設定
    plt.xlim(start_t, finish_t)  # x軸の範囲を設定
    plt.ylim(0, 70)  # y軸の範囲を設定
    plt.title(group_n)
    # plt.legend(loc='upper left')  #データの名前を表示
    fig.autofmt_xdate()  # いい感じにx軸の時刻表示を調節
    plt.savefig(fn_path + group_n[0] + "_per_counter_post_no_legend" + ".png")
    plt.show()
Exemplo n.º 4
0
    def __init__(self, I1, I2, positive=None, negative=None, **kwargs):
        """A visualizer for labelling positive and negative regions

        Args:
            I1, I2: The images to label

        Keyword Args:
            positive: The initial set of positive correspondences
            negative: The initial set of background examples
        """
        super(PNLabeller, self).__init__(I1, I2, **kwargs)
        self.positive = []
        self.negative = []
        self.mode = 'P'

        # initialize the colormaps
        self.pmap = cycle([cm.cool(i) for i in range(0, cm.cool.N, 16)])
        self.nmap = cycle([cm.autumn(i) for i in range(0, cm.autumn.N, 16)])
        self.cmap = self.pmap
        self.color = self.pmap.next()

        # redraw the initial set
        if positive is not None:
            for left, right in positive:
                left, right = tuple(left), tuple(right)
                self.positive.append((left, right))
                self.plot(left, right)

        if negative is not None:
            for left, self.color in zip(negative, self.nmap):
                left = tuple(left)
                self.negative.append(left)
                self.plot(left)
Exemplo n.º 5
0
def get_color(nr: int, all: int):
    # some magic to crate a redish hue mixed with some color
    fact = float(nr) / float(all)
    ## a bit fo magic to create a 2-d vector
    ## needed for numpy colors
    res = np.array(cm.autumn(fact))[None, :]
    return res
Exemplo n.º 6
0
def print_and_plot_results(count, results, verbose, plot_file_name):
    print("RPS calculated as 95% confidence interval")

    rps_mean_ar = []
    low_ar = []
    high_ar = []
    test_name_ar = []

    for test_name in sorted(results):
        data = results[test_name]
        rps = count / array(data)
        rps_mean = tmean(rps)
        rps_var = tvar(rps)
        low, high = norm.interval(0.95, loc=rps_mean, scale=rps_var**0.5)
        times = array(data) * 1000000 / count
        times_mean = tmean(times)
        times_stdev = tstd(times)
        print('Results for', test_name)
        print('RPS: {:d}: [{:d}, {:d}],\tmean: {:.3f} μs,'
              '\tstandard deviation {:.3f} μs'
              .format(int(rps_mean),
                      int(low),
                      int(high),
                      times_mean,
                      times_stdev))

        test_name_ar.append(test_name)
        rps_mean_ar.append(rps_mean)
        low_ar.append(low)
        high_ar.append(high)

        if verbose:
            print('    from', times)
        print()


    if plot_file_name is not None:
        import matplotlib.pyplot as plt
        from matplotlib import cm
        fig = plt.figure()
        ax = fig.add_subplot(111)
        L = len(rps_mean_ar)
        color = [cm.autumn(float(c) / (L - 1)) for c in arange(L)]
        bars = ax.bar(
            arange(L), rps_mean_ar,
            color=color, yerr=(low_ar, high_ar), ecolor='k')
        # order of legend is reversed for visual appeal
        ax.legend(
            reversed(bars), reversed(test_name_ar),
            loc='upper left')
        ax.get_xaxis().set_visible(False)
        plt.ylabel('Requets per Second', fontsize=16)
        print(plot_file_name)
        plt.savefig(plot_file_name, dpi=96)
        print("Plot is saved to {}".format(plot_file_name))
        if verbose:
            plt.show()
def clusterColor(i, norm, permutation, autumn=False):
    if i == -2:
        return (1, 0, 0, 1)  # Waypoints
    if i == -1:
        return (0, 0, 0, .1)  # Outlier
    if i == 0:
        return (0, 0, 0, 1)
    if autumn:
        return cm.autumn(norm(permutation[i]))
    return cm.rainbow(norm(permutation[i]))
Exemplo n.º 8
0
    def colorize(self, labelmap):
        #print(labelmap.shape)
        # Assign a unique color to each label
        labelmap = labelmap.astype(np.float32) / self.CONFIG.DATASET.N_CLASSES
        if self.autumn:
            colormap = cm.autumn(labelmap)[..., :-1] * 255.0
        else:
            colormap = cm.jet_r(labelmap)[..., :-1] * 255.0

        return np.uint8(colormap)
def set_color(c,n):
    if c == "rainbow":
        color = cm.rainbow(n/8.)
    elif c == "gnuplot":
        color = cm.gnuplot(n/8.)
    elif c == "autumn":
        color = cm.autumn(n/8.)
    elif c == "cool":
        color = cm.cool(n/8.)

    return color
Exemplo n.º 10
0
def colorfor(v_0_1, testname):
    if True:
        if is_c_code(testname):
            return cm.spectral(v_0_1)
        else:
            return cm.spectral(v_0_1)
    else:
        if is_c_code(testname):
            return cm.winter(v_0_1)
        else:
            return cm.autumn(v_0_1)
Exemplo n.º 11
0
def main_lidar():
    #dset = SimpleGeoDataset('/data/pointCloudStuff/img/DC/2013.utm.tif')
    dset = SimpleGeoDataset('/data/dc_tiffs/dc.tif')

    dir_ = '/data/pointCloudStuff/pc/dc'
    ext = '.las'

    #app = PointRenderer(1024//2,1024//2)
    app = PointRenderer(1024, 1024)
    #app = PointRenderer(1024*2,2*1024)

    app.init(True)

    for fname in [f for f in os.listdir(dir_) if f.endswith(ext)]:
        fname = os.path.join(dir_, fname)
        print(' - Opening', fname)
        with pylas.open(fname) as fp:
            las = fp.read()

            stride = 1
            '''
            pts0 = np.stack((las.x[::stride], las.y[::stride], las.z[::stride]),-1).astype(np.float32)
            lo,hi = np.quantile(pts0, [.003,.997], 0)
            pts0 = pts0[(pts0[:,0] > lo[0]) & (pts0[:,1] > lo[1]) & (pts0[:,2] > lo[2]) & \
                        (pts0[:,0] < hi[0]) & (pts0[:,1] < hi[1]) & (pts0[:,2] < hi[2]) ]
            pts1 = ((pts0 - lo) / max(hi - lo)) * 2 - 1
            #pts = torch.from_numpy(pts1).cuda()

            app.pts = pts1
            app.colors = (pts0 - lo) / (hi - lo)
            '''

            pts, colors, img = process_pc_get_pts(las, dset, stride)
            pts, density = voxelize.filterOutliers(torch.from_numpy(pts), 12)
            density = density.cpu().numpy()
            pts = pts.cpu().numpy()
            T = 2
            pts = pts[density > T]
            colors = autumn(density[density > T] / 5)[..., :3].astype(
                np.float32)
            #colors[density<1.7] = (0,1,0)

            #app.pts,app.colors = pts,colors
            app.setPts(pts, colors, None)

            print(' - Setting', app.pts.shape[0], 'pts')

            while not app.q_pressed:
                app.startFrame()
                app.render()
                app.endFrame()
                #if app.endFrame(): break
            app.q_pressed = False
Exemplo n.º 12
0
def view_map(map_data, stores=None, paths=None, points=None, grid=True):
    """
    View map with entities like paths, stores, and points. Each
    entity argument is a list and the z-order (visibility) increases
    with index in the list. Among entities z-order varies as
    stores < paths < points.

    The map shows passable as yellow and impassable as purple. Each
    entity list cycles through an indepedent color map, i.e. each
    path in paths will have a different color. All points are
    displayed in black color.

    Args:
        map_data:    Boolean numpy array. True for passable, False
            for impassable.
        paths:       List of paths to be shown.
        stores:      Point stores to be shown.
        points:      Special points to be displayed.
        grid:        Display grid. Defaults to True.

    Notes:
        coordinates: click anywhere on the map to view coordinates
            of that point.
    """

    if stores:
        colors = cm.autumn(np.linspace(0, 1, len(stores)))
        for c, store in zip(colors, stores):
            x, y = get_x_and_y_from_itr(store)
            plt.scatter(x, y, color=c)

    if paths:
        colors = cm.winter(np.linspace(0, 1, len(paths)))
        for c, path in zip(colors, paths):
            start, end = path[0], path[-1]
            x, y = get_x_and_y_from_itr(path)
            plt.scatter(x, y, color=c)
            plt.plot(start.x, start.y, marker='x')
            plt.plot(end.x, end.y, marker='x')

    if points:
        x = [point.x for point in points]
        y = [point.y for point in points]
        plt.scatter(x, y, color='black', marker='o')

    m, n = map_data.shape
    plt.imshow(map_data)
    plt.xticks(np.arange(0.5, n, 1.0), [])
    plt.yticks(np.arange(-0.5, m, 1.0), [])
    plt.grid(grid)
    plt.connect('button_press_event', mouse_move)
    plt.show()
    return
Exemplo n.º 13
0
def main_linear_basis():
    parser = argparse.ArgumentParser()
    parser.add_argument('model', type=str)
    parser.add_argument('initial_geometry', type=str)
    parser.add_argument('--use_linear_transform',
                        action='store_true',
                        default=False)
    parser.add_argument('axis', type=str)
    parser.add_argument('rotations', type=str)
    parser.add_argument('--in_radians', action='store_true', default=False)
    args = parser.parse_args()

    args.axis = eval(args.axis)
    args.rotations = eval(args.rotations)

    vis = VisualiseMesh()

    T = load_input_mesh(args.model)
    V = load_input_geometry(args.initial_geometry, args.use_linear_transform)
    V -= np.mean(V, axis=0)
    vis.add_mesh(V,
                 T,
                 actor_name='base',
                 color=(31, 120, 180),
                 compute_normals=True)

    axis = np.asarray(args.axis)
    assert axis.ndim == 1 and axis.shape[0] == 3
    axis /= norm(axis)

    rotations = (args.rotations if args.in_radians else map(
        np.deg2rad, args.rotations))

    q = map(lambda r: quaternion.quat(axis * r), rotations)
    R = map(quaternion.rotationMatrix, q)
    V1 = map(lambda r: np.dot(V, np.transpose(r)), R)

    n = len(V1)
    colors = cm.autumn(np.linspace(0., 1., n, endpoint=True), bytes=True)

    for i in xrange(n):
        vis.add_mesh(V1[i],
                     T,
                     actor_name='rotated_%d' % i,
                     color=colors[i],
                     compute_normals=True)

    vis.camera_actions(('SetParallelProjection', (True, )))

    for actor in vis.actors.keys():
        vis.actor_properties(actor, ('SetRepresentation', (3, )))

    vis.execute()
Exemplo n.º 14
0
def main_compositional_basis():
    parser = argparse.ArgumentParser()
    parser.add_argument('model', type=str)
    parser.add_argument('initial_geometry', type=str)
    parser.add_argument('--use_linear_transform',
                        action='store_true',
                        default=False)

    parser.add_argument('axes', type=str)
    parser.add_argument('rotations', type=str)
    parser.add_argument('--in_radians', action='store_true', default=False)

    args = parser.parse_args()

    for key in ['axes', 'rotations']:
        setattr(args, key, eval(getattr(args, key)))

    vis = VisualiseMesh()

    T = load_input_mesh(args.model)
    V = load_input_geometry(args.initial_geometry, args.use_linear_transform)
    V -= np.mean(V, axis=0)
    vis.add_mesh(V,
                 T,
                 actor_name='base',
                 color=(31, 120, 180),
                 compute_normals=True)

    axes = np.asarray(args.axes)
    assert axes.shape == (2, 3)
    axes = normalise(axes)

    rotations = np.atleast_2d(args.rotations)
    assert rotations.shape[1] == 2

    if args.in_radians:
        rotations = np.rad2deg(rotations)

    n = len(rotations)
    colors = cm.autumn(np.linspace(0., 1., n, endpoint=True), bytes=True)

    for i in xrange(n):
        x = reduce(axis_angle.axAdd, axes * rotations[i][:, np.newaxis])
        q = quaternion.quat(x)
        R = quaternion.rotationMatrix(q)
        V1 = np.dot(V, np.transpose(R))
        vis.add_mesh(V1,
                     T,
                     actor_name='rotation_%d' % i,
                     color=colors[i],
                     compute_normals=True)

    vis.execute()
Exemplo n.º 15
0
    def __init__(self, video, df_PSFs, median_filter_flag=False, step=1, color='gray', imgSizex=5, imgSizey=5, value=0):
        """
        This class displays video in the Jupyter notebook interactively while highlighting PSFs with trajectories.

        Parameters
        ----------
        video: NDArray
           Input video.

        df_PSFs: panda data_frame
            Data Frames that contains the location of PSFs.

        median_filter_flag: bool
           In case it defines as True, a median filter is applied with size 3 to remove hot pixel effect.

        color: str
           It defines the colormap for visualization.

        imgSizex: int
           Image length size.

        imgSizey: int
           Image width size.

        IntSlider_width: str
           Size of slider.

        step: int
           Stride between visualization frames.

        value: int
            Initial frame value for visualization
        """

        self.video = video
        self.df_PSFs = df_PSFs
        self.imgSizex = imgSizex
        self.imgSizey = imgSizey
        self.df_PSFs = df_PSFs
        self.median_filter_flag = median_filter_flag
        self.color = color
        self.median_filter_flag = median_filter_flag
        if self.df_PSFs.particle.isnull().any():
            self.df_PSFs['particle'] = 0
            self.list_particles_idx = self.df_PSFs.particle.unique()
        else:
            self.list_particles_idx = self.df_PSFs.particle.unique()

        colors_ = cm.autumn(np.linspace(0, 1, len(self.list_particles_idx)))

        self.colors = colors_[0:len(self.list_particles_idx), :]
        interact(self.show_psf, frame_number=widgets.IntSlider(min=0, max=self.video.shape[0] - 1, step=step, value=value,
                    readout_format='1', continuous_update=False, description='Frame:'))
Exemplo n.º 16
0
def print_and_plot_results(count, results, verbose, plot_file_name):
    print("RPS calculated as 95% confidence interval")

    rps_mean_ar = []
    low_ar = []
    high_ar = []
    test_name_ar = []

    for test_name in sorted(results):
        data = results[test_name]
        rps = count / array(data)
        rps_mean = tmean(rps)
        rps_var = tvar(rps)
        low, high = norm.interval(0.95, loc=rps_mean, scale=rps_var**0.5)
        times = array(data) * 1000000 / count
        times_mean = tmean(times)
        times_stdev = tstd(times)
        print('Results for', test_name)
        print('RPS: {:d}: [{:d}, {:d}],\tmean: {:.3f} μs,'
              '\tstandard deviation {:.3f} μs'.format(int(rps_mean), int(low),
                                                      int(high), times_mean,
                                                      times_stdev))

        test_name_ar.append(test_name)
        rps_mean_ar.append(rps_mean)
        low_ar.append(low)
        high_ar.append(high)

        if verbose:
            print('    from', times)
        print()

    if plot_file_name is not None:
        import matplotlib.pyplot as plt
        from matplotlib import cm
        fig = plt.figure()
        ax = fig.add_subplot(111)
        L = len(rps_mean_ar)
        color = [cm.autumn(float(c) / (L - 1)) for c in arange(L)]
        bars = ax.bar(arange(L),
                      rps_mean_ar,
                      color=color,
                      yerr=(low_ar, high_ar),
                      ecolor='k')
        # order of legend is reversed for visual appeal
        ax.legend(reversed(bars), reversed(test_name_ar), loc='upper left')
        ax.get_xaxis().set_visible(False)
        plt.ylabel('Requets per Second', fontsize=16)
        print(plot_file_name)
        plt.savefig(plot_file_name, dpi=96)
        print("Plot is saved to {}".format(plot_file_name))
        if verbose:
            plt.show()
Exemplo n.º 17
0
def showStressMap():
    #load data
    coords, values, time = loadStressData()
    #normalize distribution
    values = np.array(values)
    values /= (np.mean(values)/0.5)
    values = np.clip(values,0,1)
    #display data
    for i in range(len(coords)-1):
        zipped = zip(coords[i], coords[i+1])
        #choose appropriate colormap
        col = cm.autumn(values[i])
        plt.plot(zipped[0],zipped[1],lw=3,color=col)
Exemplo n.º 18
0
def _counter_post_per_user(User_list, Post_list, group_n):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    sort_uilist = sorted(User_list.keys())
    for u_i in sort_uilist:
        if u_i in except_usr_id:
            continue
        user = User_list[u_i]
        print(" user", user.name, u_i)
        x_times, y_nums = _extract_time(user.pi_list, Post_list)
        if len(x_times) == 0:
            print("     this thread has not post from users.")
            continue
        if group_n == "ALPHA":
            ax.plot(x_times, y_nums, label=user.name, color=cm.spring((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.spring((u_i - 1) / len(User_list)))
        elif group_n == "BRAVO":
            ax.plot(x_times, y_nums, label=user.name, color=cm.summer((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.summer((u_i - 1) / len(User_list)))
        elif group_n == "CHARLIE":
            ax.plot(x_times, y_nums, label=user.name, color=cm.autumn((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.autumn((u_i - 1) / len(User_list)))
        else:
            ax.plot(x_times, y_nums, label=user.name, color=cm.winter((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.winter((u_i - 1) / len(User_list)))

    days = mdates.MinuteLocator(interval=5)
    daysFmt = mdates.DateFormatter('%H:%M')
    ax.xaxis.set_major_locator(days)
    ax.xaxis.set_major_formatter(daysFmt)
    plt.xlim(start_t, finish_t)
    plt.ylim(0, 40)
    plt.title(group_n)
    plt.legend(loc='upper left')
    fig.autofmt_xdate()
    plt.savefig(fn_path + group_n[0] + "_per_user_post_counter" + ".png")
    plt.show()
Exemplo n.º 19
0
def makePlots(arr):
    clips = []
    clipi = []

    smooths = []
    smoothi = []
    for t in list(set(arr)):
        subset = stars[arr == t]

        clispec, clivar = sigclip_coadd(subset, sigLim=3.0)
        clips.append(clispec)
        clipi.append(clivar)

    for s, i in zip(clips, clipi):
        flux = Spectrum(lbin, s, ivar=i)
        flux.smooth(width=5, filtertype="gaussian", replace=True)
        smooths.append(flux.flux)
        smoothi.append(flux.ivar)

    uniqarr = list(set(arr))
    sortInd = np.argsort(uniqarr)
    n = len(uniqarr)

    fig = py.figure(1, (9, 14))
    ax = fig.add_subplot(111)

    offset = 0
    weight = np.ones(len(lbin))
    weight[(7550 < lbin) & (lbin < 7700)] = np.nan

    for i in sortInd[1:]:
        color = cmp.autumn(i / np.float(n))
        ax.plot(lbin, weight * smooths[i] + offset, lw=2.0, color=color)
        offset += 1

    ax.set_xlim(5500, 9500)
    ax.set_ylim(0, 21)
    ax.set_xlabel("$\lambda$")
    ax.axes.get_yaxis().set_visible(False)

    fig = py.figure(1, (15, 5))
    ax = fig.add_subplot(111)

    for i in sortInd:
        color = cmp.cool(i / float(n))
        ax.plot(lbin, weight * smooths[i], color=color)

    ax.set_xlim(5500, 9500)
Exemplo n.º 20
0
    def __init__(self,
                 video,
                 df_PSFs,
                 time_delay=0.1,
                 GUI_progressbar=False,
                 *args,
                 **kwargs):
        """
        This class displays video while highlighting PSFs.

        Parameters
        ----------
        video: NDArray
            Input video.

        df_PSFs: panda data_frame
            Data Frames that contains the location of PSFs.

        time_delay: float
            Delay between frames in milliseconds.

        GUI_progressbar: bool
            This actives GUI progress bar

        """
        self.cpu = CPUConfigurations()
        super(DisplayDataFramePSFsLocalization, self).__init__()

        self.video = video
        self.time_delay = time_delay
        self.df_PSFs = df_PSFs
        self.pressed_key = {}
        self.list_line = []
        if 'particle' in self.df_PSFs.keys():
            self.list_particles_idx = self.df_PSFs.particle.unique()

        else:
            self.df_PSFs['particle'] = 0
            self.list_particles_idx = self.df_PSFs.particle.unique()

        self.GUI_progressbar = GUI_progressbar
        self.args = args
        self.kwargs = kwargs

        colors_ = cm.autumn(np.linspace(0, 1, len(self.list_particles_idx)))
        self.colors = colors_[0:len(self.list_particles_idx), :]
        self.obj_connection = SignalConnection()
Exemplo n.º 21
0
def getLightColors(_log, LightPer):
    try:
        _log.info("lightColors(LightPer) =" + str(LightPer))
        #normalize item number values to colormap
        norm = matplotlib.colors.Normalize(vmin=0, vmax=100)

        #colormap possible values = viridis, jet, spectral
        #rgba_color = cm.RdBu(norm(LightPer),bytes=True)
        rgba_color = cm.autumn(norm(int(LightPer)), bytes=True)

        _log.info("rgba_color =" + str(rgba_color))

        c = Color(rgb=(rgba_color[0] / 255, rgba_color[1] / 255,
                       rgba_color[2] / 255))
        _log.info("getLightColors =" + str(c))
    except:
        c = '#00FF00'
    return c
Exemplo n.º 22
0
def plot_star_3D():
    #THIS IS NOT WORKING, ITS A WIP.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import cm, colors
    from mpl_toolkits.mplot3d import Axes3D
    from scipy.special import sph_harm  #import package to calculate spherical harmonics
    import pdb

    theta = np.linspace(0, 2 * np.pi, 100)  #setting range for theta
    phi = np.linspace(0, np.pi, 100)  #setting range for phi
    phi, theta = np.meshgrid(phi, theta)  #setting the grid for phi and theta

    #Setting the cartesian coordinates of the unit sphere
    #Converting phi, theta, z to cartesian coordinates
    x = np.sin(phi) * np.cos(theta)
    y = np.sin(phi) * np.sin(theta)
    z = np.cos(phi)

    #Setting the aspect ratio to 1 which makes the sphere look spherical and not elongated
    fig = plt.figure(figsize=plt.figaspect(1.))  #aspect ratio
    axes = fig.add_subplot(111, projection='3d')  #sets figure to 3d
    fig.suptitle('m=4   l=4', fontsize=18, x=0.52, y=.85)

    m, l = 4, 4  #m and l control the mode of pulsation and overall appearance of the figure
    #Calculating the spherical harmonic Y(l,m) and normalizing it
    axes.view_init(30, 45)
    plt.ion()
    plt.show()
    for idx, angle in enumerate(np.linspace(0, 360, 20)):
        figcolors = sph_harm(m, l, theta + angle, phi).real
        figmax, figmin = figcolors.max(), figcolors.min()
        figcolors = (figcolors - figmin) / (figmax - figmin)

        #Sets the plot surface and colors of the figure where seismic is the color scheme
        axes.plot_surface(x,
                          y,
                          z,
                          rstride=1,
                          cstride=1,
                          facecolors=cm.autumn(figcolors))
        fig.canvas.draw_idle()
        pdb.set_trace()
Exemplo n.º 23
0
def animate(i):
    global res_lcs, com_lcs, ax, scat, fig
    print i
    
    fig.suptitle('Timestep: '+str((i+1)*36))
    
    res_data = res_lcsnorm[:,(i+1)*36-36:(i+1)*36+36,:].mean(1)
    com_data = com_lcsnorm[:,(i+1)*36-36:(i+1)*36+36,:].mean(1)

    res_newdata = ternaryPlot(res_data)
    com_newdata = ternaryPlot(com_data)

    res_scat.set_offsets(res_newdata)
    com_scat.set_offsets(com_newdata)

    res_colors = cm.autumn(res_data.sum(1))
    res_colors[:,3] = res_data.sum(1) #set opacity equal to intensity (currently not working)
    res_scat.set_facecolors(res_colors)
    
    com_colors = cm.winter(com_data.sum(1))
    com_colors[:,3] = com_data.sum(1)
    com_scat.set_facecolors(com_colors)

    return res_scat, com_scat
Exemplo n.º 24
0
plt.figure()
ax=plt.gca()
zbarr=0.5*(z0bins+zfbins)
ax.imshow([[0.,1.],[0.,1.]],extent=[2.0,2.24,-0.35,-0.30],interpolation='bicubic',cmap=cm.winter,aspect='auto')
ax.imshow([[0.,1.],[0.,1.]],extent=[2.0,2.24,-0.42,-0.37],interpolation='bicubic',cmap=cm.autumn,aspect='auto')
plt.text(1.7,-0.34,'$1^{\\rm st}\\,\\,{\\rm mode}$',{'fontsize':16})
plt.text(1.7,-0.41,'$2^{\\rm nd}\\,\\,{\\rm mode}$',{'fontsize':16})
for i in (1+np.arange(199))*10 :
    ax.plot(zbarr,e_o[  i,:,0]*np.sqrt(ndens)/np.sqrt(np.sum(e_o[  i,:,0]**2*ndens)),'o-',markeredgewidth=0,
             color=cm.winter((i+0.5)/2001))
    if e_o[i,2,1]>0 :
        sign=-1
    else :
        sign=1
    ax.plot(zbarr,sign*e_o[  i,:,1]*np.sqrt(ndens)/np.sqrt(np.sum(e_o[  i,:,1]**2*ndens)),'o-',
             markeredgewidth=0,color=cm.autumn((i+0.5)/2001))
plt.xlabel('$z_\\alpha$',fontsize=18)
plt.ylabel('$\\sqrt{\\bar{n}^\\alpha}\\,({\\sf E}_\\ell)^1_\\alpha$',fontsize=18)
plt.xlim([0.5,2.3])
plt.savefig("../Draft/Figs/kl_modes_wl.pdf",bbox_inches='tight')

fisher=(larr+0.5)[:,None]*(c_p_dw0/c_p_fid)**2
fish_permode=np.sum(fisher,axis=0)
fish_cum=np.cumsum(fish_permode)
print fish_cum
print fish_permode
plt.figure();

imodes=np.arange(nbins)+1
plt.plot(imodes,fish_permode/np.sum(fish_permode),'go-',lw=2,label='${\\rm Information\\,\\,in\\,\\,mode}\\,\\,p_{\\rm KL}$',markeredgewidth=0)
plt.plot(imodes[:-1],1-fish_cum[:-1]/fish_cum[-1],'ro-',lw=2,label='${\\rm Information\\,\\,in\\,\\,modes}\\,\\,>p_{\\rm KL}$',markeredgewidth=0)
Exemplo n.º 25
0
def ikkKO(AA, AB, AC, kv, nftot, **kwargs):
    TR = kwargs.get('TR', 1)
    start = kwargs.get('start', 2)
    ikk = kwargs.get('ikk')
    ###INITIATION#######
    sol = init(AA, AB, 1, kv, nftot, 0)

    ###SIMULATION#######
    Y0 = sol.y[:, -1]
    sol1 = sim(AA, AB, 1, kv, TR, Y0, 60 * 60 * 24)

    ###PROCESSING#######
    SOL = prc.fuse(sol.t, sol.y, sol1.t, sol1.y)
    pt = np.stack(prc.hour(SOL[0]))
    py = np.stack(SOL[1:SOL.shape[0]])

    KO = False
    time = None
    for i, j in enumerate(sol1.t):
        if j / 3600 >= start:
            KO = i
            time = j / 3600
            break

    py0 = sol1.y[1, KO]  ###.00128 1.8; .00125 24###
    py1 = sol1.y[6, KO] * 1000
    pt1 = sol1.t[KO] / 3600
    y0 = sol1.y[:, KO]
    y0[1] = 0
    sol3 = sim(AA, AB, AC, kv, TR, y0, (24 - start) * 60 * 60, ikk=True)
    y0[1] = py0 / 2
    sol4 = sim(AA, AB, AC, kv, TR, y0, (24 - start) * 60 * 60, ikk=True)
    y0[1] = py0 / 4
    sol5 = sim(AA, AB, AC, kv, TR, y0, (24 - start) * 60 * 60, ikk=True)
    y0[1] = py0
    sol6 = sim(AA, AB, AC, kv, TR, y0, (24 - start) * 60 * 60, ikk=True)
    y0[1] = 2 * py0
    sol7 = sim(AA, AB, AC, kv, TR, y0, (24 - start) * 60 * 60, ikk=True)

    plt.style.use('seaborn-paper')

    MAP = np.linspace(0, 1, 6)

    fig = plt.figure()
    gs = GridSpec(9, 1, hspace=0.1)

    ax = fig.add_subplot(gs[:8, :])
    ax3 = fig.add_subplot(gs[-1, :])

    colours1 = cm.winter(MAP)

    ax.plot(pt - 101, 1000 * py[6], c=(0, 0, 128 / 255))
    ax.plot(time + sol7.t / 3600,
            1000 * sol7.y[6],
            linestyle=(0, (5, 1)),
            c=colours1[0])
    ax.plot(time + sol6.t / 3600,
            1000 * sol6.y[6],
            linestyle=(0, (5, 5)),
            c=colours1[1])
    ax.plot(time + sol4.t / 3600, 1000 * sol4.y[6], '-.', c=colours1[2])
    ax.plot(time + sol5.t / 3600,
            1000 * sol5.y[6],
            linestyle=(0, (3, 1, 1, 1, 1, 1)),
            c=colours1[3])
    ax.plot(time + sol3.t / 3600,
            1000 * sol3.y[6],
            c=colours1[4],
            linestyle=(0, (1, 1)))

    handles = [
        Line2D([0], [0], color='black', lw=1, linestyle='-'),
        Line2D([0], [0], color='black', lw=1, linestyle=(0, (5, 1))),
        Line2D([0], [0], color='black', lw=1, linestyle=(0, (5, 5))),
        Line2D([0], [0], color='black', lw=1, linestyle='-.'),
        Line2D([0], [0],
               color='black',
               lw=1,
               linestyle=(0, (3, 1, 1, 1, 1, 1))),
        Line2D([0], [0], color='black', lw=1, linestyle=(0, (1, 1)))
    ]

    PY0 = 1000 * py0
    labels = [
        'wild-type', 'IKK={} nM'.format(np.around(2 * PY0, decimals=1)),
        'IKK={} nM'.format(np.around(PY0, decimals=1)),
        'IKK={} nM'.format(np.around(PY0 / 2, decimals=1)),
        'IKK={} nM'.format(np.around(PY0 / 4, decimals=1)), 'IKK=0 nM'
    ]
    ax.legend(handles,
              labels,
              loc=0,
              fontsize=10,
              framealpha=0,
              prop={'size': 10},
              edgecolor=None)
    ax.set_xlim(-1, 8)
    ax.set_xticks([])
    ax.set_ylabel('$c$ in nM')
    ax2 = ax.twinx()
    ax2.set_yticks([])
    ax2.set_ylabel('NF$\kappa$B')

    colours2 = cm.autumn(MAP)

    ax3.plot(pt - 101, 1000 * py[1], c=(170 / 255, 0, 0))
    ax3.plot(time + sol7.t / 3600,
             1000 * sol7.y[1],
             linestyle=(0, (5, 1)),
             c=colours2[0])
    ax3.plot(time + sol6.t / 3600,
             1000 * sol6.y[1],
             linestyle=(0, (5, 5)),
             c=colours2[1])
    ax3.plot(time + sol4.t / 3600, 1000 * sol4.y[1], '-.', c=colours2[2])
    ax3.plot(time + sol5.t / 3600,
             1000 * sol5.y[1],
             linestyle=(0, (3, 1, 1, 1, 1, 1)),
             c=colours2[3])
    ax3.plot(time + sol3.t / 3600,
             1000 * sol3.y[1],
             c=colours2[4],
             linestyle=(0, (1, 1)))

    ax3.set_ylim(-.1, 3)
    ax3.set_yticks([0, 1000 * py0, 2000 * py0])
    ax3.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax3.set_xlabel('$t$ in h')
    ax4 = ax3.twinx()
    ax4.set_yticks([])
    ax4.set_ylabel('IKK')

    trans = ax3.transAxes + ax.transData.inverted()
    ((xmin, _), (xmax, _)) = trans.transform([[0, 1], [1, 1]])
    ax3.set_xlim(xmin, xmax)
    ax3.axvline(pt1, linewidth=0.5, c='gray')
    ax.axvline(pt1, linewidth=0.5, c='gray')

    fig.tight_layout()
    plt.savefig('../../graphics/IKKvar.png', dpi=500)
    plt.close()

    return [pt, py, sol1, sol.t.shape[0], sol3, time]
Exemplo n.º 26
0
data = glob.glob('/backup/yuliya/v30/graphs_largedomain/fixed/*.gpickle')
data.sort()

d1.append(data1)
d.append(data)

data1 = glob.glob('/backup/yuliya/v35/breakups_con/fixed/*.npy')
data1.sort()
data = glob.glob(
    '/backup/yuliya/v35/graphs_largedomain/fixed/*_no_term_br.gpickle')
data.sort()

d1.append(data1)
d.append(data)

colors = cm.autumn(np.linspace(0, 1, 114))
colors1 = cm.winter(np.linspace(0, 1, 12))
t = np.load('/backup/yuliya/vsi01/vsi01_TimeInSec.npy')
u = 0
ell = np.load('/backup/yuliya/vsi05/dataellg_ellp.npy')[8:-10]
ellv34 = np.load('/backup/yuliya/v34/dataellg_ellp.npy')[13:-1][::1]
ellv34[7:-1] = ellv34[8:]
ellv34[10:-1] = ellv34[11:]
ellv34[45:-1] = ellv34[46:]
ellvsi05 = np.load('/backup/yuliya/vsi05/dataellg_ellp.npy')[8:-10]
ellvsi05[19:-1] = ellvsi05[20:]
ellv30 = np.load('/backup/yuliya/v30/dataellg_ellp.npy')[10:-1]
ellv30[61:-1] = ellv30[62:]
ellv30[63:-1] = ellv30[64:]
ellv35 = np.load('/backup/yuliya/v35/dataellg_ellp.npy')[22:-1]
ellv35[4:-1] = ellv35[5:]
# ======
# this figure shows the time levels in each run
figTimes = plt.figure(30, facecolor='w')
axTimes = figTimes.add_subplot(1, 1, 1)
plt.xlabel('Year')
axTimesYlabels = []


# =========
print "Done setting up figure axes."
# =========

# --- Define colors for lines ---
#colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:olive', 'tab:cyan']
n150 = sum("amp150" in r for r in runs)
colors = [ cm.autumn(x) for x in np.linspace(0.0, 1.0, n150) ]
n300 = sum("amp300" in r for r in runs)
colors.extend( [ cm.winter(x) for x in np.linspace(0.0, 1.0, n300) ] )
color_index = 0


# ================
# Loop over runs and plot data
# ================
runNumber = 0
for run in runs:
   print "Plotting run: " + run

   thisRun = runData[run]
   # Pull needed data for plotting from this run
   # TODO: replace local variables below in plotting commands with reference to object variables
Exemplo n.º 28
0
    def plotkSpaceTraj(self, contdraw, view3d):

        if not self.active:
            return

        fgc = 'white'  # Foreground color
        bgc = 'black'  # Background color

        self.fig.clear()
        plt.figure(self.fig.number)  # Workaround to set current figure
        gridspec = plt.GridSpec(1, 50)  # Ratio Figure Width / Colorbar Width

        if not view3d:
            ax = plt.subplot(gridspec[0, :-1])
        else:
            ax = plt.subplot(gridspec[0, :-1], projection='3d')

        C = cm.autumn(np.linspace(0, 1, np.size(self.J)))[::-1, :]

        # Draw Actual Trajectory
        for j in range(np.size(self.J)):
            if j < np.size(self.J) - 1:
                n_end = self.J[j + 1] - 2 + contdraw
            else:
                n_end = np.size(self.KX) - 1

            n_all = np.arange(start=self.J[j] + 1 - contdraw,
                              stop=n_end,
                              step=1)

            if not view3d:
                ax.plot(self.KX[n_all],
                        self.KY[n_all],
                        c=C[j, :],
                        linewidth=0.5)
            else:
                ax.plot(self.KX[n_all],
                        self.KY[n_all],
                        self.KZ[n_all],
                        c=C[j, :],
                        linewidth=0.5)
                ax.view_init(elev=90, azim=-90)

        if (self.KX.min() < self.KX.max()) and (self.KY.min() < self.KY.max()):
            ax.axis([
                1.1 * self.KX.min(), 1.1 * self.KX.max(), 1.1 * self.KY.min(),
                1.1 * self.KY.max()
            ])

        ax.grid(True, color=fgc)
        ax.set_aspect('equal')

        # Set Labels
        labels = ['%s [rad / mm]' % s for s in ['Kx', 'Ky', 'Kz']]
        ax.set_xlabel(labels[0], fontsize=15, fontweight='bold', color=fgc)
        ax.set_ylabel(labels[1], fontsize=15, fontweight='bold', color=fgc)
        if view3d:
            ax.set_zlabel(labels[2], fontsize=15, fontweight='bold', color=fgc)

        # Add colorbar
        if np.size(self.J) > 2:
            cax = plt.subplot(gridspec[0, -1])
            sm = plt.cm.ScalarMappable(cmap=cm.autumn)
            sm._A = []  # fake up the array of the scalar mappable.
            h = plt.colorbar(sm, orientation='vertical', cax=cax, ax=ax)
            h.set_ticks([])
            h.set_label('Late \t\t\t\t Early'.expandtabs(),
                        fontsize=15,
                        color=fgc)

        # Color elements in foreground color
        for child in ax.get_children():
            if isinstance(child, spines.Spine):
                child.set_color(fgc)

        ax.tick_params(axis='x', colors=fgc)
        ax.tick_params(axis='y', colors=fgc)
        ax.tick_params(axis='z', colors=fgc)

        # Color background
        self.fig.set_facecolor(bgc)
        ax.set_facecolor(bgc)

        # Transparent background
        if view3d:
            ax.w_xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
            ax.w_yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
            ax.w_zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))

        self.canvas.draw()
        self.cP = None
        self.ADCs = None
Exemplo n.º 29
0
n = 0
while n <= len(df["x"]) - 1:
    function = df["x"][n]**2 + df["y"][n]**2 + df["z"][n]**2
    if function < 0.:
        function = 0.
        color_list.append(function)
    elif function > 1.:
        function = 1.
        color_list.append(function)
    else:
        color_list.append(function)
    n += 1

df["color"] = color_list

# Import data to draw lines (Could be used to draw molecules later on)
data_df = pd.read_excel(r"data.xlsx", sheet_name=0)

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

norm = mpl.colors.Normalize(vmin=0, vmax=1)
ax.scatter(df['x'], df['y'], df['z'], color=cm.autumn(df["color"]), s=1)
ax.plot(data_df['x'], data_df['y'], data_df['z'])
ax.set_title('3D Color Function')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()
plt.savefig("colorfunction.png")
Exemplo n.º 30
0
    def plot(self):
        """ Generates plots using different calc functions. """
        flu_dist = self.calc_FLU()
        pam_dist = self.calc_PAM()
        ham_dist = self.calc_Ham()
        print("Hamming distance:", ham_dist)

        # distance calculations that only reference sub matrix if two characters don't match
        hyb_flu_dist = self.calc_FLU(hybrid=True)
        hyb_pam_dist = self.calc_PAM(hybrid=True)
        print("FLU hybrid", hyb_flu_dist)
        print("PAM hybrid", hyb_pam_dist)

        plt.figure(figsize=(
            8, 5))  # set up figure for plotting, width and height in inches
        cmap_1 = cm.autumn(np.linspace(0, 1, self.size))
        cmap_2 = cm.winter(np.linspace(0, 1, self.size))

        # plot standard form of FLU matrix
        slope, intercept, r_value, p_value, std_err = stats.linregress(
            self.eff, np.log(flu_dist))
        plt.scatter(self.eff,
                    np.log(flu_dist),
                    c=cmap_1,
                    alpha=0.8,
                    label=r"$\mathrm{standard: R^{2} = }$" +
                    str(round(r_value**2, 3)))
        abline(slope, intercept, plt, cmap_1[0])

        # plot hybrid form of FLU matrix
        slope, intercept, r_value, p_value, std_err = stats.linregress(
            self.eff, np.log(hyb_flu_dist))
        plt.scatter(self.eff,
                    np.log(hyb_flu_dist),
                    marker='*',
                    c=cmap_2,
                    alpha=0.8,
                    label=r"$\mathrm{hybrid: R^{2} = }$" +
                    str(round(r_value**2, 3)))
        abline(slope, intercept, plt, cmap_2[0])

        plt.title("FLU Distance Prediction Performance")
        plt.xlabel("Observed Efficacy")
        plt.ylabel("Relative Distance (log scaled)")
        plt.legend()
        plt.savefig('Figures/FLU_validation.png')

        plt.figure(figsize=(
            8, 5))  # set up figure for plotting, width and height in inches

        # plot standard form of PAM250 matrix
        slope, intercept, r_value, p_value, std_err = stats.linregress(
            self.eff, np.log(pam_dist))
        plt.scatter(self.eff,
                    np.log(pam_dist),
                    c=cmap_1,
                    alpha=0.8,
                    label=r"$\mathrm{standard: R^{2} = }$" +
                    str(round(r_value**2, 3)))
        abline(slope, intercept, plt, cmap_1[0])

        # plot hybrid form of PAM250 matrix
        slope, intercept, r_value, p_value, std_err = stats.linregress(
            self.eff, np.log(hyb_pam_dist))
        plt.scatter(self.eff,
                    np.log(hyb_pam_dist),
                    marker='*',
                    c=cmap_2,
                    alpha=0.8,
                    label=r"$\mathrm{hybrid: R^{2} = }$" +
                    str(round(r_value**2, 3)))
        abline(slope, intercept, plt, cmap_2[0])

        plt.title("PAM250 Distance Prediction Performance")
        plt.xlabel("Observed Efficacy")
        plt.ylabel("Relative Distance (log scaled)")
        plt.legend()
        plt.savefig('Figures/PAM_validation.png')

        plt.figure(figsize=(
            8, 5))  # set up figure for plotting, width and height in inches

        slope, intercept, r_value, p_value, std_err = stats.linregress(
            self.eff, ham_dist)
        plt.scatter(self.eff,
                    ham_dist,
                    c=cmap_1,
                    alpha=0.8,
                    label=r"$\mathrm{R^{2} = }$" + str(round(r_value**2, 3)))
        abline(slope, intercept, plt, cmap_1[0])
        plt.title("Hamming Distance Prediction Performance")
        plt.xlabel("Observed Efficacy")
        plt.ylabel("Relative Distance")
        plt.legend()
        plt.savefig('Figures/Hamming_validation.png')
plt.grid()

ax4VAFrate = fig4.add_subplot(nrow, ncol, 4, sharex=ax4timelag)
plt.xlabel('SLR (mm)')
plt.ylabel('VAF rate (Gt yr$^{-1}$)')
plt.grid()

# =========
print("Done setting up figure axes.")
# =========

# --- Define colors for lines ---
colors = []
#colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:olive', 'tab:cyan']
n150 = sum("amp150" in r for r in runs)
colors.extend([cm.autumn(x) for x in np.linspace(0.0, 1.0, n150)])
n300 = sum("amp300" in r for r in runs)
colors.extend([cm.winter(x) for x in np.linspace(0.0, 1.0, n300)])
n05 = sum("amp0." in r for r in runs)
colors.extend([cm.spring(x) for x in np.linspace(0.0, 1.0, n05)])
color_index = 0

# ================
# Loop over runs and plot data
# ================
runNumber = 0
for run in runs:
    print("Plotting run: " + run)

    thisRun = runData[run]
    # Pull needed data for plotting from this run
data1.sort()
data = glob.glob('/backup/yuliya/v30/graphs_largedomain/fixed/*.gpickle')
data.sort()

d1.append(data1)
d.append(data)

data1 = glob.glob('/backup/yuliya/v35/breakups_con/fixed/*.npy')
data1.sort()
data = glob.glob('/backup/yuliya/v35/graphs_largedomain/fixed/*_no_term_br.gpickle')
data.sort()

d1.append(data1)
d.append(data)

colors = cm.autumn(np.linspace(0, 1, 114))
colors1 = cm.winter(np.linspace(0, 1, 12))
t = np.load('/backup/yuliya/vsi01/vsi01_TimeInSec.npy')
u = 0
ell = np.load('/backup/yuliya/vsi05/dataellg_ellp.npy')[8:-10]
ellv34 = np.load('/backup/yuliya/v34/dataellg_ellp.npy')[13:-1][::1]
ellv34[7:-1] = ellv34[8:]
ellv34[10:-1] = ellv34[11:]
ellv34[45:-1] = ellv34[46:]
ellvsi05 = np.load('/backup/yuliya/vsi05/dataellg_ellp.npy')[8:-10]
ellvsi05[19:-1] = ellvsi05[20:]
ellv30 = np.load('/backup/yuliya/v30/dataellg_ellp.npy')[10:-1]
ellv30[61:-1] = ellv30[62:]
ellv30[63:-1] = ellv30[64:]
ellv35 = np.load('/backup/yuliya/v35/dataellg_ellp.npy')[22:-1]
ellv35[4:-1] = ellv35[5:]
Exemplo n.º 33
0
def main(
        args,
        cfg=None,
        min_allowed_score=None):
    # Setup config
    if cfg is None:
        cfg = setup_config(args, random_seed=args.random_seed, is_testing=True)

    cfg.defrost()
    cfg.ACTUAL_TEST_DATASET = args.test_dataset

    # Build path to gt instances and inference output
    inference_output_dir = get_inference_output_dir(
        cfg['OUTPUT_DIR'],
        args.test_dataset,
        args.inference_config,
        args.image_corruption_level)

    # Get thresholds to perform evaluation on
    if min_allowed_score is None:
        # Check if F-1 Score has been previously computed.
        try:
            with open(os.path.join(inference_output_dir, "mAP_res.txt"), "r") as f:
                min_allowed_score = f.read().strip('][\n').split(', ')[-1]
                min_allowed_score = round(float(min_allowed_score), 4)
        except FileNotFoundError:
            # If not, process all detections. Not recommended as the results might be influenced by very low scoring
            # detections that would normally be removed in robotics/vision
            # applications.
            min_allowed_score = 0.0

    # get preprocessed instances
    preprocessed_predicted_instances, preprocessed_gt_instances = evaluation_utils.get_per_frame_preprocessed_instances(
        cfg, inference_output_dir, min_allowed_score)

    # get metacatalog and image infos
    meta_catalog = MetadataCatalog.get(args.test_dataset)
    images_info = json.load(open(meta_catalog.json_file, 'r'))['images']

    # Loop over all images and visualize errors
    for image_info in images_info:
        image_id = image_info['id']
        image = cv2.imread(
            os.path.join(
                meta_catalog.image_root,
                image_info['file_name']))
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        v = ProbabilisticVisualizer(
            image,
            meta_catalog,
            scale=1.5)
        class_list = v.metadata.as_dict()['thing_classes']

        predicted_box_means = preprocessed_predicted_instances['predicted_boxes'][image_id].cpu(
        ).numpy()
        gt_box_means = preprocessed_gt_instances['gt_boxes'][image_id].cpu(
        ).numpy()
        predicted_box_covariances = preprocessed_predicted_instances[
            'predicted_covar_mats'][image_id].cpu(
        ).numpy()

        predicted_cls_probs = preprocessed_predicted_instances['predicted_cls_probs'][image_id]

        if predicted_cls_probs.shape[0] > 0:
            if cfg.MODEL.META_ARCHITECTURE == "ProbabilisticGeneralizedRCNN" or cfg.MODEL.META_ARCHITECTURE == "ProbabilisticDetr":
                predicted_scores, predicted_classes = predicted_cls_probs[:, :-1].max(
                    1)
                predicted_entropies = entropy(
                    predicted_cls_probs.cpu().numpy(), base=2)

            else:
                predicted_scores, predicted_classes = predicted_cls_probs.max(
                    1)
                predicted_entropies = entropy(
                    np.stack(
                        (predicted_scores.cpu().numpy(),
                         1 - predicted_scores.cpu().numpy())),
                    base=2)
            predicted_classes = predicted_classes.cpu(
            ).numpy()
            predicted_classes = [class_list[p_class]
                                 for p_class in predicted_classes]
            assigned_colors = cm.autumn(predicted_entropies)
            predicted_scores = predicted_scores.cpu().numpy()
        else:
            predicted_scores=np.array([])
            predicted_classes = np.array([])
            assigned_colors = []

        gt_cat_idxs = preprocessed_gt_instances['gt_cat_idxs'][image_id].cpu(
        ).numpy()
        thing_dataset_id_to_contiguous_id = meta_catalog.thing_dataset_id_to_contiguous_id
        if gt_cat_idxs.shape[0] > 0:
            gt_labels = [class_list[thing_dataset_id_to_contiguous_id[gt_class]]
                         for gt_class in gt_cat_idxs[:, 0]]
        else:
            gt_labels = []

        # noinspection PyTypeChecker
        _ = v.overlay_covariance_instances(
            boxes=gt_box_means,
            assigned_colors=[
                'lightgreen' for _ in gt_box_means],
            labels=gt_labels,
            alpha=1.0)
        plotted_detections = v.overlay_covariance_instances(
            boxes=predicted_box_means,
            covariance_matrices=predicted_box_covariances,
            assigned_colors=assigned_colors,
            alpha=1.0,
            labels=predicted_classes)

        cv2.imshow(
            'Detected Instances.',
            cv2.cvtColor(
                plotted_detections.get_image(),
                cv2.COLOR_RGB2BGR))
        cv2.waitKey()
Exemplo n.º 34
0
                np.sqrt(np.sum(e_o[i, :, 0]**2 * ndens**2)),
                'o-',
                markeredgewidth=0,
                color=cm.winter((i + 0.5) / 2001))
        if e_o[i, 2, 1] > 0:
            sign = -1
        else:
            sign = 1
#        ax.plot(zbarr,sign*e_o[  i,:,1]*np.sqrt(ndens)/np.sqrt(np.sum(e_o[  i,:,1]**2*ndens)),'o-',
#                markeredgewidth=0,color=cm.autumn((i+0.5)/2001))
        ax.plot(zbarr,
                sign * e_o[i, :, 1] * ndens /
                np.sqrt(np.sum(e_o[i, :, 1]**2 * ndens**2)),
                'o-',
                markeredgewidth=0,
                color=cm.autumn((i + 0.5) / 2001))
    ax.plot(zbarr,
            f_tm1[0, :, 0] / np.sqrt(np.sum(f_tm1[0, :, 0]**2)),
            'ko-',
            markeredgewidth=0)
    plt.xlabel('$z_\\alpha$', fontsize=18)
    plt.ylabel('$\\sqrt{\\bar{n}^\\alpha}\\,({\\sf F}_\\ell)^p_\\alpha$',
               fontsize=18)
    plt.xlim([0.5, 2.3])
    plt.savefig('../Draft/Figs/kl_modes_wl.pdf', bbox_inches='tight')

fisher = (larr + 0.5)[:, None] * (c_p_dfn / c_p_fid)**2
fish_permode = np.sum(fisher, axis=0)
fish_cum = np.cumsum(fish_permode)

if plot_stuff:
Exemplo n.º 35
0
# ======
# this figure shows the time levels in each run
figTimes = plt.figure(30, facecolor='w')
axTimes = figTimes.add_subplot(1, 1, 1)
plt.xlabel('Year')
axTimesYlabels = []

# =========
print "Done setting up figure axes."
# =========

# --- Define colors for lines ---
#colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:olive', 'tab:cyan']
n150 = sum("amp150" in r for r in runs)
colors = [cm.autumn(x) for x in np.linspace(0.0, 1.0, n150)]
n300 = sum("amp300" in r for r in runs)
colors.extend([cm.winter(x) for x in np.linspace(0.0, 1.0, n300)])
color_index = 0

# ================
# Loop over runs and plot data
# ================
runNumber = 0
for run in runs:
    print "Plotting run: " + run

    thisRun = runData[run]
    # Pull needed data for plotting from this run
    # TODO: replace local variables below in plotting commands with reference to object variables
    yrs = thisRun.yrs
Exemplo n.º 36
0
def Astar(start, goal):
    #The A Star function
    
    #Translate to planner coordinates
    start = translator(start)
    goal = translator(goal)
    
    #Set up the graphs
    start_node = LLNode(start)
    goal_node = LLNode(goal)
    closed_list = []
    fringe = [start_node]
    
    #Plot all walls
    wall_plotter()
    
    #Plot
    plt.scatter(start_node.x, start_node.y, c=cm.autumn(0.0))
    
    found = False #Flag set when search is complete
    resign = False #Flag set when nothing left in fringe
    
    while (found != True and resign != True):

        cur_node = fringe.pop() #POP the least cost node from fringe  
        #print('current',cur_node.x, cur_node.y)   
        
        #check if we just popped goal if so end now
        if at_goal([cur_node.x, cur_node.y], [goal_node.x, goal_node.y]): 
            print('Found path')
            found = True
            continue
        
        #Add the popped node into closed_list
        closed_list.append(cur_node)

        #Check for allowed actions
        denied_actions = [temp.obs_actionlist for temp in params.obs_list if [cur_node.x, cur_node.y] == [temp.x, temp.y]]
        if len(denied_actions) > 0:
            denied_actions = denied_actions[0]
        #print(denied_actions, )    
        
        for i,action in enumerate(params.delta): 
            
            if i in denied_actions: #apply allowed actions on current state
                #print('bad action', i)
                continue
            
            new = expander([cur_node.x, cur_node.y], action) #get new node

            if any(new == [temp.x, temp.y] for temp in closed_list): #check if in closed list
                continue
            
            #calculate cost to get to the node 
            new_orient = np.arctan2((new[1] - cur_node.y),(new[0] - cur_node.x)) 
            if cur_node.parent == None:
                old_orient = 0.0                
            else:
                old_orient = np.arctan2((cur_node.y - cur_node.parent.y),(cur_node.x - cur_node.parent.x))
            #Penalise turns to avoid zig zag motion
            if np.abs(old_orient - new_orient) > 3.2:
                cost = 2.58*heuristic([cur_node.x, cur_node.y], new)
            else:
                cost = (1.0 + np.abs(old_orient - new_orient))*heuristic([cur_node.x, cur_node.y], new)
            
            
            #Check if we have already visited the node
            visited = False
            for temp in fringe:
                if (new == [temp.x, temp.y]):
                    visited = True
                    if (temp.g > cur_node.g + cost):
                        temp.g = cur_node.g + cost
                        temp.parent = cur_node
                        temp.parent_action = i
            
            #If not add to fringe
            if visited == False:
                new_g = cur_node.g + cost
                new_h = heuristic(new, [goal_node.x, goal_node.y])                
                new_node =  LLNode(new, new_g, new_h, cur_node, i)
                fringe.append(new_node)
            
        if len(fringe) == 0: #Check if any left to expand in fringe if not end now
            print('Failed to find path')
            resign = True
        else:
            fringe  = sorted(fringe, key=lambda llnode: llnode.g+(params.heuristic_weight*llnode.h), reverse = True) #sort fringe by g+heusristic
            
            #Debug
            for temp in fringe:
                #print(temp.x, temp.y, temp.g,temp.h ) 
                plt.scatter(temp.x, temp.y, c = cm.autumn((temp.g)/(temp.g+temp.h)))
            #time.sleep(0.1)    
            #input('h')
            
    if found:
        path = []
        action_list = []
        path.append([cur_node.x, cur_node.y])
        action_list.append(cur_node.parent_action)
        while cur_node.parent != None:
            #print(cur_node.x, cur_node.y)
            plt.plot([cur_node.x, cur_node.parent.x], [cur_node.y, cur_node.parent.y], c = [0.0, 0.5, 0.0])
            cur_node = cur_node.parent  
            path.append([cur_node.x, cur_node.y])
            action_list.append(cur_node.parent_action)
       
        #print(cur_node.x, cur_node.y)
        plt.draw()    
        plt.pause(0.15)
        
        #return path
        return path, action_list
    else:
        return None, None