static void assert_linearity(linear_map_t A, int n, void *e, int ntrials)
{
	int sn = n * sizeof(double);
	double *x = xmalloc(sn);
	double *y = xmalloc(sn);
	double *Ax = xmalloc(sn);
	double *Ay = xmalloc(sn);
	double *xpy = xmalloc(sn);
	double *AxpAy = xmalloc(sn);
	double *Axpy = xmalloc(sn);
	for (int i = 0; i < ntrials; i++) {
		fill_random_vector(x, n);
		fill_random_vector(y, n);
		vector_sum(xpy, x, y, n);
		A(Ax, x, n, e);
		A(Ay, y, n, e);
		A(Axpy, xpy, n, e);
		vector_sum(AxpAy, Ax, Ay, n);
		double error = 0;
		for (int k = 0; k < n; k++)
			error = hypot(error, fabs(AxpAy[k]-Axpy[k]));
		fprintf(stderr, "error linearity = %g\n", error);
		if (error > 1e-12)
			fprintf(stderr, "WARNING: non linear!\n");

	}
	free(x);
	free(y    );
	free(Ax   );
	free(Ay   );
	free(xpy  );
	free(AxpAy);
	free(Axpy );
}
Beispiel #2
0
int Runge_Kutta_4b(int n, void (*f)(double,double *,double *,double *,double *,double *,double *), 
                   double *p, double *fld, double *ext, double *extev, 
                   double *y, double x0, double h, double *yout, 
                   double *k1, double *k2, double *k3, double *k4, 
                   double *t1, double *t2, double *t3, double *t4, double *t5, double *t6,
                   double *t7, double *t8)
{
  double h2, h3;

  if (n == 0)
    {
      return 0;
    }

// cs:     [0,0.333333333333,0.666666666667,1]
// as:     <1, []>
//        <3, [1]>
//        <3, [~1,3]>
//        <1, [1,~1,1]>
// bs:     <8, [1,3,3,1]>

  h2 = 0.333333333333 * h;
  h3 = 0.666666666667 * h;

  (*f)(x0, p, fld, ext, extev, y, k1);
  // printf("c: k1[0] = %g\n", k1[0]);
  
  vector_scale(n, 1.0, k1, t1); 
  vector_scale(n, h/3.0, t1, t2); 
  vector_sum(n, y, t2, t3);
  (*f)(x0+h2, p, fld, ext, extev, t3, k2);
  
  vector_scale(n, -1.0, k1, t1); vector_scale(n, 3.0, k2, t2);
  vector_sum(n, t1, t2, t3); 
  vector_scale(n, h/3.0, t3, t4); vector_sum(n, y, t4, t5); 
  (*f)(x0+h3, p, fld, ext, extev, t5, k3);

  vector_scale(n, 1.0, k1, t1); vector_scale(n, -1.0, k2, t2);
  vector_scale(n, 1.0, k3, t3);
  vector_sum(n, t1, t2, t4); vector_sum(n, t3, t4, t5); 
  vector_scale(n, h, t5, t6); vector_sum(n, y, t6, t7); 
  (*f)(x0+h, p, fld, ext, extev, t7, k4);

  vector_scale(n, 1.0, k1, t1); 
  vector_scale(n, 3.0, k2, t2); 
  vector_scale(n, 3.0, k3, t3); 
  vector_scale(n, 1.0, k4, t4); 
  vector_sum(n, t1, t2, t5); vector_sum(n, t3, t4, t6);
  vector_sum(n, t5, t6, t7); 
  vector_scale(n, h/8.0, t7, t8); 
  // printf("c: t6[0] = %g\n", t6[0]);
  vector_sum(n, y, t8, yout); 
  
  return 0;
}
Beispiel #3
0
vector3d ahrs_drift_correction(dataexchange_t *data) {
	vector3d corr_vector, acc_g;

	corr_vector.x = 0.0;
	corr_vector.y = 0.0;
	corr_vector.z = 0.0;

	//do correction only then acceleration is close to 1G (unreliable if greater)
	acc_g = adxl345_raw_to_g(data, SCALE_2G_10B);
	double acc_magnitude = vector_magnitude(acc_g);
	if (fabs(acc_magnitude - 1.0) <= 0.15) {
		float corr_strength = 0.15;

		//vectors for rotation matrix
		vector3d acc_v, mag_v;

		acc_v.x = (*data).acc_x;
		acc_v.y = (*data).acc_y;
		acc_v.z = (*data).acc_z;

		mag_v.x = (*data).mag_x;
		mag_v.y = (*data).mag_y;
		mag_v.z = (*data).mag_z;

		hmc5883l_applyCalibration(&mag_v, calib_ptr);

		vector3d down = vector_inv(acc_v);
		vector3d east = vector_cross(down, mag_v);
		vector3d north = vector_cross(east, down);

		//normalize vectors
		vector_norm(&down);
		vector_norm(&east);
		vector_norm(&north);

		//matrix from rotation quaternion
		matrix3x3d rot_matrix = quaternion_to_matrix((*data).qr);

		//correction vector calculation
		vector3d sum1 = vector_sum(vector_cross(north, matrix_row_to_vector(&rot_matrix, 1)),
				vector_cross(east, matrix_row_to_vector(&rot_matrix, 2)));

		vector3d sum2 = vector_sum(sum1, vector_cross(down, matrix_row_to_vector(&rot_matrix, 3)));

		corr_vector = vector_scale(sum2, corr_strength);
	}

	return corr_vector;
}
Beispiel #4
0
int Runge_Kutta_4b_regime(int n, void (*f)(double,double *,double *,double *,int *,double *,double *,double *,double *), 
                          double *p, double *fld, double *d, int *r, double *ext, double *extev, 
                          double *y, double x0, double h, double *yout, 
                          double *k1, double *k2, double *k3, double *k4, 
                          double *t1, double *t2, double *t3, double *t4, double *t5, double *t6,
                          double *t7, double* t8)
{
  double h2, h3;

  if (n == 0)
    {
      return 0;
    }

  h2 = 0.333333333333 * h;
  h3 = 0.666666666667 * h;

  (*f)(x0, p, fld, d, r, ext, extev, y, k1);
  // printf("c: k1[0] = %g\n", k1[0]);
  
  vector_scale(n, 1.0, k1, t1); 
  vector_scale(n, h/3.0, t1, t2); 
  vector_sum(n, y, t2, t3);
  (*f)(x0+h2, p, fld, d, r, ext, extev, t3, k2);
  
  vector_scale(n, -1.0, k1, t1); vector_scale(n, 3.0, k2, t2);
  vector_sum(n, t1, t2, t3); 
  vector_scale(n, h/3.0, t3, t4); vector_sum(n, y, t4, t5); 
  (*f)(x0+h3, p, fld, d, r, ext, extev, t5, k3);

  vector_scale(n, 1.0, k1, t1); vector_scale(n, -1.0, k2, t2);
  vector_scale(n, 1.0, k3, t3);
  vector_sum(n, t1, t2, t4); vector_sum(n, t3, t4, t5); 
  vector_scale(n, h, t5, t6); vector_sum(n, y, t6, t7); 
  (*f)(x0+h, p, fld, d, r, ext, extev, t7, k4);

  vector_scale(n, 1.0, k1, t1); 
  vector_scale(n, 3.0, k2, t2); 
  vector_scale(n, 3.0, k3, t3); 
  vector_scale(n, 1.0, k4, t4); 
  vector_sum(n, t1, t2, t5); vector_sum(n, t3, t4, t6);
  vector_sum(n, t5, t6, t7); 
  vector_scale(n, h/8.0, t7, t8); 
  // printf("c: t6[0] = %g\n", t6[0]);
  vector_sum(n, y, t8, yout); 
  
  return 0;
}
Beispiel #5
0
int main()
{
	float a[N];
	float b[N];
	float res[N];
	float golden_res[N];

	unsigned int i, j, errors = 0;

	for(i = 0; i < N; i++) {
		a[i] = i*1.0;
		b[i] = i*2.0;
		golden_res[i] = a[i] + b[i];
	}

	vector_sum(a, b, res);

	for(i = 0; i < N; i++) {
		if(res[i] != golden_res[i]) {
			printf("Error, expected: %f, got: %f \n", golden_res[i], res[i]);
			errors++;
		}
	}

	if(errors == 0) {
		printf("Test succeeded!\n");
		return 0;
	} else {
		printf("Test failed, %u errors\n", errors);
		return 1;
	}
}
Beispiel #6
0
inline size_t sample_from_likelihoods (
        rng_t & rng,
        const std::vector<float, Alloc> & likelihoods)
{
    float total = vector_sum(likelihoods.size(), likelihoods.data());
    return sample_from_likelihoods(rng, likelihoods, total);
}
Beispiel #7
0
t_color3	ft_trace_ray(t_object arr[16], t_object light[16], t_ray ray, int depth, float *dist_out, t_env env)
{
	t_intersect		inter;
	t_color3		outcolor;
	t_color3		refl_color;
	int				i;
	float			dist;
	float			_dist_out;

	if (dist_out == NULL)
		dist_out = &_dist_out;
	*dist_out = INFINITY;
	outcolor = color_new(17, 25, 37);
	i = -1;
	inter.obj = NULL;
	while (++i < 16 && arr[i].type != DEFAULT)
		if (env.fctinter[arr[i].type](ray, arr + i, &dist))
			if ((!inter.obj || dist < *dist_out) && dist > 0.00001)
			{
				inter.obj = &arr[i];
				*dist_out = dist;
			}
	if (inter.obj)
	{
		inter.pos = create_intersect(ray, *dist_out);
		inter.v_normal = env.fctnormal[inter.obj->type](ray, inter.pos, inter.obj);
		outcolor = getfinalcolor(light, inter);
		if (inter.obj->reflection_index != 0.0 && depth < g_death)
		{
			refl_color = ft_trace_ray(arr, light, create_reflection(ray, inter), depth + 1, NULL, env);
			outcolor = vector_sum(outcolor, vector_mul(refl_color, inter.obj->reflection_index));
		}
	}
	return outcolor;
}
Beispiel #8
0
int vextra_response_katcl(struct katcl_line *cl, int code, char *fmt, va_list args)
{
  int result[3];
  char *name, *status;

  if(code > KATCP_RESULT_OK){
    return -1;
  }

  name = arg_copy_string_katcl(cl, 0);
  if(name == NULL){
    return -1;
  }
  name[0] = KATCP_REPLY;

  status = code_to_name_katcm(code);
  if(status == NULL){
    return -1;
  }

  result[0] = append_string_katcl(cl, KATCP_FLAG_FIRST, name);
  result[1] = append_string_katcl(cl, 0, status);
  result[2] = append_vargs_katcl(cl, KATCP_FLAG_LAST, fmt, args);

  return vector_sum(result, 3);
}
Beispiel #9
0
/*solution saved in b */
void conjugate_gradient(sparse_matrix A, double *b, int size) {
	double *x, *r, *p, *Ap, *aux, rnew, rold, alfa;
	int i;

    x = (double*) malloc(size*sizeof(double));
    r = (double*) malloc(size*sizeof(double));
    p = (double*) malloc(size*sizeof(double));
    Ap = (double*) malloc(size*sizeof(double));
    aux = (double*) malloc(size*sizeof(double));

	for (i = 0; i < size; i ++) {
		x[i] = 0;
		r[i] = b[i];
		p[i] = b[i];
	}

	rold = inner_product(r, r, size);
    /* result of operations from all void functions used here are stored in the last argument */
	while (1) {
		matrix_vector_product(A, p, Ap);
		alfa = rold / inner_product(p, Ap, size); /*step length*/
		vector_scalar_product(p, alfa, size, aux); 
		vector_sum(x, aux, size, x);
		vector_scalar_product(Ap, alfa, size, aux);
		vector_subtraction(r, aux, size, r);
		rnew = inner_product(r, r, size);
		if (sqrt(rnew) < E)
                        break;
                vector_scalar_product(p, rnew / rold, size, p);
                vector_sum(p, r, size, p);
		rold = rnew;
	}

	for (i = 0; i < size; i ++) {
		b[i] = x[i];
	}

	free(x);
	free(r);
	free(p);
	free(Ap);
	free(aux);
}
Beispiel #10
0
int basic_inform_katcl(struct katcl_line *cl, char *name, char *arg)
{
  int result[2];

  if(arg){
    result[0] = append_string_katcl(cl, KATCP_FLAG_FIRST, name);
    result[1] = append_string_katcl(cl, KATCP_FLAG_LAST, arg);
    return vector_sum(result, 2);
  } else {
    return append_string_katcl(cl, KATCP_FLAG_FIRST | KATCP_FLAG_LAST, name);
  }
}
void WeightMatrix_iter::normalize_row(std::vector<double>& rowvec)
{
    double sum_row = vector_sum(rowvec);
//     for(int cc=0; cc<_nClass; cc++){
// 	sum_row += rowvec[cc];
//     }
    if (sum_row>0){
	for(int cc=0; cc<_nClass; cc++){
	    (rowvec[cc]) /= sum_row;
	}
    }
}
	void
	train(const category_index_t &category_index,
		  const std::vector<fv_t> &data)
	{
		for (auto l = category_index.begin(); l != category_index.end(); ++l) {
			fv_t centroid;
			vector_sum(centroid, l->second, data);
			vector_normalize_l2(centroid);
			m_centroids.push_back(centroid);
			m_centroid_labels.push_back(l->first);
		}
		m_inverted_index.build(&m_centroids);
	}
Beispiel #13
0
/**
* Create a new leaf node, storing pointers back to the end points for later.
*/
static CIRC_NODE* 
circ_node_leaf_new(const POINTARRAY* pa, int i)
{
	POINT2D *p1, *p2;
	POINT3D q1, q2, c;
	GEOGRAPHIC_POINT g1, g2, gc;
	CIRC_NODE *node;
	double diameter;

	p1 = (POINT2D*)getPoint_internal(pa, i);
	p2 = (POINT2D*)getPoint_internal(pa, i+1);
	geographic_point_init(p1->x, p1->y, &g1);
	geographic_point_init(p2->x, p2->y, &g2);

	LWDEBUGF(3,"edge #%d (%g %g, %g %g)", i, p1->x, p1->y, p2->x, p2->y);
	
	diameter = sphere_distance(&g1, &g2);

	/* Zero length edge, doesn't get a node */
	if ( FP_EQUALS(diameter, 0.0) )
		return NULL;

	/* Allocate */
	node = lwalloc(sizeof(CIRC_NODE));
	node->p1 = p1;
	node->p2 = p2;
	
	/* Convert ends to X/Y/Z, sum, and normalize to get mid-point */
	geog2cart(&g1, &q1);
	geog2cart(&g2, &q2);
	vector_sum(&q1, &q2, &c);
	normalize(&c);
	cart2geog(&c, &gc);
	node->center = gc;
	node->radius = diameter / 2.0;

	LWDEBUGF(3,"edge #%d CENTER(%g %g) RADIUS=%g", i, gc.lon, gc.lat, node->radius);

	/* Leaf has no children */
	node->num_nodes = 0;
	node->nodes = NULL;
	node->edge_num = i;
	
	return node;
}
void construct_cand(vector<int>& nums,int k, int n, vector<int>& cand) {
    int nums_len = nums.size();
    int max;
    
    if (nums_len > k)//end backtrace.
        return;
    if (vector_sum(nums) >= n)//pruning.
        return;
        
    if (nums_len == 0)
        max = 0;
    else
        max = nums.at(nums_len-1);
    
    for (int i = max+1; i <= 9; i++)
            cand.push_back(i);
    
}
Beispiel #15
0
static	t_color3	getfinalcolor(t_object *light, t_intersect inter)
{
	t_color3			color;
	unsigned int		i;

	color = color_new(0., 0., 0.);
	if (inter.obj)
	{
		i = 0;
		while(light[i].type != DEFAULT)
		{
			color = vector_sum(iter_light(inter, (t_spotlight *)&light[i]), color);
			++i;
		}
		return (vector_div(color, i));
	}
	return (color_new(17, 25, 37));
}
Beispiel #16
0
int main (int argc, char* argv[]) {

    struct timespec start, end;
    
    initOpenCL();

    /* START Measurements */
    get_date(argc, argv);
    clock_gettime(CLOCK_MONOTONIC, &start);

    int arraySize = SIZE;
    size_t bufferSize = arraySize * sizeof(double);
    double* inputA = (double*) malloc (bufferSize);
    double* inputB = (double*) malloc (bufferSize);
    double* output = (double*) malloc (bufferSize);


    /* Initilise data */
    initialize_data(arraySize, inputA, inputB);

    /* Computation */
    vector_sum(arraySize, inputA, inputB, output);

    /* END Measurements */
    clock_gettime(CLOCK_MONOTONIC, &end);
    get_date(argc, argv);

    /* Check results */
    //check_results(arraySize, inputA, inputB, output);

    /* Cleaning */
    cleanUpOpenCL();

    double res=0;
    int i;
    for (i = 0; i < arraySize; i++) {
      res = res + output[i] ;
    }

    times = (((double)(end.tv_sec  - start.tv_sec)*1000) +
             ((double)(end.tv_nsec - start.tv_nsec)/1000000));
    //cout << "Time to finish: " << times << " ms" << endl;
    printf("Time to finish %6.0f ms [check = %e]\n", times, res);
}
Beispiel #17
0
static	t_color3	getfinalcolor(t_object *arr, t_intersect inter, t_env env)
{
	t_color3			color;
	t_color3			color_tmp;
	float				dist[2];
	t_ray 				newray;
	float				shade;
	t_vector3			l;

	int					i;
	int 				k;
	int 				a;

	color_tmp = color_new(0, 0, 0);
	a = 0;
	if (inter.obj)
	{
		i = -1;
		while(arr[i].type != DEFAULT)
		{
			shade = 1.0;
			if (arr[i].light == TRUE)
			{
				l = vector_substract(arr[i].pos, inter.pos);
				dist[0] = vector_magnitude(l);
				newray.pos = vector_substract(inter.pos, vector_mul(inter.v_normal, 1e-4f));
				newray.dir = vector_unit(l);
				k = -1;
				while (++k < 16 && arr[k].type != DEFAULT)
					if (env.fctinter[arr[k].type](newray, arr + k, &dist[1]))
					{
						if (arr[k].light != TRUE && dist[1] <= dist[0])
							shade -= 0.3;
					}
				color_tmp = vector_sum(color_tmp, iter_light(inter, &arr[i], shade));
				++a;
			}
			++i;
		}
		return (vector_div(color_tmp, a));
	}
	return (color_new(17, 25, 37));
}
Beispiel #18
0
int vlog_message_katcl(struct katcl_line *cl, int level, char *name, char *fmt, va_list args)
{
  int result[5];
  struct timeval now;
  unsigned int milli;
  char *subsystem, *logstring;

#ifdef DEBUG
  if(level >= KATCP_LEVEL_OFF){
    fprintf(stderr, "log: bad form to a message of level off or worse\n");
    return -1;
  }
#endif

  logstring = log_to_string_katcl(level);
  if(logstring == NULL){
#ifdef DEBUG
    fprintf(stderr, "log: bad log level\n");
    abort();
#endif
    return -1;
  }

  subsystem = name ? name : "unknown" ;

  gettimeofday(&now, NULL);
  milli = now.tv_usec / 1000;

  result[0] = append_string_katcl(cl, KATCP_FLAG_FIRST, KATCP_LOG_INFORM);
  result[1] = append_string_katcl(cl, 0, logstring);
  result[2] = append_args_katcl(cl, 0, "%lu%03d", now.tv_sec, milli);
  result[3] = append_string_katcl(cl, 0, subsystem);

#if DEBUG > 1
  fprintf(stderr, "log: my fmt string is <%s>, milli=%u\n", fmt, milli);
#endif

  result[4] = append_vargs_katcl(cl, KATCP_FLAG_LAST, fmt, args);

  /* do the right thing, collect error codes */
  return vector_sum(result, 5);
}
Beispiel #19
0
quaternion ahrs_orientation(dataexchange_t *data) {

	//angle component
	vector3d gyr_rad_s = vector_sum(l3g4200d_raw_to_rad(data), ahrs_drift_correction(data));

	//vector3d gyr_rad_s = vector_sum(l3g4200d_raw_to_rad(data), ahrs_drift_correction(data));
	double angle = vector_magnitude(gyr_rad_s) * (*data).time_period;

	//axis, normalized
	vector_norm(&gyr_rad_s);

	//quaternion from axis/angle
	quaternion q = quaternion_from_axis_angle(gyr_rad_s, angle);

	//normalize
	quaternion_norm(&q);

	(*data).qr = quaternion_product((*data).qr, q);

	return q;
}
Beispiel #20
0
int main()
{
    srand(1234);

    val_t* xs = malloc(n * sizeof(val_t));
    if (xs == NULL) {
        fprintf(stderr, "Cannot allocate %zu bytes", n * sizeof(val_t));
        return 1;
    }

    size_t i;
    for (i = 0; i < n; ++i) {
        xs[i] = randval();
    }

    vector_t* vec = vector_create(xs, n);
    if (vec == NULL) {
        fprintf(stderr, "Failed to create vector.");
        return 1;
    }

    idx_t u, v;
    for (i = 0; i < m; ++i) {
        randinterval(n, &u, &v);
        val_t true_sum   = dense_sum(xs, u, v);
        val_t sparse_sum = vector_sum(vec, u, v);

        if (true_sum != sparse_sum) {
            fprintf(stderr, "Incorrect sum.\n");
            return 1;
        }
    }

    vector_free(vec);
    free(xs);

    return 0;
}
int is_a_solution(vector<int>& nums, int k, int n) {
    if (nums.size() == k && vector_sum(nums) == n)
        return true;
    else
        return false;
}
void WeightMatrix_iter::solve(std::map<unsigned int, std::vector<double> >& ret_result)
{
    ret_result.clear();
//     _prev_result.resize(_nrows);
//     _result.resize(_nrows);
    _result_parallel.resize(_nrows);
    for(size_t i=0; i< _nrows; i++){
// 	_prev_result[i].resize(_nClass, 0.0 );
// 	_result[i].resize(_nClass, 0.0 );
	_result_parallel[i].resize(_nClass, 0.0 );
	
    }
    printf("LabelProp labeled example %u\n", _mapped_trn_idx.size());
    reassign_label();
    
    size_t ncores=8;
    _maxIter=200;
    double max_diff;

    
    for (size_t iter=0; iter< _maxIter; iter++){
	max_diff = 0;
      
// 	for(size_t row = 0 ; row < _nrows ; row++){
// 	  
//     // 	if ((! _nzd_indicator[row]) || (_trn_indicator[row]))
// 	    if (! _nzd_indicator[row])
// 		continue;
// 	    
// 	    for(size_t jj=0; jj < _Wnorm[row].size(); jj++){
// 		unsigned int col = _Wnorm[row][jj].j;
// 		double val = _Wnorm[row][jj].v;
// 		
//     // 	    if ((! _nzd_indicator[col]) || (_trn_indicator[col]))
// 		if (! _nzd_indicator[col])
// 		    continue;
// 		
// 		for(int cc=0; cc<_nClass; cc++){
// 		    (_result[row][cc]) += (val * _prev_result[col][cc]);
// 		}
// 	    }
// 	}
	
	size_t start_row=0;
	std::vector< boost::thread* > threads;
	size_t chunksz = _nrows/ncores;
	if (_nrows> (ncores*chunksz))
	    ncores++;
	for(size_t ichunk=0; ichunk < ncores; ichunk++){
	    size_t end_row = start_row + chunksz;
	    if (end_row >=_nrows)
		end_row = _nrows;
	    
	    threads.push_back(new boost::thread(&WeightMatrix_iter::solve_partial, this, start_row, end_row));
	    
	    start_row = end_row;
	}
	
// 	printf("Sync all threads \n");
	for (size_t ti=0; ti<threads.size(); ti++) 
	  (threads[ti])->join();
// 	printf("all threads done\n");
	
// 	double debug_diff=0;
// 	for(size_t row = 0 ; row < _nrows ; row++){
// 	    for(int cc=0; cc<_nClass; cc++){
// 		debug_diff += fabs(_result[row][cc] - _result_parallel[row][cc]);
// 	    }
// 	}
// 	if (debug_diff>0)
// 	    printf("Difference between serial and parallel = %f\n",debug_diff);
	
	
	
	
	
	for(size_t row = 0 ; row < _nrows ; row++){
// 	    normalize_row(_result[row]);
	    normalize_row(_result_parallel[row]);
	}
	
	
	for(size_t row = 0 ; row < _nrows ; row++){
	    if (_trn_indicator[row]){
	      continue;
	    }
	    
	    double diff=0;
	    for(int cc=0; cc<_nClass; cc++){
		diff = fabs(_prev_result[row][cc] - _result_parallel[row][cc]);
		max_diff = (max_diff>diff) ? max_diff: diff;
		
		_prev_result[row][cc] = _result_parallel[row][cc];
	    }
	}
	
	reassign_label();
	if (!(iter%10))
	  printf("max diff %.5f\n",max_diff);    
	if (max_diff<EPS)
	  break;
	
    }
    printf("max diff %.5f\n",max_diff);    
    
    for(size_t row = 0 ; row < _nrows ; row++){
	  
	if ((! _nzd_indicator[row]) || (_trn_indicator[row]))
	  continue;
	
	  
	
	if (!(vector_sum(_result_parallel[row])>0))
	    _result_parallel[row].assign(_nClass, (double)(1.0/_nClass));

	ret_result.insert(std::make_pair(row, _result_parallel[row]));
    }
    
}
Beispiel #23
0
int main()
{
    MPI_Init(NULL, NULL);
    int comm_sz;
    int my_rank;
    int *local_vector;
    int local_size;
    int sum;
    MPI_Status status;
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    if (my_rank == 0)
    {
        int i;
        int *sums = (int*) malloc((comm_sz-1) * sizeof(int));

        // Read in vector
        int *vector, size=0;
        vector = (int*) malloc(MAX_SIZE * sizeof(int));
        populate(vector, &size);
        local_size = size / comm_sz;

        // Start timer
        double start, finish;
        MPI_Barrier(MPI_COMM_WORLD);
        start = MPI_Wtime();

        // Broadcast size
        MPI_Bcast(&local_size, 1, MPI_INT, 0, MPI_COMM_WORLD);

        // Distribute array
        for (i = 1; i < comm_sz; i++)
            MPI_Send(vector+i*local_size, local_size, MPI_INT, i, TAG, MPI_COMM_WORLD);

        // Sum local vector
        sum = vector_sum(vector, local_size);

        // Read sums
        for (i = 1; i < comm_sz; i++)
            MPI_Recv(sums+(i-1), 1, MPI_INT, MPI_ANY_SOURCE, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

        // Sum sums
        sum += vector_sum(sums, comm_sz-1);

        // Stop timer
        MPI_Barrier(MPI_COMM_WORLD);
        finish = MPI_Wtime();

        printf("Sum: %d\nTime: %fs\n", sum, finish-start);

        free(sums);
        free(vector);
    }
    else
    {
        // Wait for timer
        MPI_Barrier(MPI_COMM_WORLD);

        // Get local_size
        MPI_Bcast(&local_size, 1, MPI_INT, 0, MPI_COMM_WORLD);

        // Read into local array
        local_vector = (int*) malloc(local_size * sizeof(int));
        MPI_Recv(local_vector, local_size, MPI_INT, 0, TAG, MPI_COMM_WORLD, &status);

        // Sum local array
        sum = vector_sum(local_vector, local_size);

        // Send sum
        MPI_Send(&sum, 1, MPI_INT, 0, TAG, MPI_COMM_WORLD);

        MPI_Barrier(MPI_COMM_WORLD);

        free(local_vector);
    }

    MPI_Finalize();
}
Beispiel #24
0
int Dormand_Prince_5_4(int n, void (*f)(double,double *,double *,double *,double *,double *,double *), 
                       double *p, double *fld, double *ext, double *extev, 
                       double *y, double x0, double h, double *yout, double *err,
                       double *k1, double *k2, double *k3, double *k4, double *k5, double *k6, double *k7, 
                       double *t1, double *t2, double *t3, double *t4, double *t5, double *t6, double *t7, double *t8, double *t9, double *t10, 
                       double *t11, double *t12)
{
  double h2, h3, h4, h5;

  if (n == 0)
    {
      return 0;
    }

  h2 = 0.2 * h;
  h3 = 0.3 * h;
  h4 = 0.8 * h;
  h5 = 0.888888888889 * h;

  //printf("c: h = %g\n", h);
  //printf("c: y[0] = %g\n", y[0]);
  (*f)(x0, p, fld, ext, extev, y, k1);
  //  printf("c: k1[0] = %g\n", k1[0]);

  vector_scale(n, 1.0, k1, t1); 
  //  printf("c: t1[0] = %g\n", t1[0]);
  vector_scale(n, h/5.0, t1, t2); 
  vector_sum(n, y, t2, t3);
  //  printf("c: t2[0] = %g\n", t2[0]);
  //  printf("c: k2 = %p\n", k2);
  //  printf("c: k2[0] = %g\n", k2[0]);
  (*f)(x0+h2, p, fld, ext, extev, t3, k2);
  //  printf("c: k2[0] = %g\n", k2[0]);
  // printf("c: k2[0] = %g\n", k2[0]);
  
  vector_scale(n, 3.0, k1, t1); 
  vector_scale(n, 9.0, k2, t2); 
  vector_sum(n, t1, t2, t3); vector_scale(n, h/40.0, t3, t4); vector_sum(n, y, t4, t5); 
  (*f)(x0+h3, p, fld, ext, extev, t5, k3);
  //  printf("c: k3[0] = %g\n", k3[0]);

  vector_scale(n, 44.0, k1, t1); 
  vector_scale(n, -168.0, k2, t2); 
  vector_scale(n, 160.0, k3, t3); 
  //  printf("c: t1[0] = %g\n", t1[0]);
  //  printf("c: t2[0] = %g\n", t2[0]);
  //  printf("c: t3[0] = %g\n", t3[0]);
  vector_sum(n, t1, t2, t4); vector_sum(n, t3, t4, t5); 
  vector_scale(n, h/45.0, t5, t6); vector_sum(n, y, t6, t7); 
  //  printf("c: t4[0] = %g\n", t4[0]);
  //  printf("c: t5[0] = %g\n", t5[0]);
  //  printf("c: t6[0] = %g\n", t6[0]);
  //  printf("c: t7[0] = %g\n", t7[0]);
  (*f)(x0+h4, p, fld, ext, extev, t7, k4);
  //  printf("c: k4 = %p\n", k4);
  //  printf("c: k4[0] = %g\n", k4[0]);
  
  vector_scale(n, 19372.0, k1, t1); 
  vector_scale(n, -76080.0, k2, t2); 
  vector_scale(n, 64448.0, k3, t3); 
  vector_scale(n, -1908.0, k4, t4); 
  vector_sum(n, t1, t2, t5); vector_sum(n, t3, t4, t6); vector_sum(n, t5, t6, t7); 
  vector_scale(n, h/6561.0, t7, t8);  
  //  printf("c: t8[0] = %g\n", t8[0]);
  vector_sum(n, y, t8, t9); 
  //  printf("c: t9[0] = %g\n", t9[0]);
  (*f)(x0+h5, p, fld, ext, extev, t9, k5);
  //  printf("c: k5[0] = %g\n", k5[0]);

  vector_scale(n, 477901.0, k1, t1); 
  vector_scale(n, -1806240.0, k2, t2); 
  vector_scale(n, 1495424.0, k3, t3); 
  vector_scale(n, 46746.0, k4, t4); 
  vector_scale(n, -45927.0, k5, t5); 
  vector_sum(n, t1, t2, t6); vector_sum(n, t3, t4, t7); vector_sum(n, t5, t6, t8); vector_sum(n, t7, t8, t9); 
  vector_scale(n, h/167904.0, t9, t10);  
  vector_sum(n, y, t10, t11); 
  (*f)(x0+h, p, fld, ext, extev, t11, k6 );
  //  printf("c: k6[0] = %g\n", k6[0]);

  vector_scale(n, 12985.0, k1, t1); 
  vector_scale(n, 64000.0, k3, t3); 
  vector_scale(n, 92750.0, k4, t4); 
  vector_scale(n, -45927.0, k5, t5); 
  vector_scale(n, 18656.0, k6, t6); 
  vector_sum(n, t1, t3, t7); vector_sum(n, t4, t5, t8); vector_sum(n, t6, t7, t9); vector_sum(n, t8, t9, t10); 
  vector_scale(n, h/142464.0, t10, t11);  
  vector_sum(n, y, t11, t12); 
  (*f)(x0+h, p, fld, ext, extev, t12, k7 );
  //  printf("c: k7[0] = %g\n", k7[0]);

  vector_sum(n, y, t11, yout); 
  //  printf("c: yout[0] = %g\n", yout[0]);

  vector_scale(n, 26341.0, k1, t1); 
  vector_scale(n, -90880.0, k3, t3); 
  vector_scale(n, 790230.0, k4, t4); 
  vector_scale(n, -1086939.0, k5, t5); 
  vector_scale(n, 895488.0, k6, t6); 
  vector_scale(n, -534240.0, k7, t7); 
  vector_sum(n, t1, t3, t8); vector_sum(n, t4, t5, t9); vector_sum(n, t6, t7, t10); vector_sum(n, t8, t9, t11); 
  vector_sum(n, t10, t11, t12); 
  vector_scale(n, h/21369600.0, t12, err);  

  //printf("c: xn = %g err[0] = %g\n", x0+h, err[0]);
  
  return 0;
}
Vector vector_average(Vector* data, int len) {
	Vector sum = vector_sum(data, len);
	return vector_scale(sum, 1.0 / (double) len);
}
Beispiel #26
0
/* main: application entry point.
 * @argc: the number of commandline arguments.
 * @argv: the commandline argument string array.
 */
int main (int argc, char **argv) {
  /* declare required variables. */
  struct vector *x, *y, *z, *u;
  struct matrix *V, *R, *C;
  double theta;
  char *smean, *svar, *label;
  unsigned long n;
  int i;

  /* initialize the random number generator. */
  rand_init (time (NULL));

  /* parse the command-line arguments. */
  if (!opts_init (argc, argv)) {
    /* output an error message and exit. */
    ferror ("failed to parse arguments");
    fprintf (stdout, HELP);
    return 1;
  }

  /* see if we should display the help message. */
  if (opts_geti (OPTS_S_HELP)) {
    /* print the help message and quit. */
    fprintf (stdout, HELP);
    return 0;
  }

  /* get the number of points to produce. */
  n = opts_geti (OPTS_S_COUNT);

  /* ensure the point count is valid. */
  if (!n) {
    /* output an error message and exit. */
    ferror ("invalid point count (%lu)", n);
    fprintf (stdout, HELP);
    return 1;
  }

  /* get the points label. */
  label = opts_gets (OPTS_S_LABEL);

  /* ensure the points label is valid. */
  if (!label) {
    /* output an error message and exit. */
    ferror ("invalid label '%s'", label);
    fprintf (stdout, HELP);
    return 1;
  }

  /* allocate the math structures. */
  x = vector_new (2);
  y = vector_new (2);
  z = vector_new (2);
  u = vector_new (2);
  V = matrix_new (2, 2);
  R = matrix_new (2, 2);
  C = matrix_new (2, 2);

  /* ensure we allocated the math structures. */
  if (!x || !y || !z || !u || !V || !R || !C) {
    /* output an error message and exit. */
    ferror ("failed to allocate math structures");
    return 1;
  }

  /* get the mean string. */
  smean = opts_gets (OPTS_S_MEAN);

  /* did we get a mean string? */
  if (smean) {
    /* try to parse the string. */
    if (sscanf (smean, "(%lf,%lf)", &u->d[0], &u->d[1]) != 2) {
      /* output an error message and exit. */
      ferror ("failed to parse mean string '%s'", smean);
      fprintf (stdout, HELP);
      return 1;
    }
  }
  else {
    /* initialize to the origin. */
    u->d[0] = u->d[1] = 0.0;
  }

  /* get the variance string. */
  svar = opts_gets (OPTS_S_VAR);

  /* did we get a variance string? */
  if (svar) {
    /* try to parse the string. */
    if (sscanf (svar, "(%lf,%lf)", &V->d[0][0], &V->d[1][1]) != 2) {
      /* output an error message and exit. */
      ferror ("failed to parse variance string '%s'", svar);
      fprintf (stdout, HELP);
      return 1;
    }
  }
  else {
    /* initialize to unit variances. */
    V->d[0][0] = V->d[1][1] = 1.0;
  }

  /* get the rotation value. */
  theta = opts_getf (OPTS_S_ROT) / 180.0 * M_PI;

  /* build the rotation matrix. */
  R->d[0][0] = cos (theta);
  R->d[0][1] = -sin (theta);
  R->d[1][0] = sin (theta);
  R->d[1][1] = cos (theta);

  /* calculate the covariance matrix. */
  if (!matrix_matrix_mul (1.0, R, V, C)) {
    /* output an error message and exit. */
    ferror ("failed to calculate covariance matrix");
    return 1;
  }

  /* see if we should produce a header. */
  if (opts_geti (OPTS_S_HEADER)) {
    /* yep. print one. */
    fprintf (stdout,
      "Obs ID (Primary)\tObs ID (Obs. Sec. ID:1)\tM1.t[2]\tM1.t[1]\n");
  }

  /* loop a set number of times. */
  for (i = 0; i < n; i++) {
    /* calculate the two values. */
    x->d[0] = randnormal ();
    x->d[1] = randnormal ();

    /* scale the values. */
    if (!matrix_vector_mul (1.0, C, x, y)) {
      /* output an error message and exit. */
      ferror ("failed to scale random variate %d", i + 1);
      return 1;
    }

    /* translate the values. */
    if (!vector_sum (1.0, y, 1.0, u, z)) {
      /* output an error message and exit. */
      ferror ("failed to translate random variate %d", i + 1);
      return 1;
    }

    /* print the values. */
    fprintf (stdout, "%d\t%s\t%lf\t%lf\n", i + 1, label, z->d[0], z->d[1]);
  }

  /* free the math structures. */
  vector_free (x);
  vector_free (y);
  vector_free (z);
  vector_free (u);
  matrix_free (V);
  matrix_free (R);
  matrix_free (C);

  /* return success. */
  return 0;
}
Beispiel #27
0
int Bogacki_Shampine_3_2(int n, void (*f)(double,double *,double *,double *,double *,double *,double *), 
                         double *p, double *fld, double *ext, double *extev, 
                         double *y, double x0, double h, double *yout, double *err,
                         double *k1, double *k2, double *k3, double *k4, 
                         double *t1, double *t2, double *t3, double *t4, double *t5, double *t6, double *t7)
{
  double h2, h3; 

  if (n == 0)
    {
      return 0;
    }

  h2 = 0.5 * h;
  h3 = 0.75 * h;

  //printf("c: h = %g\n", h);
  //printf("c: y[0] = %g\n", y[0]);
  (*f)(x0, p, fld, ext, extev, y, k1);
  //  printf("c: k1[0] = %g\n", k1[0]);
  
  vector_scale(n, 1.0, k1, t1); 
  //  printf("c: t1[0] = %g\n", t1[0]);
  vector_scale(n, h/2.0, t1, t2); 
  vector_sum(n, y, t2, t3);
  //  printf("c: t2[0] = %g\n", t2[0]);
  //  printf("c: k2 = %p\n", k2);
  //  printf("c: k2[0] = %g\n", k2[0]);
  (*f)(x0+h2, p, fld, ext, extev, t3, k2);
  //  printf("c: k2[0] = %g\n", k2[0]);
  // printf("c: k2[0] = %g\n", k2[0]);
  
  vector_scale(n, 3.0, k2, t2); 
  vector_scale(n, h/4.0, t2, t3); vector_sum(n, y, t3, t4); 
  (*f)(x0+h3, p, fld, ext, extev, t4, k3);
  //  printf("c: k3[0] = %g\n", k3[0]);

  vector_scale(n, 2.0, k1, t1); 
  vector_scale(n, 3.0, k2, t2); 
  vector_scale(n, 4.0, k3, t3); 
  //  printf("c: t1[0] = %g\n", t1[0]);
  //  printf("c: t2[0] = %g\n", t2[0]);
  //  printf("c: t3[0] = %g\n", t3[0]);
  vector_sum(n, t1, t2, t4); vector_sum(n, t3, t4, t5); 
  vector_scale(n, h/9.0, t5, t6); vector_sum(n, y, t6, t7); 
  //  printf("c: t4[0] = %g\n", t4[0]);
  //  printf("c: t5[0] = %g\n", t5[0]);
  //  printf("c: t6[0] = %g\n", t6[0]);
  //  printf("c: t7[0] = %g\n", t7[0]);
  (*f)(x0+h, p, fld, ext, extev, t7, k4);
  //  printf("c: k4 = %p\n", k4);
  //  printf("c: k4[0] = %g\n", k4[0]);
  
  vector_sum(n, y, t6, yout); 
  //  printf("c: yout[0] = %g\n", yout[0]);

  vector_scale(n, -5.0, k1, t1); 
  vector_scale(n, 6.0, k2, t2); 
  vector_scale(n, 8.0, k3, t3); 
  vector_scale(n, -9.0, k4, t4); 

  vector_sum(n, t1, t2, t5); vector_sum(n, t3, t4, t6); 
  vector_sum(n, t5, t6, t7); 
  vector_scale(n, h/72.0, t7, err);  

  //printf("c: xn = %g err[0] = %g\n", x0+h, err[0]);
  
  return 0;
}