Ejemplo n.º 1
0
/* read an image and generate a result */
int main(int argc, char **argv) {
    int rows=0;
    int cols=0;
    int iterations=0;
    int i;
    int **grid = NULL;
    int **neighbors = NULL;

    if (argc<2 || !(grid=read_grid(stdin,&rows,&cols))
            || (iterations=atoi(argv[1]))<0) {
        fprintf(stderr,"life usage:  life iterations <inputfile\n");
        exit(1);
    }
#ifdef DEBUG
    printf("input:\n");
    print_grid(stdout,grid,rows,cols);
#endif /* DEBUG */
    neighbors = make_grid(rows,cols);
    for (i=0; i<iterations; i++) {
        next(grid, neighbors, rows, cols);
#ifdef DEBUG
        printf("next\n");
        print_grid(stdout,grid,rows,cols);
#endif /* DEBUG */
    }
    print_grid(stdout,grid,rows,cols);
    free_grid(grid,rows);
    free_grid(neighbors,rows);
}
Ejemplo n.º 2
0
int			main(int argc, char **argv)
{
	int			nbr_tetris;
	char		**grid;
	t_tetrimino	*tetris;
	t_coord		co;
	t_path		path;

	path.square_size = -1;
	path.path = ft_strnew(27);
	co.x = 0;
	co.y = 0;
	nbr_tetris = -1;
	if (argc != 2 || !(is_valid_file(argv[1])))
		write(1, "error\n", 6);
	else if (!(nbr_tetris = process_file(argv[1], 0, &tetris)))
		write(1, "error\n", 6);
	else
	{
		grid = create_grid(nbr_tetris);
		path = fill_grid(grid, tetris, co, nbr_tetris);
		ft_strrev(path.path);
		grid_from_str(path.path, grid, tetris, co);
		display_grid(grid);
		free_grid(grid);
	}
	return (0);
}
Ejemplo n.º 3
0
void	ft_execute(int fd)
{
	t_grid			*grid;
	t_point			point;

	grid = init_grid(fd);
	ft_set_params(grid);
	if (!g_errno)
		read_first_line(grid);
	if (!g_errno)
		ft_read(grid);
	if (!g_errno)
		test_full(grid);
	if (g_errno)
		ft_putstr("Map error\n");
	else
	{
		ft_remap(grid);
		point = find_max(grid);
		draw_square(grid, point.x, point.y, point.max);
		print_index(grid);
	}
	if (fd > 0)
		close(fd);
	free_grid(grid);
}
Ejemplo n.º 4
0
int		main(int argc, char **argv)
{
	char	**sudo_tb;
	int		index;
	int		index_malloc;

	index_malloc = 0;
	if (argc == 10 && is_valid_number(argv) == 1)
	{
		index = 0;
		sudo_tb = (char**)malloc(9 * sizeof(char*));
		while (index_malloc < 9)
		{
			sudo_tb[index_malloc] = (char*)malloc(10 * sizeof(char));
			index_malloc++;
		}
		copy_sudo(argv, sudo_tb);
		if (is_valid_char(argv) == 1 && sudoku(sudo_tb, 0))
			print_sudoku(sudo_tb);
		else
			write(1, "Erreur\n", 7);
		free_grid(sudo_tb);
	}
	else
		write(1, "Errer\n", 7);
	return (0);
}
Ejemplo n.º 5
0
void	close_main(s_game		*game,
		   s_sound		*sounds,
		   s_perso		**persos)
{
  int	i = 0;

  for (i = 0; i < 32; i++)
    {
      SDL_FreeSurface(persos[1]->anim[i]);
      SDL_FreeSurface(persos[2]->anim[i]);
    }
  for (i = 0; i < 7; i++)
    SDL_FreeSurface(game->fire[i]);
  Mix_FreeChunk(sounds->bomb);
  Mix_FreeChunk(sounds->planted);
  Mix_FreeMusic(sounds->music);
  free(sounds);
  for (i = 0; i < game->max_players; i++)
    free(persos[i]);
  free_info(game->info);
  TTF_CloseFont(game->font);
  TTF_CloseFont(game->font_num);
  TTF_Quit();
  Mix_CloseAudio();
  SDL_Quit();
  free_grid(game);
  if (game->custom_mus)
    free(game->custom_mus);
  free(game);
}
int main()
{
  int **grid;
  grid = alloc_grid(5, 5);
  free_grid(grid, 5);
  return (0);
}
Ejemplo n.º 7
0
Archivo: smap.c Proyecto: VURM/slurm
/* Variation of exit() that releases memory as needed for memory leak test */
static void _smap_exit(int rc)
{
#ifdef MEMORY_LEAK_DEBUG
	free_grid();
	select_g_ba_fini();
#endif
	exit(rc);
}
Ejemplo n.º 8
0
int main() {
  int i = 0;

  struct tms before, after;

  int start = (950 / sizeof(int))  * 1000;
  int end = (1050 / sizeof(int)) * 1000;
  int step = (end - start) / 50;

  FILE *fp;
  fp = fopen("datas", "w");
  for (i = start; i < end; i += step) {
	int a, b, k, j, runtime, overall;
	int** testgrid;
	int** neighbor;
	

	a = b = (int) sqrt(i);

	testgrid = make_grid(a, b);
	neighbor = make_grid(a, b);

	for(k = 0; k < 10; k++) {
	  randomize_grid(testgrid, &a, &b);
	  zero_grid(neighbor, a, b);
	  
	  times(&before);
	  for(j = 0; j < 30; j++) {
		next(testgrid, neighbor, a, b);
	  }
	  times(&after);
	  
	  runtime = (int)  (after.tms_utime + after.tms_stime) -
		(before.tms_utime + before.tms_stime);
	  overall += runtime; 
	}
	
	free_grid(testgrid, a);
	free_grid(neighbor, a);
	
	fprintf(fp, "%d \t %d \n", i, overall);
	fflush(fp);
  }

  return 0;
}
Ejemplo n.º 9
0
void	cleanup(t_info *info)
{
	free_grid(&info->board);
	free_grid(&info->token);
	if (info->link != NULL)
	{
		free(info->link);
		info->link = NULL;
	}
	if (info->pos != NULL)
	{
		free(info->pos);
		info->pos = NULL;
	}
	info->pos_c = 0;
	info->link_c = 0;
}
Ejemplo n.º 10
0
/*  read an image and generate a result */ 
int main(int argc, char **argv) { 
   FILE *f; 
   int rows=0; int cols=0; int iterations=0; 
   int i; 
   if (argc>1 || !(grid=read_rle(stdin,&rows,&cols))) { 
	fprintf(stderr,"translate usage: translate <inputfile\n"); 
	exit(1); 
   } 
   print_grid(stdout,grid,rows,cols); 
   free_grid(grid,rows); 
} 
Ejemplo n.º 11
0
Archivo: main.c Proyecto: jons/life
int main (int argc, char **argv)
{
  int x, y, i = 0, k;
  grid_t a, b, *v, *w;

  init_grid(&a, SZ);
  init_grid(&b, SZ);

  // LIVE! LIVE, DAMN YOU
  for (x = 0; x < SZ; x++)
    for (y = 0; y < SZ; y++)
    {
      k = x * SZ + y;
      if (p[i] == k)
      {
        wcell(&a, x, y, 1);
        i++;
        if (i == PSZ) i = 0;
      }
    }

  // flip-flop next/current grid
  v = &a; w = &b; x = 0;
  for (;;) {
    draw(v);
    //
    if (v->i && !v->dt) break;
    //
    if (wait()) break;
    //
    next_grid(w, v);
    //
    if (x) { v = &a; w = &b; x = 0; }
    else   { v = &b; w = &a; x = 1; }
  }

  free_grid(&a);
  free_grid(&b);
  return 0;
}
Ejemplo n.º 12
0
int	main(void)
{
	t_filler	f;
	char		*line;

	line = NULL;
	if (!init_map(&f, &line))
		return (free_filler(&f, &line));
	if (!my_compute(&f))
		return (free_filler(&f, &line));
	free_grid(&f.form);
	while (1)
	{
		if (!read_grid(&f.grid, &line))
			return (free_filler(&f, &line));
		if (!init_grid(&f.form, &line, PIECE))
			return (free_filler(&f, &line));
		if (!my_compute(&f))
			return (free_filler(&f, &line));
		free_grid(&f.form);
	}
	return (free_filler(&f, &line));
}
Ejemplo n.º 13
0
/* Variation of exit() that releases memory as needed for memory leak test */
static void _smap_exit(int rc)
{
#ifdef MEMORY_LEAK_DEBUG
    free_grid();

#ifdef HAVE_BG
    bg_configure_ba_fini();
#endif

#endif
    if (!params.commandline)
        curs_set(1);
    exit(rc);
}
Ejemplo n.º 14
0
int resolvedor (){
  printf("Insira sudoku incompleto para resolução.\n");
  int x = 0, i, j, erro = 0;
  int** grid = malloc_grid();
  if (scan_sudoku(grid)){             // Obtem a matriz com os coeficientes do sudoku
    printf("Erro no input.\n");
    return 2;
  }
  // Chama funcao recursiva preenchedora
  if (backTracker(grid) == 0){
    printf("Sudoku insolúvel!\n");
  }

  print_sudoku(grid);// IMPRIMIR MATRIZ PREENCHIDA
  free_grid(grid);
  return 0;
}
Ejemplo n.º 15
0
int verificador(){
  printf("Insira sudoku completo para verificacao.\n");
  int x = 0, i, j, k;
  int** grid = malloc_grid();

  if(scan_sudoku(grid)){
    printf("Erro no input.\n");
    return 2;
  }
  // Gera os dados de valores faltantes.
  SudokuData missing = sudokuChecker(grid);

  if (missing.error){
    for (i=0; i<3; i++){
      for (j=0;j<9;j++){
	if (missing.data[i][j]!=0){
	  printf("Erro encontrado n");
	  switch (i){
	  case LINE:
	    printf("a linha ");
	    break;
	  case COLLUMN:
	    printf("a coluna ");
	    break;
	  case SECTOR:
	    printf("o setor ");
	    break;
	  }
	  printf("%d: falta(m) o(s) numero(s)", j + 1);
	  for (k = 1; k<=9; k++) if (containsData(missing.data[i][j],k)) printf(" %d", k);
	  printf(".\n");
	}
      }
    }
  }
  else  printf("Nenhum erro encontrado na verificacao\n");
  // Como ambos a grid e o SudokuData sao alocados dinamicamente,
  // eh preciso libera-los no fim da funcao.
  free_grid(grid);
  free_sudokuData(missing);
  return missing.error;
}
Ejemplo n.º 16
0
int dica(){
  int x = 0, i, j, erro = 0;
  int** grid = malloc_grid();
  SudokuData missing;
  printf("Insira sudoku incompleto para geração de dicas.\n");
  if (scan_sudoku(grid)){
    printf("Erro no input.\n");
    return 2;
  }
  missing = sudokuChecker(grid);
  
  if(hint_generator(grid, missing)){
    printf("Erro na verificação.\n");
    return 1;
  }

  print_sudoku(grid);
  free_grid(grid);
  free_sudokuData(missing);
  return 0;
}
Ejemplo n.º 17
0
grid_t *make_grid(int width, int height, int padding) {
	grid_t *grid = (grid_t *) calloc(1, sizeof(grid_t));
	if (grid == NULL)
		return NULL;
	int count = (width + padding * 2) * (height + padding * 2);
	grid->data = (int *) calloc(count, sizeof(int));
	grid->dbl = (double *) calloc(count, sizeof(double));
	if (grid->data == NULL || grid->dbl == NULL)
		goto error;
	grid->height = height;
	grid->width = width;
	grid->padding = padding;
	grid->pw = width + padding * 2;
	grid->ph = height + padding * 2;
done:
	return grid;
error:
	free_grid(grid);
	grid = NULL;
	goto done;
}
Ejemplo n.º 18
0
void	gen_new_token(t_info *info)
{
	char	**token;
	int		y;
	int		x;
	int		i;

	y = info->token.tok_y;
	i = 0;
	token = (char **)malloc(sizeof(char *) * (info->token.tok_y_b - y + 1));
	while (y < info->token.tok_y_b + 1)
	{
		x = info->token.tok_x;
		token[i] = str_cut(info->token.map[y], x, info->token.tok_x_b + 1);
		y++;
		i++;
	}
	free_grid(&info->token);
	info->token.map = token;
	info->token.x = info->token.tok_x_b - info->token.tok_x + 1;
	info->token.y = info->token.tok_y_b - info->token.tok_y + 1;
}
Ejemplo n.º 19
0
void loop()
{
    if( flag )
    {
        flag = 0;

        initialize_grid();

        explore( X_START, Y_START, 0);

        p.init(EXPLORE_RADIUS*2, START_ADDR);

        int i;
        for( i=0; i<EXPLORE_RADIUS*EXPLORE_RADIUS*4; i++)
        {
            p.write( get_bit( i*BITS_PER_NODE + OBSTRUCTED_BIT_OFFSET) );
        }
        p.flush();
        free_grid();

    }
}
Ejemplo n.º 20
0
int main(int argc, char **argv)
{
    srand(time(NULL));
    clock_t beg, end;

    cmd_args args;
    parse_options(argc, argv, &args);
    
    grid *gd = allocate_grid(args.width, args.height);
    
    beg = clock();
    run_percolation(gd, args.prob, args.recursive);
    end = clock();
    
    if (args.img_output)
        create_image(args.filename, gd, args.size, args.color);
    
    printf("Finished in %g sec\n", (double)(end - beg) / CLOCKS_PER_SEC);

    free_grid(gd);
    
    return 0;
}
Ejemplo n.º 21
0
int main(int argc,const char * argv[]) {
  //Robin's monitor.
  #ifdef ROOKS_MONITOR
  pthread_t t;
  #endif
  int max = 0;
  //DO NOT PUT 0 HERE ;)
  int len = 8;
  grid g;
  fill_grid(&g,len);
  #ifdef ROOKS_MONITOR
  pthread_create(&t, NULL, monitor, &g);
  #endif
  backtrack_corner(&g,&max);
  #ifdef ROOKS_MONITOR
  pthread_cancel(t);
  pthread_join(t,NULL);
  #endif
  printf("Result: %d\n",max);
  printf("Explored confs: %" PRIu64 "\n",conf_counter);
  free_grid(&g);
  return(0);
}
Ejemplo n.º 22
0
int
main(int argc, char *argv[])
{
  PLFLT *x, *y, *z, *clev;
  PLFLT *xg, *yg, **zg, **szg;
  PLFLT zmin, zmax, lzm, lzM;
  long ct;
  int i, j, k;
  PLINT alg;
  char ylab[40], xlab[40];
  char *title[] = {"Cubic Spline Approximation",
		   "Delaunay Linear Interpolation",
		   "Natural Neighbors Interpolation",
		   "KNN Inv. Distance Weighted",
		   "3NN Linear Interpolation",
		   "4NN Around Inv. Dist. Weighted"};

  PLFLT opt[] = {0., 0., 0., 0., 0., 0.};

  xm = ym = -0.2;
  xM = yM = 0.8;

  plMergeOpts(options, "x21c options", NULL);
  plparseopts(&argc, argv, PL_PARSE_FULL);

  opt[2] = wmin;
  opt[3] = (PLFLT) knn_order;
  opt[4] = threshold;

  /* Initialize plplot */

  plinit();

  create_data(&x, &y, &z, pts); /* the sampled data */
  zmin = z[0];
  zmax = z[0];
  for (i=1; i<pts; i++) {
    if (z[i] > zmax)
      zmax = z[i];
    if (z[i] < zmin)
      zmin = z[i];
  }

  create_grid(&xg, xp, &yg, yp); /* grid the data at */
  plAlloc2dGrid(&zg, xp, yp); /* the output grided data */
  clev = (PLFLT *) malloc(nl * sizeof(PLFLT));

  sprintf(xlab, "Npts=%d gridx=%d gridy=%d", pts, xp, yp);
  plcol0(1);
  plenv(xm, xM, ym, yM, 2, 0);
  plcol0(15);
  pllab(xlab, "", "The original data");
  plcol0(2);
  plpoin(pts, x, y, 5);
  pladv(0);

  plssub(3,2);

  for (k=0; k<2; k++) {
    pladv(0);
    for (alg=1; alg<7; alg++) {

      ct = clock();
      plgriddata(x, y, z, pts, xg, xp, yg, yp, zg, alg, opt[alg-1]);
      sprintf(xlab, "time=%d ms", (clock() - ct)/1000);
      sprintf(ylab, "opt=%.3f", opt[alg-1]);

      /* - CSA can generate NaNs (only interpolates?!).
       * - DTLI and NNI can generate NaNs for points outside the convex hull
       *      of the data points.
       * - NNLI can generate NaNs if a sufficiently thick triangle is not found
       *
       * PLplot should be NaN/Inf aware, but changing it now is quite a job...
       * so, instead of not plotting the NaN regions, a weighted average over
       * the neighbors is done.
       */

      if (alg == GRID_CSA || alg == GRID_DTLI || alg == GRID_NNLI || alg == GRID_NNI) {
	int ii, jj;
	PLFLT dist, d;

	for (i=0; i<xp; i++) {
	  for (j=0; j<yp; j++) {
	    if (isnan(zg[i][j])) { /* average (IDW) over the 8 neighbors */

	      zg[i][j] = 0.; dist = 0.;

	      for (ii=i-1; ii<=i+1 && ii<xp; ii++) {
		for (jj=j-1; jj<=j+1 && jj<yp; jj++) {
		  if (ii >= 0 && jj >= 0 && !isnan(zg[ii][jj])) {
		    d = (abs(ii-i) + abs(jj-j)) == 1 ? 1. : 1.4142;
		    zg[i][j] += zg[ii][jj]/(d*d);
		    dist += d;
		  }
		}
	      }
	      if (dist != 0.)
		zg[i][j] /= dist;
	      else
		zg[i][j] = zmin;

	    }
	  }
	}
      }

      plMinMax2dGrid(zg, xp, yp, &lzM, &lzm);

      plcol0(1);
      pladv(alg);

      if (k == 0) {

	lzm = MIN(lzm, zmin);
	lzM = MAX(lzM, zmax);
	for (i=0; i<nl; i++)
	  clev[i] = lzm + (lzM-lzm)/(nl-1)*i;

	plenv0(xm, xM, ym, yM, 2, 0);
	plcol0(15);
	pllab(xlab, ylab, title[alg-1]);
	plshades(zg, xp, yp, NULL, xm, xM, ym, yM,
		 clev, nl, 1, 0, 1, plfill, 1, NULL, NULL);
	plcol0(2);
      } else {

	for (i=0; i<nl; i++)
	  clev[i] = lzm + (lzM-lzm)/(nl-1)*i;

	cmap1_init();
	plvpor(0.0, 1.0, 0.0, 0.9);
	plwind(-1.0, 1.0, -1.0, 1.5);
	/*
	 * For the comparition to be fair, all plots should have the
	 * same z values, but to get the max/min of the data generated
	 * by all algorithms would imply two passes. Keep it simple.
	 *
	 * plw3d(1., 1., 1., xm, xM, ym, yM, zmin, zmax, 30, -60);
	 */

	plw3d(1., 1., 1., xm, xM, ym, yM, lzm, lzM, 30, -60);
	plbox3("bnstu", ylab, 0.0, 0,
	       "bnstu", xlab, 0.0, 0,
	       "bcdmnstuv", "", 0.0, 4);
	plcol0(15);
	pllab("", "", title[alg-1]);
	plot3dc(xg, yg, zg, xp, yp, DRAW_LINEXY | MAG_COLOR | BASE_CONT, clev, nl);
      }
    }
  }

  plend();

  free_data(x, y, z);
  free_grid(xg, yg);
  free((void *)clev);
  plFree2dGrid(zg, xp, yp);
}
Ejemplo n.º 23
0
/*
 * Read a text file, formatted like this:
 *
 *         4      <- 1st line: width as decimal integer
 *         3      <- 2nd line: height as decimal integer
 *         ....   <- rows (. = dead cell, # = living cell)
 *         .##.
 *         ....		
 *                <- final row ending with a linefeed '\n'
 *
 *	If successful, returns SUCCESS and stores the grid in
 *  the location given by result. Otherwise returns INVALID_GRID_FILE
 *  and does not change result.
 *
 */
int read_grid_file(char* filename, struct grid_t ** result) {
    int row, cell, width, height;
    FILE * file;
    int read_result;
	struct grid_t * grid;

    file = fopen(filename, "r");
	if (file == NULL) {
		printf("Error: Cannot open file\n");
		return INVALID_GRID_FILE;
	}
	

	// read first line as width
    read_result = fscanf(file, "%d ", &width);
	
	// check for errors during read 
	// (positive result = number of bytes read, negative = error code)
	if (read_result <= 0) {
		printf("Error: Cannot read width from file\n");
		
		// close file in case of error!
		fclose(file);
		return INVALID_GRID_FILE;
	}
	
	// read second line as height
	read_result = fscanf(file, "%d ", &height);
	if (read_result <= 0) {
		printf("Error: Cannot read height from file\n");
		fclose(file);
		return INVALID_GRID_FILE;
	}
	
	// allocate grid with the given dimensions
	
    make_grid(width, height, &grid);
	
	// read rows
    for (row = 0; row < height; ++row) {
		
		// for each row, read cells
        for (cell = 0; cell < width; ++cell) {
			
			// read character from file
            read_result = fgetc(file);
			
			// if there are not enough characters
			// write error message and release all resources used so far
			if (read_result == EOF) {
				free_grid(grid);
				fclose(file);
				printf("Error: Unexpected end of file\n");
				return INVALID_GRID_FILE;
			}
			
			// translate . and # to dead and living cells
			switch ((char)read_result) {
				case '.':
					grid->cells[row][cell] = CELL_DEAD;
					break;
				case '#':
					grid->cells[row][cell] = CELL_ALIVE;
					break;
					
				// other characters lead to an error
				// and we need to release/free file and memory again
				default:
					free_grid(grid);
					fclose(file);
					printf("Error: Unexpected character in grid cell: %c\n", (char)read_result);
					return INVALID_GRID_FILE;
			}
        }
		
        // read the newline character at the end of each row
		read_result = fgetc(file);
		
		// if that was'nt a newline, there is something wrong:
		if ((char)read_result != '\n') {
			free_grid(grid);
			fclose(file);
			printf("Error: Expected new line, but found character or end of file\n");
			return INVALID_GRID_FILE;
		}
    }
	
    fclose(file);
	*result = grid;	// write the grid pointer behind the given result pointer
	return SUCCESS;
}
Ejemplo n.º 24
0
void FreeMapData(void) {
	free_grid(MapData);
	free_grid(BinaryCollisionArray);
}
Ejemplo n.º 25
0
extern int      price_cdo(const int    *n_comp, 
                          const double *nominal,
                          const int     n_dates,
                          const double *dates,
                          const int     n_tranches,
                          const double *tr,
                          const double *intensity,
                          const int     n_rates,
                          const double *x_rates,
                          const double *y_rates,
                          const int    *t_recovery,
                          const double *recovery,
                          const int    *t_copula,
                          const double *p_copula,
                          const int    *t_method,
                          const int    *p_method,
                          double       *price,
                          double       *def_leg,
                          double       *pay_leg)
{
  int n=50;
  prod* produit;
  produit=malloc(sizeof(prod));
  produit->nominal=nominal[0];
  produit->nb=n_comp[0];
  produit->recov=recovery[0];
  produit->maturite=n_dates*dates[0];
  double *p;
  double *rho;
  double *tab;
  int e;
  double     **tab_sadd;
  double     ***U;

  int         n_sub = 1;
  double      x_intensity[2];
  double      y_intensity[2]; 
  double      i[n_sub];
  int         jt;
  int         jtr;
  int         n_mc;
  int         size_price;
  step_fun    *rates;
  company     **Co;
  CDO         *cdo;
  CDO         *hcdo;
  copula      *cop;
  grid        *x = NULL;
  grid        *t = NULL;
  cond_prob   *cp = NULL;
  double      **numdef = NULL;
  double      **losses = NULL;
  grid        **meanloss = NULL;
  int         jn;
  double      *dl;
  double      *pl;
  double      *hdl;
  double      *hpl;
  double      sum_nominal;
    
  Co = malloc(*n_comp * sizeof(company*));
  x_intensity[0] = 0.;
  x_intensity[1] = dates[n_dates-1];
  switch (*t_recovery) {
  case 1 :
    for (jn = 0; jn < *n_comp; jn++) { 
      y_intensity[0] = intensity[jn];
      y_intensity[1] = intensity[jn];
      Co[jn] = init_company_cov_cst(nominal[jn], n_sub, x_intensity, y_intensity, recovery[0]);
    }
    break;
  case 2 :
    for (jn = 0; jn < *n_comp; jn++) { 
      y_intensity[0] = intensity[jn];
      y_intensity[1] = intensity[jn];
      Co[jn] = init_company_cov_unif(nominal[jn], n_sub, x_intensity, y_intensity, recovery[0], recovery[1]);
    }
    break;
  case 3 :
    for (jn = 0; jn < *n_comp; jn++) { 
      y_intensity[0] = intensity[jn];
      y_intensity[1] = intensity[jn];
      Co[jn] = init_company_cov_gauss(nominal[jn], n_sub, x_intensity, y_intensity, recovery[0], recovery[1]);
    }
    break;
  }
  cdo = init_CDO(*n_comp, Co, n_dates, dates, n_tranches, tr);
  switch (*t_copula) {
  case 1 :
    cop = init_gaussian_copula(p_copula[0]);
    break;
  case 2 :
    cop = init_clayton_copula(p_copula[0]);
    break;
  case 3 :
    cop = init_nig_copula(p_copula[0], p_copula[1], p_copula[2]);
    break;
  case 4:
    cop=  init_student_copula( p_copula[0],p_copula[1]);
    break;
  case 5:
    cop=  init_double_t_copula( p_copula[0],p_copula[1],p_copula[2]);
    break;
  }
  rates = init_cont_linear_sf(n_rates-1, x_rates, y_rates);
 
  produit->rate=compute_sf(rates,1);

  switch (*t_method)
    {
    case 1 :
      if(*t_copula!=4){
        t = init_fine_grid(cdo->dates, p_method[0]);
        cp = init_cond_prob(cdo, cop, t);
        numdef = hw_numdef(cdo, cop, t, cp);
        print_numdef(cdo, t, numdef);
        meanloss = mean_losses_from_numdef(cdo, t, numdef);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      else{
        t = init_fine_grid(cdo->dates, p_method[0]);
        cp = init_cond_prob(cdo, cop, t);
        numdef = hw_numdef1(cdo, cop, t, cp);
        print_numdef(cdo, t, numdef);
        meanloss = mean_losses_from_numdef(cdo, t, numdef);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      break;
    case 2 :
      if(*t_copula!=4){
        t = init_fine_grid(cdo->dates, p_method[0]);
        cp = init_cond_prob(cdo, cop, t);
        numdef = lg_numdef(cdo, cop, t, cp);
        print_numdef(cdo, t, numdef);
        meanloss = mean_losses_from_numdef(cdo, t, numdef);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      else  {
        t = init_fine_grid(cdo->dates, p_method[0]);
        cp = init_cond_prob(cdo, cop, t);
        numdef = lg_numdef1(cdo, cop, t, cp);
   
        print_numdef(cdo, t, numdef);
        meanloss = mean_losses_from_numdef(cdo, t, numdef);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      break;
    case 3 :
      if(*t_copula!=4) {
        t = init_fine_grid(cdo->dates, p_method[0]);
        x = init_hom_grid(MINDOUBLE, (1.-recovery[0]), (1.-recovery[0])/(double) p_method[1]);
        cp = init_cond_prob(cdo, cop, t);
        losses = hw_losses_h(cdo, cop, t, x, cp);
        print_losses(cdo, t, x, losses);
        meanloss = mean_losses(cdo, t, x, losses);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      else{
        t = init_fine_grid(cdo->dates, p_method[0]);
        x = init_hom_grid(MINDOUBLE, (1.-recovery[0]), (1.-recovery[0])/(double) p_method[1]);
        cp = init_cond_prob(cdo, cop, t);
        losses = hw_losses_h1(cdo, cop, t, x, cp);
        print_losses(cdo, t, x, losses);
        meanloss = mean_losses(cdo, t, x, losses);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
     
      break;
    case 4 :
      if(*t_copula!=4){
        t = init_fine_grid(cdo->dates, p_method[0]);
        x = init_hom_grid(MINDOUBLE, (1.-recovery[0]), (1.-recovery[0])/(double) p_method[1]);
        cp = init_cond_prob(cdo, cop, t);
        losses = hw_losses_nh(cdo, cop, t, x, cp);
        print_losses(cdo, t, x, losses);
        meanloss = mean_losses(cdo, t, x, losses);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      else{  
        t = init_fine_grid(cdo->dates, p_method[0]);
        x = init_hom_grid(MINDOUBLE, (1.-recovery[0]), (1.-recovery[0])/(double) p_method[1]);
        cp = init_cond_prob(cdo, cop, t);
        losses = hw_losses_nh1(cdo, cop, t, x, cp);
        print_losses(cdo, t, x, losses);
        meanloss = mean_losses(cdo, t, x, losses);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }

      break;
    case 5 : 
      if(*t_copula!=4){   
        t = init_fine_grid(cdo->dates, p_method[0]);
        x = init_hom_grid(MINDOUBLE, (1.-recovery[0]), (1.-recovery[0])/(double) p_method[1]);
        cp = init_cond_prob(cdo, cop, t);
        losses = lg_losses(cdo, cop, t, x, cp);
        print_losses(cdo, t, x, losses);
        meanloss = mean_losses(cdo, t, x, losses);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      else{
        t = init_fine_grid(cdo->dates, p_method[0]);
        x = init_hom_grid(MINDOUBLE, (1.-recovery[0]), (1.-recovery[0])/(double) p_method[1]);
        cp = init_cond_prob(cdo, cop, t);
        losses = lg_losses1(cdo, cop, t, x, cp);
        print_losses(cdo, t, x, losses);
        meanloss = mean_losses(cdo, t, x, losses);
        pl = payment_leg(cdo, rates, t, meanloss);
        dl = default_leg(cdo, rates, t, meanloss);
      }
      break;
    case 6 :
      n_mc = p_method[0]; 
      pl = mc_payment_leg(cdo, cop, rates, n_mc);
      dl = mc_default_leg(cdo, cop, rates, n_mc);
   
      break;
    case 7 :
      if(*t_copula!=4) {
        n_mc = p_method[0];
        t = init_fine_grid(cdo->dates, p_method[1]);
        hcdo = homogenize_CDO(cdo);
        cp = init_cond_prob(hcdo, cop, t);
        numdef = lg_numdef(hcdo, cop, t, cp);
        meanloss = mean_losses_from_numdef(hcdo, t, numdef);
        hpl = payment_leg(hcdo, rates, t, meanloss);
        hdl = default_leg(hcdo, rates, t, meanloss);
        pl = mc_payment_vc_leg(cdo, cop, rates, n_mc);
        dl = mc_default_vc_leg(cdo, cop, rates, n_mc);
        for (jtr = 0; jtr < cdo->n_tranches-1; jtr++) {
          pl[jtr] = hpl[jtr] + pl[jtr];
          dl[jtr] = hdl[jtr] + dl[jtr];
        }
      }
      else
        {
          n_mc = p_method[0];
          t = init_fine_grid(cdo->dates, p_method[1]);
          hcdo = homogenize_CDO(cdo);
          cp = init_cond_prob(hcdo, cop, t);
          numdef = lg_numdef1(hcdo, cop, t, cp);
          meanloss = mean_losses_from_numdef(hcdo, t, numdef);
          hpl = payment_leg(hcdo, rates, t, meanloss);
          hdl = default_leg(hcdo, rates, t, meanloss);
          pl = mc_payment_vc_leg(cdo, cop, rates, n_mc);
          dl = mc_default_vc_leg(cdo, cop, rates, n_mc);
          for (jtr = 0; jtr < cdo->n_tranches-1; jtr++) {
            pl[jtr] = hpl[jtr] + pl[jtr];
            dl[jtr] = hdl[jtr] + dl[jtr];
          }
        }
      break;
    
    case 8:
    
      if((*t_copula!=4)&&(*t_copula!=2))
        {
          pl=malloc((cdo->n_tranches-1)*sizeof(double));
          dl=malloc((cdo->n_tranches-1)*sizeof(double));
          t = init_fine_grid(cdo->dates, p_method[0]);
          cp = init_cond_prob(cdo, cop, t);
          tab_sadd=malloc((cdo->n_tranches-1)*sizeof(double*));
          U=malloc((cdo->n_tranches-1)*sizeof(double**));
 
          for(jtr=0;jtr<cdo->n_tranches-1;jtr++){
            tab_sadd[jtr]=malloc((t->size)*sizeof(double));
            U[jtr]=malloc((t->size)*sizeof(double*)); 
          }
          for(jtr=0;jtr<cdo->n_tranches-1;jtr++){
            for(jt=0;jt<t->size;jt++){
              U[jtr][jt]=malloc((cop->size)*sizeof(double**));
            }
          }
  
          U=Uoptimal(cdo,cop,t,cp); 
          tab_sadd=saddlepoint(cdo,cop,t,cp,U);
  
          dl=default_leg_sadd(cdo,rates,t,tab_sadd,cop);      
          pl=payment_leg_sadd(cdo,rates,t,tab_sadd,cop);
        }
      else
        {
          printf("NON TREATED CASE\n");
          return(0);
        }
 
      break;


    case 9:

      rho=malloc(5*sizeof(double));
      tab=malloc(5*sizeof(double));
   
      for(e=0;e<5;e++){
        tab[e]=p_method[e];
      }

      pl=malloc((4.0+cdo->n_tranches)*sizeof(double));
      dl=malloc((4.0+cdo->n_tranches)*sizeof(double)); 
  
      rho=Base_correl(produit,tab,p_method[5],p_copula[0]);

      for (jtr = 0; jtr < cdo->n_tranches-1; jtr++) {
        produit->att=tr[jtr];
        produit->det=tr[jtr+1];
      
        pl[jtr] =pay_leg_base(produit,tab,p_method[5],p_copula[0]);
        dl[jtr] =dl_leg_base(produit,tab,p_method[5],p_copula[0]);
        
      }
      for(jtr=cdo->n_tranches-1;jtr<cdo->n_tranches+4;jtr++){
        pl[jtr]=rho[jtr-cdo->n_tranches+1];
      }
      if(p_copula[0]==1){
        for(jtr=0;jtr<4;jtr++){
          dl[jtr+cdo->n_tranches-1]=0.015+0.03*jtr;
        }
        dl[cdo->n_tranches+3]=0.17;
      }
      else if(p_copula[0]==2){
        dl[cdo->n_tranches-1]=0.015;
        dl[cdo->n_tranches]=0.05;      
        dl[cdo->n_tranches+1]=0.065;
        dl[cdo->n_tranches+2]=0.1125;
        dl[cdo->n_tranches+3]=0.225;
      }

      free(tab);
      free(rho);      
     
      
      break;

    case 10:
  
      p=malloc(n*sizeof(double));
      tab=malloc(5*sizeof(double));

      for(e=0;e<5;e++){
        tab[e]=p_method[e];
      }
      p=probaimpl(produit,tab,p_method[5],n,p_copula[0]);
      pl=malloc((n+cdo->n_tranches-1)*sizeof(double));
      dl=malloc((n+cdo->n_tranches-1)*sizeof(double));
   

      for (jtr = 0; jtr < cdo->n_tranches-1; jtr++) {
        produit->att=tr[jtr];
        produit->det=tr[jtr+1];
        pl[jtr] =pay_leg_impl(produit,p,n) ;
        dl[jtr] =dl_leg_impl(produit,p,n)  ;
      }
      dl[cdo->n_tranches-1]=p[0];
      pl[cdo->n_tranches-1]=0;   
      for(jtr=cdo->n_tranches;jtr<cdo->n_tranches+n-1;jtr++){
        pl[jtr]=(1+jtr-cdo->n_tranches)*0.1*1./(n-1);
        dl[jtr]=p[1+jtr-cdo->n_tranches]*(n-1)/0.1;
      }


      free(tab);
      free(p); 

      break;

    }

  
    
  size_price = n_tranches-1;
  if ((*t_method==6 )) size_price = 2*(n_tranches-1);
  if ((*t_method==7 )) size_price = 2*(n_tranches-1);
  if((*t_method ==9 )) size_price = (n_tranches+4.0);
  if((*t_method ==10 )) size_price = (n_tranches+49);
  
  for (jtr = 0; jtr < size_price; jtr++) {
    pay_leg[jtr] = (double) pl[jtr];
    def_leg[jtr] = (double) dl[jtr];
    price[jtr] = (def_leg[jtr] / (pay_leg[jtr])) * 10000.;
  }

  
  free_cdo(cdo);

  if (numdef != NULL) {
    for (jt = 0; jt < t->size; jt++) 
      free(numdef[jt]);
    free(numdef);
  }
  if (losses != NULL) {
    for (jt = 0; jt < t->size; jt++) 
      free(losses[jt]);
    free(losses);
  }
  if (cp != NULL) free_cond_prob(cp);
  if (meanloss != NULL) {
    for (jtr = 0; jtr < n_tranches-1; jtr++)
      free_grid(meanloss[jtr]);
    free(meanloss);
  }
  if (t != NULL) free_grid(t);
  if (x != NULL) free_grid(x);
  free(pl);
  free(dl);
  
  return (0);
}
Ejemplo n.º 26
0
int pPathfind(struct game *g, int checkonly)
{
    int i = 0, x, y;
    struct queue_t *queue;
	struct grid_t *grid;

    printf("Copying grid\n");

    grid = copy_grid(g);
    printf("Allocating queue\n");
    queue = alloc_queue(grid);
/*    printf("Have we crashed yet?\n");
    for(i=0;i< (signed int)grid->size;i++)
    {
        if ( i % grid->w == 0 ) printf("\n");
        switch(grid->ar[i]) {
            case 0:     printf("%3d",grid->path[i]); break;
            case 1:     printf("###"); break;
            case 2:     printf("XXX"); break;
            case 254:   printf("SSS"); break;
            case 255:   printf("EEE"); break;

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


    for(i=0; i < (signed int)grid->size; i++) {
        if (grid->ar[i] == 255) {
            push(queue, grid, i, 1);
        }
    }

    while (grid->marked[HEAD(queue).id] != 0) {
        checkfield(queue, grid);
        queue->head++;
		if ( queue->head >= (signed int)grid->size ) break;
//		printf("Gonna check: %d (%d)\n", HEAD(queue).id, queue->head);
    }

/*    for(i=0;i< (signed int)grid->size;i++)
    {
        if ( i % grid->w == 0 ) printf("\n");
        switch(grid->ar[i]) {
            case 0:     printf("%3d",grid->path[i]); break;
            case 1:     printf("###"); break;
			case 2:     printf("XXX"); break;
            case 254:   printf("SSS"); break;
            case 255:   printf("EEE"); break;

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


	if ( checkonly )
	{
		int ret = 0;
//		puts("We need to check if any of the entrances are blocked.");
		for(i=0;i<g->startN;i++)
		{
			if ( grid->path[g->start[i][0]+(g->start[i][1]*G_WIDTH)] > 0 )
			{
				continue;
			}
//			printf("Start position no: %d, cell %d x %d, is value %d\n", i, g->start[i][0], g->start[i][1]*G_WIDTH, grid->path[g->start[i][0]+(g->start[i][1]*G_WIDTH)]);
			ret++;
		}
		free_queue(queue);
		free_grid(grid);
		return ret;
	}

	i = 0;
    for(y=0; y < G_HEIGHT; y++) {
        for(x=0; x < G_WIDTH; x++) {
            g->path[y][x] = grid->path[i];
            i++;
        }
    }

    free_queue(queue);
    free_grid(grid);
    return 0;
}
Ejemplo n.º 27
0
/*==============================================================================
 * gen_refgrid: 
 *--------------------
 * 1. test current grid for refinement, and generate adaptive grid (if required) 
 * 2. re-link particles 
 * 3. ajdust densities as neccessary.
 *==============================================================================*/
boolean gen_refgrid(gridls **grid_list, int *no_grids)
{
  gridls *coa_grid, *fin_grid;     /* old/new grid pointer                    */
  boolean refined;                 /* refined YES/NO flag                     */
  boolean mg;                      /* does refinement hold enough particles   */
  int     idim;
  
#ifdef REF_TEST
  fprintf(stderr,"\ngen_refgrid:         current coarse grid         = %ld\n",
          (*grid_list + (*no_grids-1))->l1dim);
#endif
  
  /* set coarse grid pointer */
  coa_grid = *grid_list + *no_grids - 1;
  fin_grid = *grid_list + *no_grids;
  
  /* timing... */
  coa_grid->time.grid -= time(NULL);
  
  if(coa_grid->next == FALSE)  /* fin_grid does not exist ? */
    {
      /* reallocate the grid list array (including space for one additional grid) */
      (*grid_list) = (gridls *) realloc(*grid_list, (*no_grids + 1) * sizeof(gridls));
      
      if((*grid_list) == NULL)
        {
          fprintf(io.logfile,"gen_refgrid: error reallocating grid list\n");
          fflush(io.logfile);
          fclose(io.logfile);
          exit(1);
        }
      
      /* grid_list block might have moved in memory */
      global.dom_grid = *grid_list + global.domgrid_no;
      coa_grid        = *grid_list + *no_grids - 1;
      fin_grid        = *grid_list + *no_grids;
      
      /* fill in new grid's entries */
      fin_grid->masstodens     = coa_grid->masstodens     * CRITMULTI;
      fin_grid->masstopartdens = coa_grid->masstopartdens * CRITMULTI;
#ifdef MULTIMASS
      fin_grid->critdens       = simu.Nth_ref*fin_grid->masstopartdens;
#else
      fin_grid->critdens       = simu.Nth_ref*fin_grid->masstodens;
#endif
      fin_grid->timecounter    = coa_grid->timecounter;
      fin_grid->timestep       = coa_grid->timestep/2;
      fin_grid->l1dim          = coa_grid->l1dim * 2;
      fin_grid->spacing        = (double)1.0 / (double)fin_grid->l1dim;
      fin_grid->spacing2       = fin_grid->spacing * fin_grid->spacing;
      
      fin_grid->no_pquad       = 0;
      fin_grid->pquad_array    = NULL;

      /* we measure the time throughout the two DKD cycles of this fin_grid */
      fin_grid->time.potential = 0;
      fin_grid->time.density   = 0;
      fin_grid->time.DK        = 0;
      fin_grid->time.grid      = 0;
      fin_grid->time.hydro     = 0;
       
      fin_grid->no_sweeps      = 0;
      fin_grid->cur_resid      = 0.;
      
      /* remember that fin_grid exists from now on */
      fin_grid->next = FALSE;
      coa_grid->next = TRUE;
    }
  
  
  /* (re-)set values that are changing within the two DKD cycles the grid lives through */
  fin_grid->old_resid             = 0.0;
  fin_grid->cur_resid             = 0.0;
  
  fin_grid->multistep             = 0;
  
  
  /*------------------------------
   * now call refinement rountine 
   *------------------------------*/
  refined = refine_grid(fin_grid, coa_grid);
  
  if(refined)
    {
#ifdef REF_TEST
      fprintf(stderr,"                     placed new refinement       = %ld\n", fin_grid->l1dim);
#endif
      
      /* update number of grids */
      *no_grids += 1;
      
      /* now relink particles to new grid */
      mg = relink(coa_grid, fin_grid);        /* performs: unassign_part */
      
      /* now assign mass to new grid: THIS IS NEEDED AS IT RETURNS "mg" ! */
      zero_dens        (fin_grid);
      mg = assign_npart(fin_grid);
      
#ifdef REF_TEST
      fprintf(stderr,"             grid %6ld:  nnodes=%ld npart=%ld => %g (<! %g)\n",
              fin_grid->l1dim,fin_grid->size.no_nodes,fin_grid->size.no_part,
              (double)fin_grid->size.no_nodes/(double)fin_grid->size.no_part, CRITMULTI);
#endif
      
      /* only use grid if it holds enough particles */
      if(mg == FALSE)
        {
          refined = FALSE;
          relink_back(coa_grid, fin_grid);
          fin_grid->size.no_nodes         = 0;
          fin_grid->size.no_part          = 0;
          
          free_grid(fin_grid, no_grids);
          
#ifdef REF_TEST
          fprintf(stderr,"                     destroyed new refinement    = %ld (%g)\n",
                  fin_grid->l1dim, fin_grid->critdens);
#endif
        }
      else
        {
          /* get potential onto fine grid (important for boundaries !) */
          go_down(coa_grid);          
        }
    }
  
  else
    {
#ifdef REF_TEST
      fprintf(stderr,"                     NO new refinement grid !\n\n");
#endif
      /*
       * no need to call free_grid() 
       * -> temporary pquads, cquads, nquads already destroyed within ref_grid() 
       *
       * no need to realloc grid_list
       * -> grid will be kept in memory from now on...
       */
    }
  
  /* grid_list block might have changed position in memory */
  global.dom_grid = *grid_list + global.domgrid_no;
  
  /* ...timing */
  coa_grid->time.grid += time(NULL);
  
  return(refined);
}
Ejemplo n.º 28
0
void free_grid_all()
{
	set_status_label_info("Grid","Nothing");
	if(grid)
		grid = free_grid(grid);
}