def __init__(self, fleet_config):
        super().__init__('fleet_driver_mir')
        self.fleet_config = fleet_config
        self.robots = {}
        self.api_clients = []
        self.status_pub = self.create_publisher(FleetState, 'fleet_states', 1)
        self.pub_timer = self.create_timer(self.STATUS_PUB_PERIOD,
                                           self.pub_fleet)
        self.ref_coordinates_rmf = [[26.95, -20.23], [29.26, -22.38],
                                    [11.4, -16.48], [12.46, -16.99]]
        self.ref_coordinates_mir = [[7.2, 16.6], [5.15, 18.35], [23, 12.35],
                                    [22.05, 12.95]]
        self.rmf2mir_transform = nudged.estimate(self.ref_coordinates_rmf,
                                                 self.ref_coordinates_mir)
        self.mir2rmf_transform = nudged.estimate(self.ref_coordinates_mir,
                                                 self.ref_coordinates_rmf)
        mse = nudged.estimate_error(self.rmf2mir_transform,
                                    self.ref_coordinates_rmf,
                                    self.ref_coordinates_mir)
        self.get_logger().info(f'transformation estimate error: {mse}')

        for api_client in self.create_all_api_clients(self.fleet_config):
            self.get_logger().info(f'initializing robot from \
                                   {api_client.configuration.host}')
            robot = Robot(self)
            robot.api = mir100_client.DefaultApi(api_client)

            # temporary retry configuration to workaround startup race condition while launching
            connection_pool_kw = robot.api.api_client.rest_client.pool_manager.connection_pool_kw
            orig_retries = connection_pool_kw.get('retries')
            retries = urllib3.Retry(10)
            retries.backoff_factor = 1
            retries.status_forcelist = (404, )
            connection_pool_kw['retries'] = retries

            mir_status = robot.api.status_get()
            robot.name = mir_status.robot_name

            self.load_missions(robot)
            self.update_positions(robot)
            # reset retries
            if orig_retries is not None:
                connection_pool_kw['retries'] = orig_retries
            else:
                del connection_pool_kw['retries']

            self.robots[robot.name] = robot
            self.get_logger().info(f'successfully initialized robot \
                                   {robot.name}')

        # Setup fleet driver ROS2 topic subscriptions
        self.path_request_sub = self.create_subscription(
            PathRequest, '/robot_path_requests', self.on_path_request, 1)
        self.mode_sub = self.create_subscription(ModeRequest,
                                                 f'/robot_mode_requests',
                                                 self.on_robot_mode_request, 1)
Exemple #2
0
def compute_transforms(rmf_coordinates, mir_coordinates, node=None):
    """Get transforms between RMF and MIR coordinates."""
    transforms = {
        'rmf_to_mir': nudged.estimate(rmf_coordinates, mir_coordinates),
        'mir_to_rmf': nudged.estimate(mir_coordinates, rmf_coordinates)
    }

    if node:
        mse = nudged.estimate_error(transforms['rmf_to_mir'], rmf_coordinates,
                                    mir_coordinates)

        node.get_logger().info(f"Transformation estimate error: {mse}")
    return transforms
Exemple #3
0
 def test_error(self):
     dom = [[0,0],  [1,1],      [2, 2]]
     ran = [[0,-1], [1,2], [2,-1]]
     t = nudged.estimate(dom, ran)
     self.assertEqual(t.transform(dom), [[0,0], [1,0], [2,0]])
     mse = nudged.estimate_error(t, dom, ran)
     self.assertEqual(mse, 2.0)
Exemple #4
0
def nudgeTransf(x_p, y_p, cr_m_data):
    """
    This works but gives *very* poor results (July 2019)
    """
    ra, dec = cr_m_data['field_ra'], cr_m_data['field_dec']
    x, y = cr_m_data['field_x'], cr_m_data['field_y']

    import nudged

    dom = list(map(list, zip(x, y)))
    ran = list(map(list, zip(-ra, dec)))

    trans = nudged.estimate(dom, ran)

    cc = list(map(list, list(np.array([x_p, y_p]).T)))
    ra_p, dec_p = np.array(trans.transform(cc)).T
    ra_p = -ra_p

    print(trans.get_matrix())
    print(trans.get_rotation())
    print(trans.get_scale())
    print(trans.get_translation())

    # plt.subplot(221);plt.title("dom");plt.scatter(x, y)
    # plt.subplot(222);plt.title("ran");plt.scatter(ra, dec)
    # plt.subplot(223);plt.title("(x, y)");plt.scatter(x_p, y_p)
    # plt.subplot(224);plt.title("(x_t, y_t)");plt.scatter(ra_p, dec_p)
    # plt.show()

    ra_p = MaskedColumn(ra_p, name='ra')
    dec_p = MaskedColumn(dec_p, name='dec')

    return ra_p, dec_p
Exemple #5
0
 def test_rotation_in_radians(self):
     '''
     should give rotation in radians
     '''
     t = nudged.estimate([(1, 1), (-1, -1)], [(-2, -2), (2, 2)])
     # 's': -2, 'r': 0, 'tx': 0, 'ty': 0
     self.assertEqual(t.get_rotation(), pi)
Exemple #6
0
 def test_scale(self):
     '''
     should give scale
     '''
     t = nudged.estimate([(1, 1), (-1, -1)], [(-2, -2), (2, 2)])
     # 's': -2, 'r': 0, 'tx': 0, 'ty': 0
     self.assertEqual(t.get_scale(), 2.0)
Exemple #7
0
 def test_error(self):
     dom = [(0, 0), (1, 1), (2, 2)]
     ran = [(0, -1), (1, 2), (2, -1)]
     t = nudged.estimate(dom, ran)
     self.assertEqual(t.transform(dom), [(0, 0), (1, 0), (2, 0)])
     mse = nudged.estimate_error(t, dom, ran)
     self.assertEqual(mse, 2.0)
Exemple #8
0
 def test_scale(self):
     '''
     should give scale
     '''
     t = nudged.estimate([[ 1, 1], [-1,-1]], [[-2,-2], [ 2, 2]]);
     # 's': -2, 'r': 0, 'tx': 0, 'ty': 0
     self.assertEqual(t.get_scale(), 2.0)
Exemple #9
0
 def test_rotation_in_radians(self):
     '''
     should give rotation in radians
     '''
     t = nudged.estimate([[ 1, 1], [-1,-1]], [[-2,-2], [ 2, 2]]);
     # 's': -2, 'r': 0, 'tx': 0, 'ty': 0
     self.assertEqual(t.get_rotation(), pi)
Exemple #10
0
 def test_error(self):
     dom = [[0, 0], [1, 1], [2, 2]]
     ran = [[0, -1], [1, 2], [2, -1]]
     t = nudged.estimate(dom, ran)
     self.assertEqual(t.transform(dom), [[0, 0], [1, 0], [2, 0]])
     mse = nudged.estimate_error(t, dom, ran)
     self.assertEqual(mse, 2.0)
Exemple #11
0
    def load_label_data(self, js_list):
        self.js_list = js_list
        eg_p_l = self.eg_p_l

        for js_name in self.js_list:

            # data = open( js_name)
            # data = json.load(data)
            data = js_name
            p_l = data['annotations']

            _, pic_name = data["images"].split('/')

            self.pic_name_l.append(pic_name)

            trans = nudged.estimate(eg_p_l, p_l)
            trans_location = trans.get_translation()

            trans_scale = trans.get_scale()
            p_Transed_l = [[(i[0] - trans_location[0]) / trans_scale,
                            (i[1] - trans_location[1]) / trans_scale]
                           for i in p_l]

            exec(self.cfg['preprocess_data'])

            for k, v in zip(self.params_d.keys(), self.params_d.values()):
                """ k:funcs  v: params"""

                v = eval(v)
                v = str(v)
                # cal_dim = eval(k+'('+'eval('+'str(v)'+')'+',p_Transed_l,eg_p_l,p_l'+')')
                cal_dim = eval(k + '(' + v + ',p_Transed_l,eg_p_l,p_l' + ')')

                dim_l, score_l = cal_dim.calculate_dim()
                self.load_score(dim_l, score_l)
Exemple #12
0
 def test_list_len_zero(self):
     '''
     should allow lists of length zero
     '''
     t = nudged.estimate([], []);
     # Identity transform
     self.assertEqual(t.transform([0,0]), [0,0]);
     self.assertEqual(t.transform([7,7]), [7,7]);
Exemple #13
0
 def test_list_len_zero(self):
     '''
     should allow lists of length zero
     '''
     t = nudged.estimate([], [])
     # Identity transform
     self.assertEqual(t.transform((0, 0)), (0, 0))
     self.assertEqual(t.transform((7, 7)), (7, 7))
Exemple #14
0
def swap_faces(img1, img2):
    # get landmark points from the images
    landmarks1 = landmarks_from_pil_image(img1)
    landmarks2 = landmarks_from_pil_image(img2)
    img1_index = random.randint(0, len(landmarks1) - 1)
    img2_index = random.randint(0, len(landmarks2) - 1)
    landmarks1 = landmarks1[img1_index]
    landmarks2 = landmarks2[random.randint(0, len(landmarks2) - 1)]
    bb = coords_from_pil_image(img1)[img1_index]
    bb = coords_from_pil_image(img2)[img2_index]
    # calculate transformation matrix to go from one set of points to the other
    trans_matrix1 = nudged.estimate(landmarks2, landmarks1).get_matrix()

    trans1 = transform.ProjectiveTransform(matrix=np.array(trans_matrix1))
    # transform the images to be on top of each other
    img1_transformed = transform.warp(
        np.array(img1), trans1,
        output_shape=np.array(img2).shape[:2]).dot(255).astype('uint8')

    s = np.linspace(0, 2 * np.pi, 400)
    height = (bb.bottom() - bb.top())
    rad_y = height / 2 * 1.2
    x = (bb.left() + bb.right()) / 2 + (bb.right() - bb.left()) / 2 * np.cos(s)
    y = (bb.top() + bb.bottom()) / 2 + rad_y * np.sin(s) - height * 0.15
    init = np.array([x, y]).T
    #init = init.dot(trans_matrix1)
    shape = active_contour(gaussian(rgb2gray(img1_transformed), 3),
                           init,
                           alpha=0.08,
                           beta=1,
                           gamma=0.001,
                           max_iterations=height * 0.1,
                           max_px_move=1)
    #shape = init
    output = Image.fromarray(img1_transformed)
    mask = Image.new('L', output.size)
    draw = ImageDraw.Draw(mask)
    draw.polygon([tuple(coord)[:2] for coord in shape], fill="white")
    #draw = ImageDraw.Draw(img2)
    #draw.polygon([tuple(coord)[:2] for coord in shape], outline="red")
    #return img2

    # Match histograms on the selected areas
    hist_mask = Image.fromarray(
        morphology.dilation(np.array(mask),
                            morphology.disk(int(height * 0.1))))
    img2_histogram = generate_histogram(img2, hist_mask)
    img1_histogram = generate_histogram(Image.fromarray(img1_transformed),
                                        hist_mask)
    matched = Image.fromarray(
        match_histograms(np.asarray(img1_histogram),
                         np.asarray(img2_histogram),
                         multichannel=True))

    mask = gaussian(np.array(mask), height * 0.1)
    mask = Image.fromarray(mask.dot(255).astype('uint8'))
    output = Image.composite(matched, img2, mask)
    return output
Exemple #15
0
 def test_estimation(self):
     '''
     should estimate correctly
     '''
     for sple in samples:
         t = nudged.estimate(sple['a'], sple['b'])
         for k in ['s', 'r', 'tx', 'ty']:
             msg = sple['id'] + ': ' + k + '=' + str(getattr(t, k))
             self.assertEqual(getattr(t, k), sple[k], msg)
Exemple #16
0
 def test_estimation(self):
     '''
     should estimate correctly
     '''
     for sple in samples:
         t = nudged.estimate(sple['a'], sple['b'])
         for k in ['s', 'r', 'tx', 'ty']:
             msg = sple['id'] + ': ' + k + '=' + str(getattr(t, k))
             self.assertEqual(getattr(t, k), sple[k], msg)
Exemple #17
0
 def _align_image(self, image, shape):
     shape = np.array(shape)
     assert (np.prod(shape.shape) == 10)
     shape = shape.reshape((5, 2))
     tform = nudged.estimate(shape, self.anchor_points)
     tform = np.asarray(tform.get_matrix())
     img_align = cv2.warpPerspective(image, tform, self.align_size)
     img_resize = cv2.resize(img_align, self.input_size)
     return img_resize
Exemple #18
0
 def test_lists(self):
     '''
     should allow arrays of different length
     but ignore the points without a pair
     '''
     dom = [[1,-1], [ 3, -2], [1, 2]]
     ran = [[3, 4], [10,  8]]
     # 's': 2, 'r': 3, 'tx': -2, 'ty': 3
     t = nudged.estimate(dom, ran)
     self.assertEqual(t.transform([1,1]), [-3,8])
Exemple #19
0
 def test_lists(self):
     '''
     should allow arrays of different length
     but ignore the points without a pair
     '''
     dom = [[1, -1], [3, -2], [1, 2]]
     ran = [[3, 4], [10, 8]]
     # 's': 2, 'r': 3, 'tx': -2, 'ty': 3
     t = nudged.estimate(dom, ran)
     self.assertEqual(t.transform([1, 1]), [-3, 8])
    def tag(self, tag):
        """Called when tag needs to be inserted into data."""
        if self.collect_data:
            self.collect_file.write(json.dumps({'tag': tag}) + '\n')

        # check if validity is to be calculated
        if tag["secondary_id"] == "start":

            # go to nudged calibration mode
            if "nudged_point" in tag:

                # Nudged point format: "1.0, 0.5"
                [x, y] = tag["nudged_point"].split(",")
                xf = float(x)
                yf = float(y)
                self.nudged_current_range = [xf, yf]

                # check if previous occurrances of this point exist
                while [xf, yf] in self.nudged_range:
                    # find the index of the element in range
                    ind = self.nudged_range.index([xf, yf])

                    # remove the index from range and domains
                    self.nudged_range.pop(ind)
                    self.nudged_domain_l.pop(ind)
                    self.nudged_domain_r.pop(ind)

        elif tag["secondary_id"] == "end":

            if "nudged_point" in tag:
                self.nudged_current_range = None

                # calculate nudged transform
                print "Calculating nudged calibration for right eye with " + \
                    "vectors: dom[" + str(len(self.nudged_domain_r)) + \
                    "] and range[" + str(len(self.nudged_range))
                self.nudged_transform_r = nudged.estimate(
                    self.nudged_domain_r, self.nudged_range)

                print "Calculating new calibration..."
                self.nudged_transform_l = nudged.estimate(
                    self.nudged_domain_l, self.nudged_range)
        return False
Exemple #21
0
 def test_lists(self):
     '''
     should allow arrays of different length
     but ignore the points without a pair
     '''
     dom = [(1, -1), (3, -2), (1, 2)]
     ran = [(3, 4), (10, 8)]
     # 's': 2, 'r': 3, 'tx': -2, 'ty': 3
     t = nudged.estimate(dom, ran)
     self.assertEqual(t.transform((1, 1)), (-3, 8))
    def tag(self, tag):
        """Called when tag needs to be inserted into data."""
        if self.collect_data:
            self.collect_file.write(json.dumps({'tag': tag}) + '\n')

        # check if validity is to be calculated
        if tag["secondary_id"] == "start":

            # go to nudged calibration mode
            if "nudged_point" in tag:

                # Nudged point format: "1.0, 0.5"
                [x, y] = tag["nudged_point"].split(",")
                xf = float(x)
                yf = float(y)
                self.nudged_current_range = [xf, yf]

                # check if previous occurrances of this point exist
                while [xf, yf] in self.nudged_range:
                    # find the index of the element in range
                    ind = self.nudged_range.index([xf, yf])

                    # remove the index from range and domains
                    self.nudged_range.pop(ind)
                    self.nudged_domain_l.pop(ind)
                    self.nudged_domain_r.pop(ind)

        elif tag["secondary_id"] == "end":

            if "nudged_point" in tag:
                self.nudged_current_range = None

                # calculate nudged transform
                print "Calculating nudged calibration for right eye with " + \
                    "vectors: dom[" + str(len(self.nudged_domain_r)) + \
                    "] and range[" + str(len(self.nudged_range))
                self.nudged_transform_r = nudged.estimate(self.nudged_domain_r,
                                                          self.nudged_range)

                print "Calculating new calibration..."
                self.nudged_transform_l = nudged.estimate(self.nudged_domain_l,
                                                          self.nudged_range)
        return False
Exemple #23
0
    def calc_106_landmarks(self, image, shapes):
        images = []
        tform_reverses = []
        results = []
        # preprocess and alignment
        for shape in shapes:
            shape = shape.reshape(-1, 2)
            tform = nudged.estimate(shape, self.RefPts)
            tform = np.asarray(tform.get_matrix())

            img_warp = cv2.warpPerspective(image.copy(), tform,
                                           (self.crop_size, self.crop_size))
            img_tmp = cv2.resize(img_warp, (self.input_size, self.input_size))
            if (self.type_str == "caffe_106"):
                img_tmp = img_tmp.transpose(2, 0, 1) - 128.0
            else:
                img_tmp = (img_tmp - 127.5) * (1. / 128.0)
            tform_reverses.append(np.asarray(np.mat(tform).I))
            images.append(img_tmp)

        if (len(images) == 0):
            return results
        images = np.asarray(images)

        if (self.type_str == "tensorflow_106"):
            outputs = self.sess.run(
                'align/fc2/fc2:0',
                feed_dict={'align/alignment_input:0': images})
            for index, (output, tform_reverse) in enumerate(
                    zip(outputs, tform_reverses)):
                point_aligned = np.concatenate((output.reshape(-1, 2) * (self.crop_size*1.0 / self.input_size), \
                                  np.ones((106,1),dtype=np.float32)),axis=1)
                point_original = np.dot(tform_reverse,
                                        point_aligned.T)[:2, :].T
                point_original = point_original.reshape((-1, 1))
                results.append(point_original)
        else:
            for index, (image, tform_reverse) in enumerate(
                    zip(images, tform_reverses)):
                self.net.blobs['data'].data[...] = np.asarray([image])
                self.net.forward()
                output = (self.net.blobs['fc106pts'].data[...].reshape(-1, 2) +
                          self.input_size / 2) * (self.crop_size * 1.0 /
                                                  self.input_size)
                point_aligned = np.concatenate(
                    (output.reshape(-1, 2), np.ones(
                        (106, 1), dtype=np.float32)),
                    axis=1)
                point_original = np.dot(tform_reverse,
                                        point_aligned.T)[:2, :].T
                point_original = point_original.reshape((-1, 1))
                results.append(point_original)

        return np.around(np.array(results))
Exemple #24
0
def dissimilar(V, projections, X, min_threshold, err_threshold=0.8):
    VT = V.T
    m = 2 - min(map(lambda p: norm(VT.dot(p)), projections))
    if m < min_threshold:
        return False

    Y = X.T.dot(V).tolist()
    for p in projections:
        Y2 = X.T.dot(p)
        affine = nudged.estimate(Y, Y2.tolist())
        err = norm(Y2 - np.array(affine.transform(Y))) / norm(Y2)
        if err < err_threshold:
            return False
    return True
Exemple #25
0
    def load_label_data(self, js_list):
        self.js_list = js_list

        eg_p_l = self.eg_p_l
        for js_name, pic_name in tqdm(zip(self.js_list, self.pic_name_list)):
            data = open(self.data_path + js_name)
            data = json.load(data)
            points_ = data['shapes']
            p_l = []
            for p in points_:
                p_l.append([p['points'][0][0], p['points'][0][1]])

            self.pic_name_l.append(pic_name)
            trans = nudged.estimate(eg_p_l, p_l)
            trans_location = trans.get_translation()

            trans_scale = trans.get_scale()
            p_Transed_l = [[(i[0] - trans_location[0]) / trans_scale,
                            (i[1] - trans_location[1]) / trans_scale]
                           for i in p_l]

            exec(self.cfg['preprocess_data'])

            for k, v in zip(self.params_d.keys(), self.params_d.values()):
                """ k:funcs  v: params"""

                v = eval(v)
                v = str(v)
                # cal_dim = eval(k+'('+'eval('+'str(v)'+')'+',p_Transed_l,eg_p_l,p_l'+')')
                cal_dim = eval(k + '(' + v + ',p_Transed_l,eg_p_l,p_l' + ')')
                print(k)
                # print(v)
                dim_l, score_l = cal_dim.calculate_dim()
                self.load_score(dim_l, score_l)

            if self.vis_data:
                is_save = True
                display(self.data_path, pic_name, self.save_path, is_save, p_l,
                        eg_p_l)
                clearHis()
def get_processed_image(img):
    image = imread(img)
    a = get_facial_points(image, 49)
    b = reftracker
    trans = nudged.estimate(a, b)
    h = np.array(trans.get_matrix())[0:2]
    # h, status = cv2.findHomography(a, b)
    warpedxx = np.array(cv2.warpAffine(xxc, h, xxc.shape))
    warpedyy = np.array(cv2.warpAffine(yyc, h, yyc.shape))
    warpedmask = np.array(cv2.warpAffine(maskc, h, maskc.shape))
    # warpedxx = np.array(cv2.warpPerspective(xxc, h, xxc.shape))
    # warpedyy = np.array(cv2.warpPerspective(yyc, h, yyc.shape))
    # warpedmask = np.array(cv2.warpPerspective(maskc, h, maskc.shape))
    warpedxx = warpedxx[600:1400, 600:1200]
    warpedyy = warpedyy[600:1400, 600:1200]
    warpedmask = warpedmask[600:1400, 600:1200]
    filtered_img = np.zeros((image.shape[0], image.shape[1], 6))
    filtered_img[:, :, 0:3] = normalize_image(image)
    filtered_img[:, :, 3] = warpedxx
    filtered_img[:, :, 4] = warpedyy
    filtered_img[:, :, 5] = warpedmask
    return filtered_img
Exemple #27
0
 def setUp(self):
     dom = [[1, -1], [ 3, -2]]
     ran = [[3,  4], [10,  8]]
     self.t = nudged.estimate(dom, ran)
Exemple #28
0
 def test_zero_error(self):
     dom = [(0, 0), (1, 1)]
     ran = [(1, 1), (2, 2)]
     t = nudged.estimate(dom, ran)
     mse = nudged.estimate_error(t, dom, ran)
     self.assertEqual(mse, 0.0)
Exemple #29
0
import numpy as np
import matplotlib.pyplot as plt
import nudged

x = [[1, 0], [0, 1], [-1, 0], [0, -1]]
y = np.add([[0, -2], [2, 0], [0, 2], [-2, 0]], 1)

trans = nudged.estimate(x, y)
y1 = trans.transform([1, 0])
print(trans.get_rotation())
print(trans.get_scale())
print(trans.get_translation())
print(y1)
Exemple #30
0
 def test_list_len_one(self):
     '''
     should allow lists of length one
     '''
     t = nudged.estimate([[1, 1]], [[5, 5]])
     self.assertEqual(t.transform([4, 4]), [8, 8])
Exemple #31
0
 def test_zero_error(self):
     dom = [[0, 0], [1, 1]]
     ran = [[1, 1], [2, 2]]
     t = nudged.estimate(dom, ran)
     mse = nudged.estimate_error(t, dom, ran)
     self.assertEqual(mse, 0.0)
Exemple #32
0
 def test_singleton_domain(self):
     dom = [0,0]
     ran = [[1,1], [2,2]]
     f = lambda: nudged.estimate(dom, ran)
     self.assertRaises(TypeError, f)
Exemple #33
0
 def test_identical_points(self):
     '''
     should allow a list of identical points
     '''
     t = nudged.estimate([[1,1], [1,1]], [[5,5], [7,7]])
     self.assertEqual(t.transform([1,1]), [6,6])
Exemple #34
0
 def test_list_len_one(self):
     '''
     should allow lists of length one
     '''
     t = nudged.estimate([(1, 1)], [(5, 5)])
     self.assertEqual(t.transform((4, 4)), (8, 8))
Exemple #35
0
def findMultipleLP(X, d, k, sigma, maxIter, embMethod='lpp', labs=None):
    N = X.shape[1]
    W = np.zeros((N, N))
    B = np.zeros((N, N))

    if embMethod == 'pca':
        for i in range(N - 1):
            for j in range(i + 1, N):
                W[i, j] = 1.0 / N
        W = np.maximum(W, W.T)
        B = np.eye(N)
        L = B - W
        M1 = X.dot(L).dot(X.T)
        Mc = np.eye(M1.shape[0])

    elif embMethod == 'lpp':
        G = kneighbors_graph(X.T, k, mode='distance',
                             include_self=False).toarray()
        W = 0.5 * (G + G.T)
        W[W != 0] = np.exp(-W[W != 0] / (2 * sigma * sigma))
        B = np.diag(np.sum(W, axis=0))
        L = B - W
        M1 = X.dot(L).dot(X.T)
        Mc = X.dot(B).dot(X.T)

    elif embMethod == 'lde':
        Gw = np.zeros((N, N))
        Gb = np.zeros((N, N))

        dists = pairwise_distances(X.T)

        for ii in range(N):
            inds = np.where(labs == labs[ii])[0]
            sinds = np.argsort(dists[ii, inds])
            Gw[ii, inds[sinds[:k]]] = 1

            inds = np.where(labs != labs[ii])[0]
            sinds = np.argsort(dists[ii, inds])
            Gb[ii, inds[sinds[:k]]] = 1

        Gw = np.maximum(Gw, Gw.T)
        Bw = np.diag(np.sum(Gw, axis=0))
        Lw = Bw - Gw
        M1 = X.dot(Lw).dot(X.T)

        Gb = np.maximum(Gb, Gb.T)
        Bb = np.diag(np.sum(Gb, axis=0))
        Lb = Bb - Gb
        Mc = X.dot(Lb).dot(X.T)

    u, s = eig(M1)
    u = np.real(u)
    if np.min(u) < 0:
        M1 = M1 - np.min(u) * np.eye(M1.shape[0])

    u, s = eig(Mc)
    u = np.real(u)
    if np.min(u) < 0:
        Mc = Mc - np.min(u) * np.eye(Mc.shape[0])

    projList = []
    projListFinal = []
    if embMethod == 'lde':
        # gamma = 1e3 # bio 1e3
        gamma = 5e2
        thresh = 0.5 * 2
    else:
        gamma = 1e4
        thresh = 0.6 * 2
    for iters in range(1, maxIter + 1):
        if iters > 1:
            #print np.linalg.norm(X.dot(L).dot(X.T)), np.linalg.norm(C)
            if embMethod == 'pca':
                M1 = X.dot(L).dot(X.T) - gamma * C
            elif embMethod == 'lpp':
                M1 = X.dot(L).dot(X.T) + gamma * C
            elif embMethod == 'lde':
                M1 = X.dot(Lw).dot(X.T) + gamma * C
            M1 = 0.5 * (M1 + M1.T)
            u, s = np.linalg.eig(M1)
            if np.min(u) < 0:
                M1 = M1 - np.min(u) * np.eye(M1.shape[0])
        eigvals, eigvecs = eig(M1, Mc)

        eigvals = np.real(eigvals)
        eigvecs = np.real(eigvecs)
        eigvecs = np.dot(np.real(sp.linalg.sqrtm(Mc)), eigvecs)

        if embMethod == 'pca':
            ind = np.argsort(-eigvals)
            temp = eigvecs[:, ind[0:d]]
        elif embMethod == 'lpp' or embMethod == 'lde':
            ind = np.argsort(eigvals)
            temp = eigvecs[:, ind[0:d]]

        for dim in range(2):
            temp[:, dim] /= np.linalg.norm(temp[:, dim])

        if len(projList) == 0:
            projList.append(temp)
            C = matprod(temp, temp.T)
            projListFinal.append(temp)
        else:
            projList.append(temp)
            C = grassSum(projList)

            #print np.linalg.norm(temp[:,0]), np.linalg.norm(temp[:,1])

            mval = 1e10
            for kk in projListFinal:
                mval = np.minimum(mval,
                                  2 - np.linalg.norm(matprod(temp.T, kk)))

            if mval > thresh:
                err = []
                emb1 = (temp.T.dot(X)).T
                emb1 = emb1.tolist()
                for ps in projListFinal:
                    emb2 = (ps.T.dot(X)).T
                    emb2 = emb2.tolist()
                    trans = nudged.estimate(emb1, emb2)
                    tt = np.linalg.norm(
                        np.array(emb2) -
                        np.array(trans.transform(emb1))) / np.linalg.norm(emb2)
                    err.append(tt)
                # print np.linalg.norm(emb1), err
                #print mval, np.min(np.array(err))
                if np.min(np.array(err)) > 0.8:
                    projListFinal.append(temp)
    #print len(projList), len(projListFinal)
    return projListFinal
Exemple #36
0
 def test_zero_error(self):
     dom = [[0,0], [1,1]]
     ran = [[1,1], [2,2]]
     t = nudged.estimate(dom, ran)
     mse = nudged.estimate_error(t, dom, ran)
     self.assertEqual(mse, 0.0)
Exemple #37
0
 def test_identical_points(self):
     '''
     should allow a list of identical points
     '''
     t = nudged.estimate([(1, 1), (1, 1)], [(5, 5), (7, 7)])
     self.assertEqual(t.transform((1, 1)), (6, 6))
Exemple #38
0
 def test_singleton_domain(self):
     dom = (0, 0)
     ran = [(1, 1), (2, 2)]
     self.assertRaises(TypeError, lambda: nudged.estimate(dom, ran))
Exemple #39
0
 def setUp(self):
     dom = [(1, -1), (3, -2)]
     ran = [(3, 4), (10, 8)]
     self.t = nudged.estimate(dom, ran)
Exemple #40
0
 def test_list_len_one(self):
     '''
     should allow lists of length one
     '''
     t = nudged.estimate([[1,1]], [[5,5]])
     self.assertEqual(t.transform([4,4]), [8,8])