Exemplo n.º 1
0
/*******************************************************************************************
 * NAME :             compute_triangle_sides()
 *
 * DESCRIPTION :      Computes and sorts the lengths of each side of the triangle.
 *
 * INPUTS : 
 *      GLOBALS :
 *          struct    triangle_points[]  reads coordinate pairs for array
 *
 * OUTPUTS :
 *      GLOBALS :
 *          struct    triangle_sides[]   writes side lengths in global array
 */
void compute_triangle_sides(void) {
  int i, j;

  /* ensure a null pointer is not passed to compute_distance function */
  ASSERT_SIDE_PTRS();

  triangle_sides[0] = compute_distance(&triangle_points[0], &triangle_points[1]);
  triangle_sides[1] = compute_distance(&triangle_points[0], &triangle_points[2]);
  triangle_sides[2] = compute_distance(&triangle_points[2], &triangle_points[1]);

  /* all lengths must have positive magnitude */
  ASSERT_MAGNITUDE();

  /* Ascending order sort by length */
  for (i = 0; i < 2; i++) {
    for (j = i + 1; j < 3; j++) {
      if (triangle_sides[j] < triangle_sides[i]) {
        swap_triangle_sides(&triangle_sides[j], &triangle_sides[i]);
      }
    }
  }
  
  /* swaps must preseve lengths' magnitude */
  ASSERT_MAGNITUDE();

  return;
}
Exemplo n.º 2
0
static int compute_tour_length(int k) {/*{{{*/
	int i;

	ant[k].tour_length = 0;
	for (i = 0; i < N-1; i++) {
		ant[k].tour_length += compute_distance(ant[k].tour[i], ant[k].tour[i+1]);
	}
	ant[k].tour_length += compute_distance(ant[k].tour[i], ant[k].tour[0]);

}/*}}}*/
Exemplo n.º 3
0
// Find an island entry
struct island_data *closest_island(int x, int y) {
	struct island_data *isle, *best = NULL;
	int b = USE_SIZE;

	for (isle = island_list; isle; isle = isle->next)
		if (compute_distance(X_COORD(isle->loc), Y_COORD(isle->loc), x, y) < b) {
			best = isle;
			b = compute_distance(X_COORD(isle->loc), Y_COORD(isle->loc), x, y);
		}

	return best;
}
Exemplo n.º 4
0
// find centre closest to a given point
void closest_to_point(data_type p, centre_type *cntrs, uint *cntr_idxs , uint k, uint *idx)
{
    coord_type min_dist;
    uint min_idx = 0;
    compute_distance(conv_short_to_long(cntrs[cntr_idxs[0]].position_short), p, &min_dist);

    for (uint i=1; i<k; i++) {
        coord_type tmp_dist;
        compute_distance(conv_short_to_long(cntrs[cntr_idxs[i]].position_short), p, &tmp_dist);
        if (tmp_dist < min_dist) {
            min_dist = tmp_dist;
            min_idx = i;
        }
    }
    *idx = min_idx;
}
Exemplo n.º 5
0
void Orthographic::render_scene(const World& w) 
{
	RGBColor	L;
	ViewPlane	vp(w.vp);
	Ray	ray;
	int depth = 0;
	Point2D pp;	// sample point on a pixel
	int n = (int)sqrt((float)vp.num_samples);

	compute_direction();
	compute_distance();

	ray.d = dir;

	for (int r = 0; r < vp.vres; r++) // up
		for (int c = 0; c < vp.hres; c++) {	// across
			L = black;

			for (int p = 0; p < n; p++)	// up pixel
				for (int q = 0; q < n; q++) {	// across pixel
					pp.x = vp.s * (c - 0.5 * vp.hres + (q + 0.5) / n);
					pp.y = vp.s * (r - 0.5 * vp.vres + (p + 0.5) / n);
					ray.o = Point3D(pp.x, pp.y, 0);
					L += w.tracer_ptr->trace_ray(ray, depth);
				}

				L /= vp.num_samples;
				//L *= exposure_time;
				w.display_pixel(r, c, L);
		}
}
Exemplo n.º 6
0
static void compute_choice_information(void) {/*{{{*/
	int i, j;

	for (i = 0; i < N; i++) {
		for (j = i; j < N; j++) {
			choice_info[i][j] = choice_info[j][i] = 
					pow(pheromone[i][j], ALPHA) * pow(1.0/compute_distance(i, j), BETA);
		}
	}
}/*}}}*/
Exemplo n.º 7
0
int main()
{
    //~ typedef boost::ratio<8, BOOST_INTMAX_C(0x7FFFFFFFD)> R1;
    //~ typedef boost::ratio<3, BOOST_INTMAX_C(0x7FFFFFFFD)> R2;
    typedef User1::quantity<boost::ratio_subtract<boost::ratio<0>, boost::ratio<1> >::type,
                             boost::ratio_subtract<boost::ratio<1>, boost::ratio<0> >::type > RR;
    //~ typedef boost::ratio_subtract<R1, R2>::type RS;
    //~ std::cout << RS::num << '/' << RS::den << '\n';


    std::cout << "*************\n";
    std::cout << "* testUser1 *\n";
    std::cout << "*************\n";
    User1::Distance d(( User1::mile(110) ));
    boost_ex::chrono::hours h((2));
    User1::Time t(( h ));
    //~ boost_ex::chrono::seconds sss=boost_ex::chrono::duration_cast<boost_ex::chrono::seconds>(h);
    //~ User1::seconds sss((120));
    //~ User1::Time t(( sss ));

    //typedef User1::quantity<boost::ratio_subtract<User1::Distance::time_dim, User1::Time::time_dim >::type,
    //                        boost::ratio_subtract<User1::Distance::distance_dim, User1::Time::distance_dim >::type > R;
    RR r=d / t;
    //r.set(d.get() / t.get());

    User1::Speed rc= r;
    (void)rc;
    User1::Speed s = d / t;
    std::cout << "Speed = " << s.get() << " meters/sec\n";
    User1::Acceleration a = User1::Distance( User1::foot(32.2) ) / User1::Time() / User1::Time();
    std::cout << "Acceleration = " << a.get() << " meters/sec^2\n";
    User1::Distance df = compute_distance(s, User1::Time( User1::seconds(0.5) ), a);
    std::cout << "Distance = " << df.get() << " meters\n";
    std::cout << "There are " << User1::mile::ratio::den << '/' << User1::mile::ratio::num << " miles/meter";
    User1::meter mt = 1;
    User1::mile mi = mt;
    std::cout << " which is approximately " << mi.count() << '\n';
    std::cout << "There are " << User1::mile::ratio::num << '/' << User1::mile::ratio::den << " meters/mile";
    mi = 1;
    mt = mi;
    std::cout << " which is approximately " << mt.count() << '\n';
    User1::attosecond as(1);
    User1::seconds sec = as;
    std::cout << "1 attosecond is " << sec.count() << " seconds\n";
    std::cout << "sec = as;  // compiles\n";
    sec = User1::seconds(1);
    as = sec;
    std::cout << "1 second is " << as.count() << " attoseconds\n";
    std::cout << "as = sec;  // compiles\n";
    std::cout << "\n";
  return 0;
}
Exemplo n.º 8
0
double error_centroid(Dataset* dataset, Centroid* centroid){
    double error = 0.0;
    size_t neighbouring_points_count = 0;
    for (size_t i = 0; i < dataset->size; i++) {
        if (dataset->points[i]->affiliation_id == centroid->id) {
            error += SQR(compute_distance(dataset->points[i]->position, centroid->center));
            neighbouring_points_count++;
        }
    }
    if (neighbouring_points_count) {
        return error/(double)neighbouring_points_count;
    }
    return FLOAT_MAX;
}
Exemplo n.º 9
0
void main() {
	char a[] = "efsdfdabcdefgaabcdefgaabcdefgaabcdefgasfabcdefgefsdfdabcdefgaabcdefgaabcdefgaabcdefgasfabcdefg";
	char b[] = "efsdfdabcdefgaabcdefgaaefsdfdabcdefgaabcdefgaabcdefgaabcdefgasfabcdabcdefggaabcdefgasfabcdefg";
	int len_a = strlen(a);
	int len_b = strlen(b);

	int **temp = (int**)malloc(sizeof(int*) * (len_a + 1));
	for (int i = 0; i < len_a + 1; i++) {
		temp[i] = (int*)malloc(sizeof(int) * (len_b + 1));
		memset(temp[i], 0, sizeof(int) * (len_b + 1));
	}
	int distance = compute_distance(a, len_a, b, len_b, temp);
	printf("%d\n", distance);
	system("pause");
}
Exemplo n.º 10
0
static void identify_and_mark_bonded_atoms(atom **atomlist, double natoms)
{
  atom *atomPt_i, *atomPt_j;
  double dist;
  int i,j;
  
  for(i=0; i<(natoms - 1); i++) {
    atomPt_i = atomlist[i];
    for(j=i+1; j<natoms; j++) {
      atomPt_j = atomlist[j];
      compute_distance(atomPt_i->pos,atomPt_j->pos,&dist);
      if(dist < (atomPt_i->vdwR + atomPt_j->vdwR) * COVBOND_FACTOR) {
	mark_atoms_as_bonded(atomPt_i,atomPt_j);
      }
    }
  }
}
Exemplo n.º 11
0
atom *get_closest_atom_to_point(atom **atomlist, double natoms, double *point)
{
  atom *bestatomPt;
  double dist, bestdist;
  int i;

  bestdist = HUGE_VAL;
  bestatomPt = NULL;
  for(i=0; i<natoms; i++) {
    compute_distance(atomlist[i]->pos,point,&dist);
    if(dist < bestdist) {
      bestdist = dist;
      bestatomPt = atomlist[i];
    }
  }
  return bestatomPt;
}
Exemplo n.º 12
0
/** Compute the neighbors of a given point which are in a given radius.
 *
 * Generates a mask with [0, 1] values to activate the inside of the 'radius' 
 * radius circle centered in (x, y).
 *
 * @param[out] neigh  The resulting mask array.
 * @param[in]  x      The abscissae of the radius center.
 * @param[in]  y      The ordinates of the radius center.
 * @param[in]  radius The neighbooring radius.
 * @param[in]  width  The width of the network.
 * @param[in]  height The height of the network.
 */
static void som_neighbourhood(float *neigh, int x, int y, float radius,
                              int width, int height){
    int i, j, k = 0;
    float distance;

    for(i = 0; i < height ; i++){
        for(j = 0; j < width ; j++){
            distance = compute_distance(i, y, j, x);
            if(distance <= radius){
                neigh[k] = 1 - distance / (float)radius;
            }
            else{
                neigh[k] = 0;
            }
            k++;
        }
    }
}
Exemplo n.º 13
0
Centroid* find_closest(Centroid** centroids, Datapoint* point){
    int id_winning_centroid = 0;
    double best_score = FLOAT_MAX;
    for (int centroid_id = 0; centroid_id < CLUSTER_COUNT; centroid_id++) {
        double distance = compute_distance(centroids[centroid_id]->center, point->position);
        double score = compute_sensitive_distance(centroids[centroid_id]->sensitivity, distance);
        if (score < best_score) {
            id_winning_centroid = centroid_id;
            best_score = score;
        }
    }
    point->affiliation_id = id_winning_centroid;
    for (size_t centroid_id = 0; centroid_id < CLUSTER_COUNT; centroid_id++) {
        if (centroids[centroid_id]->id == id_winning_centroid) {
            centroids[centroid_id]->sensitivity = 0.0;
        } else {
            centroids[centroid_id]->sensitivity += SENSITIVITY_GAIN;
        }
    }
    return centroids[id_winning_centroid];
}
Exemplo n.º 14
0
static void compute_nearest_neighbor_lists(void) {/*{{{*/

	int i, j;
	static int **dlinha = NULL;

	if (dlinha == NULL) {
		dlinha = malloc(sizeof(int)*N);
	}

	for (i = 0; i < N; i++) {
		for (j = 0; j < N; j++) {
			dlinha[j] = malloc(sizeof(int)*2);
			dlinha[j][0] = j;
			dlinha[j][1] = compute_distance(i, j);
		}
		qsort(dlinha, N, sizeof(int), ordena);
		for (j = 0; j < NN; j++) {
			nn_list[i][j] = dlinha[j][0];
		}
	}

}/*}}}*/
Exemplo n.º 15
0
vector <vector <double> > compute_distance_matrix_from_centroid (vector <vector <double> > distance_matrix, vector <GDB> inGDB, vector <CENTR_VECT> centroid) {

	size_t j = 0;
	size_t k = 0;

	do {

		do {

			distance_matrix.at(k).at(j) = compute_distance (centroid.at(j), inGDB.at(k));

			j++;

		} while (j < centroid.size());

		j = 0;

		k++;

	} while (k <  inGDB.size());

	return distance_matrix;
}
Exemplo n.º 16
0
int main(int argc, char **argv) {
  char filename[200], out_filename[200];
  int i;
  logdata_t logdata;

  if(argc < 2)
    carmen_die("Error: missing arguments\n"
      "Usage: %s [--classify] [--faces] filename\n", argv[0]);

  for (i = 1; i < argc-2; ++i) {
    if (!strcmp(argv[i], "--classify"))
      classify_points = 1;
    else if (!strcmp(argv[i], "--faces"))
      generate_faces = 1;
  }

  strcpy(filename, argv[argc-1]);
  strcpy(out_filename, filename);
  if (!strcmp(out_filename+strlen(out_filename)-4, ".rec"))
    strcpy(out_filename+strlen(out_filename)-3, "glv.gz");
  else if (!strcmp(out_filename + strlen(out_filename)-7, ".rec.gz"))
    strcpy(out_filename+strlen(out_filename)-6, "glv.gz");
  else if (!strcmp(out_filename + strlen(out_filename)-7, ".log.gz"))
    strcpy(out_filename + strlen(out_filename)-6, "glv.gz");
  else if (!strcmp(out_filename + strlen(out_filename)-4, ".log"))
    strcpy(out_filename + strlen(out_filename)-3, "glv.gz");
  else
    carmen_die("Error: input file must be a .rec .rec.gz"
      ".log or .log.gz file.\n");

  read_nsick_logfile(filename, &logdata);
  interpolate_laser_pos(&logdata);
  write_glv_output(&logdata, out_filename);
  compute_distance(&logdata);

  return 0;
}
Exemplo n.º 17
0
/**
* Convert terrain from one thing to another near other terrain.
* 
* @param int from Terrain to convert from.
* @param int to Terrain to convert to.
* @param int near Terrain it must be near.
* @param int dist Distance it must be within.
*/
void replace_near(int from, int to, int near, int dist) {
	int x, y, hor, ver, at, loc;
	int found;
	
	for (x = 0; x < USE_WIDTH; ++x) {
		for (y = 0; y < USE_HEIGHT; ++y) {
			at = MAP(x, y);
			
			if (grid[at].type == from) {
				found = 0;
				for (hor = -dist; hor <= dist && !found; ++hor) {
					for (ver = -dist; ver <= dist && !found; ++ver) {
						loc = shift(at, hor, ver);
						
						if (loc != -1 && grid[loc].type == near && compute_distance(X_COORD(at), Y_COORD(at), X_COORD(loc), Y_COORD(loc)) <= dist) {
							change_grid(at, to);
							found = 1;
						}
					}
				}
			}
		}
	}
}
// main clustering kernel
void lloyds (   node_pointer n,
                centre_index_type k,
                centre_type *centres_out)
{
    // register ports of this entity
    #pragma HLS interface port=n register
    #pragma HLS interface port=k register
    #pragma HLS interface port=return register
    #pragma HLS interface ap_memory register port=data_int_memory
    #pragma HLS interface ap_memory register port=centre_positions

    // init centre buffer
    init_centre_buffer_loop: for(centre_index_type i=0; i<=k; i++) {
        #pragma HLS pipeline II=1

        for (uint p=0; p<P;p++) {
            #pragma HLS unroll
            centre_buffer[i+K*p].count = 0;
            centre_buffer[i+K*p].sum_sq = 0;
            data_type_ext tmp;
            for (uint d=0; d<D; d++) {
                #pragma HLS unroll
                set_coord_type_vector_ext_item(&tmp.value,0,d);
            }
            centre_buffer[i+K*p].wgtCent = tmp;
        }

        if (i==k) {
            #pragma HLS occurrence cycle=2
            break;
        }
    }

    data_type u[P];
    #pragma HLS array_partition variable=u complete

    // iterate over all data points
    process_data_points_loop: for (node_pointer i=0; i<=n; i+=P) {

        data_fetch_loop: for (uint p=0; p<P; p++) {
            #pragma HLS pipeline II=1
            u[p] = data_int_memory[i+p];
        }

        centre_index_type final_centre_index[P];
        coord_type_ext sum_sq_out[P];

        // iterate over all centres
        minsearch_loop: for (centre_index_type ii=0; ii<=k; ii++) {
            #pragma HLS pipeline II=1

            par_loop: for (uint p=0; p<P; p++) {
                #pragma HLS unroll
                coord_type_ext min_dist[P];

                #pragma HLS array_partition variable=final_centre_index complete
                #pragma HLS array_partition variable=sum_sq_out complete
                #pragma HLS array_partition variable=min_dist complete

                // help the scheduler by declaring inter-iteration dependencies for these variables as false
                #pragma HLS dependence variable=u inter false
                #pragma HLS dependence variable=final_centre_index inter false
                #pragma HLS dependence variable=sum_sq_out inter false
                #pragma HLS dependence variable=min_dist inter false
                #pragma HLS dependence variable=centre_buffer inter false
                #pragma HLS dependence variable=centre_positions inter false

                if (ii==0) {
                    min_dist[p]=MAX_FIXED_POINT_VAL_EXT;
                }

                coord_type_ext tmp_dist;
                compute_distance(centre_positions[p*K+ii], u[p], &tmp_dist);

                // select the centre with the smallest distance to the data point
                if (tmp_dist<min_dist[p]) {
                    min_dist[p] = tmp_dist;
                    final_centre_index[p] = ii;
                    sum_sq_out[p] = tmp_dist;
                }

                //printf("%d: i=%d, %d, %d\n",p,i.VAL+p,final_centre_index[p].VAL,sum_sq_out[p].VAL);

                if (ii == k) {
                    // trigger at most every other cycle
                    #pragma HLS occurrence cycle=2
                    if (p==P-1) {
                        break;
                    }
                }
            }
        }

        // after minsearch loop: update centre buffer
        for (uint p=0; p<P; p++) {
            #pragma HLS unroll
            data_type_ext tmp_wgtCent;
            coord_type_ext tmp1, tmp2, tmp3, tmp4, tmp5, tmp6;
            uint tmp_idx = (final_centre_index[p]+K*p);
            // weighted centroid of this centre
            for (uint d=0; d<D; d++) {
                #pragma HLS unroll
                tmp1 = get_coord_type_vector_ext_item(centre_buffer[(tmp_idx)].wgtCent.value,d);
                //if (i+p<=n) {
                    tmp2 = (coord_type_ext)get_coord_type_vector_item(u[p].value,d);
                //} else {
                    //tmp2 = 0;
                //}
                set_coord_type_vector_ext_item(&tmp_wgtCent.value,Reg(tmp1)+Reg(tmp2),d);
            }
            centre_buffer[tmp_idx].wgtCent = tmp_wgtCent;

            // update number of points assigned to centre
            tmp4 =  centre_buffer[(tmp_idx)].count;
            //if (i+p<=n) {
                tmp3 =  1;
            //} else {
                //tmp3 =  0;
            //}
            centre_buffer[tmp_idx].count = Reg(tmp3) + Reg(tmp4);

            //if (i+p<=n) {
                tmp5 =  sum_sq_out[p];
            //} else {
                //tmp5 =  0;
            //}
            tmp6 =  centre_buffer[(tmp_idx)].sum_sq;
            centre_buffer[tmp_idx].sum_sq  = Reg(tmp5) + Reg(tmp6);
        }

        if (i>=n-P+1) {
        //if (i>=n) {
            break;
        }
    }


    // readout centres
    read_out_centres_loop: for(centre_index_type i=0; i<=k; i++) {
        #pragma HLS pipeline II=1

        coord_type_ext arr_count[P];
        coord_type_ext arr_sum_sq[P];
        coord_type_vector_ext arr_wgtCent[P];
        #pragma HLS array_partition variable=arr_count complete
        #pragma HLS array_partition variable=arr_sum_sq complete
        #pragma HLS array_partition variable=arr_wgtCent complete

        for (uint p=0; p<P; p++) {
            #pragma HLS unroll
            arr_count[p] = ((coord_type_ext)centre_buffer[i+K*p].count);
            arr_sum_sq[p] = (centre_buffer[i+K*p].sum_sq);
            arr_wgtCent[p] = (centre_buffer[i+K*p].wgtCent.value);
        }

        centres_out[i].count = tree_adder(arr_count,P);
        //printf("%d\n",centres_out[i].count.VAL);
        centres_out[i].sum_sq = tree_adder(arr_sum_sq,P);
        coord_type_vector_ext tmp_sum;
        for (uint d=0; d<D; d++) {
            #pragma HLS unroll
            coord_type_ext tmp_a[P];
            for (uint p=0; p<P; p++) {
                #pragma HLS unroll
                tmp_a[p] = get_coord_type_vector_ext_item(arr_wgtCent[p],d);
            }
            coord_type_ext tmp = tree_adder(tmp_a,P);
            set_coord_type_vector_ext_item(&tmp_sum,tmp,d);
        }
        centres_out[i].wgtCent.value = tmp_sum;

        if (i==k) {
            break;
        }
    }

}
Exemplo n.º 19
0
static std::pair<int,int> leave_one_out(KnnObject* o, int stop_threshold,
                                        int* selection_vector = 0,
                                        double* weight_vector = 0,
                                        std::vector<long>* indexes = 0) {
    int* selections = selection_vector;
    if (selections == 0) {
        selections = o->selection_vector;
    }

    double* weights = weight_vector;
    if (weights == 0) {
        weights = o->weight_vector;
    }

    assert(o->feature_vectors != 0);
    kNearestNeighbors<char*, ltstr, eqstr> knn(o->num_k);

    int total_correct = 0;
    int total_queries = 0;
    if (indexes == 0) {
        for (size_t i = 0; i < o->feature_vectors->size(); ++i/*, cur += o->num_features*/) {
            // We don't want to do the calculation if there is no
            // hope that kNN will return the correct answer (because
            // there aren't enough examples in the database).
            if (o->id_name_histogram[i] < int((o->num_k + 0.5) / 2)) {
                continue;
            }
            double* current_known;
            double* unknown = (*o->feature_vectors)[i];
            for (size_t j = 0; j < o->feature_vectors->size(); ++j) {
                current_known = (*o->feature_vectors)[j];
                if (i == j)
                    continue;
                double distance;
                compute_distance(o->distance_type, current_known, o->num_features,
                                 unknown, &distance, selections, weights);
                knn.add(o->id_names[j], distance);
            }
            knn.majority();
            if (strcmp(knn.answer[0].first, o->id_names[i]) == 0) {
                total_correct++;
            }
            knn.reset();
            total_queries++;
            if (total_queries - total_correct > stop_threshold)
                return std::make_pair(total_correct, total_queries);
        }
    } else {
        for (size_t i = 0; i < o->feature_vectors->size(); ++i) {
            if (o->id_name_histogram[i] < int((o->num_k + 0.5) / 2))
                continue;
            double* current_known;
            double* unknown = (*o->feature_vectors)[i];
            for (size_t j = 0; j < o->feature_vectors->size(); ++j) {
                current_known = (*o->feature_vectors)[j];
                if (i == j)
                    continue;
                double distance;
                if (o->distance_type == CITY_BLOCK) {
                    distance = city_block_distance_skip(current_known, unknown, selections, weights,
                                                        indexes->begin(), indexes->end());
                } else if (o->distance_type == FAST_EUCLIDEAN) {
                    distance = fast_euclidean_distance_skip(current_known, unknown, selections, weights,
                                                            indexes->begin(), indexes->end());
                } else {
                    distance = euclidean_distance_skip(current_known, unknown, selections, weights,
                                                       indexes->begin(), indexes->end());
                }

                knn.add(o->id_names[j], distance);
            }
            knn.majority();
            if (strcmp(knn.answer[0].first, o->id_names[i]) == 0) {
                total_correct++;
            }
            knn.reset();
            total_queries++;
            if (total_queries - total_correct > stop_threshold)
                return std::make_pair(total_correct, total_queries);
        }
    }
    return std::make_pair(total_correct, total_queries);
}
Exemplo n.º 20
0
void k_mean_cluster(UINT k,/*group num = n/100*/ 
					UINT n,/*total surface point num = crop_size_x*crop_size_y */
					UINT vec_dim, /*vec_dim = 3*light_num : R...RRRG...GGGB...BBB */
					const vector<ublas::vector<double>>& coordinates_array, /* ublas_vec:vec_dim; std::vec:n, indexed by 1d pixel coord */
					vector<boost::unordered_set<UINT>>& groups, //k groups
					vector<ublas::vector<double>>& centroid_vec) /* vec_dim * k */
{
	//a data structure contains which point belongs to each group
	//e.g.:point_set_table[pt_id] = set_id;
	vector<UINT> point_set_table(n, 0); 

	//set up set vec
	groups.clear();
	for(UINT i = 0; i<k; i++)
	{
		boost::unordered_set<UINT> a_set;
		groups.push_back(a_set);
	}

	//get first k points as centroid and add them to different sets
	for(UINT i = 0; i<k; i++)
	{
		centroid_vec.push_back(coordinates_array[i]);
		groups[i].insert(i);
		point_set_table[i] = i;
	}

	//for each of the left n-k points, compute the distance between itself and each group centroid
	//choose the group with smallest distance and add the point into the group
	for(UINT i = k; i<n; i++)
	{
		double min_distance = std::numeric_limits<double>::max();
		UINT group_id_with_min_distance = 0;
		for(UINT x = 0; x<k; x++)
		{
			double distance = compute_distance(coordinates_array[i], centroid_vec[x]);

			if(distance < min_distance)
			{
				min_distance = distance;
				group_id_with_min_distance = x;
			}
		}
		groups[group_id_with_min_distance].insert(i);
		point_set_table[i] = group_id_with_min_distance;
	}



	//while any ptr moves into other groups, we continue iteration
	//for each set, re-compute centroid
	//for each point of n point, calculate its distance to each new centroid
	//choose the set with smallest distance
	bool certain_point_moves = true;

	UINT iter_num = 0;

	while(certain_point_moves)
	{
		//recompoute centroid
		for(UINT i = 0; i<k; i++)
		{
			ublas::vector<double> centroid(vec_dim, 0);
			for(boost::unordered_set<UINT>::iterator it = groups[i].begin(); it!=groups[i].end(); ++it)
			{
				centroid += coordinates_array[*it];
			}
			centroid /= groups[i].size();
			centroid_vec[i] = centroid;
		}

		certain_point_moves = false;

		//for each point
		for(UINT i=0; i<n; i++)
		{
			double min_distance = std::numeric_limits<double>::max();
			UINT group_id_with_min_distance = 0;

			//see each set
			for(UINT x = 0; x<k; x++)
			{
				double distance = compute_distance(coordinates_array[i], centroid_vec[x]);
				if(distance < min_distance)
				{
					min_distance = distance;
					group_id_with_min_distance = x;
				}
			}

			//new home for point
			if(point_set_table[i] != group_id_with_min_distance)
			{
				certain_point_moves = true;
				groups[group_id_with_min_distance].insert(i);
				groups[point_set_table[i]].erase(i);
				point_set_table[i] = group_id_with_min_distance;
			}
		}

		iter_num++;

	}

	//recompoute centroid again
	for(UINT i = 0; i<k; i++)
	{
		ublas::vector<double> centroid(vec_dim, 0);
		for(boost::unordered_set<UINT>::iterator it = groups[i].begin(); it!=groups[i].end(); ++it)
		{
			centroid += coordinates_array[*it];
		}
		centroid /= groups[i].size();
		centroid_vec[i] = centroid;
	}

	//debug output
	cout << "\niteration num: " << iter_num << endl;
	for(UINT xxx=0; xxx<k; xxx++)
	{
		cout << "set#" << xxx << "\t" << groups[xxx].size() << endl;
		for(boost::unordered_set<UINT>::iterator it = groups[xxx].begin(); it!=groups[xxx].end(); ++it)
		{
			cout << *it << "\t";
		}
		cout << endl << "centroid: " << centroid_vec[xxx] << endl;
		cout << endl;
	}

}
Exemplo n.º 21
0
int _tmain(int argc, _TCHAR* argv[])
{
	//1.06	9.2		151		54.4	1.6
	//0.89	10.3	202		57.9	2.2
	//1.43	15.4	113		53		3.4
	//1.02	11.2	168		56		0.3
	//1.49	8.8		192		51.2	1
	//1.32	13.5	111		60		-2.2
	//1.22	12.2	175		67.6	2.2
	//1.1	9.2		245		57		3.3
	//1.34	13		168		60.4	7.2
	//1.12	12.4	197		53		2.7
	//0.75	7.5		173		51.5	6.5
	//1.13	10.9	178		62		3.7
	//1.15	12.7	199		53.7	6.4
	//1.09	12		96		49.8	1.4
	//0.96	7.6		164		62.2	-0.1
	//1.16	9.9		252		56		9.2
	//0.76	6.4		136		61.9	9
	//1.05	12.6	150		56.7	2.7
	//1.16	11.7	104		54		-2.1
	//1.2		11.8	148		59.9	3.5
	//1.04	8.6		204		61		3.5
	//1.07	9.3		174		54.3	5.9

	UINT n = 22;
	UINT k = 3;
	UINT vec_dim = 5;

	vector<ublas::vector<double>> coord_array;

	ifstream dataset_stream("dataset.txt");
	ublas::vector<double> tmp_vec(vec_dim);

	for(UINT i = 0; i < n; i++)
	{
		for(UINT j = 0; j < vec_dim; j++)
			dataset_stream >> tmp_vec(j);

		coord_array.push_back(tmp_vec);

		cout << tmp_vec << endl;
	}

	vector<ublas::vector<double>> the_centroid_vec;
	vector<boost::unordered_set<UINT>> the_groups;

	k_mean_cluster(k, n, vec_dim, coord_array, the_groups, the_centroid_vec);

	vector<UINT> representatives;

	for(UINT i = 0; i<k; i++) //for each group
	{
		//each group
		double closest_distance_to_centroid = std::numeric_limits<double>::max();
		UINT pixel_id_closest_distance_to_centroid = 0;
		for(boost::unordered_set<UINT>::iterator it = the_groups[i].begin(); it!=the_groups[i].end(); ++it)
		{
			double distance = compute_distance(coord_array[*it], the_centroid_vec[i]);
			if(distance < closest_distance_to_centroid)
			{
				closest_distance_to_centroid = distance;
				pixel_id_closest_distance_to_centroid = *it;
			}
		}
		representatives.push_back(pixel_id_closest_distance_to_centroid);
	}

	return 0;
}
Exemplo n.º 22
0
static double compute_ev_det_loglike(const Physics_t * physics,
                                     int num_sta, const Station_t * sta_list,
                                     const Event_t * event,
                                     const Detection_t * det)
/* returns the log likelihood that the event generated that given detection */
{
  /* first compute basic event-station attributes like distance,
   * travel time, azimuth, and azimuth difference
   */
  int staidx = det->staidx;
  
  const Station_t * sta = sta_list + staidx;
  
  double dist = compute_distance(sta->lon, sta->lat, event->lon, event->lat);

  double ttime = compute_travel_time(dist);
  
  double sta_to_ev_az = compute_azimuth(sta->lon, sta->lat, event->lon,
                                        event->lat);
  
  /* the azimuth difference of observed vs. theoretical */
  double degdiff = compute_degdiff(sta_to_ev_az, det->azimuth);
  
  double loglike = 0;

  /* detection probability */
  
  double detprob = logistic(physics->mu_d0[staidx]
                            + physics->mu_d1[staidx] * event->mag
                            + physics->mu_d2[staidx] * dist);
  

  loglike += log(detprob);

  /* detection time */

  loglike += laplace_logpdf(det->time,
                            event->time + ttime + physics->mu_t[staidx],
                            physics->theta_t[staidx]);
  


  /* detection azimuth */
  
  loglike += laplace_logpdf(degdiff, physics->mu_z[staidx],
                            physics->theta_z[staidx]);
  
  
  /* detection slowness */

  loglike += laplace_logpdf(det->slowness,
                            compute_slowness(dist) + physics->mu_s[staidx],
                            physics->theta_s[staidx]);

  /* detection amplitude */

  loglike += norm_logpdf(det->logamp,
                         physics->mu_a0[staidx]
                         + physics->mu_a1[staidx] * event->mag
                         + physics->mu_a2[staidx] * dist,
                         physics->sigma_a[staidx]);
  
  return loglike;
}
void main_loop(const char** argv)
    {
    //  Process command line arguments.
    map<string, string> params;
    process_cmd_line(argv, params);
    bool verbose = get_bool_param(params, "verbose");

    //  Load feature files for templates.
    //  Get template label from matrix name.
    vector<string> templateLabelList;
    vector<matrix<double> > templateMatList;
    ifstream templateStrm(
        get_required_string_param(params, "template_file").c_str());
    while (templateStrm.peek() != EOF)
        {
        templateMatList.push_back(matrix<double>());
        string labelStr = read_float_matrix(templateStrm,
            templateMatList.back());
        templateLabelList.push_back(labelStr);
        }
    templateStrm.close();
    if (templateMatList.empty())
        throw runtime_error("No templates supplied.");

    //  Load correct label for each feature file, if present.
    vector<string> featLabelList;
    string labelFile = get_string_param(params, "feat_label_list");
    if (!labelFile.empty())
        read_string_list(labelFile, featLabelList);

    //  The main loop.
    ifstream featStrm(
        get_required_string_param(params, "feat_file").c_str());
    matrix<double> feats;
    unsigned templCnt = templateLabelList.size();
    unsigned uttCnt = 0;
    unsigned correctCnt = 0;
    while (featStrm.peek() != EOF)
        {
        int uttIdx = uttCnt++;
        string idStr = read_float_matrix(featStrm, feats);

        //  Find closest template.
        int bestTempl = -1;
        double bestScore = DBL_MAX;
        for (unsigned templIdx = 0; templIdx < templCnt; ++templIdx)
            {
            if (feats.size2() != templateMatList[templIdx].size2())
                throw runtime_error("Mismatch in test/template feature dim.");
            double curScore = compute_distance(feats,
                templateMatList[templIdx]);
            if (verbose)
                cout << format("  %s: %.3f") % templateLabelList[templIdx] %
                    curScore << endl;
            if (curScore < bestScore)
                bestScore = curScore, bestTempl = templIdx;
            }
        if (bestTempl < 0)
            throw runtime_error("No alignments found in DTW.");

        string hypLabel = (bestTempl >= 0) ? templateLabelList[bestTempl] : "";
        if (!featLabelList.empty())
            {
            //  If have reference labels, print ref and hyp classes.
            if (uttIdx >= (int) featLabelList.size())
                throw runtime_error("Mismatch in number of utterances "
                    "and labels.");
            string refLabel = featLabelList[uttIdx];
            cout << format("Reference: %s, Hyp: %s, Correct: %d") %
                refLabel % hypLabel % (hypLabel == refLabel) << endl;
            if (hypLabel == refLabel)
                ++correctCnt;
            }
        else
            //  If don't have reference labels, just print hyp class.
            cout << hypLabel << " (" << idStr << ")" << endl;
        }
    featStrm.close();
    if (!featLabelList.empty())
        {
        //  If have reference labels, print accuracy.
        unsigned errCnt = uttCnt - correctCnt;
        cout << format("Accuracy: %.2f%% (%d/%d), Error rate: %.2f%% (%d/%d)")
            % (100.0 * correctCnt / uttCnt) % correctCnt % uttCnt %
            (100.0 * errCnt / uttCnt) % errCnt % uttCnt << endl;
        }
    }
Exemplo n.º 24
0
int main ( int argc, char ** argv ) 
{
    /* General variables */
    int hwidth, rank, size, err;

    int i, j, k,it;
    char *winner_name;
    int impl_classes[NB_OF_SIZES][NB_OF_IMPL];
    int winners[NB_OF_SIZES][2];
    double t_start, dmax, distance[NB_OF_SIZES], relation[NB_OF_SIZES], elapsed_time[14], g_elapsed_time[NB_OF_SIZES][14];

    /* Definition of the 2-D vector */
    int dims[3], neighbors[6];
    double ***data, ****data2;
    ADCL_Vmap vmap; 
    ADCL_Vector vec;

    /* Variables for the process topology information */
    int cdims[]={0,0,0};
    int periods[]={0,0,0};
    MPI_Comm cart_comm;
    ADCL_Topology topo;
    ADCL_Request request;

    /* Initiate the MPI environment */
    MPI_Init ( &argc, &argv );
    MPI_Comm_rank ( MPI_COMM_WORLD, &rank );
    MPI_Comm_size ( MPI_COMM_WORLD, &size );

    /* Describe the neighborhood relations */
    MPI_Dims_create ( size, 3, cdims );
    MPI_Cart_create ( MPI_COMM_WORLD, 3, cdims, periods, 0, &cart_comm);
    MPI_Cart_shift ( cart_comm, 0, 1, &(neighbors[0]), &(neighbors[1]));
    MPI_Cart_shift ( cart_comm, 1, 1, &(neighbors[2]), &(neighbors[3]));
    MPI_Cart_shift ( cart_comm, 2, 1, &(neighbors[4]), &(neighbors[5]));


    /* Initiate the ADCL library and register a topology object with ADCL */
    ADCL_Init ();
    ADCL_Topology_create ( cart_comm, &topo );

    /**********************************************************************/
    /* hwidth=1, nc=0 */
    hwidth=1;
    for (i=0; i<NB_OF_SIZES; i++) {
        dims[0] = ProblemSizes[i][0] + 2*hwidth;
        dims[1] = ProblemSizes[i][1] + 2*hwidth;
        dims[2] = ProblemSizes[i][2] + 2*hwidth;

        if(rank == 0) {
            printf("Explored Problem Size %dX%dX%d \n", ProblemSizes[i][0],ProblemSizes[i][1], ProblemSizes[i][2] );
        }
        err = ADCL_Vmap_halo_allocate ( hwidth, &vmap );
        if ( ADCL_SUCCESS != err) goto exit;
        err = ADCL_Vector_allocate_generic ( 3,  dims, 0, vmap, MPI_DOUBLE, &data, &vec );
        if ( ADCL_SUCCESS != err) goto exit;
        ADCL_Request_create ( vec, topo, ADCL_FNCTSET_NEIGHBORHOOD, &request );

        /* Evaluate implementation 1 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_aao_IsendIrecv( request );
        }
        elapsed_time[0] = MPI_Wtime()-t_start;

        /* Evaluate implementation 2 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_aao_SendIrecv( request );
        }
        elapsed_time[1] = MPI_Wtime()-t_start;

        /* Evaluate implementation 3 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_aao_IsendIrecv_pack( request );
        }
        elapsed_time[2] = MPI_Wtime()-t_start;

        /* Evaluate implementation 4 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_aao_SendIrecv_pack( request );
        }
        elapsed_time[3] = MPI_Wtime()-t_start;

        /* Evaluate implementation 5 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_IsendIrecv( request );
        }
        elapsed_time[4] = MPI_Wtime()-t_start;

        /* Evaluate implementation 6 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_IsendIrecv_pack( request );
        }
        elapsed_time[5] = MPI_Wtime()-t_start;

       /* Evaluate implementation 7 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_SendIrecv( request );
        }
        elapsed_time[6] = MPI_Wtime()-t_start;

        /* Evaluate implementation 8 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_SendIrecv_pack( request );
        }
        elapsed_time[7] = MPI_Wtime()-t_start;

        /* Evaluate implementation 9 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_Sendrecv( request );
        }
        elapsed_time[8] = MPI_Wtime()-t_start;

        /* Evaluate implementation 10 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_Send_Recv( request );
        }
        elapsed_time[9] = MPI_Wtime()-t_start;

        /* Evaluate implementation 11 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_Sendrecv_pack( request );
        }
        elapsed_time[10] = MPI_Wtime()-t_start;

        /* Evaluate implementation 12 */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_change_sb_pair_Send_Recv_pack( request );
        }
        elapsed_time[11] = MPI_Wtime()-t_start;

        /* Evaluate ADCL B.F amd P.H. */
        /* So far, ADCL will behace according to the config.adcl file */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_Request_start( request );
        }
        elapsed_time[12] = MPI_Wtime()-t_start;
        /* Get winning implementation name */
        ADCL_Request_get_curr_function ( request, &winner_name, NULL, NULL, NULL, NULL);
        /* Get winning implementation number */
        winners[i][0] = winner_name2num(winner_name);

        /* Evaluate ADCL P.H */
        t_start = MPI_Wtime();
        for ( it=0; it<NB_OF_ITERATIONS; it++ ) {
             ADCL_Request_start( request );
        }
        elapsed_time[13] = MPI_Wtime()-t_start;
        /* Get winning implementation name */
        ADCL_Request_get_curr_function ( request, &winner_name, NULL, NULL, NULL, NULL);
        /* Get winning implementation number */
        winners[i][1] = winner_name2num(winner_name);

        MPI_Allreduce ( &elapsed_time, &g_elapsed_time[i], 14 , MPI_DOUBLE, MPI_MAX , MPI_COMM_WORLD);
        if(rank == 0) {
#ifdef VERBOSE
            /* Printing the timing for each implementation and ADCL */
            for(j=0;j<12;j++) {
                printf("Elapsed time using f%d:%s is %f\n",j,impl_names[j],g_elapsed_time[i][j]);
	    }
#endif
            printf("Winner using ADCL B.F. is f%d:%s\nWinner using ADCL P.H. is f%d:%s\n", 
                   winners[i][0], impl_names[winners[i][0]], winners[i][1], impl_names[winners[i][1]] );
            /* Cluster implementations */
            cluster_implementations(g_elapsed_time[i], impl_classes[i]);
	}

        ADCL_Request_free ( &request );
        ADCL_Vector_free ( &vec );
        ADCL_Vmap_free ( &vmap );
    }

    ADCL_Topology_free ( &topo );
    MPI_Comm_free ( &cart_comm );

    /* Processing the results */
    if(rank == 0) {
        /* Comparaison between problem sizes */
        for(i=0; i<NB_OF_SIZES; i++) {
            for (j=0; j<NB_OF_SIZES; j++) {
                distance[j] = compute_distance(i,j);
#ifdef VERBOSE
                printf("The distance between problems %d and %d is %f\n",i,j,distance[2*j]);
#endif
                relation[j] = 0;
                /* Is the winner of pb size i among the best impl of pb size j ? */
                for(k=0;k<NB_OF_IMPL;k++) {
                    if ( (winners[i][0]==k) && (impl_classes[j][k] == BEST_CLASS) ) {
                        relation[j] = 1;
#ifdef VERBOSE
                        printf("similar pb sizes: %d can help optimizing %d\n",i,j);
#endif
		    }
		}
            }
            dmax = find_dmax(distance,relation);
            printf( "Max distance for Pb size %dX%dX%d is %f\n",ProblemSizes[i][0],
                    ProblemSizes[i][1], ProblemSizes[i][2], dmax);
        }
    }
   
exit: 
    ADCL_Finalize ();
    MPI_Finalize ();
    return 0;
}
Exemplo n.º 25
0
int det_dup_reg_in_self(int num_list, struct DotList *self, struct I check_x, struct I check_y, int sign)
{
	int i = 0, j = 0;
	struct I temp_1, temp_2;
	struct I cur_1, cur_2, cmp_1, cmp_2;
	bool is_end = false;
	int count_left = 0, count_right = 0;
	int left_pid = 0, right_pid = 0;
	int cut_len_left = 0, cut_len_right = 0;
	int res = TIE;
	int distance = 0;
	bool is_candi = false;
	bool is_assigned = false;

	temp_1 = assign_I(0, 1);
	temp_2 = assign_I(0, 1);

	for( i = 0; i < num_list; i++ )
	{
		cur_1 = assign_I(0, 1);
		cur_2 = assign_I(0, 1);
		cmp_1 = assign_I(0, 1);
		cmp_2 = assign_I(0, 1);
		is_candi = false;
		left_pid = self[i].identity;
		right_pid = self[i].identity;

		if( ( is_assigned == true ) && ((width(temp_1) <= MIN_INTERVAL) || (width(temp_2) <= MIN_INTERVAL)) ) {
			is_end = true;
		}
		else if( (width(self[i].x) <= MIN_INTERVAL) || (width(self[i].y) <= MIN_INTERVAL) )
		{
			is_candi = false;
		}
		else if( (almost_subset(self[i].x, check_x) == true) || ((f_loose_overlap(self[i].x, check_x, SECOND_RUN) == true) && (width(intersect(self[i].x, check_x)) >= MIN_LEN) ))
		{
			temp_1 = assign_I(self[i].x.lower, self[i].x.upper);
			temp_2 = assign_I(self[i].y.lower, self[i].y.upper);
			is_assigned = true;
			is_candi = true;
		}
		else if( (almost_subset(self[i].y, check_x) == true) || (f_loose_overlap(self[i].y, check_x, SECOND_RUN) == true) )
		{
			temp_1 = assign_I(self[i].y.lower, self[i].y.upper);
			temp_2 = assign_I(self[i].x.lower, self[i].x.upper);
			is_assigned = true;
			is_candi = true;
		}
		else {
			is_candi = false;
		}

		if( (is_end == false) && (is_candi == true) )
		{
			if( (temp_1.lower < check_x.lower) && (temp_1.upper > check_x.upper) )
			{
				if( width(check_x) > 0 ) {
					cur_1 = assign_I(0, width(check_x));

					cut_len_left = check_x.lower - temp_1.lower;
					cut_len_right = temp_1.upper - check_x.upper; 
					if( (temp_2.upper - cut_len_right) <= (temp_2.lower + cut_len_left) )
					{
						is_end = true;
					}
					else
					{
						cur_2 = assign_I(temp_2.lower + cut_len_left, temp_2.upper - cut_len_right);
					}
				}
				else {
					is_end = true;
				}
			}
			else
			{
				if( temp_1.lower < check_x.lower )
				{
					if( temp_1.upper > check_x.lower ) {
						cur_1 = assign_I( 0, temp_1.upper - check_x.lower );

						cut_len_left = check_x.lower - temp_1.lower;
						if( temp_2.upper <= (temp_2.lower + cut_len_left) )
						{
							is_end = true;
						}
						else
						{
							cur_2 = assign_I( temp_2.lower + cut_len_left, temp_2.upper );
						}
					}
					else {
						is_end = true;
					}	
				}
				else if( temp_1.upper > check_x.upper )
				{
					if( width(check_x) > (temp_1.lower - check_x.lower) ) {
						cur_1 = assign_I( temp_1.lower - check_x.lower, width(check_x) );
						cut_len_right = temp_1.upper - check_x.upper;
						if( (temp_2.upper - cut_len_right) <= temp_2.lower )
						{
							is_end = true;
						}
						else
						{
							cur_2 = assign_I( temp_2.lower, temp_2.upper - cut_len_right );
						}			
					}
					else {
						is_end = true;
					}
				}
				else
				{
					if( ( temp_1.upper - check_x.lower ) <= (temp_1.lower - check_x.lower) ) {
						is_end = true;
					}
					else {
						cur_1 = assign_I( temp_1.lower - check_x.lower, temp_1.upper - check_x.lower);
						cur_2 = assign_I( temp_2.lower, temp_2.upper );
					}
				}
			}

			if( is_end == false )
			{
				if( sign == 0 )
				{
					if( (cur_1.upper + check_y.lower) > (cur_1.lower + check_y.lower) ) {
						cmp_1 = assign_I(cur_1.lower + check_y.lower, cur_1.upper + check_y.lower);
						cmp_2 = assign_I(cur_2.lower, cur_2.upper);
					}
					else is_end = true;
				}
				else if( sign == 1 )
				{
					if( (check_y.upper - cur_1.lower) > (check_y.upper - cur_1.upper) ) {
						cmp_1 = assign_I(check_y.upper - cur_1.upper, check_y.upper - cur_1.lower);
						cmp_2 = assign_I(cur_2.lower, cur_2.upper);
					}
					else is_end = true;
				}

				if( is_end == false ) {
					if( (width(cmp_1) <= MIN_INTERVAL) || (width(cmp_2) <= MIN_INTERVAL) ) is_end = true;
				}
			}

			j = 0;
			while( (is_end == false) && (j < num_list) )
			{
				if( j == i ) {}
				else
				{
					if( (strict_almost_equal(self[j].x, cmp_1) == true) && ( strict_almost_equal(self[j].y, cmp_2) == true ) )
					{
						right_pid = self[j].identity;
						is_end = true;
						if( left_pid > right_pid ) count_left++;
						else if( left_pid < right_pid ) count_right++;
					}	
					else if( (loose_subset(cmp_1, self[j].x) == true) && (loose_subset(cmp_2, self[j].y) == true ) )
					{
						distance = compute_distance(cmp_1, cmp_2, self[j].x, self[j].y, sign);
						if( distance <= DIS_THRESHOLD )
						{
							right_pid = self[j].identity;
							is_end = true;
							if( left_pid > right_pid ) count_left++;
							else if( left_pid < right_pid ) count_right++;
						}
					}
				}
				j++;
			}
			is_end = false;
		}
	}	

	if( count_left > count_right )
	{
		res = LEFT_SIDE;
	}
	else if( count_left < count_right )
	{
		res = RIGHT_SIDE;
	}
	else
	{
		res = TIE;
	}

	return(res);
}
Exemplo n.º 26
0
//---------------------------------------------------------------------------------------
bool HandlerCircle::hit_test(LUnits x, LUnits y)
{
    return compute_distance(x, y, m_origin.x, m_origin.y) <= m_radius;
}
Exemplo n.º 27
0
void compute_spring_force_C(
        double *spring_force,
        double *y,
        double *tangents,
        double k,
        int n_images,
        int n_dofs_image,
        double (* compute_distance)(double *, double *, int, int *, int),
        int * material,
        int n_dofs_image_material
        ) {

    /* Compute the spring force for every image of an energy band, which is
     * defined in the *y array. The *y array has (n_images * n_dofs_image)
     * elements. The degrees od freedom (spin components) of the i-th image of
     * the band start at the (i * n_dofs_image) position of the array.
     *
     * For the i-th image, the spring force is defined as:

     *      spring_force_i = k * ( | Y_(i+1) - Y_i| - | Y_i - Y_(i-1)| ) * t_i

     * where t_i is the tangent of the i-th image (see the coresponding
     * function for its definition). Thus, spring_force_i has a length of
     * (n_dofs_image). We do not compute the force for the extremal images,
     * i.e. (i=0, (n_images-1))
     *
     * The norm  | . | between two neighbouring images is calculated as an
     * distance, which depends on the coordinate system chosen.
     *
     * The function: (* compute_distance)(double *, double *, int, int *, int)
     * depends on: (Image_1, 
     *              Image_2, 
     *              number of spins per image,
     *              array indicating dofs (spins) in sites WITH material,
     *              number of dofs in sites with material
     *              ) 
     *
     *  - With material we mean Ms > 0 or mu_s > 0
     */

    int i, j;

    // Index where the components of an image start in the *y array,
    int im_idx;
    // And also the previous and next images:
    int next_im_idx, prev_im_idx;

    double dY_plus_norm, dY_minus_norm;

    for(i = 1; i < n_images - 1; i++){

        im_idx = i * (n_dofs_image);
        next_im_idx = (i + 1) * (n_dofs_image);
        prev_im_idx = (i - 1) * (n_dofs_image);

        double * sf = &spring_force[im_idx];
        double * t = &tangents[im_idx];

        // Compute the distances between the i-th image, Y_i, and its
        // neighbours, the (i+1)-th and (i-1)-th images. The distance between
        // two images is just the norm of their difference scaled by the length
        // of the array (see the compute_norm function)
        dY_plus_norm  = compute_distance(&y[next_im_idx], &y[im_idx],
                                         n_dofs_image,
                                         material, n_dofs_image_material
                                         );
        dY_minus_norm = compute_distance(&y[im_idx], &y[prev_im_idx],
                                         n_dofs_image,
                                         material, n_dofs_image_material
                                         );

        // Now compute the spring force
        for(j = 0; j < n_dofs_image; j++) {
            sf[j] = k * (dY_plus_norm - dY_minus_norm) * t[j];
        }
    }

}
// top-level function of the design
void lloyds_kernel_top(  uint block_address,
						 volatile bus_type *master_portA,
						 //volatile bus_type *master_portB,
						 uint data_points_addr,
                         uint centres_in_addr,
                         uint output_addr,
                         uint update_points,
                         uint n,
                         uint k, //changed so that the AXI slave interface can be used.
			 uint *debug
                         )
{

	// set up the axi bus interfaces
	#pragma HLS INTERFACE ap_bus port=master_portA depth=0x200000
	#pragma HLS resource core=AXI4M variable=master_portA

	//#pragma HLS INTERFACE ap_bus port=master_portB depth=0x002000
	//#pragma HLS resource core=AXI4M variable=master_portB

	#pragma HLS INTERFACE ap_none register port=data_points_addr
	#pragma HLS RESOURCE core=AXI4LiteS variable=data_points_addr metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=centres_in_addr
	#pragma HLS RESOURCE core=AXI4LiteS variable=centres_in_addr metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=output_addr
	#pragma HLS RESOURCE core=AXI4LiteS variable=output_addr metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=n
	#pragma HLS RESOURCE core=AXI4LiteS variable=n metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=k
	#pragma HLS RESOURCE core=AXI4LiteS variable=k metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=update_points
	#pragma HLS RESOURCE core=AXI4LiteS variable=update_points metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=block_address
	#pragma HLS RESOURCE core=AXI4LiteS variable=block_address metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS INTERFACE ap_none register port=debug
	#pragma HLS RESOURCE core=AXI4LiteS variable=debug metadata="-bus_bundle CONFIG_BUS"

	#pragma HLS RESOURCE variable=return core=AXI4LiteS	metadata="-bus_bundle CONFIG_BUS"

	data_type data_points_buffer[B];
	data_type centres_buffer[K];
	output_type output_buffer[B];
	data_type output_points_buffer[B];


	//void load_points_buffer(uint offset,uint address, volatile bus_type *bus, data_type *buffer)
	//void load_centres_buffer(uint offset, uint address, volatile bus_type *bus, centre_index_type k, data_type *buffer)

	uint data_points_block_address = D*block_address;
	uint kernel_info_block_address = 2*block_address;

	load_points_buffer(data_points_addr, data_points_block_address, master_portA, data_points_buffer);
	load_centres_buffer(centres_in_addr, 0, master_portA, k, centres_buffer);
	*debug = data_points_buffer[0].value[0];

	/*
	for (uint i=0; i<B; i++) {
		data_type u = data_points_buffer[i];
		printf("%d %d %d\n", u.value[0], u.value[1], u.value[2]);
	}
	*/



    // iterate over all data points
    process_data_points_loop: for (uint i=0; i<B; i++) {

    	data_type u = data_points_buffer[i];

    	/*
		#ifndef __SYNTHESIS
			for (uint d=0; d<D; d++) {
				printf("%d ", u.value[d]);
			}
			printf("\n");
		#endif
		*/

        centre_index_type final_centre_index = 0;
        coord_type sum_sq_out = MAX_FIXED_POINT_VAL_EXT;
        coord_type min_dist = MAX_FIXED_POINT_VAL_EXT;

        data_type closest_centre;

        // iterate over all centres
        minsearch_loop: for (centre_index_type ii=0; ii<=k; ii++) {
           #pragma HLS pipeline II=1

			coord_type tmp_dist;
			data_type cntr = centres_buffer[ii];

			//printf("%d %d %d\n", u.value[0], u.value[1], u.value[2]);
			//printf("%d %d %d\n", cntr.value[0], cntr.value[1], cntr.value[2]);

			compute_distance(cntr, u, &tmp_dist);

			//printf("%d\n\n", tmp_dist);

			// select the centre with the smallest distance to the data point
			if (tmp_dist<min_dist) {
				closest_centre = cntr;
				min_dist = tmp_dist;
				final_centre_index = ii;
				sum_sq_out = tmp_dist;
			}

			if (ii == k) {
				break;
			}
		}
        /*
		#ifndef __SYNTHESIS__
        	printf("%d %d\n",final_centre_index.VAL, sum_sq_out);
		#endif
		*/

        output_buffer[i].min_idx = final_centre_index;
        output_buffer[i].sum_sq = sum_sq_out;

        output_points_buffer[i] = closest_centre;

        //printf("%d %d %d\n", closest_centre.value[0], closest_centre.value[1], closest_centre.value[2]);

	}

    //printf("\n\n");

	//void store_output_buffer(uint offset, output_type *buffer, uint address, volatile bus_type *bus)
    if (update_points == 0) {
    	store_output_buffer(output_addr, output_buffer, kernel_info_block_address, master_portA);
    } else {
    	store_output_points_buffer(output_addr, output_points_buffer, data_points_block_address, master_portA);
    }




}
Exemplo n.º 29
0
//LOF
int main (const int argc, const char **argv) {
	
	FILE *verbose = stderr; 	// set to NULL to turn off verbose progress messages.

	char SYNOPSIS[4000]; 
	sprintf(SYNOPSIS, "Compute LOF score for a set of instances.  Input is a set of instances, one per line, with feature values separated by commas.  This is a special implementation that allows semi-supervised anomaly detection by specifying the number of training and testing instances.  The LOF for a test example is then computed considering the distance to and among *training* instances, but not the distance to other *test* set instances (which are themselves possibly outliers).  The input file consists of all training instances, followed by all testing instances (the number of training instances plus the number of testing instances should equal the number of lines of input).  If the number of testing instances is not supplied, the program will print the LOF for all instances (i.e., unsupervised anomaly detection).  This implementation uses the distance function:  %s.", distance_function_name());

	char USAGE[2000]; 
	sprintf(USAGE, "Usage:  %s <MinPtsLB> <MinPtsUB> <No.Features> <Train.set.size> [<Test.set.size>]  <  <comma-separated-input>", argv[0]);

	const parameter_set param = parse_command_line(argc,argv,SYNOPSIS,USAGE);
	const int T = param.T; const int C0 = param.C0; const int C = param.C; 
	const int M = param.M; const int N = param.N; 
	const int MinPtsLB = param.kLB; const int MinPtsUB = param.kUB;

	const int vperiod = T/20 + 100 - (T/20)%100;	// adjust to a percentage of training set, round to nearest 100

	double **stored_dist = compute_distance(&param, verbose); // subroutine to read data, compute distance.

	// LOF 

	int i,j,p,k;
	time_t t0;

	t0 = time(NULL);
	if (verbose) { fprintf(verbose, "# Find %i neighbors for each of %i instances...", MinPtsUB, M); }

	// The efficient way to proceed is to find the MinPtsUB (upper bound)
	// nearest neighbors for each example, then choose a subset among them for
	// all k <= MinPtsUB
		
	neighbor **knn = malloc(sizeof(neighbor*) * M); // a neighbor is an index and its distance, freed at the bottom of the program
	for (i=0;i<M;i++) { 
		knn[i] = malloc(sizeof(neighbor)*MinPtsUB); 
		for (k=0; k<MinPtsUB; k++) { 
			knn[i][k].index = -1;		
			knn[i][k].distance = 1e999;
		}
	}
	
	// loop to find nearest neighbors and calculate k-distance
  	for (i=0; i<M; ++i) {
		if (verbose && !(i%vperiod)) { fprintf(verbose, "."); }
		for (j=0; j<N; ++j) {
			if (i==j) { continue; }
	  		if (dist(i,j) < knn[i][MinPtsUB-1].distance) { 
				// we found a nearer neighbor

				// overwrite most distant neighbor
				knn[i][MinPtsUB-1].index = j;
				knn[i][MinPtsUB-1].distance = dist(i,j);

				// sort so that knn[i] is a list of MinPtsUB neighbors, closest one first, 
				// index knn[i][MinPts-1] is the most distant neighbor
				qsort(knn[i], MinPtsUB, sizeof(neighbor), neighborcmp);

	  		}
		}

	} // next i
	
	if (verbose) { fprintf(verbose, "%.0lf second(s).\n# Compute LOF for %i <= k <= %i", difftime(time(NULL),t0), MinPtsLB, MinPtsUB); }

	// store the (max) LOF for C test examples
	double max_LOF[C];
	for (i=0; i < C; i++) { max_LOF[i]=0.0; }

	t0 = time(NULL);
	for (k=MinPtsLB; k<=MinPtsUB; k++) {

		if (verbose) { fprintf(verbose,"."); }
			
		double **reach_dist = malloc(sizeof(double*)*M);
		for (i=0; i<M; i++) { reach_dist[i] = malloc(sizeof(double)*k); } // freed at bottom of loop

	  	// reach-dist
	  	for (i=0; i<M; ++i) {
			for (j=0; j<k; ++j) {
		 		int nn_i = knn[i][j].index;
		  		reach_dist[i][j] = (dist(i,nn_i)) > knn[nn_i][k-1].distance ? (dist(i,nn_i)) : knn[nn_i][k-1].distance;
			}
	  	}


	  	// lrd
	  	double *lrd = malloc(sizeof(double)*M); 	// freed at the bottom of loop

	  	for (i=0; i<M; ++i) {
			double sum_reach_dist = 0.0;
			for (j=0; j<k; ++j) {
				sum_reach_dist += reach_dist[i][j];
			}
			lrd[i] = k / sum_reach_dist;

		}

		// LOF
		for (i=C0; i < C0+C; i++) { 

			//calculate LOF
			double sum_lrd = 0.0;
			for (p=0; p < k; ++p) {
		  		sum_lrd += lrd[knn[i][p].index]/lrd[i];
			}

			int test_index = i - C0;
			double LOF_k_test_index = sum_lrd / k;
			max_LOF[test_index] = (!isinf(LOF_k_test_index) && LOF_k_test_index > max_LOF[test_index]) ? LOF_k_test_index : max_LOF[test_index];	// keep max LOF
        
	  	}

		free(lrd);
		for (i=0; i<M; i++) { free(reach_dist[i]); }
		free(reach_dist);
	
	
	} // next value of k
		
	if (verbose) { fprintf(verbose, "%.0f second(s).\n", difftime(time(NULL),t0)); }
			
	for (i=0;i<M;i++) { free(knn[i]); }
	free(knn);

	// output:  print max(LOF(i)) for all test cases
	for (i=0; i<C; i++) { 
		fprintf(stdout, "%g\n", max_LOF[i]);
	}

	// free stored_dist
	for (i=0; i<M; i++) { free(stored_dist[i]); }
	free(stored_dist);

	return 0;
}
Exemplo n.º 30
0
void test_target2() {
  double dist = compute_distance();
  printf("DISTANCE Restante %f\n",dist);
  sleep(1);
}