Esempio n. 1
0
void gen_biosum( char *runname, int year, struct image_header out_head)
{
    int row;                // row counter
    int col;                // column counter
    int index;              // array index
    double livebiomass;
    double livebiomass2;
    double deadbiomass;
    double deadbiomass2;
    char yearstr[10];       // current summary year
    char outfilename[30];   // output file name
    char outfilename2[30];  // transition output file name

    // open output files
    strcpy(outfilename, runname);
    itoa(year, yearstr, 10);
    strcat(outfilename, yearstr);
    strcat(outfilename, "l");
    strcat(outfilename, ".gis");

    strcpy(outfilename2, runname);
    itoa(year, yearstr, 10);
    strcat(outfilename2, yearstr);
    strcat(outfilename2, "d");
    strcat(outfilename2, ".gis");

    // write grid cell information to temporary grids
   	for(row=0; row<maxrow; row++) {
		for(col=0; col<maxcol; col++) {
			index=row*maxcol + col;

            if(buffer[index] == 1) {
                if(tsfire[index] == age[index]) {
                    livebiomass = calc_live_biomass ( index );
                } else {
                    livebiomass = calc_live_biomass ( index );
                }
                livebiomass2 = ceil(livebiomass/10) + 1;
                temp[index] = (unsigned char)livebiomass2;
                deadbiomass = deadgrid[index];
                deadbiomass2 = ceil(deadbiomass/10) + 1;
                temp2[index] = (unsigned char)deadbiomass2;
            } else {
                temp[index] = 0;
                temp2[index] = 0;
            }
        }
    }

    // write grids to output files
    write_grid(outfilename, temp, out_head);
    write_grid(outfilename2, temp2, out_head);




    return;
}
Esempio n. 2
0
//----------------------------------------------------------------------------
// gen_agesum - generate "snapshot" of age variables
//----------------------------------------------------------------------------
void gen_agesum( char *runname, int year, struct image_header out_head, int timestep)
{
    int row;                // row counter
    int col;                // column counter
    int index;              // array index
    char yearstr[10];       // current summary year
    char outfilename[30];   // output file name
    char outfilename2[30];  // transition output file name

    // open output file
    strcpy(outfilename, runname);
    strcpy(outfilename2, runname);
    itoa(year, yearstr, 10);
    strcat(outfilename, yearstr);
    strcat(outfilename2, yearstr);
    strcat(outfilename, "a");
    strcat(outfilename2, "t");
    strcat(outfilename, ".gis");
    strcat(outfilename2, ".gis");

    // write grid cell information to temporary grids
   	for(row=0; row<maxrow; row++) {
		for(col=0; col<maxcol; col++) {
			index=row*maxcol + col;

            if(buffer[index] == 1) {
                if(age[index] <= 255 * timestep) {
                    temp[index] = 1 + (unsigned char)(age[index]/timestep);
                } else {
                    temp[index] = 255;
                }
                if(tsfire[index] <= 255 * timestep) {
                    temp2[index] = 1 + (unsigned char)(tsfire[index]/timestep);
                } else {
                    temp2[index] = 255;
                }
            } else {
                temp[index] = 0;
                temp2[index] = 0;
            }
        }
    }

    // write grids to output files
    write_grid(outfilename, temp, out_head);
    write_grid(outfilename2, temp2, out_head);

    return;
}
Esempio n. 3
0
//----------------------------------------------------------------------------
// gen_sevsum - generates two fire severity summary grids
// one for % of stand-replacement fires, one for % of mixed-severity fires
//----------------------------------------------------------------------------
void gen_sevsum( char *filename, int nsum, struct image_header out_head )
{
    int row;                // row counter
    int col;                // column counter
    int index;              // array index
    short int struc;        // forest structure index
    char outfilename1[30], outfilename2[30];   // output file name


    // open output file
    strcpy(outfilename1, filename);
    strcat(outfilename1, "hs.gis");

    // write summary information - stand-replacement fire severity
   	for(row=0; row<maxrow; row++) {
		for(col=0; col<maxcol; col++) {
			index=row*maxcol + col;
            if(buffer[index] == 1 && fsum1[index] > 0) {
                struc = (short)ceil(100 *(long double)fsum2[index]/(long double)fsum1[index]);
            } else {
                struc = 0;
            }
            temp[index] = (unsigned char)struc;
        }
    }

    write_grid(outfilename1, temp, out_head);

    // open output file
    strcpy(outfilename2, filename);
    strcat(outfilename2, "ms.gis");

	// write summary information - mixed fire severity
   	for(row=0; row<maxrow; row++) {
		for(col=0; col<maxcol; col++) {
			index=row*maxcol + col;
            if(buffer[index] == 1 && fsum1[index] > 0) {
                struc = (short)ceil(100 *(long double)fsum3[index]/(long double)fsum1[index]);
            } else {
                struc = 0;
            }
            temp[index] = (unsigned char)struc;
        }
    }

    write_grid(outfilename2, temp, out_head);

    return;
}
Esempio n. 4
0
/*
 * Prepare process for a clean termination.
 */
void cleanup (struct life_t * life) 
{
	write_grid(life);
	free_grids(life);

	MPI_Finalize();
}
Esempio n. 5
0
int main()
{
    herr_t status = FAIL;    
    hid_t  gdfid = FAIL;

    /* Create a file. */
    gdfid = HE5_GDopen("grid_2_2d.h5", H5F_ACC_TRUNC);

    /* Write two identical grids except names. */
    write_grid(gdfid, "GeoGrid1");
    write_grid(gdfid, "GeoGrid2");

    /* Close the file. */
    status = HE5_GDclose(gdfid);
    return 0;
}
Esempio n. 6
0
//----------------------------------------------------------------------------
// gen_firesum - generates summary grid for fire frequency
//----------------------------------------------------------------------------
void gen_firesum( char *filename, int nsum, struct image_header out_head, int timestep )
{
    int row;                // row counter
    int col;                // column counter
    int index;              // array index
    short int struc;        // forest structure index
    char outfilename[30];   // output file name

    // open output file
    strcpy(outfilename, filename);
    strcat(outfilename, "ff.gis");

    // write grid cell information
   	for(row=0; row<maxrow; row++) {
		for(col=0; col<maxcol; col++) {
			index=row*maxcol + col;
            if(buffer[index] == 1 && fsum1[index] > 0) {
                struc = (short)ceil((long double)nsum/(long double)fsum1[index]/ timestep);
            } else {
                struc = 0;
            }
            temp[index] = (unsigned char)struc;
        }
    }

    write_grid(outfilename, temp, out_head);

    return;
}
Esempio n. 7
0
void agrid2_write (agrid2 pnt, float*** dat) 
/*< dump the grid in an array >*/
{
    int i2;

    for (i2 = 0; i2 < pnt->n2; i2++) {
	dat[i2] = write_grid (pnt->ent[i2]);
    }
}
Esempio n. 8
0
int main()
{
    herr_t status = FAIL;
    hid_t  gdfid = FAIL;
    /* Create a file. */
    gdfid = HE5_GDopen("grid_1_3d_zz.h5", H5F_ACC_TRUNC);

    /* Write a grid. */
    write_grid(gdfid, "GeoGrid");

    /* Close the file. */
    status = HE5_GDclose(gdfid);
    return 0;
}
Esempio n. 9
0
    exit_t main()
    {
        std::vector<int> grid;
        dimension dim;
        read_grid(stdin, &grid, &dim);
        const int grid_size = dim.area_without_border();
        int idx;
        for(int i = 1; i < argc; i++)
        {
            idx = atoi(argv[i]);
            if(! human_idx_on_grid(grid_size, idx))
                exit("You must assert for each index i: 0 <= i < area.");
            grid[human2internal(atoi(argv[i]),dim.width())]++;
        }

        write_grid(stdout, &grid, &dim);
        return exit_t::success;
    }
Esempio n. 10
0
//----------------------------------------------------------------------------
// gen_snapshot - generate "snapshot" of landscape configuration at a single point in time
//----------------------------------------------------------------------------
void gen_snapshot( char *runname, int year, struct image_header out_head,
    int snapsum, int transsum )
{
    int row;                // row counter
    int col;                // column counter
    int index;              // array index
    short int struc;        // forest structure index
    char yearstr[10];       // current summary year
    char outfilename[30];   // output file name

    // open output file
    strcpy(outfilename, runname);
    itoa(year, yearstr, 10);
    strcat(outfilename, yearstr);
    strcat(outfilename, ".gis");

    // write grid cell information to temporary grids
   	for(row=0; row<maxrow; row++) {
		for(col=0; col<maxcol; col++) {
			index=row*maxcol + col;
            if(buffer[index] == 1) {
                struc = get_struc(index);
                temp[index] = (unsigned char)struc;
            } else {
                temp[index] = 0;
            }

        }
    }
	
	//Added by Ashis 12/28/2012
	// write lcc info into temp grid

	merg_lccSnapshot();

    // write grids to output files
    if (snapsum > 0) {
        write_grid(outfilename, temp, out_head);
    }

    return;
}
Esempio n. 11
0
//----------------------------------------------------------------------------
// gen_strucsum - generates summary grids for percent time in each successional stage
//----------------------------------------------------------------------------
void gen_strucsum( char *runname, int nclass, int nsum, struct image_header out_head )
{
    int row;                // row counter
    int col;                // column counter
    int index;              // grid index
    int index2;             // index for accessing 3-d stucture summary array
    int clasloop;           // counter for looping through structure classes
    int struc;              // forest structure index
    char classtr[10];       // current summary year
    char outfilename[30];   // output file name

    for(clasloop = 0; clasloop < nclass; clasloop ++) {

        // open output file
        strcpy(outfilename, runname);
        strcat(outfilename, "s");
        itoa(clasloop + 1, classtr, 10);
        strcat(outfilename, classtr);
        strcat(outfilename, ".gis");

   	    for(row=0; row<maxrow; row++) {
		    for(col=0; col<maxcol; col++) {
			    index=row*maxcol + col;
                if(buffer[index] == 1) {
                    index2=row*maxcol + col + clasloop * size;
					struc = (int)ceil(100 * runstep * (long double)strucsum[index2]/(long double)nsum);
					//struc = (int)ceil(100 * (long double)strucsum[index2]/(long double)nsum);
                } else {
                    struc = 0;
                }
                temp[index] = (unsigned char)struc;
            }
        }

        write_grid(outfilename, temp, out_head);

    }

    return;
}
BOOL WeeklyRout_InsertDia::DestroyWindow()
{
	// TODO: 在此添加专用代码和/或调用基类
	write_grid();//////////////////////////////////////////////write_multi only ont times
	return CDialog::DestroyWindow();
}
Esempio n. 13
0
int main(int argc, char* argv[])
{
    int nx, na, na2, ia, nz, order, maxsplit, ix, iz, *siz;
    float **place, *slow, **out, dx,dz, x0,z0, x[2];
    float max1, min1, max2, min2;
    bool isvel, lsint;
    agrid grd;
    sf_file vel, outp, size, grid;
        
    sf_init (argc,argv);

    /* get 2-D grid parameters */
    vel = sf_input("in");
    if (!sf_histint(vel,"n1",&nz)) sf_error("No n1= in input");
    if (!sf_histint(vel,"n2",&nx)) sf_error("No n2= in input");
    if (!sf_histfloat(vel,"d1",&dz)) sf_error("No d1= in input");
    if (!sf_histfloat(vel,"d2",&dx)) sf_error("No d2= in input");
    if (!sf_histfloat(vel,"o1",&z0)) z0=0.;
    if (!sf_histfloat(vel,"o2",&x0)) x0=0.;

    outp = sf_output("out");
    
    sf_putint(outp,"n4",nz);
    sf_putfloat(outp,"d4",dz);
    sf_putfloat(outp,"o4",z0);

    sf_putint(outp,"n3",nx);
    sf_putfloat(outp,"d3",dx);
    sf_putfloat(outp,"o3",x0);

    if (!sf_getint("na",&na)) na=60;
    /* number of angles */
    if (!sf_getfloat("da",&da)) da=3.1;
    /* angle increment (in degrees) */
    if (!sf_getfloat("a0",&a0)) a0=-90.;
    /* initial angle (in degrees) */

    if (!sf_getint("maxsplit",&maxsplit)) maxsplit=10;
    /* maximum splitting for adaptive grid */

    if (!sf_getfloat("minx",&min1)) min1=0.5*dx;
    /* parameters for adaptive grid */
    if (!sf_getfloat("maxx",&max1)) max1=2.*dx;
    if (!sf_getfloat("mina",&min2)) min2=0.5*da;
    if (!sf_getfloat("maxa",&max2)) max2=2.*da;

    sf_putint(outp,"n2",na);
    sf_putfloat(outp,"d2",da);
    sf_putfloat(outp,"o2",a0);

    da *= (SF_PI/180.);
    a0 *= (SF_PI/180.);

    sf_putint(outp,"n1",5);

    size = sf_output("size");
    sf_putint(size,"n1",nx);
    sf_putint(size,"n2",nz);
    sf_settype(size,SF_INT);

    grid = sf_output("grid");

    /* additional parameters */
    if(!sf_getbool("vel",&isvel)) isvel=true;
    /* y: velocity, n: slowness */
    if(!sf_getint("order",&order)) order=3;
    /* velocity interpolation order */
    if (!sf_getbool("lsint",&lsint)) lsint=false;
    /* if use least-squares interpolation */

    slow  = sf_floatalloc(nz*nx);
    place = sf_floatalloc2(5,na);
    siz  = sf_intalloc(nx);

    sf_floatread(slow,nx*nz,vel);

    if (isvel) {
      for(ix = 0; ix < nx*nz; ix++){
	slow[ix] = 1./slow[ix];
      }
    }

    ct = sf_celltrace_init (lsint, order, nz*nx, nz, nx, dz, dx, z0, x0, slow);
    free (slow);

    grd = agrid_init (na, 5, maxsplit);
    agrid_set (grd,place);

    for (iz = 0; iz < nz; iz++) {
	x[0] = z0+iz*dz;

	sf_warning("depth %d of %d;",iz+1, nz);
	for (ix = 0; ix < nx; ix++) {
	    x[1] = x0+ix*dx;

	    fill_grid(grd,min1,max1,min2,max2,(void*) x, raytrace);
	
	    na2 = grid_size (grd);
	    out = write_grid (grd);

	    siz[ix] = na2;
	
	    for (ia=0; ia < na2; ia++) {
	      if (ia < na)
		  sf_floatwrite (place[ia], 5, outp);

	      sf_floatwrite(out[ia], 5, grid);
	    }
	    free (out);
	}
	
	sf_intwrite (siz,nx,size);
    }
    sf_warning(".");

    exit (0);
}
Esempio n. 14
0
File: main.c Progetto: caomw/grass
int main(int argc, char *argv[])
{

    /* loop */
    int i, j;

    /* store filename and path  */
    char *dig_file;
    
    char buf[2000];

    /* Other local variables */
    int attCount, nbreaks;

    struct grid_description grid_info;
    struct Cell_head window;
    struct Map_info Map;
    struct Option *vectname, *grid, *coord, *box, *angle, *position_opt, *breaks;
    struct GModule *module;
    struct Flag *points_fl, *line_fl;
    int points_p, line_p, output_type;
    char *desc;

    struct line_pnts *Points;
    struct line_cats *Cats;

    /* Attributes */
    struct field_info *Fi;
    dbDriver *Driver;
    dbString sql;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    module->description = _("Creates a vector map of a user-defined grid.");

    vectname = G_define_standard_option(G_OPT_V_OUTPUT);
    vectname->key = "map";

    grid = G_define_option();
    grid->key = "grid";
    grid->key_desc = _("rows,columns");
    grid->type = TYPE_INTEGER;
    grid->required = YES;
    grid->multiple = NO;
    grid->description = _("Number of rows and columns in grid");

    position_opt = G_define_option();
    position_opt->key = "position";
    position_opt->type = TYPE_STRING;
    position_opt->required = NO;
    position_opt->multiple = NO;
    position_opt->options = "region,coor";
    position_opt->answer = "region";
    position_opt->description = _("Where to place the grid");
    desc = NULL;
    G_asprintf(&desc,
            "region;%s;coor;%s",
            _("current region"),
            _("use 'coor' and 'box' options"));
    position_opt->descriptions = desc;

    coord = G_define_option();
    coord->key = "coor";
    coord->key_desc = "x,y";
    coord->type = TYPE_DOUBLE;
    coord->required = NO;
    coord->multiple = NO;
    coord->description =
	_("Lower left easting and northing coordinates of map");

    box = G_define_option();
    box->key = "box";
    box->key_desc = _("width,height");
    box->type = TYPE_DOUBLE;
    box->required = NO;
    box->multiple = NO;
    box->description = _("Width and height of boxes in grid");

    angle = G_define_option();
    angle->key = "angle";
    angle->type = TYPE_DOUBLE;
    angle->required = NO;
    angle->description =
	_("Angle of rotation (in degrees counter-clockwise)");
    angle->answer = "0";

    breaks = G_define_option();
    breaks->key = "breaks";
    breaks->type = TYPE_INTEGER;
    breaks->required = NO;
    breaks->description =
	_("Number of vertex points per grid cell");
    breaks->options = "0-60";
    breaks->answer = "3";

    points_fl = G_define_flag();
    points_fl->key = 'p';
    points_fl->description =
	_("Create grid of points instead of areas and centroids");

    line_fl = G_define_flag();
    line_fl->key = 'l';
    line_fl->description =
	_("Create grid as lines, instead of areas");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    line_p = line_fl->answer;
    if (line_p) {
	output_type = GV_LINE;
    } else {
	output_type = GV_BOUNDARY;
    }

    points_p = points_fl->answer;

    /* get the current window  */
    G_get_window(&window);

    /*
     * information we need to collect from user: origin point x and y (lower
     * left), shift in x, shift in y,  number of rows, number of cols
     */
    dig_file = G_store(vectname->answer);

    /* Number of row and cols */
    grid_info.num_rows = atoi(grid->answers[0]);
    grid_info.num_cols = atoi(grid->answers[1]);

    grid_info.angle = M_PI / 180 * atof(angle->answer);

    nbreaks = atoi(breaks->answer);

    /* Position */
    if (position_opt->answer[0] == 'r') {	/* region */
	if (coord->answer)
	    G_fatal_error(_("'coor' and 'position=region' are exclusive options"));

	if (box->answer)
	    G_fatal_error(_("'box' and 'position=region' are exclusive options"));

	if (grid_info.angle != 0.0)
	    G_fatal_error(_("'angle' and 'position=region' are exclusive options"));

	grid_info.origin_x = window.west;
	grid_info.origin_y = window.south;

	grid_info.length = (window.east - window.west) / grid_info.num_cols;
	grid_info.width = (window.north - window.south) / grid_info.num_rows;

	G_debug(2, "x = %e y = %e l = %e w = %e", grid_info.origin_x,
		grid_info.origin_y, grid_info.length, grid_info.width);
    }
    else {
	if (!coord->answer)
	    G_fatal_error(_("'coor' option missing"));

	if (!box->answer)
	    G_fatal_error(_("'box' option missing"));

	if (!G_scan_easting
	    (coord->answers[0], &(grid_info.origin_x), window.proj))
	    G_fatal_error(_("Invalid easting"));;
	if (!G_scan_northing
	    (coord->answers[1], &(grid_info.origin_y), window.proj))
	    G_fatal_error(_("Invalid northing"));;

	if (!G_scan_resolution
	    (box->answers[0], &(grid_info.length), window.proj))
	    G_fatal_error(_("Invalid distance"));;
	if (!G_scan_resolution
	    (box->answers[1], &(grid_info.width), window.proj))
	    G_fatal_error(_("Invalid distance"));;

    }

    /*
     * vector rows are the actual number of rows of vectors to make up the
     * entire grid.   ditto for cols.
     */
    grid_info.num_vect_rows = grid_info.num_rows + 1;
    grid_info.num_vect_cols = grid_info.num_cols + 1;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    db_init_string(&sql);

    /* Open output map */
    if (0 > Vect_open_new(&Map, dig_file, 0)) {
	G_fatal_error(_("Unable to create vector map <%s>"), dig_file);
    }

    Vect_hist_command(&Map);

    /* Open database, create table */
    Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Map, Fi->number, Fi->name, Fi->table, Fi->key,
			Fi->database, Fi->driver);

    Driver =
	db_start_driver_open_database(Fi->driver,
				      Vect_subst_var(Fi->database, &Map));
    if (Driver == NULL)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);
    db_set_error_handler_driver(Driver);

    if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer, "
		"rown varchar(1), coln varchar(1))", Fi->table);
    }
    else {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer)",
		Fi->table);
    }
    db_set_string(&sql, buf);

    G_debug(1, "SQL: %s", db_get_string(&sql));

    if (db_execute_immediate(Driver, &sql) != DB_OK) {
	G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql));
    }

    if (db_create_index2(Driver, Fi->table, Fi->key) != DB_OK)
	G_warning(_("Unable to create index"));

    if (db_grant_on_table
	(Driver, Fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK)
	G_fatal_error(_("Unable to grant privileges on table <%s>"),
		      Fi->table);

    if (!points_p) {
	/* create areas */
	write_grid(&grid_info, &Map, nbreaks, output_type);
    }

    /* Create a grid of label points at the centres of the grid cells */
    G_verbose_message(_("Creating centroids..."));

    /* Write out centroids and attributes */
    /* If the output id is lines it skips to add centroids and attributes
       TODO decide what to write in the attribute table
     */
    if (!line_p) {
      db_begin_transaction(Driver);
      attCount = 0;
      for (i = 0; i < grid_info.num_rows; ++i) {
	  for (j = 0; j < grid_info.num_cols; ++j) {
	      double x, y;
	      const int point_type = points_p ? GV_POINT : GV_CENTROID;

	      x = grid_info.origin_x + (0.5 + j) * grid_info.length;
	      y = grid_info.origin_y + (0.5 + i) * grid_info.width;

	      rotate(&x, &y, grid_info.origin_x, grid_info.origin_y,
		    grid_info.angle);

	      Vect_reset_line(Points);
	      Vect_reset_cats(Cats);

	      Vect_append_point(Points, x, y, 0.0);
	      Vect_cat_set(Cats, 1, attCount + 1);
	      Vect_write_line(&Map, point_type, Points, Cats);

	      sprintf(buf, "insert into %s values ", Fi->table);
	      if (db_set_string(&sql, buf) != DB_OK)
		  G_fatal_error(_("Unable to fill attribute table"));

	      if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
		  sprintf(buf,
			  "( %d, %d, %d, '%c', '%c' )",
			  attCount + 1, grid_info.num_rows - i,
			  j + 1, 'A' + grid_info.num_rows - i - 1, 'A' + j);
	      }
	      else {
		  sprintf(buf, "( %d, %d, %d )",
			  attCount + 1, i + 1, j + 1);
	      }
	      if (db_append_string(&sql, buf) != DB_OK)
		      G_fatal_error(_("Unable to fill attribute table"));

	      G_debug(3, "SQL: %s", db_get_string(&sql));

	      if (db_execute_immediate(Driver, &sql) != DB_OK) {
		  G_fatal_error(_("Unable to insert new record: %s"),
			      db_get_string(&sql));
	      }
	      attCount++;
	  }
      }
    }
    db_commit_transaction(Driver);

    db_close_database_shutdown_driver(Driver);

    Vect_build(&Map);
    Vect_close(&Map);

    exit(EXIT_SUCCESS);
}
Esempio n. 15
0
int
main(int argc, char *argv[])
{
    char input[MAX_FILENAME_SIZE];
    int c;
    int iterations = 1;
    int generate = 0;
    struct Grid *grid;
    struct Grid *tmp_grid;

    if (argc < 2) {
        help();
        return 0;
    }

    while ((c = getopt(argc, argv, "?hv:n:i:g")) != -1) {
        switch (c) {
            case 'h':
            case 'v':
                help();
                return 0;
            case 'n':
                iterations = atoi((char *) getopt);
                break;
            case 'i':
                strncpy(input, optarg, MAX_FILENAME_SIZE);
                break;
            case 'g':
                generate = 1;
                break;
            default:
                help();
                return 0;
        }
    } 

    if (argc != optind) {
        help();
        return 0;
    }

    grid = allocate_grid();
    tmp_grid = allocate_grid();
    if (!grid || !tmp_grid) {
        printf("error: out of memory\n");
        return -1;
    }
    if (generate) {
        generate_grid(grid);
    } else {
        read_grid(input, grid); 
    }
    for (c = 0; c < iterations; c++) {
        mean_filter(grid, tmp_grid);
        struct Grid *tmp = grid;
        grid = tmp_grid;
        tmp_grid = tmp;
    }
    write_grid(grid);
    cleanup_grid(grid);
    cleanup_grid(tmp_grid);

    return 0;
}
Esempio n. 16
0
int main(int argc, char *argv[]){
  int     n_species;
  int     n_load;
  int     n_used;
  int     flag_used[N_GADGET_TYPE];
  char    species_name[256];
  double  h_Hubble;
  double  n_spec;
  double  redshift;
  int     i_species;
  char    n_string[64];
  int             n[3];
  double          L[3];
  FILE           *fp_1D;
  FILE           *fp_2D;
  cosmo_info     *cosmo;
  field_info     *field[N_GADGET_TYPE];
  field_info     *field_norm[N_GADGET_TYPE];
  plist_info      plist_header;
  plist_info      plist;
  FILE           *fp;
  int     i_temp;
  int     n_temp;
  double *k_temp;
  double *kmin_temp;
  double *kmax_temp;
  double *P_temp;
  size_t *n_mode_temp;
  double *sigma_P_temp;
  double *shot_noise_temp;
  double *dP_temp;
  int     snapshot_number;
  int     i_compute;
  int     distribution_scheme;
  double  k_min_1D;
  double  k_max_1D;
  double  k_min_2D;
  double  k_max_2D;
  int     n_k_1D;
  int     n_k_2D;
  double *k_1D;
  double *P_k_1D;
  double *dP_k_1D;
  int    *n_modes_1D;
  double *P_k_2D;
  double *dP_k_2D;
  int    *n_modes_2D;
  int     n_groups=1;
  double  dk_1D;
  double  dk_2D;
  char   *grid_identifier;

  // Initialization -- MPI etc.
  SID_init(&argc,&argv,NULL,NULL);

  // Parse arguments
  int grid_size;
  char filename_in_root[MAX_FILENAME_LENGTH];
  char filename_out_root[MAX_FILENAME_LENGTH];
  strcpy(filename_in_root,  argv[1]);
  snapshot_number=(int)atoi(argv[2]);
  strcpy(filename_out_root, argv[3]);
  grid_size      =(int)atoi(argv[4]);
  if(!strcmp(argv[5],"ngp") || !strcmp(argv[5],"NGP"))
     distribution_scheme=MAP2GRID_DIST_NGP;
  else if(!strcmp(argv[5],"cic") || !strcmp(argv[5],"CIC"))
     distribution_scheme=MAP2GRID_DIST_CIC;
  else if(!strcmp(argv[5],"tsc") || !strcmp(argv[5],"TSC"))
     distribution_scheme=MAP2GRID_DIST_TSC;
  else if(!strcmp(argv[5],"d12") || !strcmp(argv[5],"D12"))
     distribution_scheme=MAP2GRID_DIST_DWT12;
  else if(!strcmp(argv[5],"d20") || !strcmp(argv[5],"D20"))
     distribution_scheme=MAP2GRID_DIST_DWT20;
  else
     SID_trap_error("Invalid distribution scheme {%s} specified.",ERROR_SYNTAX,argv[5]);

  SID_log("Smoothing Gadget file {%s;snapshot=#%d} to a %dx%dx%d grid with %s kernel...",SID_LOG_OPEN|SID_LOG_TIMER,
          filename_in_root,snapshot_number,grid_size,grid_size,grid_size,argv[5]);

  // Initialization -- fetch header info
  SID_log("Reading Gadget header...",SID_LOG_OPEN);
  gadget_read_info   fp_gadget;
  int                flag_filefound=init_gadget_read(filename_in_root,snapshot_number,&fp_gadget);
  int                flag_multifile=fp_gadget.flag_multifile;
  int                flag_file_type=fp_gadget.flag_file_type;
  gadget_header_info header        =fp_gadget.header;
  double             box_size      =(double)(header.box_size);
  size_t            *n_all         =(size_t *)SID_calloc(sizeof(size_t)*N_GADGET_TYPE);
  size_t             n_total;
  if(flag_filefound){
     if(SID.I_am_Master){
        FILE *fp_in;
        char  filename[MAX_FILENAME_LENGTH];
        int   block_length_open;
        int   block_length_close;
        set_gadget_filename(&fp_gadget,0,filename);
        fp_in=fopen(filename,"r");
        fread_verify(&block_length_open, sizeof(int),1,fp_in);
        fread_verify(&header,            sizeof(gadget_header_info),1,fp_in);
        fread_verify(&block_length_close,sizeof(int),1,fp_in);
        fclose(fp_in);
        if(block_length_open!=block_length_close)
           SID_trap_error("Block lengths don't match (ie. %d!=%d).",ERROR_LOGIC,block_length_open,block_length_close);
     }
     SID_Bcast(&header,sizeof(gadget_header_info),MASTER_RANK,SID.COMM_WORLD);
     redshift=header.redshift;
     h_Hubble=header.h_Hubble;
     box_size=header.box_size;
     if(SID.n_proc>1)
        n_load=1;
     else
        n_load=header.n_files;
     for(i_species=0,n_total=0,n_used=0;i_species<N_GADGET_TYPE;i_species++){
        n_all[i_species]=(size_t)header.n_all_lo_word[i_species]+((size_t)header.n_all_hi_word[i_species])<<32;
        n_total+=n_all[i_species];
        if(n_all[i_species]>0){
           n_used++;
           flag_used[i_species]=TRUE;
        }
        else
           flag_used[i_species]=FALSE;
     }

     // Initialize cosmology
     double box_size        =((double *)ADaPS_fetch(plist.data,"box_size"))[0];
     double h_Hubble        =((double *)ADaPS_fetch(plist.data,"h_Hubble"))[0];
     double redshift        =((double *)ADaPS_fetch(plist.data,"redshift"))[0];
     double expansion_factor=((double *)ADaPS_fetch(plist.data,"expansion_factor"))[0];
     double Omega_M         =((double *)ADaPS_fetch(plist.data,"Omega_M"))[0];
     double Omega_Lambda    =((double *)ADaPS_fetch(plist.data,"Omega_Lambda"))[0];
     double Omega_k         =1.-Omega_Lambda-Omega_M;
     double Omega_b=0.; // not needed, so doesn't matter
     double f_gas  =Omega_b/Omega_M;
     double sigma_8=0.; // not needed, so doesn't matter
     double n_spec =0.; // not needed, so doesn't matter
     char   cosmo_name[16];
     sprintf(cosmo_name,"Gadget file's");
     init_cosmo(&cosmo,
                cosmo_name,
                Omega_Lambda,
                Omega_M,
                Omega_k,
                Omega_b,
                f_gas,
                h_Hubble,
                sigma_8,
                n_spec);
  }
  SID_log("Done.",SID_LOG_CLOSE);

  grid_identifier=(char *)SID_calloc(GRID_IDENTIFIER_SIZE*sizeof(char));

  // Only process if there are >0 particles present
  if(n_used>0){

     // Loop over ithe real-space and 3 redshift-space frames
     int i_write;
     int i_run;
     int n_run;
     int n_grids_total; 
     n_grids_total=4; // For now, hard-wire real-space density and velocity grids only
     n_run=1;         // For now, hard-wire real-space calculation only
     for(i_run=0,i_write=0;i_run<n_run;i_run++){

        // Read catalog
        int  n_grid;
        char i_run_identifier[8];
        switch(i_run){
        case 0:
           SID_log("Processing real-space ...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"r");
           n_grid=4;
           break;
        case 1:
           SID_log("Processing v_x redshift space...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"x");
           n_grid=1;
           break;
        case 2:
           SID_log("Processing v_y redshift space...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"y");
           n_grid=1;
           break;
        case 3:
           SID_log("Processing v_z redsift space...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"z");
           n_grid=1;
           break;
        }

        // For each i_run case, loop over the fields we want to produce
        int i_grid;
        for(i_grid=0;i_grid<n_grid;i_grid++){

           char i_grid_identifier[8];
           switch(i_grid){
           case 0:
              SID_log("Processing density grid ...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"rho");
              break;
           case 1:
              SID_log("Processing v_x velocity grid...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"v_x");
              break;
           case 2:
              SID_log("Processing v_y velocity grid...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"v_y");
              break;
           case 3:
              SID_log("Processing v_z velocity grid...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"v_z");
              break;
           }

           // Initialize the field that will hold the grid
           int        n[]={grid_size,grid_size,grid_size};
           double     L[]={box_size, box_size, box_size};
           int        i_init;
           for(i_species=0;i_species<N_GADGET_TYPE;i_species++){
              if(flag_used[i_species]){
                 field[i_species]     =(field_info *)SID_malloc(sizeof(field_info));
                 field_norm[i_species]=(field_info *)SID_malloc(sizeof(field_info));
                 init_field(3,n,L,field[i_species]);
                 init_field(3,n,L,field_norm[i_species]);
                 i_init=i_species;
              }
              else{
                 field[i_species]     =NULL;
                 field_norm[i_species]=NULL;
              }
           }

           // Loop over all the files that this rank will read
           int i_load;
           for(i_load=0;i_load<n_load;i_load++){
              if(n_load>1)
                 SID_log("Processing file No. %d of %d...",SID_LOG_OPEN|SID_LOG_TIMER,i_load+1,n_load);

              // Initialization -- read gadget file
              GBPREAL mass_array[N_GADGET_TYPE];
              init_plist(&plist,&((field[i_init])->slab),GADGET_LENGTH,GADGET_MASS,GADGET_VELOCITY);
              char filename_root[MAX_FILENAME_LENGTH];
              read_gadget_binary_local(filename_in_root,
                                       snapshot_number,
                                       i_run,
                                       i_load,
                                       n_load,
                                       mass_array,
                                       &(field[i_init]->slab),
                                       cosmo,
                                       &plist);

              // Generate power spectra
              for(i_species=0;i_species<plist.n_species;i_species++){

                 // Determine how many particles of species i_species there are
                 if(n_all[i_species]>0){
                    // Fetch the needed information
                    size_t   n_particles;
                    size_t   n_particles_local;
                    int      flag_alloc_m;
                    GBPREAL *x_particles_local;
                    GBPREAL *y_particles_local;
                    GBPREAL *z_particles_local;
                    GBPREAL *vx_particles_local;
                    GBPREAL *vy_particles_local;
                    GBPREAL *vz_particles_local;
                    GBPREAL *m_particles_local;
                    GBPREAL *v_particles_local;
                    GBPREAL *w_particles_local;
                    n_particles      =((size_t  *)ADaPS_fetch(plist.data,"n_all_%s",plist.species[i_species]))[0];
                    n_particles_local=((size_t  *)ADaPS_fetch(plist.data,"n_%s",    plist.species[i_species]))[0];
                    x_particles_local= (GBPREAL *)ADaPS_fetch(plist.data,"x_%s",    plist.species[i_species]);
                    y_particles_local= (GBPREAL *)ADaPS_fetch(plist.data,"y_%s",    plist.species[i_species]);
                    z_particles_local= (GBPREAL *)ADaPS_fetch(plist.data,"z_%s",    plist.species[i_species]);
                    vx_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"vx_%s",   plist.species[i_species]);
                    vy_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"vy_%s",   plist.species[i_species]);
                    vz_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"vz_%s",   plist.species[i_species]);
                    if(ADaPS_exist(plist.data,"M_%s",plist.species[i_species])){
                       flag_alloc_m=FALSE;
                       m_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"M_%s",plist.species[i_species]);
                    }
                    else{
                       flag_alloc_m=TRUE;
                       m_particles_local=(GBPREAL *)SID_malloc(n_particles_local*sizeof(GBPREAL));
                       int i_particle;
                       for(i_particle=0;i_particle<n_particles_local;i_particle++)
                          m_particles_local[i_particle]=mass_array[i_species];
                    }

                    // Decide the map_to_grid() mode
                    int mode;
                    if(n_load==1)
                       mode=MAP2GRID_MODE_DEFAULT;
                    else if(i_load==0 || n_load==1)
                       mode=MAP2GRID_MODE_DEFAULT|MAP2GRID_MODE_NONORM;
                    else if(i_load==(n_load-1))
                       mode=MAP2GRID_MODE_NOCLEAN;
                    else
                       mode=MAP2GRID_MODE_NOCLEAN|MAP2GRID_MODE_NONORM;

                    // Set the array that will weight the grid
                    field_info *field_i;
                    field_info *field_norm_i;
                    double factor;
                    switch(i_grid){
                    case 0:
                       v_particles_local=m_particles_local;
                       w_particles_local=NULL;
                       field_i          =field[i_species];
                       field_norm_i     =NULL;
                       mode|=MAP2GRID_MODE_APPLYFACTOR;
                       factor=pow((double)grid_size/box_size,3.);
                       break;
                    case 1:
                       v_particles_local=vx_particles_local;
                       w_particles_local=m_particles_local;
                       field_i          =field[i_species];
                       field_norm_i     =field_norm[i_species];
                       factor=1.;
                       break;
                    case 2:
                       v_particles_local=vy_particles_local;
                       w_particles_local=m_particles_local;
                       field_i          =field[i_species];
                       field_norm_i     =field_norm[i_species];
                       factor=1.;
                       break;
                    case 3:
                       v_particles_local=vz_particles_local;
                       w_particles_local=m_particles_local;
                       field_i          =field[i_species];
                       field_norm_i     =field_norm[i_species];
                       factor=1.;
                       break;
                    }

                    // Generate grid
                    map_to_grid(n_particles_local,
                                x_particles_local,
                                y_particles_local,
                                z_particles_local,
                                v_particles_local,
                                w_particles_local,
                                cosmo,
                                redshift,
                                distribution_scheme,
                                factor,
                                field_i,
                                field_norm_i,
                                mode);
                    if(flag_alloc_m)
                       SID_free(SID_FARG m_particles_local);
                 }
              }

              // Clean-up
              free_plist(&plist);
              if(n_load>1)
                 SID_log("Done.",SID_LOG_CLOSE);
           } // loop over i_load
           
           // Write results to disk
           char filename_out_species[MAX_FILENAME_LENGTH];
           init_plist(&plist,NULL,GADGET_LENGTH,GADGET_MASS,GADGET_VELOCITY);
           for(i_species=0;i_species<plist.n_species;i_species++){
              if(flag_used[i_species]){
                 sprintf(grid_identifier,"%s_%s_%s",i_grid_identifier,i_run_identifier,plist.species[i_species]);
                 sprintf(filename_out_species,"%s_%s",filename_out_root,plist.species[i_species]);
                 write_grid(field[i_species],
                            filename_out_species,
                            i_write,
                            n_grids_total,
                            distribution_scheme,
                            grid_identifier,
                            header.box_size);
                 free_field(field[i_species]);
                 free_field(field_norm[i_species]);
                 SID_free(SID_FARG field[i_species]);
                 SID_free(SID_FARG field_norm[i_species]);
                 i_write++;
              }
           }

           // Clean-up
           free_plist(&plist);
           SID_log("Done.",SID_LOG_CLOSE);

        } // loop over i_grid

        SID_log("Done.",SID_LOG_CLOSE);
     } // loop over i_run
  } // if n_used>0 

  // Clean-up
  free_cosmo(&cosmo);
  SID_free(SID_FARG grid_identifier);
  SID_free(SID_FARG n_all);

  SID_log("Done.",SID_LOG_CLOSE);

  SID_exit(ERROR_NONE);
}