Esempio n. 1
0
//  BPW -- this really doesn't have anything to do with "edgemate" but
//  it's commonly called with check_symmetry_of_the_edge_mates(), and
//  they're both disabled.
//
void count_fragment_and_edge_labels(Tfragment frags[],
                                    Tedge     edges[],
                                    char      comment[]) {
  FILE *fout = stderr;

  fprintf(stderr, "count_fragment_and_edge_labels()--  Disabled.\n");
  return;

  const int nsample=500;
  const int nbucket=500;

  IntFragment_ID nfrag = GetNumFragments(frags);
  IntFragment_ID vid;
  Histogram_t *frag_lab_histogram = create_histogram(nsample,nbucket,TRUE,FALSE);

  fprintf(fout,"*** Histogram Fragment Labels <%s> ***\n",comment);

  for(vid=0; vid<nfrag; vid++) {
    const Tlab ilab = get_lab_fragment(frags,vid);
    add_to_histogram(frag_lab_histogram, (int)ilab, NULL);
  }

  fprintf(fout,"Histogram of the fragment label \n");
  print_histogram(fout,frag_lab_histogram, 0, 1);
  free_histogram(frag_lab_histogram);

  IntEdge_ID ie;
  IntEdge_ID nedge = GetNumEdges(edges);
  Histogram_t *inter_chunk_edge_nes_histogram = create_histogram(nsample,nbucket,TRUE,FALSE);
  Histogram_t *intra_chunk_edge_nes_histogram = create_histogram(nsample,nbucket,TRUE,FALSE);

  fprintf(fout,
          "*** Histogram Edge Labels (2 edges/overlap) <%s> ***\n",
          comment);

  for(ie=0; ie<nedge; ie++) {
    const Tnes nes = get_nes_edge(edges,ie);
    const IntFragment_ID avx = get_avx_edge(edges,ie);
    const IntFragment_ID bvx = get_bvx_edge(edges,ie);
    const IntChunk_ID a_cid = get_cid_fragment(frags,avx);
    const IntChunk_ID b_cid = get_cid_fragment(frags,bvx);
    if( a_cid == b_cid ) {
      add_to_histogram(intra_chunk_edge_nes_histogram, (int)nes, NULL);
    } else {
      add_to_histogram(inter_chunk_edge_nes_histogram, (int)nes, NULL);
    }
  }

  fprintf(fout,"Histogram of the inter-chunk overlap labels \n");
  print_histogram(fout,inter_chunk_edge_nes_histogram, 0, 1);
  free_histogram(inter_chunk_edge_nes_histogram);

  fprintf(fout,"Histogram of the intra-chunk overlap labels \n");
  print_histogram(fout,intra_chunk_edge_nes_histogram, 0, 1);
  free_histogram(intra_chunk_edge_nes_histogram);
}
Esempio n. 2
0
int main(void)
{
	srand(time(NULL));
	int SIZE,counter; 
	int a[MAX];
	int b[MAX2]={0};
	printf("Input the size of the first input:");
	scanf("%d",&SIZE);
	while (check_error(SIZE)==0)
	{
		printf("Invalid input enter the size of the input again");
		scanf("%d",&SIZE);
	}
	initialize_array(a,SIZE);
	printf("Input array\n");
	print_array(a,SIZE);
	frequency(a,b,SIZE);
	printf("\nMode for the array is number %d",mode(b));
	printf("\nPrinting histogram\n");
	print_histogram(b);
	printf("Bonus part\n");
	printf("\nArray before sorting\n");
	print_array(a,SIZE);	
	printf("\nArray after sorting\n");
	sort_array(a,SIZE);
	print_array(a,SIZE);
	printf("\n");
}
Esempio n. 3
0
static void client_thread(thread_args *args) {
  char *buf = calloc(args->msg_size, sizeof(char));
  gpr_histogram *histogram = gpr_histogram_create(0.01, 60e9);
  double start_time;
  double end_time;
  double interval;
  const int kNumIters = 100000;
  int i;

  if (args->setup(args) < 0) {
    gpr_log(GPR_ERROR, "Setup failed");
  }
  for (i = 0; i < kNumIters; ++i) {
    start_time = now();
    if (args->write_bytes(args, buf) < 0) {
      gpr_log(GPR_ERROR, "Client write failed");
      goto error;
    }
    if (args->read_bytes(args, buf) < 0) {
      gpr_log(GPR_ERROR, "Client read failed");
      goto error;
    }
    end_time = now();
    if (i > kNumIters / 2) {
      interval = end_time - start_time;
      gpr_histogram_add(histogram, interval);
    }
  }
  print_histogram(histogram);
error:
  free(buf);
  gpr_histogram_destroy(histogram);
}
Esempio n. 4
0
int main(){

	int wordstats[MAX_WORDLENGTH];
	int c, i, state, lenc;
	lenc = 0;
	state = OUT;

	for(i = 0; i < MAX_WORDLENGTH; i++){
		wordstats[i] = 0;
	}

	//gather stats
	while((c = getchar()) != EOF){
		if((c == ' ') || (c == '\n') || (c == '\t')){
			if(state == IN){
				wordstats[lenc]++;
				lenc = 0;
				state = OUT;
			}
			//Do nothing if repeating whitespace
		} else {
			state = IN;
			lenc++;
		}
	}
	print_histogram(wordstats, MAX_WORDLENGTH);
	return 0;
}
Esempio n. 5
0
int main()
{
    int c, i, prevc, curlen;
    int wordsize[MAX_WORD_LEN];
    prevc = curlen = 0;

    for(i = 0; i < MAX_WORD_LEN; ++i)
        wordsize[i] = 0;

    while((c = getchar()) != EOF) {
        if(is_whitespace(c)) {
            if(!is_whitespace(prevc)) {
                if(curlen <= MAX_WORD_LEN-1)
                    ++wordsize[curlen-1];
                else
                    ++wordsize[MAX_WORD_LEN-1];
            }
            curlen = 0;
        }
        else
            ++curlen;

        prevc = c;
    }

    print_histogram(wordsize, 2);

    return 0;
}
Esempio n. 6
0
int main(int argc, char ** argv) {
try {
  using float_t = double;
  using size_type = std::uint32_t;
  if (4 != argc)
    throw std::invalid_argument("usage: simplify <<t> | -p> <in_file> <out_file>");
  // read the flow complex from file
  auto fc = FC::flow_complex<float_t, size_type>(42, 42);  // dummy
  {
    auto in_filename = argv[2];
    std::ifstream in_file(in_filename);
    in_file >> fc;
  }
  char const* action = argv[1];
  if (std::string(action) == "-p") {
    char const* out_filename = argv[3];
    std::ofstream out_file(out_filename);
    print_histogram(out_file, std::move(fc));
  } else {
    // simplify
    float_t const t = std::atof(argv[1]);
    if (t < 1)
      throw std::invalid_argument("prerequisite: t >= 1");
    fc = simplify(std::move(fc), t);
    // write result flow complex to file
    char const* out_filename = argv[3];
    std::ofstream out_file(out_filename);
    out_file << fc;
  }
} catch (std::exception & e) {
  std::cerr << e.what() << std::endl;
  std::exit(EXIT_FAILURE);
}
  std::exit(EXIT_SUCCESS);
}
Esempio n. 7
0
void run_test_on_file(fs::path const& filename)
{
    std::vector<char> input = read_whole_file(filename);
    input.push_back(guard_value);

    std::cout << filename << '\t' << input.size() << " bytes" << "\n";

    histogram_accumulator acc;
    size_t const N = 10000;
    for (size_t i = 0; i != N; ++i)
    {
        auto start_time = std::chrono::high_resolution_clock::now();

        lexer lex(input.data(), input.data() + input.size() - 1);
        token tok = lex.fetch(true);
        while (tok.tok_type != token_type::eof)
            tok = lex.fetch(false);

        auto end_time = std::chrono::high_resolution_clock::now();
        auto dur = end_time - start_time;
        //print_time(std::cout, dur);
        //std::cout << '\t';
        acc.push(dur);
    }
    print_histogram(acc.build());
    /*std::cout << "\n\tmin = ";
    print_time(std::cout, *min);
    std::cout << " max = ";
    print_time(std::cout, *max);
    std::cout << " avg = ";
    print_time(std::cout, sum / N);
    std::cout << " MB/s = " << (double)input.size() / std::chrono::duration_cast<std::chrono::microseconds>(sum).count() * N;
    std::cout << '\n';*/
}
Esempio n. 8
0
void print_level_histogram(const TimingGraph& tg, int nbuckets) {
    cout << "Levels Width Histogram" << endl;

    std::vector<float> level_widths;
    for(const LevelId level_id : tg.levels()) {
        level_widths.push_back(tg.level_nodes(level_id).size());
    }
    print_histogram(level_widths, nbuckets);
}
Esempio n. 9
0
void print_node_fanout_histogram(const TimingGraph& tg, int nbuckets) {
    cout << "Node Fan-out Histogram" << endl;

    std::vector<float> fanout;
    for(const NodeId node_id : tg.nodes()) {
        fanout.push_back(tg.node_out_edges(node_id).size());
    }

    std::sort(fanout.begin(), fanout.end(), std::greater<float>());
    print_histogram(fanout, nbuckets);
}
Esempio n. 10
0
ex_t histogram(bfpath *bfp)
{
    ex_t rc;
    uint count;
    void *dsh, *dbe;
    dsv_t val;

    rhistogram_t hist;

    dbe = ds_init(bfp);
    if (dbe == NULL)
	return EX_ERROR;

    dsh = ds_open(dbe, bfp, DS_READ);
    if (dsh == NULL)
	return EX_ERROR;

    if (DST_OK != ds_txn_begin(dsh)) {
	ds_close(dsh);
	ds_cleanup(dbe);
	fprintf(stderr, "cannot begin transaction!\n");
	return EX_ERROR;
    }

    ds_get_msgcounts(dsh, &val);
    mgood = val.goodcount;
    mbad = val.spamcount;

    memset(&hist, 0, sizeof(hist));
    rc = ds_foreach(dsh, ds_histogram_hook, &hist);

    if (DST_OK != ds_txn_commit(dsh)) {
	ds_close(dsh);
	ds_cleanup(dbe);
	fprintf(stderr, "cannot commit transaction!\n");
	return EX_ERROR;
    }

    ds_close(dsh);
    ds_cleanup(dbe);

    count = print_histogram(&hist);

    if (verbose > 0) {
	printf("hapaxes:  ham %7u, spam %7u\n", ham_hapax, spam_hapax);
	printf("   pure:  ham %7u, spam %7u\n", ham_only,  spam_only);
    }
    else {
	printf("hapaxes:  ham %7u (%5.2f%%), spam %7u (%5.2f%%)\n", ham_hapax, PCT(ham_hapax), spam_hapax, PCT(spam_hapax));
	printf("   pure:  ham %7u (%5.2f%%), spam %7u (%5.2f%%)\n", ham_only,  PCT(ham_only),  spam_only,  PCT(spam_only));
    }

    return rc;
}
Esempio n. 11
0
int main(int argc, char *argv[]) {
  if(argc != 2) {
    printf("Usage: %s input-file\n", argv[0]);
    exit(1);
  }
  
  struct img input;

  if(!ppmb_read(argv[1], &input.xsize, &input.ysize, &input.maxrgb, 
		&input.r, &input.g, &input.b)) {
    if(input.maxrgb > 255) {
      printf("Maxrgb %d not supported\n", input.maxrgb);
      exit(1);
    }

    int *hist_r, *hist_g, *hist_b;

    hist_r = (int *) calloc(input.maxrgb+1, sizeof(int));
    hist_g = (int *) calloc(input.maxrgb+1, sizeof(int));
    hist_b = (int *) calloc(input.maxrgb+1, sizeof(int));

    ggc::Timer t("histogram");

    t.start();
    histogram(&input, hist_r, hist_g, hist_b);
    t.stop();

    char *output = get_output_file(argv[1]);

    FILE *out = fopen(output, "w");
    if(out) {
      print_histogram(out, hist_r, input.maxrgb);
      print_histogram(out, hist_g, input.maxrgb);
      print_histogram(out, hist_b, input.maxrgb);
      fclose(out);
    } else {
      fprintf(stderr, "Unable to output!\n");
    }
    printf("Time: %llu ns\n", t.duration());
  }  
}
Esempio n. 12
0
File: ex_1-6-114.c Progetto: dm3/knr
/**
 * Print the histogram of frequencies of characters of the input.  Bars will
 * point horizontally.
 *
 * Considering input of "a bb ccc dddd eeeee", which contains
 *
 * 1 x a
 * 2 x b
 * 3 x c
 * 4 x d
 * 5 x e
 *
 * the output should look like this:
 *
 * 1 (a) ====
 * 2 (b) ========
 * 3 (c) ============
 * 4 (d) ================
 * 5 (e) ====================
 *
 * Maximum length of the bar (100%) should be 20 symbols
 */
int main() {
    int counts[MAX_CHARACTERS], c;
    int current_len = 0;

    init_zeroes(counts, MAX_CHARACTERS);

    while ((c = getchar()) != EOF) {
        counts[(int) c]++;
    }

    print_histogram(counts, MAX_CHARACTERS);
    return 0;
}
Esempio n. 13
0
/**
 * Count the number of digits, white spaces and other characters. Display
 * the result using a vertical histogram.
 */
int main(int argc, char const* argv[])
{
  int c, i , max, count;
  int state;
  int words[MAX_LENGTH];
  int result[MAX_LENGTH];

  max = count = 0;
  state = OUT;

  for (i = 0; i < MAX_LENGTH; i++)
    words[i] = 0;

  while ((c = getchar()) != EOF) {
    if (state == IN)
      {
        if (c == ' ' || c == '\t' || c == '\n')
          {
            ++count;
            words[count]++;
            count = 0;
            state = OUT;
          }
        else
            ++count;
      }
    else if (state == OUT)
      {
        if (c == ' ' || c == '\t' || c == '\n')
          ;
        else
            state = IN;
      }
  }

  for (i = 0; i < MAX_LENGTH; i++)
      if (words[i] > max)
        max = words[i];

  for (i = 0; i < MAX_LENGTH; i++) {
    result[i] = max - words[i];
  }

  print_histogram(result, max);

  return 0;
}
Esempio n. 14
0
int main()
{
	int len[MAX_WORDS];
	int number_of_words = 0;

	int i;
	for(i=0; i<MAX_WORDS; ++i)
	{
		len[i] = 0;
	}

	number_of_words = get_words_data(len, MAX_WORDS);
	
	print_histogram(len, number_of_words);

	return 0;
}
Esempio n. 15
0
int main ()
{
  //declaring variables
  int char_totals[num_of_letters];
  int num_of_lines = 0;
	
  //set all array values to zero 
  zeroed_out_array(char_totals, num_of_letters);

  //input data and alter array accordingly
  count_frequency (char_totals);
	
  //find the nuber of lines by finding the highest total
  num_of_lines = highest_pos_int_in_an_int_array (char_totals, num_of_letters);
	
  print_histogram(char_totals, num_of_lines);

  return 0; //to indicate no errors
}
Esempio n. 16
0
int main(int argc, char** argv)
{
  int num_vertices, edges_per_vertex;
  float prob_of_swap;

  if (argc < 4)
    goto err_usage;
  if (sscanf(argv[1], "%i", &num_vertices) != 1)
    goto err_usage;
  if (sscanf(argv[2], "%i", &edges_per_vertex) != 1)
    goto err_usage;
  if (sscanf(argv[3], "%f", &prob_of_swap) != 1)
    goto err_usage;

  if (edges_per_vertex % 2) {
    fprintf(stderr, "edges_per_vertex should be even\n");
    return EXIT_FAILURE;
  }

  fprintf(stderr,
      "Configuration:\n"
      "  Vertices:         %d\n"
      "  Edges per vertex: %d\n"
      "  Swap probability: %f\n\n",
      num_vertices, edges_per_vertex, prob_of_swap);

  struct graph_t *g = build_regular_graph(num_vertices, edges_per_vertex);
  randomise_graph(g, prob_of_swap);
  struct histogram_t *h = get_degree_distribution(g);

  for (int i = 0; i < h->bins; i++)
    fprintf(stdout, "%d %d\n", i, h->data[i]);

  print_histogram(stderr, h);
  delete_histogram(h);
  delete_graph(g);
  return 0;

err_usage:
  print_usage(stderr);
  return EXIT_FAILURE;
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
  histogram_t *myhist;
  struct timeval start, stop;

  double min, max;

  /* <app> bin_count file-name */
  if (argc < 4) {
    fprintf(stderr, "Invalid number of parameters\n");
    exit(EXIT_FAILURE);
  }

  char *filename;
  size_t bin_count = strtol(argv[1], NULL, 10);
  filename = argv[2];
  thread_count = atoi(argv[3]);

  read_data(filename, &count, &min, &max);

  pthread_mutex_init(&mutexsum, NULL);

  gettimeofday(&start, NULL);
  myhist = create_histogram(min, max, bin_count, thread_count);
  gettimeofday(&stop, NULL);

  double t = (((double)(stop.tv_sec)*1000.0  + (double)(stop.tv_usec / 1000.0)) - \
                   ((double)(start.tv_sec)*1000.0 + (double)(start.tv_usec / 1000.0)));

  fprintf(stdout, "Time elapsed = %g ms\n", t);

  print_histogram(myhist);

  // missing: deallocate memory

  return 0;
}
Esempio n. 18
0
int main(int argc, char* argv[]) {

	// declarations
	struct stat st;
	unsigned int i, buffer_size;
	struct timespec begin, end;
	char *buffer;
	histogram_t histogram = {0};
	char *filename = "war_and_peace.txt";
	long num_threads = 1, repetitions=0;
 
	// argument handling
	if (argc < 2 || argc > 4) {
		printf("usage: %s filename [#threads] [#repetition]\n", argv[0]);
		return 1;
	}
	if (argc >= 2)
		filename = argv[1];
	if (argc >= 3)
		if ((num_threads = strtol(argv[2], NULL, 0)) == 0 || num_threads < 0) {
    			fprintf(stderr, "#threads not valid!\n");
    			return 1;
  		}
	if (argc >= 4)
		if ((repetitions = strtol(argv[3], NULL, 0)) == 0 || repetitions < 0) {
    	fprintf(stderr, "#repetition not valid!\n");
    	return 1;
  	}

 	printf("\nProcess %s by %ld thread(s) with %ld repetition(s)\n\n",
		filename, num_threads, repetitions);

	printf(" main will get file size...");
	// get file size and allocate array
	stat(filename, &st);
	buffer_size = (unsigned int)st.st_size * (repetitions+1);
	buffer = (char*)malloc(buffer_size);
	printf("main allocated array");

	// open file and read all characters
	FILE *fp = fopen(filename, "r");
	if (fp == NULL) {
		fprintf(stderr, "Could not open file %s", filename);
		exit(EXIT_FAILURE);
	}
	if (fread(buffer, 1, st.st_size, fp) == 0) {
		fprintf(stderr, "Could not read from file %s", filename);
		exit(EXIT_FAILURE);
	}

	// [optional] do the repetition
	for (i = 1; i <= repetitions; i++)
		memcpy(buffer + i*st.st_size, buffer, st.st_size);

	// set the buffer
	printf("main sets bufer");
	set_buffer(buffer, buffer_size);

	// build the histogram	
	clock_gettime(CLOCK_MONOTONIC, &begin);
	printf("main calls histogram");
	get_histogram(histogram, num_threads);
	clock_gettime(CLOCK_MONOTONIC, &end);

	free(buffer);
	print_histogram(histogram);
	printf("\n\nTime: %.5f seconds\n", ((double)end.tv_sec + 1.0e-9*end.tv_nsec) -
									   ((double)begin.tv_sec + 1.0e-9*begin.tv_nsec));

	return 0;
}
Esempio n. 19
0
//void main_function(cyg_addrword_t data) {
void * main_function(void * data) {

    
    int tmp = 1;

    region_information = (int *) malloc (4 * sizeof(int));

     // create particles
    create_particle_filter(100, 10); 

    /*slots = (int *) malloc (6 * sizeof(int));
    slots[0] = 0;
    slots[1] = 1;
    slots[2] = 2;
    slots[3] = 3;
    slots[4] = 4;
    slots[5] = 5;
    set_importance_hw_static(1, &slots[0]);*/

    /*rthread_attr_init(&hwthread_sorter_attr);
    rthread_attr_setslotnum(&hwthread_sorter_attr, 0);
    rthread_attr_setresources(&hwthread_sorter_attr, hwthread_sorter_resources, 3);
    reconos_hwthread_create( 15,                                               // priority
                             &hwthread_sorter_attr,                             // hardware thread attributes
                             0,                                                // entry data (not needed)
                             "MT_HW_SORT",                                     // thread name
                             hwthread_sorter_stack,                            // stack
                             STACK_SIZE,                                       // stack size
                             &hwthread_sorter_handle,                          // thread handle
                             &hwthread_sorter                                  // thread object
    );
    cyg_thread_resume( hwthread_sorter_handle );*/
    
    //cyg_thread_delay(50);

#ifndef NO_ETHERNET
    init_all_network_interfaces();
    if(!eth0_up){
		printf("failed to initialize eth0\naborting\n");
		return NULL;
    }
    else{
		printf(" eth0 up\n");
    }

    diag_printf( "initializing ECAP interface..." );
    ecap_init();
    diag_printf( "done\n" );

    // establish connection
    while (tmp == 1){
         tmp = establish_connection(6666, region_information);
    }
#endif


    // start read_new_frame 
    cyg_semaphore_post(sem_read_new_frame_start);

    srand(1);

    // set region information for equal time measurements

   #define VIDEO 1
    
   printf("\n#################################################");
   printf("\n#################################################");
      #ifdef VIDEO    
      #if VIDEO==1
       printf("\n##########  S O C C E R   V I D E O  ############");
       region_information[0] = 286;
       region_information[1] = 247;
       region_information[2] = 117;
       region_information[3] = 171;
      #else
      #if VIDEO==2
       printf("\n########  F O O T B A L L   V I D E O  ##########");
       region_information[0] = 255;
       region_information[1] = 252;
       region_information[2] =  23;
       region_information[3] =  41;
      #else
      #if VIDEO==3
       printf("\n##########  H O C K E Y   V I D E O  ############");
       region_information[0] = 152;
       region_information[1] =  95;
       region_information[2] =  19;
       region_information[3] =  39;
      #else
      #if VIDEO==4
       printf("\n##########  H O C K E Y   V I D E O (FULL PICTURE) ############");
       region_information[0] = 159;
       region_information[1] = 119;
       region_information[2] = 320;
       region_information[3] = 240;
      #endif
      #endif
      #endif
      #endif
      #else
       printf("\n######  N O   V I D E O   D E F I N E D  ########");

      #endif
    printf("\n#################################################");
    printf("\n#################################################\n");
    
    // init particles
    init_particles(region_information, 4);


    // Output Object Region
    printf("\n\nx0 = %d\ny0 = %d\nwidth = %d\nheight = %d\n\n", region_information[0], region_information[1], region_information[2], region_information[3]);
    
    particle p;
    p.x = region_information[0]*PF_GRANULARITY;
    p.y = region_information[1]*PF_GRANULARITY;
    p.x0 = p.x;
    p.y0 = p.y;
    p.xp = p.x;
    p.yp = p.y;
    p.s = PF_GRANULARITY;
    p.sp = p.s;
    p.width = region_information[2];
    p.height = region_information[3]; 

    // get reference data
    get_reference_data(&p, &reference_data);

    init_reference_data (&reference_data);

    print_histogram(&reference_data);
    //print_histogram2(&reference_data);

#ifdef STORE_VIDEO
    int i;
    printf("\n\nThe first %d Frames will be stored into Main Memory. Again this will take some time.\n", (int)MAX_FRAMES);

    
    // load first frames
    for(i=0; i<MAX_FRAMES-1; i++){

	  //switch_framebuffer();
	    read_frame();
    }

    printf("\nFinished: The first %d Frames are stored in the Main Memory.\n", (int)MAX_FRAMES);
#endif

       
    parameter_s = (int *) malloc (5 * sizeof(int));
    parameter_s[0] = SIZE_X;
    parameter_s[1] = SIZE_Y;
    parameter_s[2] = 16384; // GRANULARITY / TRANS_STD_X
    parameter_s[3] = 8192;  // GRANULARITY / TRANS_STD_Y
    parameter_s[4] = 16;    // GRANULARITY / TRANS_STD_S

    parameter_o = (int *) malloc (2 * sizeof(int));
    parameter_o[0] = SIZE_X;
    parameter_o[1] = SIZE_Y;

    slots = (int *) malloc (6 * sizeof(int));
    slots[0] = 0;
    slots[1] = 1;
    slots[2] = 2;
    slots[3] = 3;
    slots[4] = 4;
    slots[5] = 5;


    // create sampling, importance, resampling thread

   printf("\n#################################################");
   printf("\n#################################################");
   #ifdef PARTITIONING
    #if PARTITIONING==1
    printf("\n######   P A R T I T I O N I N G    S W   #######");
    set_sample_sw(1);
    set_observe_sw(1);
    set_importance_sw(1);
    set_resample_sw(1);
    #else
    #if PARTITIONING==2
    printf("\n####   P A R T I T I O N I N G    H W  I   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_importance_sw(1);
    set_importance_hw_static(1, &slots[2]);
    set_resample_sw(1);   
    #else
    #if PARTITIONING==3
    printf("\n####   P A R T I T I O N I N G    H W   II   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_importance_sw(1);
    set_importance_hw_static(2, &slots[2]);
    set_resample_sw(1); 
   #else
   #if PARTITIONING==4
    printf("\n####   P A R T I T I O N I N G    H W   O   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_observe_hw_static(1, &slots[0], parameter_o, 2);
    set_importance_sw(1);
    set_resample_sw(1);
   #else
   #if PARTITIONING==5
    printf("\n####   P A R T I T I O N I N G    H W   OO   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_observe_hw_static(1, &slots[0], parameter_o, 2);
    set_importance_sw(1);
    set_resample_sw(1);
   #else
   #if PARTITIONING==6
    printf("\n####   P A R T I T I O N I N G    H W   IO   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_observe_hw_static(1, &slots[0], parameter_o, 2);
    set_importance_sw(1);
    set_importance_hw_static(1, &slots[2]);
    set_resample_sw(1);
   #else
   #if PARTITIONING==7
    printf("\n####   P A R T I T I O N I N G    H W   IIO   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_observe_hw_static(2, &slots[0], parameter_o, 2);
    set_importance_sw(1);
    set_importance_hw_static(1, &slots[2]);
    set_resample_sw(1);
   #else
   #if PARTITIONING==8
    printf("\n####   P A R T I T I O N I N G    H W   IOO   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_observe_hw_static(1, &slots[0], parameter_o, 2);
    set_importance_sw(1);
    set_importance_hw_static(2, &slots[2]);
    set_resample_sw(1);
   #else
   #if PARTITIONING==9
    printf("\n####   P A R T I T I O N I N G    H W   IIOO   #####");
    set_sample_sw(1);
    set_observe_sw(1);
    set_observe_hw_static(2, &slots[0], parameter_o, 2);
    set_importance_sw(1);
    set_importance_hw_static(2, &slots[2]);
    set_resample_sw(1);
   #endif
   #endif
   #endif
   #endif
   #endif
   #endif
   #endif
   #endif
   #endif
   #else
    //printf("\n#  N O  P A R T I T I O N I N G   D E F I N E D #");
    printf("\n####   P A R T I T I O N I N G    S W   O   #####");
    reconf_mode_observation_on = TRUE;
    reconf_mode_observation_last_slot_on = FALSE;

    // I. SAMPLING ////////////////////////////////////////
    set_sample_sw(1);
    //set_sample_hw_dynamic(1, &hw_thread_s_circuit, parameter_s, 5);

    // II. OBSERVATION ////////////////////////////////////
    //set_observe_sw(1);
    set_observe_hw_dynamic(2, &hw_thread_o_circuit, parameter_o, 2);
    //set_observe_hw_dynamic(2, &hw_thread_o_circuit, parameter_o, 2);
    //set_observe_hw_static(1, &slots[2], parameter_o, 2);

    // III. IMPORTANCE ////////////////////////////////////
    set_importance_sw(1);
    //set_importance_hw_dynamic(1, &hw_thread_i_circuit);
    //set_importance_hw_dynamic(2, &hw_thread_i_circuit);
    set_importance_hw_static(1, &slots[2]); //[2]

    // IV. RESAMPLING /////////////////////////////////////
    set_resample_sw(1);
   #endif
   printf("\n#################################################");
   printf("\n#################################################\n");
   /*
   // create and start sorting thread
    init_all_network_interfaces();
    if(!eth0_up){
        printf("failed to initialize eth0\naborting\n");
        return NULL;
    }
    else{
        printf(" eth0 up\n");
    }  
   diag_printf( "initializing ECAP interface..." );
   ecap_init();
   diag_printf( "done\n" );*/
   //create_particle_filter(100, 10); 
   //set_observe_hw_dynamic(2, &hw_thread_o_circuit, 0, 0);
   //sw_test_thread = (cyg_thread *) malloc (sizeof(cyg_thread));
   //sw_test_thread_stack = (char *) malloc (sizeof(char) * STACK_SIZE);
   //sw_test_thread_handle = (cyg_handle_t *) malloc(sizeof(cyg_handle_t));
   /*cyg_thread_create(PRIO,                       // scheduling info (eg pri)  
                      test_thread,               // entry point function   
                      0,                         // entry data                
                      "TEST",                    // optional thread name      
                      //sw_test_thread_stack,      // stack base          
                      sw_measurement_thread_4_stack,    // stack base          
                      STACK_SIZE,                // stack size,       
                      //sw_test_thread_handle,     // returned thread handle 
                      &sw_measurement_thread_4_handle,  // returned thread handle  
                      //sw_test_thread             // put thread here 
                      &sw_measurement_thread_4          // put thread here 
          
     );

    // resume thread
    cyg_thread_resume(sw_measurement_thread_4_handle);*/
    //cyg_thread_resume(*sw_test_thread_handle);
   /*cyg_thread_create(PRIO,                             // scheduling info (eg pri)  
                      test_thread,               // entry point function     
                      0,                                // entry data                
                      "READ_MEASUREMENTS_4",            // optional thread name      
                      sw_measurement_thread_4_stack,    // stack base                
                      STACK_SIZE,                       // stack size,       
                      &sw_measurement_thread_4_handle,  // returned thread handle    
                      &sw_measurement_thread_4          // put thread here           
     );

    // resume thread
    cyg_thread_resume(sw_measurement_thread_4_handle);*/

   //cyg_thread_delay(1000);
   //diag_printf( "Reconfigure!\n" );
   /*old_number_of_sortings = 0;
   start_sorting();
   set_sort8k_hw_dynamicB(2);
   set_sort8k_hw_dynamic(2);
   cyg_thread_delay(1000);*/

   start_particle_filter();

   printf("\nstart particle filter");
   return NULL;
  }
Esempio n. 20
0
int main(int nNumberofArgs, char *argv[])
{
  //Test for correct input arguments
	if (nNumberofArgs!=5)
	{
		cout << "FATAL ERROR: wrong number of inputs. The program needs the path (with trailing slash), the filename prefix, the DEM file format, the window size in spatial units.";
		exit(EXIT_FAILURE);
	}

  //get input args
  string path = argv[1];
  string Prefix = argv[2];
  string DEM_Format = argv[3];
  int WindowSize = atoi(argv[4]);

  //surface fitting
  vector<int> raster_selection;
  raster_selection.push_back(0);
  raster_selection.push_back(1); //slope
  raster_selection.push_back(0);
	raster_selection.push_back(1); //curvature

  //set up a writer to write the output data
  ofstream WriteData;

  //create an output filename based on the dem name
  stringstream ss;

  ss << path << Prefix << "_ChtResData.txt";
  WriteData.open(ss.str().c_str());

  //write headers
  WriteData << "resoulution 2pc 25pc median mean 75pc 98pc minimum maximum" << endl;

  //array of resolutions to load
  int Resolutions[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  // vectors to hold the stats about the fitted surface
  vector<float> Curv_vec;

	//set boundary conditions
  vector<string> BoundaryConditions(4, "No Flux");

  for (int a = 0; a < 10; ++a){

	  cout << "Processing DEM " << a+1 << " of " << "10" << endl;

		//load the DEM
    //build the string of the filename to load
		stringstream ss2;
		ss2 << path << Prefix << "_" << Resolutions[a] << "_DEM";
		LSDRaster DEM(ss2.str(), DEM_Format);

		//Fill
		float MinSlope = 0.0001;
		LSDRaster FilledDEM = DEM.fill(MinSlope);

	  int CurrentWindowSize = WindowSize;
	  vector<LSDRaster> Surfaces = FilledDEM.calculate_polyfit_surface_metrics(CurrentWindowSize, raster_selection);

		// get a flow info object
	  LSDFlowInfo FlowInfo(BoundaryConditions,FilledDEM);

	  //get stream net from channel heads
	  vector<int> sources = FlowInfo.Ingest_Channel_Heads((path+Prefix+"_CH"), "csv", 2);

	  LSDJunctionNetwork ChanNetwork(sources, FlowInfo);

		// extract hilltops
    LSDRaster hilltops = ChanNetwork.ExtractRidges(FlowInfo);
    LSDRaster Hilltops = ChanNetwork.ExtractHilltops(hilltops, Surfaces[1], 0.4);


    //get hilltop curvature using filter to remove positive curvatures
    LSDRaster cht_raster = FilledDEM.get_hilltop_curvature(Surfaces[3], Hilltops);
    LSDRaster CHT = FilledDEM.remove_positive_hilltop_curvature(cht_raster);

	  //go through the landscape and get every curvature value into a 1D vector
    Curv_vec = Flatten_Without_Nodata(CHT.get_RasterData(), CHT.get_NoDataValue());

    stringstream ss3;
    ss3 << path << Prefix << "_" << Resolutions[a] << "_Hist_CHT.txt";

    print_histogram(Curv_vec, 0.01, ss3.str());

    vector<float> Boxplot = BoxPlot(Curv_vec);

	  //write the values to the output file
	  WriteData << Resolutions[a] << " " << Boxplot[0] << " " << Boxplot[1] << " " << Boxplot[2] << " " << Boxplot[3] << " " << Boxplot[4] << " " << Boxplot[5] << " " << Boxplot[6] << " " << Boxplot[7];

		WriteData << endl;

  }
  WriteData.close();

}
int main(int argc, char *argv[])
{
	int pseudo_hash[NHASH];
	int x, y, z;

	clear_array(pseudo_hash, NHASH);
	for (x = -5; x <= 5; x++) {
		for (y = -5; y <= 5; y++) {
			struct point p;
			p.x = x;
			p.y = y;
			pseudo_hash[hash_point(&p)]++;
		}
	}
	printf("2D integer\n");
	print_histogram(pseudo_hash, NHASH);

	printf("\n");

	clear_array(pseudo_hash, NHASH);
	for (x = -5; x <= 5; x++) {
		for (y = -5; y <= 5; y++) {
			struct point_polar p;
			p.r = sqrt(x * x + y * y);
			p.theta = atan2(y, x);
			pseudo_hash[hash_point_polar(&p)]++;
		}
	}
	printf("2D integer polar\n");
	print_histogram(pseudo_hash, NHASH);
	printf("\n");

	clear_array(pseudo_hash, NHASH);
	for (x = -4; x <= 4; x++) {
		for (y = -4; y <= 4; y++) {
			for (z = -4; z <= 4; z++) {
				struct point_3d p;
				p.x = x;
				p.y = y;
				p.z = z;
				pseudo_hash[hash_point_3d(&p)]++;
			}
		}
	}
	printf("3D integer\n");
	print_histogram(pseudo_hash, NHASH);

	printf("\n");

	clear_array(pseudo_hash, NHASH);
	for (x = -5; x <= 5; x++) {
		for (y = -5; y <= 5; y++) {
			struct point_float p;
			p.x = cos(x);
			p.y = tan(y);
			pseudo_hash[hash_point_float(&p)]++;
		}
	}
	printf("2D float\n");
	print_histogram(pseudo_hash, NHASH);

	printf("\n");

	clear_array(pseudo_hash, NHASH);
	for (x = -5; x <= 5; x++) {
		for (y = -5; y <= 5; y++) {
			struct point_float p;
			p.x = x / 100.0;
			p.y = y / 100.0;
			pseudo_hash[hash_point_float(&p)]++;
		}
	}
	printf("2D float, closely spaced\n");
	print_histogram(pseudo_hash, NHASH);

	printf("\n");

	clear_array(pseudo_hash, NHASH);
	for (x = -5; x <= 5; x++) {
		for (y = -5; y <= 5; y++) {
			struct point_float p;
			p.x = x / 1000.0;
			p.y = y / 1000.0;
			pseudo_hash[hash_point_float(&p)]++;
		}
	}
	printf("2D float, very closely spaced\n");
	print_histogram(pseudo_hash, NHASH);

	return 0;
}
Esempio n. 22
0
int main(int argc, char* argv[]) {

	// declarations
	struct stat st;
	unsigned int nBlocks, i;
	block_t *blocks;
	struct timespec begin, end;
	histogram_t histogram = {0};
	char *filename = "war_and_peace.txt";
	long num_threads = 1, repetitions=0;

	// argument handling
	if (argc < 2 || argc > 4) {
		printf("usage: %s filename [#threads] [#repetition]\n", argv[0]);
		return 1;
	}
	if (argc >= 2)
		filename = argv[1];
	if (argc >= 3)
		if ((num_threads = strtol(argv[2], NULL, 0)) == 0 || num_threads < 0) {
    			fprintf(stderr, "#threads not valid!\n");
    			return 1;
  		}
	if (argc >= 4)
		if ((repetitions = strtol(argv[3], NULL, 0)) == 0 || repetitions < 0) {
    	fprintf(stderr, "#repetition not valid!\n");
    	return 1;
  	}

 	printf("\nProcess %s by %ld thread(s) with %ld repetition(s)\n\n", 
		filename, num_threads, repetitions);

	// get file size and allocate array
	stat(filename, &st);
	nBlocks = st.st_size / BLOCKSIZE;
	nBlocks += (st.st_size % BLOCKSIZE) == 0 ? 0 : 1;
	blocks = (block_t*)calloc(nBlocks, BLOCKSIZE * (repetitions+1)); //numb of elts alocated is nBlock, size of each elt is blocksize*(rep+1)

	// open file and read all blocks
	FILE *fp = fopen(filename, "r");
	if (fp == NULL) {
		fprintf(stderr, "Could not open file %s", filename);
		exit(EXIT_FAILURE);
	}
	if (fread(blocks, BLOCKSIZE, nBlocks, fp) == 0) {
		fprintf(stderr, "Could not read from file %s", filename);
		exit(EXIT_FAILURE);
	}

	// [optional] do the repetition
	for (i = 1; i < repetitions; i++)
		memcpy(blocks + i*nBlocks, blocks, nBlocks*BLOCKSIZE);

	// build the histogram	
	clock_gettime(CLOCK_MONOTONIC, &begin);
	get_histogram(nBlocks*(repetitions+1), blocks, histogram, num_threads);
	clock_gettime(CLOCK_MONOTONIC, &end);

	free(blocks);
	print_histogram(histogram);
	printf("\n\nTime: %.5f seconds\n", ((double)end.tv_sec + 1.0e-9*end.tv_nsec) -
									   ((double)begin.tv_sec + 1.0e-9*begin.tv_nsec));

	return 0;
}
int main (int nNumberofArgs,char *argv[])
{

  //Test for correct input arguments
	if (nNumberofArgs!=7)
	{
		cout << "FATAL ERROR: wrong number of inputs. The program needs the path (with trailing slash), the filename prefix, the DEM file format, the window radius, ";
    cout << "basin order, and a switch to write rasters if desired." << endl;
		exit(EXIT_SUCCESS);
	}

  //load input arguments
  string Path = argv[1];
	string Prefix = argv[2];
  string DEM_Format = argv[3];
  float window_radius = atof(argv[4]); //6
  int BasinOrder = atoi(argv[5]);  //2
  int WriteRasters = atoi(argv[6]);  //0 (do not write rasters) or 1 (write rasters)

  //set up writers to write the output data
  stringstream ssLH;
  stringstream ssR;
  ssLH << Path << Prefix << "_LHResData_variable.txt";
  ssR << Path << Prefix << "_RResData_variable.txt";

  ofstream WriteLHData;
  WriteLHData.open(ssLH.str().c_str());
  ofstream WriteRData;
  WriteRData.open(ssR.str().c_str());

  //write headers
  WriteLHData << "resolution 2pc 25pc median mean 75pc 98pc minimum maximum" << endl;
  WriteRData << "resolution 2pc 25pc median mean 75pc 98pc minimum maximum" << endl;

  //set boundary conditions
  vector<string> BoundaryConditions(4, "No Flux");

  //array of resolutions to load
  int Resolutions[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};

  for (int a = 0; a < 19; ++a){
	  cout << "Processing DEM " << a+1 << " of " << "19" << endl;

    //create an output filename based on the dem name and the resolution
    stringstream ss;
    ss << Path << Prefix << "_" << Resolutions[a];
    string Filename = ss.str();

    //load dem
    LSDRaster DEM((Filename + "_DEM"), DEM_Format);

    stringstream ssa;
    ssa << Path << Prefix << "_" << Resolutions[a] << "_variable";
    string Filename_variable = ssa.str();

    //Fill
    float MinSlope = 0.0001;
    LSDRaster FilledDEM = DEM.fill(MinSlope);

    //surface fitting
    vector<int> raster_selection;

    raster_selection.push_back(0);
    raster_selection.push_back(1); //slope
    raster_selection.push_back(1); //aspect
    raster_selection.push_back(1); //curvature
    raster_selection.push_back(1); //plan curvature
    raster_selection.push_back(0);
    raster_selection.push_back(0);
    raster_selection.push_back(0);

    int CurrentWindowSize = window_radius;

    vector<LSDRaster> Surfaces = FilledDEM.calculate_polyfit_surface_metrics(CurrentWindowSize, raster_selection);
    LSDRaster slope = Surfaces[1];
    LSDRaster aspect = Surfaces[2];

    cout << "\nGetting drainage network and basins\n" << endl;

    // get a flow info object
  	LSDFlowInfo FlowInfo(BoundaryConditions,FilledDEM);

    //get stream net from channel heads
    stringstream ss_ch;
    ss_ch << Path << "Pelletier/" << Prefix << "_" << Resolutions[a] << "_CH";

    vector<int> sources = FlowInfo.Ingest_Channel_Heads(ss_ch.str(), "bil");
    LSDJunctionNetwork ChanNetwork(sources, FlowInfo);
    LSDIndexRaster StreamNetwork = ChanNetwork.StreamOrderArray_to_LSDIndexRaster();

    //Extract basins based on input stream order
    vector< int > basin_junctions = ChanNetwork.ExtractBasinJunctionOrder(BasinOrder, FlowInfo);
    LSDIndexRaster Basin_Raster = ChanNetwork.extract_basins_from_junction_vector(basin_junctions, FlowInfo);

    cout << "\nExtracting hilltops and hilltop curvature" << endl;

    // extract hilltops - no critical slope filtering is performed here
    LSDRaster hilltops = ChanNetwork.ExtractRidges(FlowInfo);

    //get hilltop curvature using filter to remove positive curvatures
    LSDRaster cht_raster = FilledDEM.get_hilltop_curvature(Surfaces[3], hilltops);
    LSDRaster CHT = FilledDEM.remove_positive_hilltop_curvature(cht_raster);

    cout << "Starting hilltop flow routing\n" << endl;

    // these params do not need changed during normal use of the HFR algorithm
    bool print_paths_switch = false;
    int thinning = 1;
    string trace_path = "";
    bool basin_filter_switch = false;
    vector<int> Target_Basin_Vector;

    //run HFR
    vector< Array2D<float> > HFR_Arrays = FlowInfo.HilltopFlowRouting(FilledDEM, hilltops, slope, StreamNetwork, aspect, Filename_variable, Basin_Raster, Surfaces[4], print_paths_switch, thinning, trace_path, basin_filter_switch, Target_Basin_Vector);

    LSDRaster HFR_LH = hilltops.LSDRasterTemplate(HFR_Arrays[1]);
    LSDRaster relief = hilltops.LSDRasterTemplate(HFR_Arrays[3]);

    //Filter Relief and LH data to remove any values < 2 pixels, as in Grieve et al (2015)
    LSDRaster LH1 = HFR_LH.RemoveBelow(2.0*Resolutions[a]);
    LSDRaster Relief1 = relief.RemoveBelow(2.0*Resolutions[a]);

    //Filter Relief and LH data to remove any values > 10000
    //These are created due to using 1m channel heads on low res data, and inadvertantly
    //sampling nodata values, which gives us massive relief values
    LSDRaster LH = LH1.RemoveAbove(10000);
    LSDRaster Relief = Relief1.RemoveAbove(10000);

    //go through the lh raster and get every value into a 1D vector
    vector<float> LH_vec = Flatten_Without_Nodata(LH.get_RasterData(), LH.get_NoDataValue());
    vector<float> Boxplot = BoxPlot(LH_vec);

    //write the values to the output file
    WriteLHData << Resolutions[a] << " " << Boxplot[0] << " " << Boxplot[1] << " " << Boxplot[2] << " " << Boxplot[3] << " " << Boxplot[4] << " " << Boxplot[5] << " " << Boxplot[6] << " " << Boxplot[7];

    WriteLHData << endl;

    stringstream ss3;
    ss3 << Path << Prefix << "_" << Resolutions[a] << "_Hist_LH_variable.txt";
    print_histogram(LH_vec, 1, ss3.str());

    //go through the relief raster and get every value into a 1D vector
    vector<float> R_vec = Flatten_Without_Nodata(Relief.get_RasterData(), Relief.get_NoDataValue());
    vector<float> Boxplot_R = BoxPlot(R_vec);

    //write the values to the output file
    WriteRData << Resolutions[a] << " " << Boxplot_R[0] << " " << Boxplot_R[1] << " " << Boxplot_R[2] << " " << Boxplot_R[3] << " " << Boxplot_R[4] << " " << Boxplot_R[5] << " " << Boxplot_R[6] << " " << Boxplot_R[7];

    WriteRData << endl;

    stringstream ss4;
    ss4 << Path << Prefix << "_" << Resolutions[a] << "_Hist_R_variable.txt";
    print_histogram(R_vec, 1, ss4.str());

    //if the user requests the rasters to be written, write the rasters
    if (WriteRasters == 1){
      cout << "Writing Rasters\n" << endl;

      Surfaces[1].write_raster((Filename + "_Slope_variable"), DEM_Format);
      CHT.write_raster((Filename + "_CHT_variable"), DEM_Format);
      LH.write_raster((Filename + "_HFR_LH_variable"), DEM_Format);
      Relief.write_raster((Filename + "_Relief_variable"), DEM_Format);

    }
  }
    WriteLHData.close();
    WriteRData.close();
}