Exemplo n.º 1
0
def test_optimize_new_scipy():
    opt = Optimizer(fun=func, x0=np.array([1., 1., 1.]), method='Powell')

    npt.assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    npt.assert_almost_equal(opt.fopt, 0)

    opt = Optimizer(fun=func, x0=np.array([1., 1., 1.]), method='L-BFGS-B',
                    options={'maxcor': 10, 'ftol': 1e-7,
                             'gtol': 1e-5, 'eps': 1e-8})

    npt.assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    npt.assert_almost_equal(opt.fopt, 0)
    npt.assert_equal(opt.evolution, None)

    npt.assert_equal(opt.evolution, None)

    opt = Optimizer(fun=func, x0=np.array([1., 1., 1.]), method='L-BFGS-B',
                    options={'maxcor': 10, 'ftol': 1e-7,
                             'gtol': 1e-5, 'eps': 1e-8},
                    evolution=False)

    npt.assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    npt.assert_almost_equal(opt.fopt, 0)

    opt.print_summary()

    opt = Optimizer(fun=func2, x0=np.array([1., 1., 1., 5.]),
                    method='L-BFGS-B',
                    options={'maxcor': 10, 'ftol': 1e-7,
                             'gtol': 1e-5, 'eps': 1e-8},
                    evolution=True)

    npt.assert_equal(opt.evolution.shape, (opt.nit, 4))

    opt = Optimizer(fun=func2, x0=np.array([1., 1., 1., 5.]),
                    method='Powell',
                    options={'xtol': 1e-6, 'ftol': 1e-6, 'maxiter': 1e6},
                    evolution=True)

    npt.assert_array_almost_equal(opt.xopt, np.array([0, 0, 0, 0.]))
Exemplo n.º 2
0
def test_optimize_new_scipy():

    opt = Optimizer(fun=func, x0=np.array([1., 1., 1.]), method='Powell')

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    assert_almost_equal(opt.fopt, 0)

    opt = Optimizer(fun=func, x0=np.array([1., 1., 1.]), method='L-BFGS-B',
                    options={'maxcor': 10, 'ftol': 1e-7,
                             'gtol': 1e-5, 'eps': 1e-8})

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    assert_almost_equal(opt.fopt, 0)
    assert_equal(opt.evolution, None)

    assert_equal(opt.evolution, None)

    opt = Optimizer(fun=func, x0=np.array([1., 1., 1.]), method='L-BFGS-B',
                    options={'maxcor': 10, 'ftol': 1e-7,
                             'gtol': 1e-5, 'eps': 1e-8},
                    evolution=False)

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    assert_almost_equal(opt.fopt, 0)

    opt.print_summary()

    opt = Optimizer(fun=func2, x0=np.array([1., 1., 1., 5.]),
                    method='L-BFGS-B',
                    options={'maxcor': 10, 'ftol': 1e-7,
                             'gtol': 1e-5, 'eps': 1e-8},
                    evolution=True)

    assert_equal(opt.evolution.shape, (opt.nit, 4))

    opt = Optimizer(fun=func2, x0=np.array([1., 1., 1., 5.]),
                    method='Powell',
                    options={'xtol': 1e-6, 'ftol': 1e-6, 'maxiter': 1e6},
                    evolution=True)

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0, 0.]))
Exemplo n.º 3
0
    def optimize(self, static, moving, mat=None):
        """ Find the minimum of the provided metric.

        Parameters
        ----------
        static : streamlines
            Reference or fixed set of streamlines.
        moving : streamlines
            Moving set of streamlines.
        mat : array
            Transformation (4, 4) matrix to start the registration. ``mat``
            is applied to moving. Default value None which means that initial
            transformation will be generated by shifting the centers of moving
            and static sets of streamlines to the origin.

        Returns
        -------
        map : StreamlineRegistrationMap

        """

        msg = 'need to have the same number of points. Use '
        msg += 'set_number_of_points from dipy.tracking.streamline'

        if not np.all(np.array(list(map(len, static))) == static[0].shape[0]):
            raise ValueError('Static streamlines ' + msg)

        if not np.all(np.array(list(map(len, moving))) == moving[0].shape[0]):
            raise ValueError('Moving streamlines ' + msg)

        if not np.all(np.array(list(map(len, moving))) == static[0].shape[0]):
            raise ValueError('Static and moving streamlines ' + msg)

        if mat is None:
            static_centered, static_shift = center_streamlines(static)
            moving_centered, moving_shift = center_streamlines(moving)
            static_mat = compose_matrix44([static_shift[0], static_shift[1],
                                           static_shift[2], 0, 0, 0])

            moving_mat = compose_matrix44([-moving_shift[0], -moving_shift[1],
                                           -moving_shift[2], 0, 0, 0])
        else:
            static_centered = static
            moving_centered = transform_streamlines(moving, mat)
            static_mat = np.eye(4)
            moving_mat = mat

        self.metric.setup(static_centered, moving_centered)

        distance = self.metric.distance

        if self.method == 'Powell':

            if self.options is None:
                self.options = {'xtol': 1e-6, 'ftol': 1e-6, 'maxiter': 1e6}

            opt = Optimizer(distance, self.x0.tolist(),
                            method=self.method, options=self.options,
                            evolution=self.evolution)

        if self.method == 'L-BFGS-B':

            if self.options is None:
                self.options = {'maxcor': 10, 'ftol': 1e-7,
                                'gtol': 1e-5, 'eps': 1e-8,
                                'maxiter': 100}

            opt = Optimizer(distance, self.x0.tolist(),
                            method=self.method,
                            bounds=self.bounds, options=self.options,
                            evolution=self.evolution)

        if self.verbose:
            opt.print_summary()

        opt_mat = compose_matrix44(opt.xopt)

        mat = compose_transformations(moving_mat, opt_mat, static_mat)

        mat_history = []

        if opt.evolution is not None:
            for vecs in opt.evolution:
                mat_history.append(
                    compose_transformations(moving_mat,
                                            compose_matrix44(vecs),
                                            static_mat))

        srm = StreamlineRegistrationMap(mat, opt.xopt, opt.fopt,
                                        mat_history, opt.nfev, opt.nit)
        del opt
        return srm
Exemplo n.º 4
0
    def optimize(self, static, moving, mat=None):
        """ Find the minimum of the provided metric.

        Parameters
        ----------
        static : streamlines
            Reference or fixed set of streamlines.
        moving : streamlines
            Moving set of streamlines.
        mat : array
            Transformation (4, 4) matrix to start the registration. ``mat``
            is applied to moving. Default value None which means that initial
            transformation will be generated by shifting the centers of moving
            and static sets of streamlines to the origin.

        Returns
        -------
        map : StreamlineRegistrationMap

        """

        msg = 'need to have the same number of points. Use '
        msg += 'set_number_of_points from dipy.tracking.streamline'

        if not np.all(np.array(list(map(len, static))) == static[0].shape[0]):
            raise ValueError('Static streamlines ' + msg)

        if not np.all(np.array(list(map(len, moving))) == moving[0].shape[0]):
            raise ValueError('Moving streamlines ' + msg)

        if not np.all(np.array(list(map(len, moving))) == static[0].shape[0]):
            raise ValueError('Static and moving streamlines ' + msg)

        if mat is None:
            static_centered, static_shift = center_streamlines(static)
            moving_centered, moving_shift = center_streamlines(moving)
            static_mat = compose_matrix44(
                [static_shift[0], static_shift[1], static_shift[2], 0, 0, 0])

            moving_mat = compose_matrix44([
                -moving_shift[0], -moving_shift[1], -moving_shift[2], 0, 0, 0
            ])
        else:
            static_centered = static
            moving_centered = transform_streamlines(moving, mat)
            static_mat = np.eye(4)
            moving_mat = mat

        self.metric.setup(static_centered, moving_centered)

        distance = self.metric.distance

        if self.method == 'Powell':

            if self.options is None:
                self.options = {'xtol': 1e-6, 'ftol': 1e-6, 'maxiter': 1e6}

            opt = Optimizer(distance,
                            self.x0.tolist(),
                            method=self.method,
                            options=self.options,
                            evolution=self.evolution)

        if self.method == 'L-BFGS-B':

            if self.options is None:
                self.options = {
                    'maxcor': 10,
                    'ftol': 1e-7,
                    'gtol': 1e-5,
                    'eps': 1e-8,
                    'maxiter': 100
                }

            opt = Optimizer(distance,
                            self.x0.tolist(),
                            method=self.method,
                            bounds=self.bounds,
                            options=self.options,
                            evolution=self.evolution)
        if self.verbose:
            opt.print_summary()

        opt_mat = compose_matrix44(opt.xopt)

        mat = compose_transformations(moving_mat, opt_mat, static_mat)

        mat_history = []

        if opt.evolution is not None:
            for vecs in opt.evolution:
                mat_history.append(
                    compose_transformations(moving_mat, compose_matrix44(vecs),
                                            static_mat))

        srm = StreamlineRegistrationMap(mat, opt.xopt, opt.fopt, mat_history,
                                        opt.nfev, opt.nit)
        del opt
        return srm
Exemplo n.º 5
0
def test_optimize_old_scipy():

    opt = Optimizer(fun=func,
                    x0=np.array([1., 1., 1.]),
                    method='L-BFGS-B',
                    options={
                        'maxcor': 10,
                        'ftol': 1e-7,
                        'gtol': 1e-5,
                        'eps': 1e-8
                    })

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    assert_almost_equal(opt.fopt, 0)

    opt = Optimizer(fun=func2,
                    x0=np.array([1., 1., 1., 5.]),
                    method='Powell',
                    options={
                        'xtol': 1e-6,
                        'ftol': 1e-6,
                        'maxiter': 1e6
                    },
                    evolution=True)

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0, 0.]))

    opt = Optimizer(fun=func,
                    x0=np.array([1., 1., 1.]),
                    method='L-BFGS-B',
                    options={
                        'maxcor': 10,
                        'eps': 1e-8
                    })

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    assert_almost_equal(opt.fopt, 0)

    opt = Optimizer(fun=func,
                    x0=np.array([1., 1., 1.]),
                    method='L-BFGS-B',
                    options=None)

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0]))
    assert_almost_equal(opt.fopt, 0)

    opt = Optimizer(fun=func2,
                    x0=np.array([1., 1., 1., 5.]),
                    method='L-BFGS-B',
                    options={
                        'gtol': 1e-7,
                        'ftol': 1e-7,
                        'maxiter': 10000
                    })

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0, 0.]), 4)
    assert_almost_equal(opt.fopt, 0)

    opt = Optimizer(fun=func2,
                    x0=np.array([1., 1., 1., 5.]),
                    method='Powell',
                    options={'maxiter': 1e6},
                    evolution=True)

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0, 0.]))

    opt = Optimizer(fun=func2,
                    x0=np.array([1., 1., 1., 5.]),
                    method='Powell',
                    options={'maxiter': 1e6},
                    evolution=True)

    assert_array_almost_equal(opt.xopt, np.array([0, 0, 0, 0.]))
Exemplo n.º 6
0
moving_clusters = KMeans(n_clusters=num).fit(np.concatenate(moving))

#x = np.array([[i,i,i,i,i,i,i] for i in range(1,9)])
x0 = np.array([[0, 0, 0, 0, 0, 0, 1] for _ in range(num)])

options = {
    'maxcor': 10,
    'ftol': 1e-7,
    'gtol': 1e-5,
    'eps': 1e-8
}  #,'maxiter': 10000000}#,'maxfun':200}

start = time()
m = Optimizer(cost_fun,
              x0,
              args=(static_clusters.cluster_centers_,
                    moving_clusters.cluster_centers_, 7),
              method='L-BFGS-B',
              options=options)
end = time()

m.print_summary()

#np.save('out/new_x0_00.npy',m.xopt)

x1 = np.reshape(m.xopt, (num, 7))
new_moving = transform(x1, moving, moving_clusters.cluster_centers_)
draw_bundles([static, moving], [[1, 0, 0], [0, 0, 1]])
#draw_bundles([new_moving])

hours = int((end - start) / 3600)
minutes = int(((end - start) % 3600) / 60)
Exemplo n.º 7
0
    elif init_from == 'random':
        f0 = np.random.uniform(0, 1, len(fmean_t1lab))
    else:
        raise ValueError('Unknown initial point type:%s' % (init_from, ))

    ofname = 'fopt_t1lab_' + str(radius) + '_' + init_from + '.npy'
    fopt_t1lab = None
    if os.path.isfile(ofname):
        print('Found precomputed t1lab transfer. Skipping optimization.')
        fopt_t1lab = np.load(ofname)
    else:
        print('Computing optimal llr transfer, t1lab. Radius=%d, init:%s' %
              (radius, init_from))
        opt_t1lab = Optimizer(value_and_gradient_t1lab,
                              f0,
                              "BFGS",
                              jac=True,
                              options=options)
        fopt_t1lab = opt_t1lab.xopt
        np.save(ofname, fopt_t1lab)

    options = {'maxiter': 20}
    if init_from == 'mean':
        f0 = fmean_t2lab
    elif init_from == 'random':
        f0 = np.random.uniform(0, 1, len(fmean_t2lab))
    else:
        raise ValueError('Unknown initial point type:%s' % (init_from, ))

    ofname = 'fopt_t2lab_' + str(radius) + '_' + init_from + '.npy'
    fopt_t2lab = None
Exemplo n.º 8
0
def registration_icp(static,
                     moving,
                     points=20,
                     pca=True,
                     maxiter=100000,
                     affine=[0, 0, 0, 0, 0, 0, 1],
                     clustering=None,
                     medoids=[0, 1, 2],
                     k=3,
                     beta=999,
                     max_dist=40,
                     dist='pc'):
    options = {
        'maxcor': 10,
        'ftol': 1e-7,
        'gtol': 1e-5,
        'eps': 1e-8,
        'maxiter': maxiter
    }
    #options1 = {'xtol': 1e-6, 'ftol': 1e-6, 'maxiter': 1e6}
    if pca:
        moving = pca_transform_norm(static, moving, max_dist)
    else:
        mean_m = np.mean(np.concatenate(moving), axis=0)
        mean_s = np.mean(np.concatenate(static), axis=0)
        moving = [i - mean_m + mean_s for i in moving]

    original_moving = moving.copy()
    static = set_number_of_points(static, points)
    moving = set_number_of_points(moving, points)

    if clustering == 'kmeans':
        kmeans = KMeans(k).fit(np.concatenate(moving))
        idx = {i: np.where(kmeans.labels_ == i)[0] for i in range(k)}
        #dist = Clustering().distance_pc_clustering_mean
        if dist == 'pc':
            dist_fun = distance_pc_clustering_mean
        else:
            dist_fun = distance_tract_clustering_mean
        args = (static, moving, kmeans, idx, beta, max_dist)
        print('kmeans')
    elif clustering == 'kmedoids':
        k_medoids = kmedoids(np.concatenate(moving), medoids)
        k_medoids.process()
        #dist = Clustering().distance_pc_clustering_medoids
        if dist == 'pc':
            dist_fun = distance_pc_clustering_medoids
        else:
            dist_fun = distance_tract_clustering_medoids
        args = (static, moving, k_medoids, beta, max_dist)
        print('kmedoids')
    else:
        if dist == 'pc':
            dist_fun = distance_pc
            args = (static, moving, beta, max_dist)
        else:
            dist_fun = distance_mdf
            args = (static, moving)
        print('Without Clustering')

    'L-BFGS-B,Powell'
    m = Optimizer(dist_fun,
                  affine,
                  args=args,
                  method='L-BFGS-B',
                  options=options)
    #m = Optimizer(dist, affine,args=args,method='Powell',options=options1)
    m.print_summary()
    mat = compose_matrix44(m.xopt)
    return transform_streamlines(original_moving, mat)
Exemplo n.º 9
0
pca_moving = pca_transform_norm(static, moving)

max_range = 46
x0 = [0, 0, 0, 0, 0, 0, 1]
options = {
    'maxcor': 10,
    'ftol': 1e-7,
    'gtol': 1e-5,
    'eps': 1e-8,
    'maxiter': 1000
}

start = time()
m = Optimizer(distance_pc,
              x0,
              args=(static, pca_moving, 1, 50),
              method='L-BFGS-B',
              options=options)
end = time()

aff = compose_matrix44(m.xopt)
new_moving = transform_streamlines(pca_moving, aff)
draw_bundles([new_moving, static], [[0, 0, 1], [1, 0, 0]])
''' Build KDTree '''
kdtree = KDTree(np.concatenate(static))
distances = kdtree.query(np.concatenate(new_moving), k=1)[0]

hours = int((end - start) / 3600)
minutes = int(((end - start) % 3600) / 60)
seconds = int(((end - start) % 3600) % 60)
print("Duration: {:02}:{}:{}".format(hours, minutes, seconds))
Exemplo n.º 10
0
length = 5
x0 = np.array([[0, 0, 0, 0, 0, 0, 1] for _ in range(length)])
lnk_cost = link_cost(transform(x0, pca_moving))
options = {
    'maxcor': 10,
    'ftol': 1e-7,
    'gtol': 1e-5,
    'eps': 1e-8,
    'maxiter': 1000
}  #,'maxfun':200}

start = time()
m = Optimizer(dist_new,
              x0,
              args=(static, pca_moving, length, lnk_cost, 50, 10),
              method='L-BFGS-B',
              options=options)
end = time()

m.print_summary()

np.save('out/dist_link11.npy', m.xopt)
np.save('out/costs11.npy', costs)

x1 = np.reshape(m.xopt, (5, 7))
new_moving = transform(x1, moving)
#draw_bundles([moving,new_moving],[[1,0,0],[0,0,1]])
#draw_bundles([new_moving])

hours = int((end - start) / 3600)