Esempio n. 1
0
/* Prints the current values of u. */
void write_frame() {
  if (rank != 0) {
    MPI_Send(u+1, nxl, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
  } else {
    print_time_header();
    print_cell(lbound); // left boundary
    for (int source = 0; source < nprocs; source++) {
      int count;

      if (source != 0) {
        MPI_Status status;

        MPI_Recv(buf, 1+nx/nprocs, MPI_DOUBLE, source, 0, MPI_COMM_WORLD,
                 &status);
        MPI_Get_count(&status, MPI_DOUBLE, &count);
      } else {
        for (int i = 1; i <= nxl; i++)
          buf[i-1] = u[i];
        count = nxl;
      }
      for (int i = 0; i < count; i++)
        print_cell(buf[i]);
    }
    print_cell(rbound); // right boundary
    //printf("\n");
  }
}
void time_copy_container(I first, I last, size_t iterations, size_t max_size) {
  C c(first, last);
  double t0 = time_copy_into_vector(begin(c), end(c), iterations);

  C c1(c);
  double t1 = time_copy_into_vector(begin(c1), end(c1), iterations);

  print_cell(t0 / max_size);
  print_cell(t1 / max_size);
  print_cell(t0 / t1, 1);
}
Esempio n. 3
0
void LExec::DumpStack()
{
  CHOICE_POINTptr Bx;
  ENVptr          Ex;
  FILE*           f;
  
  //f = pLOG->GetLogFile();
  //if (f == NULL)
  f = fopen("dump", "a");
  
  fprintf(f, "\n-----Dumping Choice Points-----\n\n");
  
  for(Bx=pCNTL->BTop(); Bx!=NULL; Bx=Bx->Bc)
	 {
      fprintf(f, "B= %p\n", Bx);
#ifdef xBUG_CODE
      fprintf(f, "  HBc= %p, H[%d] ", Bx->HBc, Bx->HBc -Heap);
      if (IsMscw(Bx->HBc -2))
		  {
			 print_cell(Bx->HBc -2, 0);
		  }
      else fprintf(f, "\n");
#endif
	 }
  
  fprintf(f, "\n-----Dumping Environments-----\n\n");
  for(Ex=pCNTL->ETop(); Ex!=NULL; Ex=Ex->Ee)
	 {
      fprintf(f, "E = %p\n", Ex);
	 }
  //   fclose(f);
  return;
}
Esempio n. 4
0
static void load_code_heap(FILE *file, image_header *h, vm_parameters *p)
{
	cell good_size = h->code_size + (1 << 19);

	if(good_size > p->code_size)
		p->code_size = good_size;

	init_code_heap(p->code_size);

	if(h->code_size != 0)
	{
		size_t bytes_read = fread(first_block(&code),1,h->code_size,file);
		if(bytes_read != h->code_size)
		{
			print_string("truncated image: ");
			print_fixnum(bytes_read);
			print_string(" bytes read, ");
			print_cell(h->code_size);
			print_string(" bytes expected\n");
			fatal_error("load_code_heap failed",0);
		}
	}

	code_relocation_base = h->code_relocation_base;
	build_free_list(&code,h->code_size);
}
Esempio n. 5
0
void factor_vm::load_data_heap(FILE *file, image_header *h, vm_parameters *p)
{
	cell good_size = h->data_size + (1 << 20);

	if(good_size > p->tenured_size)
		p->tenured_size = good_size;

	init_data_heap(p->young_size,
		p->aging_size,
		p->tenured_size,
		p->secure_gc);

	clear_gc_stats();

	fixnum bytes_read = fread((void*)data->tenured->start,1,h->data_size,file);

	if((cell)bytes_read != h->data_size)
	{
		print_string("truncated image: ");
		print_fixnum(bytes_read);
		print_string(" bytes read, ");
		print_cell(h->data_size);
		print_string(" bytes expected\n");
		fatal_error("load_data_heap failed",0);
	}

	data->tenured->here = data->tenured->start + h->data_size;
}
Esempio n. 6
0
static void load_data_heap(FILE *file, image_header *h, vm_parameters *p)
{
	cell good_size = h->data_size + (1 << 20);

	if(good_size > p->tenured_size)
		p->tenured_size = good_size;

	init_data_heap(p->gen_count,
		p->young_size,
		p->aging_size,
		p->tenured_size,
		p->secure_gc);

	clear_gc_stats();

	zone *tenured = &data->generations[data->tenured()];

	fixnum bytes_read = fread((void*)tenured->start,1,h->data_size,file);

	if((cell)bytes_read != h->data_size)
	{
		print_string("truncated image: ");
		print_fixnum(bytes_read);
		print_string(" bytes read, ");
		print_cell(h->data_size);
		print_string(" bytes expected\n");
		fatal_error("load_data_heap failed",0);
	}

	tenured->here = tenured->start + h->data_size;
	data_relocation_base = h->data_relocation_base;
}
void run_test(size_t min_size, size_t max_size) {
  time_t now = time(0);
  std::cout << "Iterating over " << type_description(T(0))
            << " from " << min_size << " up to " << max_size
            << " elements at: " << asctime(localtime(&now));

  std::vector<const char*> names {
    "   vec",
    "   set",
    "  copy",
    " ratio",
    " h-set",
    "h-copy",
    " ratio"
  };
  std::cout << std::setw(12) << "size";
  for (auto x: names) print_cell(x);
  std::cout << std::endl;

  std::vector<T> vec(max_size);
  random_iota(begin(vec), end(vec));
  for (size_t array_size(min_size); array_size <= max_size; array_size *= 2) {
    const size_t n = (max_size / array_size);
    auto last = begin(vec) + array_size;

    std::cout << std::setw(12) << array_size;

    time_copy_vector(begin(vec), last, n, max_size);
    time_copy_container<std::set<T>>(begin(vec), last, n, max_size);
    time_copy_container<std::unordered_set<T>>(begin(vec), last, n, max_size);
    std::cout << std::endl;
  }
}
Esempio n. 8
0
static void emit(buffer *b, int s, int c)
{
	if (c == '\n') {
		if (pi > 0) print_cell(b, s, row, col, instring);
		pi = 0;
		row++;
		col = 1;
	} else if (strchr(ifs, c)) {
		if (pi > 0) print_cell(b, s, row, col, instring);
		pi = 0;
		col++;
	} else {
		instring[pi++] = c;
	}
	instring[pi] = 0;
}
Esempio n. 9
0
CELL *
bi_print(
        CELL *sp)        /* stack ptr passed in */
{
    register CELL *p;
    register int k;
    FILE *fp;

    k = sp->type;
    if (k < 0) {
    /* k holds redirection */
    if ((--sp)->type < C_STRING)
        cast1_to_s(sp);
    fp = (FILE *) file_find(string(sp), k);
    free_STRING(string(sp));
    k = (--sp)->type;
    /* k now has number of arguments */
    } else
    fp = stdout;

    if (k) {
    p = sp - k;        /* clear k variables off the stack */
    sp = p - 1;
    k--;

    while (k > 0) {
        print_cell(p, fp);
        print_cell(OFS, fp);
        cell_destroy(p);
        p++;
        k--;
    }

    print_cell(p, fp);
    cell_destroy(p);
    } else {            /* print $0 */
    sp--;
    print_cell(&field[0], fp);
    }

    print_cell(ORS, fp);
    if (ferror(fp))
    write_error();
    return sp;
}
Esempio n. 10
0
static void set_end_of_first (plocal_propagate_store_t * pv, int x, int y,
			     int state, cell * end_of_first){
#ifdef DEBUG
  if (y > pv->len_y || state > pv->mo->N || y < - pv->mo->max_offset_y) {
    fprintf(stderr, "set_end_of_first: out of bounds %i %i %i\n", 
	    x + pv->mo->max_offset_x, y + pv->mo->max_offset_y, 
	    state);
    print_cell(end_of_first);
  }
#endif
  pv->end_of_first[0][y + pv->mo->max_offset_y][state] = end_of_first;
}
Esempio n. 11
0
void print_field()
{
	print_dashline();
	for (int i = 0; i < SIZE; i++) {
		putchar('|');
		for (int j = 0; j < SIZE; j++) {
			print_cell(field[i][j]);
		}
		putchar('|');
		printf("\n");
	}
	print_dashline();
}
Esempio n. 12
0
void cell_spin(int rank, int ncell, MPI_Comm comm)
{
    cell_list cells;
    int i;
    int msg;
    cells = make_cell_list();
    /* Build the list of cells */
    for ( i = 0; i < ncell; i++ ) {
        if ( rank == get_cell_rank(i) ) {
            push(make_cell(i), &(cells->cells));
        }
    }
    i = 0;
    /* Loop, updating the list of cells.  Every time through the loop,
     * we look to see if we have a control message (from the master)
     * and if so, act accordingly (reset cells for end of year, or
     * finish simulation).  Note the the control message could arrive
     * while in the update_cell_list function, so that also probes for
     * interrupts and returns early if it gets one. */
    do {
        MPI_Status status;
        int flag;
        msg = -1;
        update_cell_list(cells, comm);
        MPI_Iprobe(0, CONTROL_TAG, comm, &flag, &status);
        if ( flag ) {
            MPI_Recv(&msg, 1, MPI_INT, status.MPI_SOURCE,
                     status.MPI_TAG, comm, &status);
        }
        if ( msg == YEAR_END ) {
            list it;
            for ( it = cells->cells; it; it = it->next ) {
                print_cell((cell)(it->data));
            }
            reset_cell_list(cells);
        }
    } while ( msg != SIMULATION_END )
        ;

    delete_cell_list(cells);
}
Esempio n. 13
0
/* 
 * prints the cell line. we either need to print yaxis labels, xaxis labels,
 * pegs, holes, or spaces. we also need to print an extra character on the end
 * of each row to complete the line.
 */
void print_cell_line (CELL_CONTENTS board[][BOARD_WIDTH], int row, int col)
{
	if ((col == 0) && (row != BOARD_DISPLAY_HEIGHT - 1)) {
		printf("  %d ", row + Y_OFFSET);
	} else if (row == BOARD_DISPLAY_HEIGHT - 1) {
		if (col == 0)
			print_spaces(board, row, col, CELL_LINE);
		else
			printf("  %c ", (char)(col - LABEL_LEN) + X_OFFSET);
	} else if ((col != 0) && (row != BOARD_DISPLAY_HEIGHT - 1)) {
		print_cell(board, row, col);
	}

	if (col == BOARD_DISPLAY_WIDTH - 1) {
		if (get_contents(board, row, col) != INVALID) {
			printf(COLOR_LINES);
			putchar('|');
			printf(COLOR_RESET);
		} else {
			putchar(' ');
		}
	}
}
Esempio n. 14
0
void factor_vm::load_code_heap(FILE *file, image_header *h, vm_parameters *p)
{
	if(h->code_size > p->code_size)
		fatal_error("Code heap too small to fit image",h->code_size);

	init_code_heap(p->code_size);

	if(h->code_size != 0)
	{
		size_t bytes_read = fread(code->first_block(),1,h->code_size,file);
		if(bytes_read != h->code_size)
		{
			print_string("truncated image: ");
			print_fixnum(bytes_read);
			print_string(" bytes read, ");
			print_cell(h->code_size);
			print_string(" bytes expected\n");
			fatal_error("load_code_heap failed",0);
		}
	}

	code->build_free_list(h->code_size);
}
Esempio n. 15
0
/* Dump all code blocks for debugging */
void dump_heap(F_HEAP *heap)
{
	CELL size = 0;

	F_BLOCK *scan = first_block(heap);

	while(scan)
	{
		char *status;
		switch(scan->status)
		{
		case B_FREE:
			status = "free";
			break;
		case B_ALLOCATED:
			size += object_size(block_to_compiled(scan)->relocation);
			status = "allocated";
			break;
		case B_MARKED:
			size += object_size(block_to_compiled(scan)->relocation);
			status = "marked";
			break;
		default:
			status = "invalid";
			break;
		}

		print_cell_hex((CELL)scan); print_string(" ");
		print_cell_hex(scan->size); print_string(" ");
		print_string(status); print_string("\n");

		scan = next_block(heap,scan);
	}
	
	print_cell(size); print_string(" bytes of relocation data\n");
}
Esempio n. 16
0
void
txt_print_region (struct rng *print, FILE *fp)
{
  CELLREF rr, cc;
  CELL *cp;
  char *ptr;
  int w;
  int j;
  int lenstr;
  int spaces;
  CELLREF c_lo, c_hi;

  for (c_lo = print->lc, c_hi = 0; c_hi != print->hc; c_lo = c_hi + 1)
    {
      w = 0;
      for (w = get_width (cc = c_lo); w <= print_width && cc <= print->hc; w += get_width (++cc))
	;
      if (cc != c_lo)
	--cc;
      c_hi = cc;

      for (rr = print->lr; rr <= print->hr; rr++)
	{
	  spaces = 0;
	  for (cc = c_lo; cc <= c_hi; cc++)
	    {
	      w = get_width (cc);
	      if (!w)
		continue;
	      cp = find_cell (rr, cc);
	      if (!cp || !GET_TYP (cp))
		{
		  spaces += w;
		  continue;
		}
	      ptr = print_cell (cp);
	      lenstr = strlen (ptr);
	      if (lenstr == 0)
		{
		  spaces += w;
		  continue;
		}
	      if (spaces)
		{
		  fprintf (fp, "%*s", spaces, "");
		  spaces = 0;
		}
	      j = GET_JST (cp);
	      if (j == JST_DEF)
		j = default_jst;
	      if (lenstr <= w - 1)
		{
		  if (j == JST_LFT)
		    {
		      fprintf (fp, "%s", ptr);
		      spaces = w - lenstr;
		    }
		  else if (j == JST_RGT)
		    {
		      fprintf (fp, "%*s", w - 1, ptr);
		      spaces = 1;
		    }
		  else if (j == JST_CNT)
		    {
		      w = (w - 1) - lenstr;
		      fprintf (fp, "%*s", w / 2 + lenstr, ptr);
		      spaces = (w + 3) / 2;
		    }
#ifdef TEST
		  else
		    {
		      panic ("What just %d", j);
		    }
#endif
		}
	      else
		{
		  CELLREF ccc = cc;
		  CELL *ccp;
		  int tmp_wid;
		  unsigned int ww;

		  for (ww = w;; tmp_wid = get_width (ccc), w += tmp_wid, spaces -= tmp_wid)
		    {
		      if (lenstr < w - 1)
			break;
		      if (++ccc > c_hi)
			break;
		      ccp = find_cell (rr, ccc);
		      if (!ccp || !GET_TYP (ccp) || GET_FORMAT (ccp) == FMT_HID)
			continue;
		      if (GET_FORMAT (ccp) == FMT_DEF && default_fmt == FMT_HID)
			continue;
		      break;
		    }
		  if (lenstr > w - 1)
		    {
		      if (GET_TYP (cp) == TYP_FLT)
			{
			  ptr = adjust_prc (ptr, cp, w - 1, ww - 1, j);
			  lenstr = strlen (ptr);
			}
		      else if (GET_TYP (cp) == TYP_INT)
			{
			  ptr = numb_oflo;
			  lenstr = 80;
			}
		      fprintf (fp, "%.*s", w - 1, ptr);
		      if (lenstr < w)
			spaces += w - lenstr;
		      else
			spaces++;
		    }
		  else
		    {
		      fprintf (fp, "%s", ptr);
		      spaces += w - lenstr;
		    }
		}
	    }
	  (void) putc ('\n', fp);
	}
    }
}
Esempio n. 17
0
void main(int argc, char* argv[]) {
    
    int my_rank, comm_size;
	int arr_size_x, arr_size_y;
    int i,j,count,livecount,totalcount;
    char intmp[10];
    double start_time, end_time, elapsed_time, all_time;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
    MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);

    if(my_rank==0){
	    printf("Enter array size:");
	    scanf("%d %d",&arr_size_x, &arr_size_y);
    }

    // include ghost cell size to both
    arr_size_x += 2;
    arr_size_y += 2;

    MPI_Status status;
    // after broadcast each proc knows arr_size_x and arr_size_y
    MPI_Bcast(&arr_size_x, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&arr_size_y, 1, MPI_INT, 0, MPI_COMM_WORLD);


    // now we know how to divide the matrix vertically between ranks
    int rank_sub_arr_x = arr_size_x / comm_size;
    int rank_sub_arr_y = arr_size_y;
	//printf("PROC %d:%d %d\n",my_rank, rank_sub_arr_x, rank_sub_arr_y);

    /* Now only consider evenly distributed situation
     * i.e. 20 * 30 matrix size with 4 * 3 processes
     * TODO:possible residue
    int rank_sub_arr_x_res = arr_size_x + arr_size_x % comm_size;
    int rank_sub_arr_y_res = arr_size_y;
     */


    // allocate local storage
	int *old_loc_cell_1d = malloc((rank_sub_arr_x+2) * rank_sub_arr_y * sizeof(int));
	int **old_loc_cell = malloc((rank_sub_arr_x+2) * sizeof(int*));
	int *new_loc_cell_1d = malloc((rank_sub_arr_x+2) * rank_sub_arr_y * sizeof(int));
	int **new_loc_cell = malloc((rank_sub_arr_x+2) * sizeof(int*));
	int *tmp;

	int **cell;
	int print_ghostcell = 1;

	for(i = 0; i < (rank_sub_arr_x+2); i++){
		old_loc_cell[i] = &old_loc_cell_1d[i * rank_sub_arr_y];
		new_loc_cell[i] = &new_loc_cell_1d[i * rank_sub_arr_y];
	}


    // real rank sub-matrix size
    if(my_rank == 0 || my_rank == comm_size - 1)
    	rank_sub_arr_x++;
    else
    	rank_sub_arr_x += 2;

    if(my_rank == 0){

    			// proc 0 will generate and store the whole matrix
    			int *cell_1d = malloc(arr_size_x * arr_size_y * sizeof(int));
    			cell = malloc(arr_size_x * sizeof(int*));
    			for(i = 0; i < arr_size_x; i++){
    				cell[i] = &cell_1d[i * arr_size_y];
    			}

    			gen_life(cell, arr_size_x, arr_size_y);
    			//print_cell(cell, arr_size_x, arr_size_y, 1);

    			update_ghostcell(cell, arr_size_x, arr_size_y);
    			printf("Origin:\n");
    			print_cell(cell, arr_size_x, arr_size_y, print_ghostcell);
    }

    while(1){

    	start_time = MPI_Wtime();

		if(my_rank == 0){

			// distribute matrix
			// special operation to first: just copy, no need to send.
			for(i = 0; i < rank_sub_arr_x ; i++){
				for(j = 0; j < rank_sub_arr_y; j++)
					old_loc_cell[i][j] = cell[i][j];
			}
			// send to last rank
			MPI_Send(cell[(comm_size - 1) * (rank_sub_arr_x - 1) - 1], rank_sub_arr_x * rank_sub_arr_y
					, MPI_INT, comm_size - 1, 0, MPI_COMM_WORLD);

			// all other ranks
			for(i = 1; i < comm_size - 1; i++){
				MPI_Send(cell[((rank_sub_arr_x - 1) * i) - 1], (rank_sub_arr_x + 1) * rank_sub_arr_y, MPI_INT, i, 0, MPI_COMM_WORLD);
			}

		}


		if(my_rank != 0)
			MPI_Recv(old_loc_cell[0], rank_sub_arr_x * rank_sub_arr_y, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);

	#if DEBUG
		printf("From Proc %d:\n", my_rank);
		print_cell(old_loc_cell, rank_sub_arr_x, rank_sub_arr_y, print_ghostcell);
	#endif

		// populate
		livecount = polpulate(old_loc_cell, new_loc_cell, rank_sub_arr_x, rank_sub_arr_y);
		MPI_Reduce(&livecount, &totalcount, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

	#if DEBUG
		printf("After Popoulate from Proc %d:\n", my_rank);
		print_cell(old_loc_cell, rank_sub_arr_x, rank_sub_arr_y, print_ghostcell);
	#endif


		// collect results
		if(my_rank == 0){
			for(i = 1; i < comm_size; i++)
				MPI_Recv(cell[i * (rank_sub_arr_x - 1)], (rank_sub_arr_x - 1) * rank_sub_arr_y, MPI_INT, i, i, MPI_COMM_WORLD, &status);

			for(i = 1; i < rank_sub_arr_x - 1; i++){
				for(j = 0; j < rank_sub_arr_y; j++)
					cell[i][j] = new_loc_cell[i][j];
			}

			update_ghostcell(cell, arr_size_x, arr_size_y);
	    	printf("Living cells:%d\n", totalcount);
			print_cell(cell, arr_size_x, arr_size_y, print_ghostcell);

		}
		else{
			// only send row 1 ~ rank_sub_arr_x - 1
			MPI_Send(new_loc_cell[1], (rank_sub_arr_x - 2) * rank_sub_arr_y, MPI_INT, 0, my_rank, MPI_COMM_WORLD);
		}

    	end_time = MPI_Wtime();
    	elapsed_time = end_time - start_time;
		MPI_Reduce(&elapsed_time, &all_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);

    	if(my_rank == 0){

    		printf("Time needed: %f\n", all_time);

    		printf("Enter n to proceed, q to exit\n");
			scanf("%s",intmp);

			if(totalcount<=0){
				printf("All died out!\n");
				strcpy(intmp,"q"); //no need to go on once all died
			}
			MPI_Bcast(intmp, 10, MPI_CHAR, 0, MPI_COMM_WORLD);
			if(strcmp(intmp,"q")==0)
				break;
    	}
    	else{

	        MPI_Bcast(intmp, 10, MPI_CHAR, 0, MPI_COMM_WORLD);
	    	if(strcmp(intmp,"q")==0)
	    		break;
    	}

    }

	MPI_Finalize();

}
Esempio n. 18
0
int
cmp_cells (int n1, int n2)
{
  CELL *c1, *c2;
  int t1, t2;
  union vals v1, v2;
  CELLREF row1, row2, col1, col2;
  int keyn;
  int cmpval;

  if (n1 == n2)
    return 0;

  for (keyn = 0; keyn < sort_keys_num; keyn++)
    {
      row1 = sort_rng.lr + (n1 * erdiff) + sort_keys[keyn].row;
      col1 = sort_rng.lc + (n1 * ecdiff) + sort_keys[keyn].col;
      row2 = sort_rng.lr + (n2 * erdiff) + sort_keys[keyn].row;
      col2 = sort_rng.lc + (n2 * ecdiff) + sort_keys[keyn].col;
#ifdef TEST
      if (debug & 04)
	io_error_msg ("Cmp %u %u  r%uc%u <-%u-> r%uc%u", n1, n2, row1, col1, sort_keys[keyn].mult, row2, col2);
#endif
      c1 = find_cell (row1, col1);
      c2 = find_cell (row2, col2);
      if (!c1 && !c2)
	continue;

      if (c1)
	{
	  t1 = GET_TYP (c1);
	  v1 = c1->c_z;
	}
      else
	t1 = 0;
      if (c2)
	{
	  t2 = GET_TYP (c2);
	  v2 = c2->c_z;
	}
      else
	t2 = 0;

      if (t1 == TYP_ERR || t1 == TYP_BOL)
	{
	  t1 = TYP_STR;
	  v1.c_s = print_cell (c1);
	}
      if (t2 == TYP_ERR || t2 == TYP_BOL)
	{
	  t2 = TYP_STR;
	  v2.c_s = print_cell (c2);
	}
      if (t1 != t2)
	{
	  if (t1 == 0)
	    {
	      if (t2 == TYP_STR)
		{
		  t1 = TYP_STR;
		  v1.c_s = "";
		}
	      else if (t2 == TYP_INT)
		{
		  t1 = TYP_INT;
		  v1.c_l = 0;
		}
	      else
		{
		  t1 = TYP_FLT;
		  v1.c_d = 0.0;
		}
	    }
	  else if (t2 == 0)
	    {
	      if (t1 == TYP_STR)
		{
		  t2 = TYP_STR;
		  v2.c_s = "";
		}
	      else if (t1 == TYP_INT)
		{
		  t2 = TYP_INT;
		  v2.c_l = 0;
		}
	      else
		{
		  t2 = TYP_FLT;
		  v2.c_d = 0.0;
		}
	    }
	  else if (t1 == TYP_STR)
	    {
	      t2 = TYP_STR;
	      v2.c_s = print_cell (c2);
	    }
	  else if (t2 == TYP_STR)
	    {
	      t1 = TYP_STR;
	      v1.c_s = print_cell (c1);
	      /* If we get here, one is INT, and the other
			   is FLT  Make them both FLT */
	    }
	  else if (t1 == TYP_INT)
	    {
	      t1 = TYP_FLT;
	      v1.c_d = (double) v1.c_l;
	    }
	  else
	    {
	      t2 = TYP_FLT;
	      v2.c_d = (double) v2.c_l;
	    }
	}
      if (t1 == TYP_STR)
	cmpval = strcmp (v1.c_s, v2.c_s);
      else if (t1 == TYP_FLT)
	cmpval = (v1.c_d < v2.c_d) ? -1 : ((v1.c_d > v2.c_d) ? 1 : 0);
      else if (t1 == TYP_INT)
	cmpval = (v1.c_l < v2.c_l) ? -1 : ((v1.c_l > v2.c_l) ? 1 : 0);
      else
	cmpval = 0;
      if (cmpval)
	return cmpval * sort_keys[keyn].mult;
    }

  return 0;
}
Esempio n. 19
0
/**
 * Append entry to list of found items
 *
 * @param __dir - directory where item has been found
 * @param __name - name of item
 * @param __stat - stat information of item
 * @param __res_wnd - window with results
 */
static void
append_result (const wchar_t *__dir, const wchar_t *__name, vfs_stat_t __stat,
               action_find_res_wnd_t *__res_wnd)
{
  wchar_t *string, *dummy;
  size_t len, tmp_len;
  wchar_t buf[128];
  wchar_t suffix;
  w_list_item_t *item;

#ifdef __USE_FILE_OFFSET64
  __u64_t size;
  static wchar_t format[] = L"%lld %c";
#else
  __u32_t size;
  static wchar_t format[] = L"%ld %c";
#endif

  len = __res_wnd->list->position.width - 2;
  string = malloc ((len + 1) * sizeof (wchar_t));
  dummy = malloc ((len + 1) * sizeof (wchar_t));

  /* Append directory for which item belongs to */
  if (!__res_wnd->dir_opened)
    {
      size_t l;

      prepare_row (string, len);
      l = __res_wnd->list->position.width / 4 * 3 - 5;

      fit_dirname (__dir, l, dummy);
      print_cell (string, dummy, 0, len);
      print_cell (string, _(L"<DIR>"), l + 1, len);
      item = w_list_append_item (__res_wnd->list, string, FIND_RES_DIR);

      store_item_value (item, FIND_RES_DIR, __dir, NULL);

      __res_wnd->dir_opened = TRUE;
    }

  prepare_row (string, len);

  /* Name of file */
  fit_dirname (__name, __res_wnd->list->position.width / 2, dummy);
  print_cell (string, dummy, 4, len);

  /* Mode of file */
  umasktowcs (__stat.st_mode, buf);
  print_cell (string, buf, __res_wnd->list->position.width - 10, len);

  /* Modification time */
  format_file_time (buf, BUF_LEN (buf), __stat.st_mtime);
  print_cell (string, buf, __res_wnd->list->position.width - 24, len);

  /* Size of file */
  if (!S_ISDIR (__stat.st_mode))
    {
      size = fsizetohuman (__stat.st_size, &suffix);
      swprintf (buf, BUF_LEN(buf), format, size, suffix);
    }
  else
    {
      wcscpy (buf, _(L"<DIR>"));
    }
  tmp_len = wcslen (buf);
  if (buf[tmp_len - 1] == ' ')
    {
      buf[tmp_len - 1] = 0;
      --tmp_len;
    }
  print_cell (string, buf,
              __res_wnd->list->position.width - 26 - tmp_len, len);

  item = w_list_append_item (__res_wnd->list, string, FIND_RES_ITEM);

  store_item_value (item, FIND_RES_ITEM, __dir, __name);

  free (string);
  free (dummy);
}
void time_copy_vector(I first, I last, size_t iterations, size_t max_size) {
  double t = time_copy_into_vector(first, last, iterations);
  print_cell(t / max_size, 2);
}
Esempio n. 21
0
// START FUNC DECL
int
read_csv(
	 FLD_META_TYPE *flds,
	 int n_flds,
	 char *infile,
	 char *str_load_fld,
	 char fld_delim, /* double quote character */
	 char fld_sep, /* comma */
	 char rec_delim, /* new line character */
	 bool ignore_hdr, /* whether to ignore header or not */
	 bool is_null_null, /* whether to convert "null" to null */
	 char ***ptr_nn_fnames,
	 char ***ptr_sz_fnames,
	 long long *ptr_num_rows
	 )
// STOP FUNC DECL
{
  int status = 0;
  int *load_fld = NULL; int n_load_fld = 0;
  char *X = NULL; size_t nX = 0;
  bool in_fld, is_fld_delim;
  long long num_rows = 0; long long num_cells = 0, fld_idx; 
  long long lb, ub;
  FILE **fps = NULL; char **fnames = NULL;
  FILE **nn_fps = NULL; char **nn_fnames = NULL;
  FILE **sz_fps = NULL; char **sz_fnames = NULL;
  bool in_escape_mode = false, is_fld_delim_escaped = false;
  
  g_num_rows = 0;
  g_buflen = 8192;
  g_buffer = (char *)malloc(g_buflen * sizeof(char));
  return_if_malloc_failed(g_buffer);
  zero_string(g_buffer, g_buflen);

  /*----------------------------------------------------------------------------*/
  if ( n_flds <= 0 ) { go_BYE(-1); }
  fps = (FILE **)malloc(n_flds * sizeof(FILE *));
  return_if_malloc_failed(fps);
  fnames = (char **)malloc(n_flds * sizeof(char *));
  return_if_malloc_failed(fnames);

  nn_fps = (FILE **)malloc(n_flds * sizeof(FILE *));
  return_if_malloc_failed(nn_fps);
  nn_fnames = (char **)malloc(n_flds * sizeof(char *));
  return_if_malloc_failed(nn_fnames);

  sz_fps = (FILE **)malloc(n_flds * sizeof(FILE *));
  return_if_malloc_failed(sz_fps);
  sz_fnames = (char **)malloc(n_flds * sizeof(char *));
  return_if_malloc_failed(sz_fnames);

  for ( int i = 0; i < n_flds; i++ ) { 
    fps[i] = NULL;
    nn_fps[i] = NULL;
    sz_fps[i] = NULL;
    fnames[i] = nn_fnames[i] = sz_fnames[i] = NULL;
  }
  /*----------------------------------------------------------------------------*/

  if ( ( str_load_fld == NULL ) || ( *str_load_fld == '\0' ) ) {
    load_fld = (int *)malloc(n_flds * sizeof(int));
    return_if_malloc_failed(load_fld);
    for ( int i = 0; i < n_flds; i++ ) { 
      load_fld[i]= 1;
    }
  }
  status = parse_scalar_vals(str_load_fld, &load_fld, &n_load_fld);
  cBYE(status);
  if ( n_load_fld != n_flds ) { go_BYE(-1); }
  status = rs_mmap(infile, &X, &nX, 0);
  cBYE(status);
  lb = 0; fld_idx = 0; in_fld = false; is_fld_delim = false;
  for ( int i = 0; i < n_flds; i++ ) { 
    if ( load_fld[i] == TRUE ) { 
      status = open_temp_file(&(fps[i]), &(fnames[i]));
      cBYE(status);
      status = open_temp_file(&(nn_fps[i]), &(nn_fnames[i]));
      cBYE(status);
      if ( strcmp(flds[i].fldtype, "char string" ) == 0 ) {
        status = open_temp_file(&(sz_fps[i]), &(sz_fnames[i]));
	cBYE(status);
      }
    }
  }
  for ( long long i = 0; i < nX; i++ ) {
    // START: Error handling for escape conventions
    /* TODO: If I get an incorrect backslash, I simply replace it with a
     * space. This is incorrect. But I need it to read files created 
     * with jspool utility from Jay Thomas. The correct thing to do is
     * to fix the utility.
     */
    if ( in_escape_mode ) { 
      if ( ( X[i] != '\\' ) && ( X[i] != '"' ) ) {
	/* replace the backslash that put is into escape mode wih a space */
	X[i-1] = ' '; 
      }
    }
    // STOP: Error handling for escape conventions
    // START: Handling bslash and dquote 
    if ( X[i] == '\\' ) { 
      if ( in_escape_mode ) { 
	in_escape_mode = false;
      }
      else {
	in_escape_mode = true;
      }
    }
    // STOP: Handling bslash and dquote 
    if ( X[i] == '"' ) { 
      if ( in_escape_mode ) {
	is_fld_delim_escaped = true;
	in_escape_mode = false;
      }
    }
    if ( in_fld == false ) {
      in_fld = true;
      if ( X[i] == fld_delim ) { /* consume this character */
	is_fld_delim = true;
        lb = i+1;
      }
      else {
        lb = i; 
	if ( ( ( fld_idx < (n_flds-1) ) && ( X[i] == fld_sep ) ) || 
	     ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) ) {
	  /* field has terminated */
	  ub = i-1;
	  if ( load_fld[fld_idx] == 1 ) { 
	    if ( ( ignore_hdr ) & ( num_rows == 0 ) ) {
	      /* Do nothing */
	    }
	    else {
	      status = print_cell(X, lb, ub+1, flds[fld_idx].fldtype,
				  flds[fld_idx].n_sizeof, is_null_null,
				  fps[fld_idx], nn_fps[fld_idx],
				  sz_fps[fld_idx]);
	      cBYE(status);
	    }
	  }
	  in_fld = false;
	  num_cells++;
          if ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) {
	    num_rows++;
	    g_num_rows = num_rows;
	  }
	  fld_idx++;
	  if ( fld_idx == n_flds ) { fld_idx = 0; }
	}
      }
    }
    else { /* Now within field. Decide whether to continue or stop. */
      if ( is_fld_delim ) {
	/* if field started with a fld_delim, it must end with one */
	/* Note that we need to take care of escaping the dquote */
	if ( ( X[i] == fld_delim ) && ( !is_fld_delim_escaped ) ) {
	  /* next char must be fld_sep or rec_delim or we have come to eof */
	  if ( i+1 > nX ) { go_BYE(-1); }
	  if ( ( fld_idx < (n_flds-1) ) && ( X[i+1] != fld_sep ) ) { 
	    go_BYE(-1); 
	  }
	  if ( fld_idx == n_flds-1 ) {
	    if ( X[i+1] != rec_delim ) { 
	      go_BYE(-1); 
	    }
	    else {
	      num_rows++;
	      g_num_rows = num_rows;
	    }
	  }
	  ub = i-1;
	  if ( load_fld[fld_idx] == 1 ) { 
	    if ( ( ignore_hdr ) & ( num_rows == 0 ) ) {
	      /* Do nothing */
	    }
	    else {
	      status = print_cell(X, lb, ub+1, flds[fld_idx].fldtype,
				  flds[fld_idx].n_sizeof, is_null_null,
				  fps[fld_idx], nn_fps[fld_idx], sz_fps[fld_idx]);
	      cBYE(status);
	    }
	  }
	  in_fld = false;
	  is_fld_delim = false;
	  fld_idx++;
	  if ( fld_idx == n_flds ) { fld_idx = 0; }
	  num_cells++;
	  i++; /* Consume next char which must be fld_sep or rec_delim */
	}
      }
      else {
	if ( ( i == nX ) ||  
	     ( ( fld_idx < (n_flds-1) ) && ( X[i] == fld_sep ) ) || 
	     ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) ) {
	  /* field has terminated */
	  if ( i == nX ) { 
	    ub = i;
	  }
	  else {
	    ub = i-1;
	  }
	  if ( load_fld[fld_idx] == 1 ) { 
	    if ( ( ignore_hdr ) & ( num_rows == 0 ) ) {
	      /* Do nothing */
	    }
	    else {
	      status = print_cell(X, lb, ub+1, flds[fld_idx].fldtype,
				  flds[fld_idx].n_sizeof, is_null_null,
				  fps[fld_idx], nn_fps[fld_idx], sz_fps[fld_idx]);
	      cBYE(status);
	    }
	  }
	  in_fld = false;
	  num_cells++;
          if ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) {
	    num_rows++;
	    g_num_rows = num_rows;
	  }
	  fld_idx++;
	  if ( fld_idx == n_flds ) { fld_idx = 0; }
	}
      }
    }
    is_fld_delim_escaped = false;
  }
  if ( num_cells != ( n_flds * num_rows ) ) { 
    fprintf(stderr, "num_cells = %lld   \n", num_cells);
    fprintf(stderr, "n_flds    = %d   \n", n_flds   );
    fprintf(stderr, "num_rows  = %lld \n", num_rows);
    go_BYE(-1); 
  }
  if ( ignore_hdr ) { 
    num_rows--; // Because you have eliminated first row 
  }
  /* TODO: Copy information into meta data structure */
  for ( int i = 0; i < n_flds; i++ ) { 
    if ( fnames[i] != NULL ) { // since not all fields are loaded
      strcpy(flds[i].filename, fnames[i]);
    }
  }
  for ( int i = 0; i < n_flds; i++ ) { 
    if ( fnames != NULL ) { free_if_non_null(fnames[i]); }
    if ( fps != NULL ) { fclose_if_non_null(fps[i]); }
    if ( nn_fps != NULL ) { fclose_if_non_null(nn_fps[i]); }
    if ( sz_fps != NULL ) { fclose_if_non_null(sz_fps[i]); }
  }
  *ptr_nn_fnames = nn_fnames;
  *ptr_sz_fnames = sz_fnames;
  *ptr_num_rows = num_rows;
 BYE:
  rs_munmap(X, nX);
  free_if_non_null(load_fld);
  free_if_non_null(nn_fps);
  free_if_non_null(sz_fps);
  free_if_non_null(fnames);
  free_if_non_null(fps);
  free_if_non_null(g_buffer);
  return(status);
}
Esempio n. 22
0
// START FUNC DECL
int
read_csv(
	 char *infile,
	 char fld_delim, /* double quote character */
	 char fld_sep, /* comma */
	 char rec_delim, /* new line character */
	 bool ignore_hdr, /* whether to ignore header or not */
	 char flds[MAX_NUM_FLDS][MAX_LEN_FLD_NAME+1],
	 int n_flds,
	 FLD_TYPE *fldtype,
	 bool *is_null_null, /* whether to convert "null" to null */
	 bool *is_load, /* to load or not */
	 bool *is_all_def, /* whether all values are defined */
	 char fnames[MAX_NUM_FLDS][MAX_LEN_FILE_NAME+1],
	 char nn_fnames[MAX_NUM_FLDS][MAX_LEN_FILE_NAME+1],
	 long long *ptr_num_rows
	 )
// STOP FUNC DECL
{
  int status = 0;
  char *X = NULL; size_t nX = 0;
  bool in_fld, is_fld_delim;
  long long num_rows = 0; long long num_cells = 0, fld_idx; 
  long long lb, ub;
  FILE *fps[MAX_NUM_FLDS];
  FILE *nn_fps[MAX_NUM_FLDS];
  bool in_escape_mode = false, is_fld_delim_escaped = false;
  
  g_num_rows = 0;
  g_buflen = 8192;
  g_buffer = (char *)malloc(g_buflen * sizeof(char));
  return_if_malloc_failed(g_buffer);
  zero_string(g_buffer, g_buflen);

  /*----------------------------------------------------------------------------*/
  if ( n_flds <= 0 ) { go_BYE(-1); }
  for ( int i = 0; i < MAX_NUM_FLDS; i++ ) { 
    fps[i] = NULL; 
    nn_fps[i] = NULL; 
  }
  /*----------------------------------------------------------------------------*/
  status = rs_mmap(infile, &X, &nX, 0);
  cBYE(status);
  lb = 0; fld_idx = 0; in_fld = false; is_fld_delim = false;
  for ( int i = 0; i < n_flds; i++ ) { 
    if ( is_load[i] ) {
      status = open_temp_file((fnames[i]), 0);
      cBYE(status);
      fps[i] = fopen(fnames[i], "wb");
      return_if_fopen_failed(fps[i], fnames[i],  "wb");
      if ( is_all_def[i] == false ) { 
        status = open_temp_file(nn_fnames[i], 0);
        cBYE(status);
        nn_fps[i] = fopen(nn_fnames[i], "wb");
        return_if_fopen_failed(nn_fps[i], nn_fnames[i],  "wb");
      }
    }
  }
  for ( long long i = 0; i < nX; i++ ) {
    // START: Error handling for escape conventions
    /* TODO: If I get an incorrect backslash, I simply replace it with a
     * space. This is incorrect. But I need it to read files created 
     * with jspool utility from Jay Thomas. The correct thing to do is
     * to fix the utility.
     */
    if ( fld_sep != '\t' ) {
      if ( in_escape_mode ) { 
	if ( ( X[i] != '\\' ) && ( X[i] != '"' ) ) {
	  fprintf(stderr, "Error. Bad backslash. \n");
	  fprintf(stderr, "num_rows  = %lld \n", num_rows);
	  go_BYE(-1);
	}
      }
    }
    // STOP: Error handling for escape conventions
    // START: Handling bslash and dquote 
    if ( fld_sep != '\t' ) {
      if ( X[i] == '\\' ) { 
	if ( in_escape_mode ) { 
	  in_escape_mode = false;
	}
	else {
	  in_escape_mode = true;
	}
      }
    }
    // STOP: Handling bslash and dquote 
    if ( fld_sep != '\t' ) {
      if ( X[i] == '"' ) { 
	if ( in_escape_mode ) {
	  is_fld_delim_escaped = true;
	  in_escape_mode = false;
	}
      }
    }
    if ( in_fld == false ) {
      in_fld = true;
      if ( X[i] == fld_delim ) { /* consume this character */
	is_fld_delim = true;
        lb = i+1;
      }
      else {
        lb = i; 
	if ( ( ( fld_idx < (n_flds-1) ) && ( X[i] == fld_sep ) ) || 
	     ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) ) {
	  /* field has terminated */
	  ub = i-1;
	  if ( is_load[fld_idx] ) { 
	    if ( ( ignore_hdr ) & ( num_rows == 0 ) ) {
	      /* Do nothing */
	    }
	    else {
	      status = print_cell(X, lb, ub+1, fldtype[fld_idx], 
		  is_null_null[fld_idx], is_all_def[fld_idx], 
		  fps[fld_idx], nn_fps[fld_idx], fld_sep);
	      cBYE(status);
	    }
	  }
	  in_fld = false;
	  num_cells++;
          if ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) {
	    num_rows++;
	    g_num_rows = num_rows;
	  }
	  fld_idx++;
	  if ( fld_idx == n_flds ) { fld_idx = 0; }
	}
      }
    }
    else { /* Now within field. Decide whether to continue or stop. */
      if ( is_fld_delim ) {
	/* if field started with a fld_delim, it must end with one */
	/* Note that we need to take care of escaping the dquote */
	if ( ( X[i] == fld_delim ) && ( !is_fld_delim_escaped ) ) {
	  /* next char must be fld_sep or rec_delim or we have come to eof */
	  if ( i+1 > nX ) { go_BYE(-1); }
	  if ( ( fld_idx < (n_flds-1) ) && ( X[i+1] != fld_sep ) ) { 
	    fprintf(stderr, "num_rows  = %lld \n", num_rows);
	    go_BYE(-1); 
	  }
	  if ( fld_idx == n_flds-1 ) {
	    if ( X[i+1] != rec_delim ) { 
	      go_BYE(-1); 
	    }
	    else {
	      num_rows++;
	      g_num_rows = num_rows;
	    }
	  }
	  ub = i-1;
	  if ( is_load[fld_idx] ) { 
	    if ( ( ignore_hdr ) & ( num_rows == 0 ) ) {
	      /* Do nothing */
	    }
	    else {
	      status = print_cell(X, lb, ub+1, fldtype[fld_idx], 
		  is_null_null[fld_idx], is_all_def[fld_idx], 
		  fps[fld_idx], nn_fps[fld_idx], fld_sep);
	      cBYE(status);
	    }
	  }
	  in_fld = false;
	  is_fld_delim = false;
	  fld_idx++;
	  if ( fld_idx == n_flds ) { fld_idx = 0; }
	  num_cells++;
	  i++; /* Consume next char which must be fld_sep or rec_delim */
	}
      }
      else {
	if ( ( i == nX ) ||  
	     ( ( fld_idx < (n_flds-1) ) && ( X[i] == fld_sep ) ) || 
	     ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) ) {
	  /* field has terminated */
	  if ( i == nX ) { 
	    ub = i;
	  }
	  else {
	    ub = i-1;
	  }
	  if ( is_load[fld_idx] ) { 
	    if ( ( ignore_hdr ) & ( num_rows == 0 ) ) {
	      /* Do nothing */
	    }
	    else {
	      status = print_cell(X, lb, ub+1, fldtype[fld_idx], 
		  is_null_null[fld_idx], is_all_def[fld_idx], 
		  fps[fld_idx], nn_fps[fld_idx], fld_sep);
	      cBYE(status);
	    }
	  }
	  in_fld = false;
	  num_cells++;
          if ( ( fld_idx == n_flds-1 ) && ( X[i] == rec_delim ) ) {
	    num_rows++;
	    g_num_rows = num_rows;
	  }
	  fld_idx++;
	  if ( fld_idx == n_flds ) { fld_idx = 0; }
	}
      }
    }
    is_fld_delim_escaped = false;
  }
  if ( num_cells != ( n_flds * num_rows ) ) { 
    fprintf(stderr, "num_cells = %lld   \n", num_cells);
    fprintf(stderr, "n_flds    = %d   \n", n_flds   );
    fprintf(stderr, "num_rows  = %lld \n", num_rows);
    go_BYE(-1); 
  }
  if ( ignore_hdr ) { 
    num_rows--; // Because you have eliminated first row 
  }
  /* TODO: Copy information into meta data structure */
  for ( int i = 0; i < n_flds; i++ ) { 
    if ( fps != NULL ) { fclose_if_non_null(fps[i]); }
    if ( nn_fps != NULL ) { fclose_if_non_null(nn_fps[i]); }
  }
  *ptr_num_rows = num_rows;
 BYE:
  rs_munmap(X, nX);
  free_if_non_null(g_buffer);
  return(status);
}
Esempio n. 23
0
static int * pviterbi_propagate_recursion (pmodel *mo, psequence * X,
					   psequence * Y, double *log_p,
					   int *path_length, cell *start,
					   cell *stop, double max_size,
					   plocal_propagate_store_t * pv) {
#define CUR_PROC "pviterbi_propagate_recursion"
  /* Divide and conquer algorithm to reduce the memory requirement */
  
  /* 1. Compute the alignment of X vs Y and propagate the middle point */
  
  /* 2. Solve recursively the two alignments X[0:len/2] vs Y[0:m] and 
     X[len/2+1:len] vs Y[m+1:len] */

  /* Break the recursion if the lengths of both sequences become tractable
     for the normal pviterbi algorithm */

  /* start of the implementation */
  int * path_seq = NULL;
  int start_x, start_y, stop_x, stop_y;
  double * original_pi=NULL;
  int i;
  cell * middle;
  int length1, length2;
  double log_p1, log_p2;
  int * path1, * path2;

  init_start_stop(start, stop, X, Y, &start_x, &start_y, &stop_x, &stop_y);
#ifdef DEBUG
  printf("Recursion: start, stop cells\n");
  if(start)
    print_cell(start);
  else
    printf("(0, 0) first segment\n");
  if(stop)
    print_cell(stop);
  else
  printf("(%i, %i) last segment\n", stop_x, stop_y);
#endif
  /* Break the recursion if the lengths of both sequences become tractable
     for the normal pviterbi algorithm */
  if ((double)(stop_x - start_x) * (double)(stop_y - start_y) < max_size) {
    /* to use the unchanged pviterbi algorithm take slices of the sequences */
    psequence * tractable_X = slice_psequence(X, start_x, stop_x);
    psequence * tractable_Y = slice_psequence(Y, start_y, stop_y);
    /* if this is not the very first path segment starting at zero:
       temporarily change the initial probabability to go into state k+1 */
#ifdef DEBUG
    printf("pviterbi on slice  x[%i:%i], y[%i:%i]\n", 
	   start_x, stop_x, start_y, stop_y); 
#endif
    if (start != NULL) {
      ARRAY_CALLOC (original_pi, mo->N);
      /* save original pi and set all to zero */
      for (i=0; i<mo->N; i++) {
	original_pi[i] = mo->s[i].log_pi;
	mo->s[i].log_pi = 1;
      }
      /* set the initial prob. for the state that was in the middle of path */
      mo->s[start->state].log_pi = start->log_p + start->log_a;
      
      /* compute the partial path */
      if (stop != NULL)
	path_seq = pviterbi_variable_tb(mo, tractable_X, tractable_Y, log_p, path_length, stop->previous_state);
      else
	path_seq = pviterbi_variable_tb(mo, tractable_X, tractable_Y, log_p, path_length, -1);
      /* restore the original model */
      for (i=0; i<mo->N; i++) 
	mo->s[i].log_pi = original_pi[i];
      m_free(original_pi);
    }
    else {
      if (stop != NULL)
	path_seq = pviterbi_variable_tb(mo, tractable_X, tractable_Y, log_p, path_length, stop->previous_state);
      else
	path_seq = pviterbi_variable_tb(mo, tractable_X, tractable_Y, log_p, path_length, -1);
    }
    if (*log_p == 1) {
      fprintf(stderr, "Problem with slice x[%i:%i], y[%i:%i]\n", 
	      start_x, stop_x, start_y, stop_y);
    }
    return path_seq;
  }
  else {
    /* 1. Compute the alignment of X vs Y and propagate the middle point */
    double step_log_p = 1;
    /* if this is not the very first path segment starting at zero:
       temporarily change the initial probabability to go into state k+1 */
    if (start != NULL) {
      ARRAY_CALLOC(original_pi, mo->N);
      /* save original pi and set all to zero */
      for (i=0; i<mo->N; i++) {
	original_pi[i] = mo->s[i].log_pi;
	mo->s[i].log_pi = 1;
      }
      /* set the initial prob. for the state that was in the middle of path */
      mo->s[start->state].log_pi =  start->log_p + start->log_a;
    }
    middle = pviterbi_propagate_step(mo, X, Y, start, stop, &step_log_p, pv);
    if (start != NULL) {
      /* restore the original model */
      for (i=0; i<mo->N; i++) 
	mo->s[i].log_pi = original_pi[i];
      m_free(original_pi);
    }
    /* check if there is a middle */
    if (!middle) {
      fprintf(stderr, "(%i, %i)->(%i, %i) No middle found!\n", 
	      start_x, start_y, stop_x, stop_y);
      ARRAY_CALLOC(path_seq, 1);
      path_seq[0] = -1;
      *path_length = 1;
      *log_p = 1;
      return path_seq;
    }
#ifdef DEBUG
    else {
      printf("(%i, %i)->(%i, %i) Middlepoint ", start_x, start_y,
	     stop_x, stop_y);
      print_cell(middle);
    } 
#endif
    /* check if there is a path */
    if (step_log_p == 1) {
      ARRAY_CALLOC(path_seq, 1);
      path_seq[0] = -1;
      *path_length = 1;
      *log_p = 1;
      return path_seq;
    }
    /* 2. Solve recursively the two alignments X[0:len/2] vs Y[0:m] and 
       X[len/2+1:len] vs Y[m+1:len] */
    length1 = 0;
    log_p1 = 0;
    path1 = pviterbi_propagate_recursion(mo, X, Y, &log_p1, &length1, 
					       start, middle,
					       max_size, pv);
    length2 = 0;
    log_p2 = 0;
    path2 = pviterbi_propagate_recursion(mo, X, Y, &log_p2, &length2, 
					       middle, stop,
					       max_size, pv);
    /* check the paths */
    if (log_p1 == 1 || log_p2 == 1) {
      ARRAY_CALLOC (path_seq, 1);
      path_seq[0] = -1;
      *path_length = 1;
      *log_p = 1;
      return path_seq;
    }  
    /* concatenate the paths */
    *path_length = length1 + length2;
    *log_p = log_p2;

#ifdef DEBUG
    /* check if the transition between the ends of the paths is possible */
    for (i=0; i<mo->s[path1[length1-1]].in_states; i++){
      if (mo->s[path1[length1-1]].in_id[i] == path2[0])
	break;
    }
    if (i == mo->s[path1[length1-1]].in_states) {
      printf("no transition between states %i -> %i\n", path1[length1-1], path2[0]);
    }

    printf("Conquer: start, stop cells\n");
    if(start)
      print_cell(start);
    else
      printf("(0, 0) first segment\n");
    if(stop)
      print_cell(stop);
    else
      printf("(%i, %i) last segment\n", stop_x, stop_y);
    printf("Path 1:\n[");
    for (i=0; i<length1; i++)
      printf("%i,", path1[i]);
    printf("\nPath 2:\n[");
    for (i=0; i<length2; i++)
      printf("%i,", path2[i]); 
    printf("]\n");
#endif
	
    ARRAY_CALLOC (path_seq, *path_length);

    for (i=0; i<length1; i++)
      path_seq[i] = path1[i];
    for (i=0; i<length2; i++)
      path_seq[length1 + i] = path2[i];
    return path_seq;
  }
STOP:     /* Label STOP from ARRAY_[CM]ALLOC */
  return NULL;
#undef CUR_PROC
}
Esempio n. 24
0
void distribute_cells ( int myid, int np, int nspt, int dim, int *nbpaths )
{
   int nbcell,*cell,nbsols,i,j,k,left[np],L,R,*m,sn,mysolnum;
   int count,labSize,cnt,dest;
   MPI_Status status;
   MPI_Comm com = MPI_COMM_WORLD;
   int length[nspt],*labels ;
   int fail,A[2],n;
   double normal[dim],sol[2*(dim-1)+5],*c;
   lisStack *s;
   int *a,*b;
   
   n=dim-1;A[0]=n;
   if(myid == 0)
   { 
      fail=celcon_number_of_cells(&nbcell);  /* get the number of cells */
      cell=(int*)calloc(nbcell,sizeof(int));
      for(i=0; i<nbcell; i++)
         fail = celcon_mixed_volume(i+1,&cell[i]);

      nbsols=0;
      for(i=0; i<nbcell; i++) nbsols=nbsols+cell[i];   
      if(v>0) printf("The number cells are %d\n",nbcell);
      if(v>0) print_cell(nbcell,cell);
      if(v>0) printf("The total solutions are %d\n",nbsols);
   }
   MPI_Bcast(&nbsols,1,MPI_INT,0,com);
   
   if(myid == 0)
   {
      if(v>0) printf("\n");
      left[0] = 0;
      for(i=1; i<np; i++)
         if(i <= (nbsols%(np-1))) 
            left[i] = nbsols/(np-1)+1; 
         else
            left[i] = nbsols/(np-1);
      if(v>0) printf("left:");
      if(v>0) Print_Integer_Array(np,left);
   }

   MPI_Scatter(left,1,MPI_INT,&mysolnum,1,MPI_INT,0,com);

   if(myid == 0)
   {
      fail = celcon_number_of_points_in_cell(1,nspt,length);
      labSize=0;
      for(i=0; i<nspt; i++) labSize = labSize+length[i];
      labSize = 1+nspt+labSize;
   }
   MPI_Bcast(&labSize,1,MPI_INT,0,MPI_COMM_WORLD);
   labels = (int*)calloc(labSize,sizeof(int));
   m=(int*)calloc(3,sizeof(int));

   if(myid==0)
   {
      L=1; R=np-1;
      for(i=0; i<nbcell; i++)
      { 
         m[0] = i+1;
         m[2] = labSize;
         celcon_retrieve_mixed_cell(dim,nspt,i+1,labels,normal);
         
         sn=1;
         while(cell[i]!=0)
         { 
            if(cell[i]>=left[L])
            {   
               m[1] = left[L]; m[2] = sn;      
	       MPI_Send(&m[1],2,MPI_INT,L,SEND_CELL,com);
               /*
               if(v>0)
                  printf("%2d paths from cell %d is sending to node %d\n",
                         m[1],m[0],L);
                */
               MPI_Send(labels,labSize,MPI_INT,L,SEND_SUPP,com);
               MPI_Send(normal,dim,MPI_DOUBLE,L,SEND_NORMAL,com) ;
               cell[i] = cell[i]-left[L]; sn = sn+left[L];
               L++;  
            }
            else if(cell[i]>=left[R])
            { 
               m[1] = left[R]; m[2] = sn;      
               MPI_Send(&m[1],2,MPI_INT,R,SEND_CELL,com);
               /*
               if(v>0)
                  printf("%2d paths from cell %d is sending to node %d\n",
                         m[1],m[0],R);
               */
               MPI_Send(labels,labSize,MPI_INT,R,SEND_SUPP,com);
               MPI_Send(normal,dim,MPI_DOUBLE,R,SEND_NORMAL,com) ;
               cell[i] = cell[i]-left[R]; sn = sn+left[R];
               R--;   
            }
            else
            {              
               m[1] = cell[i]; m[2] = sn;     
               MPI_Send(&m[1],2,MPI_INT,R,SEND_CELL,com);
               /*
               if(v>0)
                  printf("%2d paths from cell %d is sending to node %d\n",
                         m[1],m[0],R);
               */
               MPI_Send(labels,labSize,MPI_INT,R,SEND_SUPP,com);
               MPI_Send(normal,dim,MPI_DOUBLE,R,SEND_NORMAL,com);
               left[R]=left[R]-cell[i]; sn = sn+cell[i];
               cell[i]=0;  
            }
         }
      }
      if(v>0) printf("****************************************************\n");
      printf("writing random coefficient system and its solutions to file\n");
      fail = celcon_write_random_coefficient_system();
      fail = solcon_write_solution_dimensions_to_defined_output_file(nbsols,n);
      cnt = 0;
      for(k=1; k<=nbsols; k++)
      {
         MPI_Recv(&A[1],1,MPI_INT,MPI_ANY_SOURCE,SEND_MUL,
                  MPI_COMM_WORLD,&status);
         MPI_Recv(sol,2*n+5,MPI_DOUBLE,MPI_ANY_SOURCE,SEND_SOL,
                  MPI_COMM_WORLD,&status);
         fail = solcon_write_next_solution_to_defined_output_file
                  (&cnt,n,A[1],sol);
      }
      *nbpaths = nbsols;

   } /* myid=0 finish */
   else
   {  
      *nbpaths = mysolnum;
      if(v>0) printf("Node %d has %d paths\n",myid,mysolnum);
      s=(lisStack*)calloc(1,sizeof(lisStack));
      ls_init(s);
      count = 0; sn = 0;
      while(count < mysolnum)
      {  
         MPI_Recv(&m[1],2,MPI_INT,0,SEND_CELL,com,&status);
         sn++;
         m[0] = sn;
         ls_push(s,m);
         count = count+m[1];
         /*
     	 if(v>0) printf("Node %d is receving %2d paths from cell %d\n",
		        myid,m[1],m[0]);
         */
	 MPI_Recv(labels,labSize,MPI_INT,0,SEND_SUPP,com,&status) ;
	 MPI_Recv(normal,dim,MPI_DOUBLE,0,SEND_NORMAL,com,&status) ;
      	 fail = celcon_append_mixed_cell(dim,nspt,labSize,labels,normal);
      }
      fail = celcon_create_polyhedral_homotopy();
      
      for(i=1; i<=sn; i++)
      {
         m = ls_cur(s);
         fail = celcon_solve_start_system(m[0],&R);

         if(fail == 1)
         {
            printf("Solving start system failed.\n");
            printf("Node %d skips cell %d with volume %d...\n",myid,m[0],R);
         }
         else
         {
    /* printf("found %d start solutions from cell %d\n",R,m[0]); */

            fail=celcon_mixed_volume(m[0],&L);

    /* if(R==L)  printf("#start solutions equals mixed volume %d, OK\n",L);
       else  printf("#start solutions not equals mixed volume %d!!!, \n",L);
    */
            for(j=m[2]; j<m[1]+m[2]; j++)
            {          
               fail = celcon_track_solution_path(m[0],j,0);
               fail = solcon_clear_solutions();
               fail = celcon_copy_target_solution_to_container(m[0],j-m[2]+1);
               fail = solcon_retrieve_solution(n,1,&A[1],sol);
               MPI_Send(&A[1],1,MPI_INT,0,SEND_MUL,MPI_COMM_WORLD);
               MPI_Send(sol,2*n+5,MPI_DOUBLE,0,SEND_SOL,MPI_COMM_WORLD);
            }
         }
         ls_pop(s);
      }
   } /* end else */

 /*  MPI_Barrier(com);  */  
   if(myid == 0)
      free(cell);
   else
      free(s);
   free(labels);
   free(m);
}