示例#1
0
 def trip_time(self, cargo):
     """Calculate time needed to deliver cargo."""
     # TODO Refactoring.
     if not cargo:
         return 0
     total_time = 0
     self.position = self.base
     self.used_capacity = sum(parcel.weight for parcel in cargo)
     self.fuel = self.max_fuel
     for parcel in cargo:
         distance = dist(self.position, parcel.position)
         velocity = self.absolute_speed(self.position, parcel.position)
         self.position = parcel.position
         flight_time = (distance +
                        2 * self.factor * self.altitude) / velocity
         total_time += flight_time
         total_time += self.waiting_at_client
         self.fuel -= self.fuel_consumption * flight_time
         self.used_capacity -= parcel.weight
     distance = dist(self.position, self.base)
     velocity = self.absolute_speed(self.position, self.base)
     self.position = self.base
     flight_time = (distance + 2 * self.factor * self.altitude) / velocity
     total_time += flight_time
     total_time += self.waiting_at_base
     self.fuel -= self.fuel_consumption * flight_time
     return total_time
示例#2
0
 def is_possible(self):
     """Check whether such a cargo is possible to be delivered in one go."""
     # TODO Refactoring.
     self.position = self.base
     cargo_weight = sum(parcel.weight for parcel in self.cargo)
     if cargo_weight > self.max_capacity:
         return False
     self.used_capacity = cargo_weight
     self.fuel = self.max_fuel
     for parcel in self.cargo:
         distance = dist(self.position, parcel.position)
         velocity = self.absolute_speed(self.position, parcel.position)
         self.position = parcel.position
         flight_time = (distance +
                        2 * self.factor * self.altitude) / velocity
         self.fuel -= self.fuel_consumption * flight_time
         self.used_capacity -= parcel.weight
         if self.fuel < 0:
             return False
     distance = dist(self.position, self.base)
     velocity = self.absolute_speed(self.position, self.base)
     self.position = self.base
     flight_time = (distance + 2 * self.factor * self.altitude) / velocity
     self.fuel -= self.fuel_consumption * flight_time
     if self.fuel < 0:
         return False
     return True
示例#3
0
def makeWeights(options, X, Y, GX, GY):
    # hack to compute scores using normalized projections
    if options.normalize_projections == 1:
        X = common.normalize_rows(X, 2)  # note that normalize_rows works on arrays, not matrices.
        Y = common.normalize_rows(Y, 2)

    X = np.mat(X)
    Y = np.mat(Y)

    if GX is not None or GY is not None:
        GX = np.mat(GX)
        GY = np.mat(GY)
    Z = np.mat(0)
    if options.weight_type == 'inner':
        U = X*Y.T  # linear kernel
        if options.alpha > 0:  # TODO: add higher order graphs
            Z = GX * U * GY.T
            W = (1-options.alpha)*U + options.alpha*Z
        else:
            W = U
        W = np.max(W) - W
    elif options.weight_type == 'dist':
        U = common.dist(X, Y)
        if options.alpha > 0:  # TODO: add higher order graph
            Z = common.dist(GX * X, GY * Y)
            W = (1-options.alpha)*U + options.alpha*Z
        else:
            W = U
    elif options.weight_type == 'sqrdist':
        U = common.dist(X, Y, metric='sqeuclidean')
        if options.alpha > 0:  # TODO: add higher order graph
            Z = common.dist(GX * X, GY * Y, metric='sqeuclidean')
            W = (1-options.alpha)*U + options.alpha*Z
        else:
            W = U
    elif options.weight_type == 'graph_min_dist':
        U = common.dist(X, Y)
        GX = np.array(GX)
        GY = np.array(GY)
        if options.alpha > 0:  # TODO: add higher order graph
            Z, IX, IY = cy_getGraphMinDist(GX, GY, U)
        W = (1-options.alpha)*U + options.alpha*Z
    else:
        W = []

    saveWUZ(U, W, Z, options)
    #print 'norm(U) = ', np.linalg.norm(U, 2), '| norm(Z) = ', np.linalg.norm(Z, 2)
    return W, U, Z
示例#4
0
def build():
    global selected_build
    # make sure cursor is visible
    if selected_build not in range(len(player['inventory'])):
        selected_build = 0
    max_build_dist = 3
    mouse_coords = get_coords_at_mouse()
    mouse_x, mouse_y = mouse_coords
    mouse_wants_to_build = pygame.mouse.get_pressed()[2] == 1
    if not rules['powder_like']:
        mouse_distance_good = dist(mouse_coords,
                                   player['pos']) <= max_build_dist
        if not mouse_distance_good:
            return None
        if set(von_neumann_neighborhood(mouse_coords, world)) == {None}:
            return None
    mouse_on_map = (0 <= mouse_x < len(world[0])) and (0 <= mouse_y <
                                                       len(world))
    if mouse_on_map and mouse_wants_to_build and player[
            'inventory'] and not world[mouse_y][mouse_x]:
        block_name = list(player['inventory'].keys())[selected_build]
        block_block = get_block_by_name(block_name)
        if 'item' not in block_block.tags:
            # remove block from inventory
            if not rules['powder_like']:
                inv_edit(block_name, -1)
            # place block in world
            world[mouse_y][mouse_x] = block_block
示例#5
0
def doplot(prefix='/media/scratch/peri/bad/platonic-form',
        images='/media/scratch/peri/does_matter/platonic-form-images.pkl',
        forms=['ev-exact-gaussian', 'ev-constrained-cubic', 'ev-lerp', 'ev-logistic'],
        labels=['EG', 'CC', 'LP', 'LG']):

    print "Generating a image comparison"
    images = pickle.load(open(images))
    im,pos = images[0]
    s,im = create_comparison_state(im, pos)
    common.set_image(s, im, 0.0001)
    h,l = runner.do_samples(s, 20, 0, stepout=0.1, quiet=True)
    h = h.mean(axis=0)
    s.obj.pos = np.array([h[:3]])
    s.obj.rad = np.array([h[3]])
    s.reset()

    nn = np.s_[:,:,im.shape[2]/2]
    diff = (im - s.get_model_image()[s.inner])
    image0, image1 = im[nn], diff[nn]

    print "Plotting"
    xs, crbs, errors = [], [], []
    for i, form in enumerate(forms):
        fn = prefix+'-'+form+'.pkl'
        crb, val, err, pos, time = pickle.load(open(fn))
        pos += 16

        xs.append(time)
        crbs.append(common.dist(crb))
        errors.append(common.errs(val, pos))

    common.doplot(image0, image1, xs, crbs, errors, labels, diff_image_scale=0.05,
        dolabels=True, multiple_crbs=False, xlim=None, ylim=None, highlight=None,
        detailed_labels=True, title='Platonic form', xlabel=r"$1/\rm{SNR}$")
示例#6
0
def doplot(prefix='/media/scratch/peri/does_matter/z-jitter',
           snrs=[20, 50, 200, 500]):

    s, im, pos = zjitter(jitter=0.1, radius=5)
    diff = (im - s.get_model_image()[s.inner])
    nn = np.s_[:, :, im.shape[2] / 2]
    image0, image1 = im[nn], diff[nn]

    xs, crbs, errors = [], [], []
    for i, snr in enumerate(snrs):
        fn = prefix + '-snr-' + str(snr) + '.pkl'
        crb, val, err, pos, time = pickle.load(open(fn))

        xs.append(time)
        crbs.append(common.dist(crb))
        errors.append(common.errs(val, pos))

    labels = ['SNR %i' % i for i in snrs]

    common.doplot(image0,
                  image1,
                  xs,
                  crbs,
                  errors,
                  labels,
                  diff_image_scale=0.05,
                  dolabels=True,
                  multiple_crbs=True,
                  xlim=(0, time[-1]),
                  ylim=(1e-4, 1e0),
                  highlight=None,
                  detailed_labels=False,
                  title=r"$z$-scan jitter",
                  xlabel=r"$z$-scan NSR")
示例#7
0
def search(unseenX, trainX, k, want_self=False):
    """ find K nearest neighbours of unseenX within trainX """
    N = trainX.shape[1]  # samples are rows
    k = np.min([k, N])
    # compute euclidean distances from the other points
    sqd = dist(unseenX, trainX)
    return find_knn(sqd, k, want_self)
示例#8
0
def test2():
    N = 3000
    D = 50
    X = common.randn((N, D))
    Y = common.randn((N, D))
    U = common.dist(X, Y)

    import cProfile
    #cProfile.runctx('(cost, pi, edge_cost) = approxMatch(U)', globals(), locals())
    cProfile.runctx('(cy_cost0, cy_pi0, cy_edge_cost0) = cy_ApproxMatch(U)', globals(), locals())
    print cy_cost0
示例#9
0
def main():
    global mouse_info
    game_config = configparser.ConfigParser()
    game_config.read(args.game_config)
    input_rows = game_config.getint('PinballFieldVideo', 'rows')
    input_cols = game_config.getint('PinballFieldVideo', 'cols')

    # A standard pinball is 17/16", a standard playfield is 20.25", so the ratio
    # between them is ~5%. Assuming we've cropped the playfield correctly, the
    # number of columns should represent 20.25" in pixels.
    PINBALL_RADIUS_PX = int(17.0 / 16 / 20.25 * input_cols / 2)

    video_frames = common.get_all_frames_from_video(
        game_config.get('PinballFieldVideo', 'path'))
    frame_to_keypoints_list = common.load_json_keypoints_as_list(
        game_config.get('PinballFieldVideo', 'keypoints_path'))
    if not frame_to_keypoints_list:
        print("No keypoints found, starting from scratch.")
        frame_to_keypoints_list = [[] for _ in video_frames]
    keypoint_circles = common.get_all_keypoint_masks(input_rows, input_cols,
                                                     frame_to_keypoints_list,
                                                     PINBALL_RADIUS_PX, 1)

    # Display our windows and set up their callbacks.
    common.display_image(video_frames[0], title=WINDOW_COLOR_FRAME)
    cv2.setMouseCallback(WINDOW_COLOR_FRAME, handle_click, WINDOW_COLOR_FRAME)
    #if keypoint_circles:
    common.display_image(keypoint_circles[0], title=WINDOW_KEYPOINTS)
    common.display_image(common.add_bgr_and_gray(video_frames[0],
                                                 keypoint_circles[0]),
                         title=WINDOW_COMBINED)
    #else:
    #  common.display_image(np.zeros_like(video_frames[0]), title=WINDOW_KEYPOINTS)
    #  common.display_image(np.zeros_like(video_frames[0]), title=WINDOW_COMBINED)
    # No callback on the keypoints only window, they're just to help see.
    cv2.setMouseCallback(WINDOW_COMBINED, handle_click, WINDOW_COMBINED)

    # TODO: Combine the keypoints and golden keypoints into one structured file,
    # ideally a sort of per-frame object that contains arbitrary information
    # about it. Then we can wrap each frame in a python object, providing utility
    # methods on a per-frame basis.
    # If the golden keypoints file already exists, load it.
    try:
        with open(
                game_config.get('PinballFieldVideo', 'keypoints_golden_path'),
                'r') as golden_keypoints_file:
            golden_keypoints = json.load(golden_keypoints_file)
        last_frame_processed = None
        for i, keypoint in enumerate(reversed(golden_keypoints)):
            if keypoint:
                last_frame_processed = len(golden_keypoints) - i - 1
                print("The last frame processed is", last_frame_processed)
                break
    except IOError:
        print("No golden keypoints found, starting from scratch.")
        golden_keypoints = [[]] * len(video_frames)
        last_frame_processed = -1

    i = last_frame_processed + 1
    while i < len(video_frames):
        video_frame = video_frames[i]
        keypoint_circle = keypoint_circles[i]
        keypoints_in_frame = frame_to_keypoints_list[i]
        golden_keypoint = golden_keypoints[i]
        if golden_keypoint:
            print("Frame", i, "has golden keypoint", golden_keypoint)
        else:
            print("Frame", i, "needs a keypoint")

        common.display_image(video_frame, title=WINDOW_COLOR_FRAME)
        common.display_image(keypoint_circle, title=WINDOW_KEYPOINTS)
        common.display_image(common.add_bgr_and_gray(video_frame,
                                                     keypoint_circle),
                             title=WINDOW_COMBINED)

        print("Waiting for key or click...")
        while True:
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                with open(
                        game_config.get('PinballFieldVideo',
                                        'keypoints_golden_path'),
                        'w') as golden_keypoints_file:
                    json.dump(golden_keypoints, golden_keypoints_file)
                cv2.destroyAllWindows()
                return 0
            elif key == ord('n'):
                break  # The while loop, continue with next frame
            elif key == ord('p'):
                i -= 2
                break  # The while loop, continue with previous frame
            elif mouse_info:
                window, mouse_xy = mouse_info
                mouse_info = None

                if window == WINDOW_COMBINED:
                    selected_keypoint = None
                    for (x, y, size) in keypoints_in_frame:
                        if common.dist(mouse_xy,
                                       (x, y)) < 5 * PINBALL_RADIUS_PX:
                            selected_keypoint = [x, y, size]
                    if selected_keypoint:
                        print("Setting frame", i, "golden keypoint:",
                              selected_keypoint)
                        golden_keypoints[i] = [selected_keypoint]
                        break  # Go to the next frame
                    else:
                        # Must've been a missed click / not close enough.
                        print(
                            "No keypoint detected close by, please try again.")
                elif window == WINDOW_COLOR_FRAME:
                    golden_keypoints[i] = [mouse_xy + [PINBALL_RADIUS_PX]]
                    print("Setting frame", i, "golden keypoint:",
                          golden_keypoints[i])
                    break
        i += 1
    print("All done! :)")
    with open(game_config.get('PinballFieldVideo', 'keypoints_golden_path'),
              'w') as golden_keypoints_file:
        json.dump(golden_keypoints, golden_keypoints_file)
    cv2.destroyAllWindows()
    return 0
示例#10
0
def lasttime_adjacency_check(first_ride, second_ride):
    return first_ride[2][1] + first_ride[3] + dist(
        first_ride[1], second_ride[0]) <= second_ride[2][1]
示例#11
0
    return G, idx


def toSymmetricStochastic(G, sym=True, stochastic=True, norm='l1'):
    if sym:
        print >> sys.stderr, 'symmetrizing'
        G = (G + G.T) / 2
    if stochastic:
        print >> sys.stderr, 'normalizing'
        G = normalize(G, norm, axis=1)  # make stochastic matrix.
    return G


# def permute(G, pi):
#     (N, _) = G.shape
#     M = len(pi)
#     pi = np.append(pi, np.arange(M, N))
#     G = G[:, pi]
#     G = G[pi, :]
#     return G

if __name__ == '__main__':
    A = np.mat(common.randn((4, 5)))
    K = A * A.T
    D = np.mat(common.dist(A))
    k = 2
    (G, I) = knn_graph(A, k)
    (KG, KI) = kernel_knn_graph(K, k)
    print "G-KG", np.linalg.norm((G-KG).todense())
    print 'G:\n', G.todense()
    print 'D:\n', D
示例#12
0
def doplot(prefix='/media/scratch/peri/does_matter/brownian-motion',
           snrs=[20, 50, 200, 500]):
    fig = pl.figure(figsize=(14, 7))

    ax = fig.add_axes([0.43, 0.15, 0.52, 0.75])
    gs = ImageGrid(fig,
                   rect=[0.05, 0.05, 0.25, 0.90],
                   nrows_ncols=(2, 1),
                   axes_pad=0.25,
                   cbar_location='right',
                   cbar_mode='each',
                   cbar_size='10%',
                   cbar_pad=0.04)

    s, im, pos = diffusion(1.0, 0.1, samples=200)
    h, l = runner.do_samples(s, 30, 0, quiet=True)
    nn = np.s_[:, :, im.shape[2] / 2]

    figlbl, labels = ['A', 'B'], ['Reference', 'Difference']
    diff = (im - s.get_model_image()[s.inner])[nn]
    diffm = 0.1  #np.abs(diff).max()
    im0 = gs[0].imshow(im[nn], vmin=0, vmax=1, cmap='bone_r')
    im1 = gs[1].imshow(diff, vmin=-diffm, vmax=diffm, cmap='RdBu')
    cb0 = pl.colorbar(im0, cax=gs[0].cax, ticks=[0, 1])
    cb1 = pl.colorbar(im1, cax=gs[1].cax, ticks=[-diffm, diffm])
    cb0.ax.set_yticklabels(['0', '1'])
    cb1.ax.set_yticklabels(['-%0.1f' % diffm, '%0.1f' % diffm])

    for i in xrange(2):
        gs[i].set_xticks([])
        gs[i].set_yticks([])
        gs[i].set_ylabel(labels[i])
        #lbl(gs[i], figlbl[i])

    aD = 1.0 / (25. / 0.15)

    symbols = ['o', '^', 'D', '>']
    for i, snr in enumerate(snrs):
        c = common.COLORS[i]
        fn = prefix + '-snr-' + str(snr) + '.pkl'
        crb, val, err, pos, time = pickle.load(open(fn))

        if i == 0:
            label0 = r"$\rm{SNR} = %i$ CRB" % snr
            label1 = r"$\rm{SNR} = %i$ Error" % snr
        else:
            label0 = r"$%i$, CRB" % snr
            label1 = r"$%i$, Error" % snr

        time *= aD  # a^2/D, where D=1, and a=5 (see first function)
        ax.plot(time, common.dist(crb), '-', c=c, lw=3, label=label0)
        ax.plot(time,
                common.errs(val, pos),
                symbols[i],
                ls='--',
                lw=2,
                c=c,
                label=label1,
                ms=12)

    # 80% glycerol value
    ax.vlines(0.100 * aD,
              1e-6,
              100,
              linestyle='-',
              lw=40,
              alpha=0.2,
              color='k')
    #pl.text(0.116*aD*1.45, 3e-4, 'G/W')

    # 100% water value
    ax.vlines(0.100 * aD * 60,
              1e-6,
              100,
              linestyle='-',
              lw=40,
              alpha=0.2,
              color='b')
    #ax.text(0.116*aD*75*2, 0.5, 'W')

    ax.loglog()
    ax.set_ylim(5e-4, 2e0)
    ax.set_xlim(time[0], time[-1])
    ax.legend(loc='best', ncol=2, prop={'size': 18}, numpoints=1)
    ax.set_xlabel(r"$\tau_{\rm{exposure}} / (a^2/D)$")
    ax.set_ylabel(r"Position CRB, Error")
    ax.grid(False, which='both', axis='both')
    ax.set_title("Brownian motion")
示例#13
0
 def path_length(self):
     """Get recalculated path length."""
     path = self.path
     return sum(
         dist(point1, point2)
         for point1, point2 in zip(path[:-1], path[1:]))