コード例 #1
0
 void MapGradient::compute_tangent_and_binormal(
     MapVertexProperty<vec3>& tangent,
     MapVertexProperty<vec3>& binormal
 ) {
     vec2 du(1,0) ; vec2 dv(0,1) ;
     FOR_EACH_VERTEX(Map, map_, it) {
         tangent[it] = compute_gradient(it, du) ;
         binormal[it] = compute_gradient(it, dv) ;
     }
コード例 #2
0
    void gradient_check()
    {
        std::vector<int> const Labels{0, 1, 2, 0};
        auto const UniqueLabels = get_unique_labels(Labels);
        auto const NumClass = UniqueLabels.size();
        EigenMat const Train = EigenMat::Random(10, 2);
        weight_ = EigenMat::Random(NumClass, Train.rows());
        grad_ = EigenMat::Zero(NumClass, Train.rows());
        int const TrainCols = static_cast<int>(Train.cols());
        EigenMat const GroundTruth = get_ground_truth(NumClass, TrainCols,
                                                      UniqueLabels,
                                                      Labels);
        gradient_checking gc;
        auto func = [&](EigenMat &theta)->double
        {
            return compute_cost(Train, theta, GroundTruth);
        };

        EigenMat const WeightBuffer = weight_;
        EigenMat const Gradient =
                gc.compute_gradient(weight_, func);

        compute_cost(Train, WeightBuffer, GroundTruth);
        compute_gradient(Train, WeightBuffer, GroundTruth);

        std::cout<<std::boolalpha<<"gradient checking pass : "******"\n";//*/
    }
コード例 #3
0
ファイル: normal_map.c プロジェクト: wwatkins42/RT
void			create_normal_map(t_env *e, t_obj *obj)
{
	int		x;
	int		y;
	double	*grad;

	y = -1;
	grad = NULL;
	obj->mat.texture.bump =
	(t_rgb**)malloc(sizeof(t_rgb*) * obj->mat.texture.h);
	obj->mat.texture.bump == NULL ? error(e, E_MALLOC, NULL, 1) : 0;
	while (++y < obj->mat.texture.h)
	{
		x = -1;
		obj->mat.texture.bump[y] =
		(t_rgb*)malloc(sizeof(t_rgb) * obj->mat.texture.w);
		obj->mat.texture.bump[y] == NULL ? error(e, E_MALLOC, NULL, 1) : 0;
		while (++x < obj->mat.texture.w)
		{
			grad = get_gradient(obj->mat.texture.img, y, x, obj->mat.texture);
			grad == NULL ? error(e, E_MALLOC, NULL, 1) : 0;
			obj->mat.texture.bump[y][x] = compute_gradient(grad, obj);
			ft_memdel((void**)&grad);
		}
	}
}
コード例 #4
0
ファイル: gnm-nlsolve.c プロジェクト: paulfitz/gnumeric
static gboolean
newton_improve (GnmNlsolve *nl, gnm_float *xs, gnm_float *y, gnm_float ymax)
{
	GnmSolver *sol = nl->parent;
	const int n = nl->vars->len;
	gnm_float *g, **H, *d;
	gboolean ok;

	g = compute_gradient (nl, xs);
	H = compute_hessian (nl, xs, g);
	d = g_new (gnm_float, n);
	ok = (gnm_linear_solve (H, g, n, d) == 0);

	if (ok) {
		int i;
		gnm_float y2, *xs2 = g_new (gnm_float, n);
		gnm_float f, best_f = -1;

		ok = FALSE;
		for (f = 1; f > 1e-4; f /= 2) {
			int i;
			for (i = 0; i < n; i++)
				xs2[i] = xs[i] - f * d[i];
			set_vector (nl, xs2);
			y2 = get_value (nl);
			if (nl->debug) {
				print_vector ("xs2", xs2, n);
				g_printerr ("Obj value %.15" GNM_FORMAT_g "\n",
					    y2);
			}

			if (y2 < ymax && gnm_solver_check_constraints (sol)) {
				best_f = f;
				ymax = y2;
				break;
			}
		}

		if (best_f > 0) {
			for (i = 0; i < n; i++)
				xs[i] = xs[i] - best_f * d[i];
			*y = ymax;
			ok = TRUE;
		}

		g_free (xs2);
	} else {
		if (nl->debug)
			g_printerr ("Failed to solve Newton step.\n");
	}

	g_free (d);
	g_free (g);
	free_matrix (H, n);

	return ok;
}
コード例 #5
0
 vec3 MapGradient::compute_gradient(Map::Vertex* v, const vec2& w) {
     vec3 result(0,0,0) ;
     Map::Halfedge* h = v->halfedge() ;
     int count = 0 ;
     do {
         result = result + compute_gradient(h->prev(), h, h->next(), w) ;
         h = h->next() ;
         count++ ;
     } while(h != v->halfedge()) ;
     return real(1.0 / double(count)) * result ;
 }
コード例 #6
0
void gradient_descent(double X[][MAX_FEATURE_DIMENSION], int y[],
	double theta[], int feature_number, int sample_number,
	double alpha, int iterate_number, double J[]){
	for (int i = 0; i < iterate_number; i++){
		double temp[MAX_FEATURE_DIMENSION] = {0};
		for (int j = 0; j <= feature_number; j++){
			temp[j] = theta[j] - alpha * compute_gradient(X, y, theta, feature_number, j, sample_number);
		}
		for (int j = 0; j <= feature_number; j++){
			theta[j] = temp[j];
		}
		J[i] = compute_cost(X, y, theta, feature_number, sample_number);
	}
}
コード例 #7
0
 void MapGradient::compute_gradient(
     Map::Halfedge* h1,
     Map::Halfedge* h2,
     Map::Halfedge* h3,
     double* TU,
     double* TV
 ) {
     compute_gradient(
         h1->vertex()->point(),
         h2->vertex()->point(),
         h3->vertex()->point(),
         *halfedge_tex_vertex_[h1],
         *halfedge_tex_vertex_[h2],
         *halfedge_tex_vertex_[h3],
         TU, TV
     ) ;
 }
コード例 #8
0
void softmax<T>::train(const Eigen::Ref<const EigenMat> &train,
                       const std::vector<int> &labels)
{
#ifdef OCV_TEST_SOFTMAX
    gradient_check();
#endif

    auto const UniqueLabels = get_unique_labels(labels);
    auto const NumClass = UniqueLabels.size();
    weight_ = EigenMat::Random(NumClass, train.rows());
    grad_ = EigenMat::Zero(NumClass, train.rows());
    auto const TrainCols = static_cast<int>(train.cols());
    EigenMat const GroundTruth = get_ground_truth(static_cast<int>(NumClass),
                                                  TrainCols,
                                                  UniqueLabels,
                                                  labels);

    std::random_device rd;
    std::default_random_engine re(rd());
    int const Batch = (get_batch_size(TrainCols));
    int const RandomSize = TrainCols != Batch ?
                TrainCols - Batch - 1 : 0;
    std::uniform_int_distribution<int>
            uni_int(0, RandomSize);
    for(size_t i = 0; i != params_.max_iter_; ++i){
        auto const Cols = uni_int(re);
        auto const &TrainBlock =
                train.block(0, Cols, train.rows(), Batch);
        auto const &GTBlock =
                GroundTruth.block(0, Cols, NumClass, Batch);
        auto const Cost = compute_cost(TrainBlock, weight_, GTBlock);
        if(std::abs(params_.cost_ - Cost) < params_.epsillon_ ||
                Cost < 0){
            break;
        }
        params_.cost_ = Cost;
        compute_gradient(TrainBlock, weight_, GTBlock);
        weight_.array() -= grad_.array() * params_.lrate_;//*/
    }
}
コード例 #9
0
 vec3 MapGradient::compute_gradient(
     Map::Halfedge* h1,
     Map::Halfedge* h2,
     Map::Halfedge* h3,
     const vec2& W
 ) {
     double TU[3] ;
     double TV[3] ;
     compute_gradient(h1,h2,h3,TU,TV) ;
     const vec3& p1 = h1->vertex()->point() ;
     const vec3& p2 = h2->vertex()->point() ;
     const vec3& p3 = h3->vertex()->point() ;
     vec3 grad_u(
         real(TU[0] * p1.x + TU[1] * p2.x + TU[2] * p3.x),
         real(TU[0] * p1.y + TU[1] * p2.y + TU[2] * p3.y),
         real(TU[0] * p1.z + TU[1] * p2.z + TU[2] * p3.z)
     ) ; 
     vec3 grad_v(
         real(TV[0] * p1.x + TV[1] * p2.x + TV[2] * p3.x),
         real(TV[0] * p1.y + TV[1] * p2.y + TV[2] * p3.y),
         real(TV[0] * p1.z + TV[1] * p2.z + TV[2] * p3.z)
     ) ; 
     return W.x * grad_u + W.y * grad_v ;
 }
コード例 #10
0
void GeodesicInHeat::compute_distance(const Vertex& start_vertex)
{
	int n = mesh.n_vertices();
	int start_idx = start_vertex.idx();
	VecN delta(n);
	delta.setZero();
	delta(start_idx) =1.0f;

	//The laplacian, gradient divergence matrix only need to compute once.
	if (!initialized)
		initialization();
	float timestep = avglength*avglength*factor;
	VecN uNeumann = compute_heat(delta,Laplacian, AreaMatrix,timestep);
	VecN uDirichlet = compute_heat(delta, LaplacianDirichlet, AreaMatrix, timestep);
	VecN u =0.5*uNeumann+0.5*uDirichlet;

	//Method::the three boundary function will active one, if all false, display the average.
	if (Neumann)
		u = uNeumann;
	if (Dirichlet)
		u = uDirichlet;
	MatMxN X = compute_gradient(Grad_x, Grad_y, Grad_z, u);
	VecN div_X = compute_divergence(Div_x, Div_y, Div_z, X);

	Eigen::SimplicialCholesky<Sparse, Eigen::RowMajor> Solver;
	Solver.compute(Laplacian);
	VecN phi = Solver.solve(div_X);	
	
	//shift phi and find out the Max G, Min G and the Max geodesic distance span along edge.
	for (auto const& vertex : mesh.vertices())
	{
		float d1 = phi[vertex.idx()];
		HeatDisplay[vertex] = d1;
		float d2 = 0.0;
		for (auto const& vj : mesh.vertices(vertex))
		{
			float d = std::abs(phi[vertex.idx()] - phi[vj.idx()]);
			if (d > d2)
				d2 = d;
		}
		if (d1 > MaxGeodesic)
			MaxGeodesic = d1;
		if (d2 > MaxEdgeSpan)
			MaxEdgeSpan = d2;
		if (d1 < MinGeodesic)
			MinGeodesic = d1;
	}
	
	for (auto const& vertex : mesh.vertices())
	{
		HeatDisplay[vertex] = HeatDisplay[vertex] - MinGeodesic;
		HeatDistance[vertex] = HeatDisplay[vertex];
	}
	MaxGeodesic -= MinGeodesic;
	MinGeodesic = 0;

	if (Neumann) {
		mLogger() << "Heat: Neumann Boudary Condition, M=" << factor;
		return;
	}
	if (Dirichlet) {
		mLogger() << "Heat: Dirichlet Boudary Condition, M=" << factor;
		return;
	}
	mLogger() << "Heat: Average Boudary Condition, M=" << factor;
}
コード例 #11
0
void
detect_edges(Image *img, float sigma, float threshold, \
             unsigned char *edge_pix, PList *edge_pts)
{
	int x, y;
	int w = img->w;
	int h = img->h;

	// convert image to grayscale
	float **gray = array_create(w, h);
	convert_grayscale(img, gray);

	// blur grayscale image
	float **gray2 = array_create(w, h);
	gaussian_blur(gray, gray2, w, h, sigma);

	// compute gradient of blurred image
	float **g_mag = array_create(w, h);
	float **g_ang = array_create(w, h);
	compute_gradient(gray2, w, h, g_mag, g_ang);

	// mark edge pixels
	#define PIX(y,x) edge_pix[(y)*w+(x)]
#pragma omp parallel 
{
#pragma omp for private(x) nowait
	for (y = 0; y < h; y++)
	for (x = 0; x < w; x++)
	{
		PIX(y,x) = is_edge(g_mag,g_ang,threshold,x,y,w,h) ? 255 : 0;
	}

	// connect horizontal edges
#pragma omp for private(x) nowait
	for (y = 0; y < h  ; y++)
	for (x = 1; x < w-1; x++)
	{
		if (!PIX(y,x) && PIX(y,x+1) && PIX(y,x-1))
			PIX(y,x) = 255;
	}

	// connect vertical edges
#pragma omp for private(y) nowait
	for (x = 0; x < w  ; x++)
	for (y = 1; y < h-1; y++)
	{
		if (!PIX(y,x) && PIX(y+1,x) && PIX(y-1,x))
			PIX(y,x) = 255;
	}
#pragma omp for private(x) 
	// connect diagonal edges
	for (y = 1; y < h-1; y++)
	for (x = 1; x < w-1; x++)
	{
		if (!PIX(y,x) && PIX(y-1,x-1) && PIX(y+1,x+1))
			PIX(y,x) = 255;
		if (!PIX(y,x) && PIX(y-1,x+1) && PIX(y+1,x-1))
			PIX(y,x) = 255;
	}
}
	// add edge points to list
	if (edge_pts)
	{
		for (y = 0; y < h; y++)
		for (x = 0; x < w; x++)
		{
			if (PIX(y,x)) PList_push(edge_pts, x, y);
		}
	}

	// cleanup
	array_free(g_mag, h);
	array_free(g_ang, h);
	array_free(gray2, h);
	array_free(gray, h);
}
コード例 #12
0
ファイル: hess.c プロジェクト: psi4/libefp
static void compute_hessian(struct state *state, double *hess)
{
	size_t n_frags, n_coord;
	double *xyzabc, *grad_f, *grad_b;
	bool central = cfg_get_bool(state->cfg, "hess_central");

	check_fail(efp_get_frag_count(state->efp, &n_frags));
	n_coord = 6 * n_frags;

	xyzabc = xmalloc(n_coord * sizeof(double));
	grad_f = xmalloc(n_coord * sizeof(double));
	grad_b = xmalloc(n_coord * sizeof(double));

	check_fail(efp_get_coordinates(state->efp, xyzabc));

	if (!central) {
		memcpy(grad_b, state->grad, n_frags * 6 * sizeof(double));

		for (size_t i = 0; i < n_frags; i++) {
			const double *euler = xyzabc + 6 * i + 3;
			double *gradptr = grad_b + 6 * i + 3;

			efp_torque_to_derivative(euler, gradptr, gradptr);
		}
	}

	for (size_t i = 0; i < n_coord; i++) {
		double save = xyzabc[i];
		double step = i % 6 < 3 ? cfg_get_double(state->cfg, "num_step_dist") :
					  cfg_get_double(state->cfg, "num_step_angle");

		show_progress(i + 1, n_coord, "FORWARD");
		xyzabc[i] = save + step;
		compute_gradient(state, n_frags, xyzabc, grad_f);

		if (central) {
			show_progress(i + 1, n_coord, "BACKWARD");
			xyzabc[i] = save - step;
			compute_gradient(state, n_frags, xyzabc, grad_b);
		}

		double delta = central ? 2.0 * step : step;

		for (size_t j = 0; j < n_coord; j++)
			hess[i * n_coord + j] = (grad_f[j] - grad_b[j]) / delta;

		xyzabc[i] = save;
	}

	/* restore original coordinates */
	check_fail(efp_set_coordinates(state->efp, EFP_COORD_TYPE_XYZABC, xyzabc));

	/* reduce error by computing the average of H(i,j) and H(j,i) */
	for (size_t i = 0; i < n_coord; i++) {
		for (size_t j = i + 1; j < n_coord; j++) {
			double sum = hess[i * n_coord + j] + hess[j * n_coord + i];

			hess[i * n_coord + j] = 0.5 * sum;
			hess[j * n_coord + i] = hess[i * n_coord + j];
		}
	}

	free(xyzabc);
	free(grad_f);
	free(grad_b);

	msg("\n\n");
}
コード例 #13
0
ファイル: KLInference.cpp プロジェクト: minxuancao/shogun
SGMatrix<float64_t> CKLInference::get_posterior_covariance()
{
	compute_gradient();

	return SGMatrix<float64_t>(m_Sigma);
}
コード例 #14
0
ファイル: KLInference.cpp プロジェクト: minxuancao/shogun
SGVector<float64_t> CKLInference::get_posterior_mean()
{
	compute_gradient();

	return SGVector<float64_t>(m_mu);
}