Ejemplo n.º 1
0
int close_file(char *name)
{
    int cell_file, row, k;
    int row_count, col_count;
    CELL *buf;

    cell_file = Rast_open_c_new(name);

    row_count = n_rows - (PAD << 1);
    col_count = n_cols - (PAD << 1);
    G_message(_("Output file %d rows X %d columns"), row_count, col_count);
    G_message(_("Window %d rows X %d columns"), Rast_window_rows(),
	      Rast_window_cols());

    for (row = 0, k = PAD; row < row_count; row++, k++) {
	buf = get_a_row(k);
	Rast_put_row(cell_file, buf + PAD, CELL_TYPE);
    }
    Rast_close(cell_file);
    Rowio_flush(&row_io);
    close(Rowio_fileno(&row_io));
    Rowio_release(&row_io);
    unlink(work_file_name);

    return 0;
}
Ejemplo n.º 2
0
void openfiles(char *r_name, char *g_name, char *b_name,
	       char *h_name, char *i_name, char *s_name,
	       int fd_input[3], int fd_output[3], CELL * rowbuf[3])
{
    fd_input[0] = Rast_open_old(r_name, "");
    fd_input[1] = Rast_open_old(g_name, "");
    fd_input[2] = Rast_open_old(b_name, "");

    /* open output files */
    fd_output[0] = Rast_open_c_new(h_name);
    fd_output[1] = Rast_open_c_new(i_name);
    fd_output[2] = Rast_open_c_new(s_name);

    /* allocate the cell row buffer */
    rowbuf[0] = Rast_allocate_c_buf();
    rowbuf[1] = Rast_allocate_c_buf();
    rowbuf[2] = Rast_allocate_c_buf();
}
Ejemplo n.º 3
0
void openfiles(char *h_name, char *i_name, char *s_name,
	       char *r_name, char *g_name, char *b_name,
	       int fd_input[3], int fd_output[3], CELL * rowbuf[3])
{
    /* open output files */
    fd_output[0] = Rast_open_c_new(r_name);
    fd_output[1] = Rast_open_c_new(g_name);
    fd_output[2] = Rast_open_c_new(b_name);

    /* allocate the cell row buffer */
    rowbuf[0] = Rast_allocate_c_buf();
    rowbuf[1] = Rast_allocate_c_buf();
    rowbuf[2] = Rast_allocate_c_buf();

    /* open input files (maps can be in different mapsets) */
    fd_input[0] = Rast_open_old(h_name, "");
    fd_input[1] = Rast_open_old(i_name, "");
    fd_input[2] = Rast_open_old(s_name, "");
}
Ejemplo n.º 4
0
Archivo: main.c Proyecto: caomw/grass
static void init_channel(channel *c)
{
    sprintf(c->name, "%s%s", output, c->suffix);

    if (Float)
    {
	c->fd = Rast_open_fp_new(c->name);
	c->fbuf = Rast_allocate_f_buf();
    }
    else
    {
	c->fd = Rast_open_c_new(c->name);
	c->buf = Rast_allocate_c_buf();
    }

    c->active = 1;
}
Ejemplo n.º 5
0
int cseg_write_cellfile(CSEG * cseg, char *map_name)
{
    int map_fd;
    GW_LARGE_INT row, nrows;
    CELL *buffer;

    map_fd = Rast_open_c_new(map_name);
    nrows = Rast_window_rows();
    buffer = Rast_allocate_c_buf();
    Segment_flush(&(cseg->seg));
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 1);
	Segment_get_row(&(cseg->seg), buffer, row);
	Rast_put_row(map_fd, buffer, CELL_TYPE);
    }
    G_percent(row, nrows, 1);    /* finish it */
    G_free(buffer);
    Rast_close(map_fd);
    return 0;
}
Ejemplo n.º 6
0
int open_files(void)
{
    char *name, *mapset;
    FILE *fd;
    int n;

    I_init_group_ref(&Ref);
    if (!I_find_group(group))
	G_fatal_error(_("Group <%s> not found"), group);

    if (!I_find_subgroup(group, subgroup))
	G_fatal_error(_("Subgroup <%s> in group <%s> not found"),
		      subgroup, group);

    I_get_subgroup_ref(group, subgroup, &Ref);

    if (Ref.nfiles <= 1) {
	if (Ref.nfiles <= 0)
	    G_fatal_error(_("Subgroup <%s> of group <%s> doesn't have any raster maps. "
			    "The subgroup must have at least 2 raster maps."));
	else
	    G_fatal_error(_("Subgroup <%s> of group <%s> only has 1 raster map. "
			    "The subgroup must have at least 2 raster maps."));
    }

    cell = (DCELL **) G_malloc(Ref.nfiles * sizeof(DCELL *));
    cellfd = (int *)G_malloc(Ref.nfiles * sizeof(int));
    P = (double *)G_malloc(Ref.nfiles * sizeof(double));
    for (n = 0; n < Ref.nfiles; n++) {
	cell[n] = Rast_allocate_d_buf();
	name = Ref.file[n].name;
	mapset = Ref.file[n].mapset;
	cellfd[n] = Rast_open_old(name, mapset);
    }

    I_init_signatures(&S, Ref.nfiles);
    fd = I_fopen_signature_file_old(group, subgroup, sigfile);
    if (fd == NULL)
	G_fatal_error(_("Unable to open signature file <%s>"),
		      sigfile);

    n = I_read_signatures(fd, &S);
    fclose(fd);
    if (n < 0)
	G_fatal_error(_("Unable to read signature file <%s>"),
		      sigfile);

    if (S.nsigs > 255)
	G_fatal_error(_("<%s> has too many signatures (limit is 255)"),
		      sigfile);

    B = (double *)G_malloc(S.nsigs * sizeof(double));
    invert_signatures();

    class_fd = Rast_open_c_new(class_name);
    class_cell = Rast_allocate_c_buf();

    reject_cell = NULL;
    if (reject_name) {
	reject_fd = Rast_open_c_new(reject_name);
	reject_cell = Rast_allocate_c_buf();
    }

    return 0;
}
Ejemplo n.º 7
0
void Indep(void)
{
    int Count, DRow, DCol;
    int Found, R, C;
    double RowDist, RowDistSq, ColDist;
    struct History history;

    G_debug(2, "indep()");

    Count = 0;
    Found = 0;

    while (CellCount > 0) {
	G_debug(3, "(CellCount):%d", CellCount);
	G_debug(3, "(Count):%d", Count);

	DRow = DoNext[Count].R;
	DCol = DoNext[Count++].C;

	if (0 != FlagGet(Cells, DRow, DCol)) {
	    /* FLAG_SET( Out, DRow, DCol); */
	    Out[DRow][DCol] = ++Found;
	    for (R = DRow; R < Rs; R++) {
		RowDist = NS * (R - DRow);
		if (RowDist > MaxDistSq) {
		    R = Rs;
		}
		else {
		    RowDistSq = RowDist * RowDist;
		    for (C = DCol; C < Cs; C++) {
			ColDist = EW * (C - DCol);
			G_debug(3, "(RowDistSq):%.12lf", RowDistSq);
			G_debug(3, "(ColDist):%.12lf", ColDist);
			G_debug(3, "(MaxDistSq):%.12lf", MaxDistSq);
			
			if (MaxDistSq >= RowDistSq + ColDist * ColDist) {
			    if (0 != FlagGet(Cells, R, C)) {
				G_debug(2, "unset()");
				FLAG_UNSET(Cells, R, C);
				CellCount--;
			    }
			}
			else {
			    C = Cs;
			}
		    }
		}
	    }

	    G_debug(2, "it1()");
	    for (R = DRow - 1; R >= 0; R--) {
		RowDist = NS * (DRow - R);
		if (RowDist > MaxDistSq) {
		    R = 0;
		}
		else {
		    RowDistSq = RowDist * RowDist;
		    for (C = DCol; C < Cs; C++) {
			ColDist = EW * (C - DCol);
			if (MaxDistSq >= RowDistSq + ColDist * ColDist) {
			    if (0 != FlagGet(Cells, R, C)) {
				G_debug(2, "unset()");
				FLAG_UNSET(Cells, R, C);
				CellCount--;
			    }
			}
			else {
			    C = Cs;
			}
		    }
		}
	    }

	    G_debug(2, "it2()");
	    for (R = DRow; R < Rs; R++) {
		RowDist = NS * (R - DRow);
		if (RowDist > MaxDistSq) {
		    R = Rs;
		}
		else {
		    RowDistSq = RowDist * RowDist;
		    for (C = DCol - 1; C >= 0; C--) {
			ColDist = EW * (DCol - C);
			if (MaxDistSq >= RowDistSq + ColDist * ColDist) {
			    if (0 != FlagGet(Cells, R, C)) {
				G_debug(2, "unset()");
				FLAG_UNSET(Cells, R, C);
				CellCount--;
			    }
			}
			else {
			    C = 0;
			}
		    }
		}
	    }

	    G_debug(2, "it3()");
	    for (R = DRow - 1; R >= 0; R--) {
		RowDist = NS * (DRow - R);
		if (RowDist > MaxDistSq) {
		    R = 0;
		}
		else {
		    RowDistSq = RowDist * RowDist;
		    for (C = DCol - 1; C >= 0; C--) {
			ColDist = EW * (DCol - C);
			if (MaxDistSq >= RowDistSq + ColDist * ColDist) {
			    if (0 != FlagGet(Cells, R, C)) {
				G_debug(2, "unset()");
				FLAG_UNSET(Cells, R, C);
				CellCount--;
			    }
			}
			else {
			    C = 0;
			}
		    }
		}
	    }
	}
    }

    G_debug(2, "outputting()");
    OutFD = Rast_open_c_new(Output->answer);

    G_message(_("Writing raster map <%s>..."),
	      Output->answer);
    for (R = 0; R < Rs; R++) {
	G_percent(R, Rs, 2);
	for (C = 0; C < Cs; C++) {
	    CellBuffer[C] = Out[R][C];
	}
	Rast_put_row(OutFD, CellBuffer, CELL_TYPE);
    }
    G_percent(1, 1, 1);
    
    Rast_close(OutFD);
    Rast_short_history(Output->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(Output->answer, &history);
}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
    int n, verbose = 1,
	backrow, backcol,
	col, row,
	len, flag,
	srows, scols,
	backrow_fd, backcol_fd, path_fd, in_row_fd, in_col_fd, out_fd;
    const char *current_mapset,
	*search_mapset,
	*path_mapset,
	*backrow_mapset,
	*backcol_mapset, *in_row_file, *in_col_file, *out_file;
    CELL *cell;
    POINT *PRES_PT, *PRESENT_PT, *OLD_PT;
    struct Cell_head window;
    double east, north;
    struct Option *opt1, *opt2, *opt3, *opt4;
    struct Flag *flag1;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("fire"));
    G_add_keyword(_("cumulative costs"));
    module->description =
	_("Recursively traces the least cost path backwards to "
	  "cells from which the cumulative cost was determined.");

    opt1 = G_define_option();
    opt1->key = "x_input";
    opt1->type = TYPE_STRING;
    opt1->required = YES;
    opt1->gisprompt = "old,cell,raster";
    opt1->description =
	_("Name of raster map containing back-path easting information");

    opt2 = G_define_option();
    opt2->key = "y_input";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->gisprompt = "old,cell,raster";
    opt2->description =
	_("Name of raster map containing back-path northing information");

    opt3 = G_define_option();
    opt3->key = "coordinate";
    opt3->type = TYPE_STRING;
    opt3->multiple = YES;
    opt3->key_desc = "x,y";
    opt3->description =
	_("The map E and N grid coordinates of starting points");

    opt4 = G_define_option();
    opt4->key = "output";
    opt4->type = TYPE_STRING;
    opt4->required = YES;
    opt4->gisprompt = "new,cell,raster";
    opt4->description = _("Name of spread path raster map");

    flag1 = G_define_flag();
    flag1->key = 'v';
    flag1->description = _("Run verbosely");

    /*   Do command line parsing    */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    current_mapset = G_mapset();
    in_row_file = G_tempfile();
    in_col_file = G_tempfile();
    out_file = G_tempfile();

    /*  Get database window parameters      */
    G_get_window(&window);

    verbose = flag1->answer;

    /*  Check if backrow layer exists in data base  */
    search_mapset = "";

    strcpy(backrow_layer, opt2->answer);
    strcpy(backcol_layer, opt1->answer);

    backrow_mapset = G_find_raster(backrow_layer, search_mapset);
    backcol_mapset = G_find_raster(backcol_layer, search_mapset);

    if (backrow_mapset == NULL)
	G_fatal_error("%s - not found", backrow_layer);

    if (backcol_mapset == NULL)
	G_fatal_error("%s - not found", backcol_layer);

    search_mapset = "";

    strcpy(path_layer, opt4->answer);

    path_mapset = G_find_raster(path_layer, search_mapset);

    /*  find number of rows and cols in window    */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    cell = Rast_allocate_c_buf();

    /*  Open back cell layers for reading  */
    backrow_fd = Rast_open_old(backrow_layer, backrow_mapset);
    backcol_fd = Rast_open_old(backcol_layer, backcol_mapset);

    /*   Parameters for map submatrices   */
    len = sizeof(CELL);

    srows = nrows / 4 + 1;
    scols = ncols / 4 + 1;

    if (verbose)
	G_message
	    ("\nReading the input map -%s- and -%s- and creating some temporary files...",
	     backrow_layer, backcol_layer);

    /* Create segmented files for back cell and output layers  */
    in_row_fd = creat(in_row_file, 0666);
    segment_format(in_row_fd, nrows, ncols, srows, scols, len);
    close(in_row_fd);
    in_col_fd = creat(in_col_file, 0666);
    segment_format(in_col_fd, nrows, ncols, srows, scols, len);
    close(in_col_fd);

    out_fd = creat(out_file, 0666);
    segment_format(out_fd, nrows, ncols, srows, scols, len);
    close(out_fd);

    /*   Open initialize and segment all files  */
    in_row_fd = open(in_row_file, 2);
    segment_init(&in_row_seg, in_row_fd, 4);
    in_col_fd = open(in_col_file, 2);
    segment_init(&in_col_seg, in_col_fd, 4);

    out_fd = open(out_file, 2);
    segment_init(&out_seg, out_fd, 4);

    /*   Write the back cell layers in the segmented files, and  
     *   Change UTM coordinates to ROWs and COLUMNs */
    for (row = 0; row < nrows; row++) {
	Rast_get_c_row(backrow_fd, cell, row);

	for (col = 0; col < ncols; col++)
	    if (cell[col] > 0)
		cell[col] =
		    (window.north - cell[col]) / window.ns_res /* - 0.5 */ ;
	    else
		cell[col] = -1;
	segment_put_row(&in_row_seg, cell, row);
	Rast_get_c_row(backcol_fd, cell, row);

	for (col = 0; col < ncols; col++)
	    if (cell[col] > 0)
		cell[col] =
		    (cell[col] - window.west) / window.ew_res /* - 0.5 */ ;
	segment_put_row(&in_col_seg, cell, row);
    }

    /* Convert easting and northing from the command line to row and col */
    if (opt3->answer) {
	for (n = 0; opt3->answers[n] != NULL; n += 2) {
	    G_scan_easting(opt3->answers[n], &east, G_projection());
	    G_scan_northing(opt3->answers[n + 1], &north, G_projection());
	    row = (window.north - north) / window.ns_res;
	    col = (east - window.west) / window.ew_res;
	    /* ignore pt outside window */
	    if (east < window.west || east > window.east ||
		north < window.south || north > window.north) {
		G_warning("Ignoring point outside window: ");
		G_warning("   %.4f,%.4f", east, north);
		continue;
	    }

	    value = (char *)&backrow;
	    segment_get(&in_row_seg, value, row, col);
	    /* ignore pt in no-data area */
	    if (backrow < 0) {
		G_warning("Ignoring point in NO-DATA area :");
		G_warning("   %.4f,%.4f", east, north);
		continue;
	    }
	    value = (char *)&backcol;
	    segment_get(&in_col_seg, value, row, col);

	    insert(&PRESENT_PT, row, col, backrow, backcol);
	}
    }

    /*  Set flag according to input */
    if (path_mapset != NULL) {
	if (head_start_pt == NULL)
	    /*output layer exists and start pts are not given on cmd line */
	    flag = 1;

	/* output layer exists and starting pts are given on cmd line */
	else
	    flag = 2;
    }
    else
	flag = 3;		/* output layer does not previously exist */

    /* If the output layer containing the starting positions */
    /* create a linked list of of them  */
    if (flag == 1) {
	path_fd = Rast_open_old(path_layer, path_mapset);

	/*  Search for the marked starting pts and make list    */
	for (row = 0; row < nrows; row++) {
	    Rast_get_c_row(path_fd, cell, row);

	    for (col = 0; col < ncols; col++) {
		if (cell[col] > 0) {
		    value = (char *)&backrow;
		    segment_get(&in_row_seg, value, row, col);
		    /* ignore pt in no-data area */
		    if (backrow < 0) {
			G_warning("Ignoring point in NO-DATA area:");
			G_warning("   %.4f,%.4f\n",
				  window.west + window.ew_res * (col + 0.5),
				  window.north - window.ns_res * (row + 0.5));
			continue;
		    }
		    value = (char *)&backcol;
		    segment_get(&in_col_seg, value, row, col);
		    insert(&PRESENT_PT, row, col, backrow, backcol);
		}
	    }			/* loop over cols */
	}			/* loop over rows */

	Rast_close(path_fd);
    }

    /* loop over the starting points to find the least cost paths */
    if (verbose)
	G_message("\nFinding the least cost paths ...");

    PRES_PT = head_start_pt;
    while (PRES_PT != NULL) {
	path_finder(PRES_PT->row, PRES_PT->col, PRES_PT->backrow,
		    PRES_PT->backcol);

	OLD_PT = PRES_PT;
	PRES_PT = NEXT_PT;
	G_free(OLD_PT);
    }

    /* Write pending updates by segment_put() to outputmap */
    segment_flush(&out_seg);

    if (verbose)
	G_message("\nWriting the output map  -%s-...", path_layer);

    path_fd = Rast_open_c_new(path_layer);
    for (row = 0; row < nrows; row++) {
	segment_get_row(&out_seg, cell, row);
	Rast_put_row(path_fd, cell, CELL_TYPE);
    }

    if (verbose)
	G_message("finished.");

    segment_release(&in_row_seg);	/* release memory  */
    segment_release(&in_col_seg);
    segment_release(&out_seg);

    close(in_row_fd);		/* close all files */
    close(in_col_fd);
    close(out_fd);

    Rast_close(path_fd);
    Rast_close(backrow_fd);
    Rast_close(backcol_fd);

    unlink(in_row_file);	/* remove submatrix files  */
    unlink(in_col_file);
    unlink(out_file);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 9
0
int close_array_seg(void)
{
    struct Colors colors;
    int incr, max, red, green, blue, rd, gr, bl, flag;
    int c, r, map_fd;
    CELL *cellrow, value;
    CELL *theseg;
    RAMSEG thesegseg;

    cellrow = Rast_allocate_c_buf();
    if (seg_flag || bas_flag || haf_flag) {
	if (seg_flag) {
	    theseg = bas;
	    thesegseg = bas_seg;
	}
	else if (bas_flag) {
	    theseg = bas;
	    thesegseg = bas_seg;
	}
	else {
	    theseg = haf;
	    thesegseg = haf_seg;
	}
	max = n_basins;
	G_debug(1, "%d basins created", max);
	Rast_init_colors(&colors);
	if (max > 0)
	    Rast_make_random_colors(&colors, 1, max);
	else {
	    G_warning(_("No basins were created. Verify threshold and region settings."));
	    Rast_make_random_colors(&colors, 1, 2);
	}

	if (max < 1000 && max > 0) {
	    Rast_set_c_color((CELL) 0, 0, 0, 0, &colors);
	    r = 1;
	    incr = 0;
	    while (incr >= 0) {
		G_percent(r, max, 2);
		for (gr = 130 + incr; gr <= 255; gr += 20) {
		    for (rd = 90 + incr; rd <= 255; rd += 30) {
			for (bl = 90 + incr; bl <= 255; bl += 40) {
			    flag = 1;
			    while (flag) {
				Rast_get_c_color(&r, &red, &green, &blue, &colors);
				/* if existing rule is too dark then append a new
				   rule to override it */
				if ((blue * .11 + red * .30 + green * .59) <
				    100) {
				    Rast_set_c_color(r, rd, gr, bl, &colors);
				    flag = 0;
				}
				if (++r > max) {
				    gr = rd = bl = 300;
				    flag = 0;
				    incr = -1;
				}
			    }
			}
		    }
		}
		if (incr >= 0) {
		    incr += 15;
		    if (incr > 120)
			incr = 7;
		}
	    }
	    G_percent(r - 1, max, 3);	/* finish it */
	}
	else
	    G_debug(1,
		    "Too many subbasins to reasonably check for color brightness");
	/* using the existing stack of while/for/for/for/while loops ... */
    }

    /* stream segments map */
    if (seg_flag) {
	map_fd = Rast_open_c_new(seg_name);
	for (r = 0; r < nrows; r++) {
	    Rast_set_c_null_value(cellrow, ncols);	/* reset row to all NULL */
	    for (c = 0; c < ncols; c++) {
		value = FLAG_GET(swale, r, c);
		if (value)
		    cellrow[c] = bas[SEG_INDEX(bas_seg, r, c)];
	    }
	    Rast_put_row(map_fd, cellrow, CELL_TYPE);
	}
	Rast_close(map_fd);
	Rast_write_colors(seg_name, this_mapset, &colors);
    }

    /* basins map */
    if (bas_flag) {
	map_fd = Rast_open_c_new(bas_name);
	for (r = 0; r < nrows; r++) {
	    for (c = 0; c < ncols; c++) {
		cellrow[c] = bas[SEG_INDEX(bas_seg, r, c)];
		if (cellrow[c] == 0)
		    Rast_set_c_null_value(cellrow + c, 1);
	    }
	    Rast_put_row(map_fd, cellrow, CELL_TYPE);
	}
	Rast_close(map_fd);
	Rast_write_colors(bas_name, this_mapset, &colors);
    }

    /* half_basins map */
    if (haf_flag) {
	map_fd = Rast_open_c_new(haf_name);
	for (r = 0; r < nrows; r++) {
	    for (c = 0; c < ncols; c++) {
		cellrow[c] = haf[SEG_INDEX(haf_seg, r, c)];
		if (cellrow[c] == 0)
		    Rast_set_c_null_value(cellrow + c, 1);
	    }
	    Rast_put_row(map_fd, cellrow, CELL_TYPE);
	}
	Rast_close(map_fd);
	Rast_write_colors(haf_name, this_mapset, &colors);
    }

    if (seg_flag || bas_flag || haf_flag)
	Rast_free_colors(&colors);

    G_free(haf);
    G_free(bas);
    G_free(cellrow);
    if (arm_flag)
	fclose(fp);
    close_maps();

    return 0;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
    int fd, maskfd;
    CELL *cell, *mask;
    struct Cell_head window;
    int row, col;
    double north, east;
    double dx, dy;
    double maxdist, dist;
    double sum1, sum2;
    int i, n, max;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *npoints, *output;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("IDW"));
    module->description = _("Surface generation program.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.npoints = G_define_option();
    parm.npoints->key = "npoints";
    parm.npoints->key_desc = "count";
    parm.npoints->type = TYPE_INTEGER;
    parm.npoints->required = NO;
    parm.npoints->description = _("Number of interpolation points");
    parm.npoints->answer = "12";

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

    /* Make sure that the current projection is not lat/long */
    if ((G_projection() == PROJECTION_LL))
	G_fatal_error(_("Lat/long databases not supported by r.surf.idw2. Use r.surf.idw instead!"));

    if (sscanf(parm.npoints->answer, "%d", &search_points) != 1 ||
	search_points < 1)
	G_fatal_error(_("%s=%s - illegal number of interpolation points"),
		      parm.npoints->key, parm.npoints->answer);

    list = (struct Point *)G_calloc(search_points, sizeof(struct Point));

    /* read the elevation points from the input raster map */
    read_cell(parm.input->answer);

    if (npoints == 0)
	G_fatal_error(_("%s: no data points found"), G_program_name());
    nsearch = npoints < search_points ? npoints : search_points;

    /* get the window, allocate buffers, etc. */
    G_get_set_window(&window);

    cell = Rast_allocate_c_buf();

    if ((maskfd = Rast_maskfd()) >= 0)
	mask = Rast_allocate_c_buf();
    else
	mask = NULL;

    fd = Rast_open_c_new(parm.output->answer);

    G_message(_("Interpolating raster map <%s>... %d rows... "),
	      parm.output->answer, window.rows);

    north = window.north - window.ns_res / 2.0;
    for (row = 0; row < window.rows; row++) {
	G_percent(row, window.rows, 2);

	if (mask)
	    Rast_get_c_row(maskfd, mask, row);

	north += window.ns_res;
	east = window.west - window.ew_res / 2.0;
	for (col = 0; col < window.cols; col++) {
	    east += window.ew_res;
	    /* don't interpolate outside of the mask */
	    if (mask && mask[col] == 0) {
		cell[col] = 0;
		continue;
	    }
	    /* fill list with first nsearch points */
	    for (i = 0; i < nsearch; i++) {
		dy = points[i].north - north;
		dx = points[i].east - east;
		list[i].dist = dy * dy + dx * dx;
		list[i].z = points[i].z;
	    }
	    /* find the maximum distance */
	    maxdist = list[max = 0].dist;
	    for (n = 1; n < nsearch; n++) {
		if (maxdist < list[n].dist)
		    maxdist = list[max = n].dist;
	    }
	    /* go thru rest of the points now */
	    for (; i < npoints; i++) {
		dy = points[i].north - north;
		dx = points[i].east - east;
		dist = dy * dy + dx * dx;

		if (dist < maxdist) {
		    /* replace the largest dist */
		    list[max].z = points[i].z;
		    list[max].dist = dist;
		    maxdist = list[max = 0].dist;
		    for (n = 1; n < nsearch; n++) {
			if (maxdist < list[n].dist)
			    maxdist = list[max = n].dist;
		    }
		}
	    }

	    /* interpolate */
	    sum1 = 0.0;
	    sum2 = 0.0;
	    for (n = 0; n < nsearch; n++) {
		if ((dist = list[n].dist)) {
		    sum1 += list[n].z / dist;
		    sum2 += 1.0 / dist;
		}
		else {
		    sum1 = list[n].z;
		    sum2 = 1.0;
		    break;
		}
	    }
	    cell[col] = (CELL) (sum1 / sum2 + 0.5);
	}

	Rast_put_row(fd, cell, CELL_TYPE);
    }

    G_free(points);
    G_free(cell);
    Rast_close(fd);

    /* writing history file */
    Rast_short_history(parm.output->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(parm.output->answer, &history);
    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
    unsigned char *hue_n, *hue_r, *hue_g, *hue_b;
    unsigned char *int_n, *int_r;
    unsigned char *sat_n, *sat_r;
    unsigned char *dummy;
    CELL *r_array, *g_array, *b_array;
    char *name_h, *name_i, *name_s;
    int intensity;
    int saturation;
    int atrow, atcol;
    int hue_file;
    int int_file = 0;
    int int_used;
    int sat_file = 0;
    int sat_used;
    char *name_r, *name_g, *name_b;
    int r_file = 0;
    int r_used;
    int g_file = 0;
    int g_used;
    int b_file = 0;
    int b_used;
    struct Cell_head window;
    struct Colors hue_colors;
    struct Colors int_colors;
    struct Colors sat_colors;
    struct Colors gray_colors;
    struct History history;
    struct GModule *module;
    struct Option *opt_h, *opt_i, *opt_s;
    struct Option *opt_r, *opt_g, *opt_b;
    struct Flag *nulldraw;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("color transformation"));
    G_add_keyword(_("RGB"));
    G_add_keyword(_("HIS"));
    module->description =
	_("Generates red, green and blue raster map layers "
	  "combining hue, intensity and saturation (HIS) "
	  "values from user-specified input raster map layers.");

    opt_h = G_define_option();
    opt_h->key = "h_map";
    opt_h->type = TYPE_STRING;
    opt_h->required = YES;
    opt_h->gisprompt = "old,cell,raster";
    opt_h->description = _("Name of layer to be used for HUE");

    opt_i = G_define_option();
    opt_i->key = "i_map";
    opt_i->type = TYPE_STRING;
    opt_i->required = NO;
    opt_i->gisprompt = "old,cell,raster";
    opt_i->description = _("Name of layer to be used for INTENSITY");

    opt_s = G_define_option();
    opt_s->key = "s_map";
    opt_s->type = TYPE_STRING;
    opt_s->required = NO;
    opt_s->gisprompt = "old,cell,raster";
    opt_s->description = _("Name of layer to be used for SATURATION");

    opt_r = G_define_option();
    opt_r->key = "r_map";
    opt_r->type = TYPE_STRING;
    opt_r->required = YES;
    opt_r->gisprompt = "new,cell,raster";
    opt_r->description = _("Name of output layer to be used for RED");

    opt_g = G_define_option();
    opt_g->key = "g_map";
    opt_g->type = TYPE_STRING;
    opt_g->required = YES;
    opt_g->gisprompt = "new,cell,raster";
    opt_g->description = _("Name of output layer to be used for GREEN");

    opt_b = G_define_option();
    opt_b->key = "b_map";
    opt_b->type = TYPE_STRING;
    opt_b->required = YES;
    opt_b->gisprompt = "new,cell,raster";
    opt_b->description = _("Name of output layer to be used for BLUE");

    nulldraw = G_define_flag();
    nulldraw->key = 'n';
    nulldraw->description = _("Respect NULL values while drawing");

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


    /* read in current window */
    G_get_window(&window);

    /* Get name of layer to be used for hue */
    name_h = opt_h->answer;

    /* Make sure map is available */
    hue_file = Rast_open_old(name_h, "");

    hue_r = G_malloc(window.cols);
    hue_g = G_malloc(window.cols);
    hue_b = G_malloc(window.cols);
    hue_n = G_malloc(window.cols);

    dummy = G_malloc(window.cols);

    /* Reading color lookup table */
    if (Rast_read_colors(name_h, "", &hue_colors) == -1)
	G_fatal_error(_("Color file for <%s> not available"), name_h);

    int_used = 0;

    if (opt_i->answer != NULL) {
	/* Get name of layer to be used for intensity */
	name_i = opt_i->answer;
	int_used = 1;
	/* Make sure map is available */
	int_file = Rast_open_old(name_i, "");

	int_r = G_malloc(window.cols);
	int_n = G_malloc(window.cols);

	/* Reading color lookup table */
	if (Rast_read_colors(name_i, "", &int_colors) == -1)
	    G_fatal_error(_("Color file for <%s> not available"), name_i);
    }

    sat_used = 0;

    if (opt_s->answer != NULL) {
	/* Get name of layer to be used for saturation */
	name_s = opt_s->answer;
	    sat_used = 1;

	    /* Make sure map is available */
	    sat_file = Rast_open_old(name_s, "");

	    sat_r = G_malloc(window.cols);
	    sat_n = G_malloc(window.cols);

	    /* Reading color lookup table */
	    if (Rast_read_colors(name_s, "", &sat_colors) == -1)
		G_fatal_error(_("Color file for <%s> not available"), name_s);
    }

    r_used = 0;

    if (opt_r->answer != NULL) {
	name_r = opt_r->answer;
	r_file = Rast_open_c_new(name_r);
	r_used = 1;
    }

    g_used = 0;

    if (opt_g->answer != NULL) {
	name_g = opt_g->answer;
	g_file = Rast_open_c_new(name_g);
	g_used = 1;
    }

    b_used = 0;

    if (opt_b->answer != NULL) {
	name_b = opt_b->answer;
	b_file = Rast_open_c_new(name_b);
	b_used = 1;
    }

    r_array = Rast_allocate_c_buf();
    g_array = Rast_allocate_c_buf();
    b_array = Rast_allocate_c_buf();

    /* Make color table */
    make_gray_scale(&gray_colors);

    /* Now do the work */
    intensity = 255;		/* default is to not change intensity */
    saturation = 255;		/* default is to not change saturation */


    for (atrow = 0; atrow < window.rows; atrow++) {
	G_percent(atrow, window.rows, 2);

	Rast_get_row_colors(hue_file, atrow, &hue_colors, hue_r, hue_g, hue_b, hue_n);
	if (int_used)
	    Rast_get_row_colors(int_file, atrow, &int_colors, int_r, dummy, dummy, int_n);
	if (sat_used)
	    Rast_get_row_colors(sat_file, atrow, &sat_colors, sat_r, dummy, dummy, sat_n);

	for (atcol = 0; atcol < window.cols; atcol++) {
	    if (nulldraw->answer) {
		if (hue_n[atcol]
		    || (int_used && int_n[atcol])
		    || (sat_used && sat_n[atcol])) {
		    Rast_set_c_null_value(&r_array[atcol], 1);
		    Rast_set_c_null_value(&g_array[atcol], 1);
		    Rast_set_c_null_value(&b_array[atcol], 1);
		    continue;
		}
	    }

	    if (int_used)
		intensity = int_r[atcol];

	    if (sat_used)
		saturation = sat_r[atcol];

	    HIS_to_RGB(hue_r[atcol], hue_g[atcol], hue_b[atcol],
		       intensity, saturation,
		       &r_array[atcol], &g_array[atcol], &b_array[atcol]);
	}

	if (r_used)
	    Rast_put_row(r_file, r_array, CELL_TYPE);

	if (g_used)
	    Rast_put_row(g_file, g_array, CELL_TYPE);

	if (b_used)
	    Rast_put_row(b_file, b_array, CELL_TYPE);
    }
    G_percent(window.rows, window.rows, 5);

    /* Close the cell files */
    Rast_close(hue_file);
    if (int_used)
	Rast_close(int_file);
    if (sat_used)
	Rast_close(sat_file);

    if (r_used) {
	Rast_close(r_file);
	Rast_write_colors(name_r, G_mapset(), &gray_colors);
	Rast_short_history(name_r, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(name_r, &history);
	Rast_put_cell_title(name_r, "Red extracted from HIS");
    }
    if (g_used) {
	Rast_close(g_file);
	Rast_write_colors(name_g, G_mapset(), &gray_colors);
	Rast_short_history(name_g, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(name_g, &history);
	Rast_put_cell_title(name_g, "Green extracted from HIS");
    }
    if (b_used) {
	Rast_close(b_file);
	Rast_write_colors(name_b, G_mapset(), &gray_colors);
	Rast_short_history(name_b, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(name_b, &history);
	Rast_put_cell_title(name_b, "Blue extracted from HIS");
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 12
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char **argv)
{
    struct GModule *module;
    struct Option *opt_out;
    struct Option *opt_lev;
    struct Flag *flg_d;
    struct Flag *flg_c;
    int dither;
    char *out_name;
    int out_file;
    CELL *out_array;
    struct Colors out_colors;
    int levels;
    int atrow, atcol;
    struct Cell_head window;
    unsigned char *dummy, *nulls;
    int i, j;
    struct History history;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("composite"));
    G_add_keyword("RGB");
    module->description =
	_("Combines red, green and blue raster maps into "
	  "a single composite raster map.");

    for (i = 0; i < 3; i++) {
	struct Option *opt;
	char buff[80];

	B[i].opt_name = opt = G_define_standard_option(G_OPT_R_INPUT);

	sprintf(buff, "%s", color_names[i]);
	opt->key = G_store(buff);

	opt->answer = NULL;

	sprintf(buff, _("Name of raster map to be used for <%s>"),
		color_names[i]);
	opt->description = G_store(buff);
    }

    opt_lev = G_define_option();
    opt_lev->key = "levels";
    opt_lev->type = TYPE_INTEGER;
    opt_lev->required = NO;
    opt_lev->options = "1-256";
    opt_lev->answer = "32";
    opt_lev->description =
	_("Number of levels to be used for each component");
    opt_lev->guisection = _("Levels");

    for (i = 0; i < 3; i++) {
	struct Option *opt;
	char buff[80];

	B[i].opt_levels = opt = G_define_option();

	sprintf(buff, "lev_%s", color_names[i]);
	opt->key = G_store(buff);

	opt->type = TYPE_INTEGER;
	opt->required = NO;
	opt->options = "1-256";

	sprintf(buff, _("Number of levels to be used for <%s>"),
		color_names[i]);
	opt->description = G_store(buff);
	opt->guisection = _("Levels");
    }

    opt_out = G_define_standard_option(G_OPT_R_OUTPUT);

    flg_d = G_define_flag();
    flg_d->key = 'd';
    flg_d->description = _("Dither");

    flg_c = G_define_flag();
    flg_c->key = 'c';
    flg_c->description = _("Use closest color");

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

    levels = atoi(opt_lev->answer);

    dither = flg_d->answer;
    closest = flg_c->answer;

    /* read in current window */
    G_get_window(&window);

    dummy = G_malloc(window.cols);

    nulls = G_malloc(window.cols);

    for (i = 0; i < 3; i++) {
	struct band *b = &B[i];

	/* Get name of layer to be used */
	b->name = b->opt_name->answer;

	/* Make sure map is available */
	b->file = Rast_open_old(b->name, "");

	b->type = Rast_get_map_type(b->file);

	b->size = Rast_cell_size(b->type);

	/* Reading color lookup table */
	if (Rast_read_colors(b->name, "", &b->colors) == -1)
	    G_fatal_error(_("Unable to read color file of raster map <%s>"), b->name);

	for (j = 0; j < 3; j++)
	    b->array[j] = (i == j)
		? G_malloc(window.cols)
		: dummy;

	b->levels = b->opt_levels->answer ? atoi(b->opt_levels->answer)
	    : levels;
	b->maxlev = b->levels - 1;
	b->offset = 128 / b->maxlev;

	if (dither)
	    for (j = 0; j < 2; j++)
		b->floyd[j] = G_calloc(window.cols + 2, sizeof(short));
    }

    /* open output files */
    out_name = opt_out->answer;

    out_file = Rast_open_c_new(out_name);

    out_array = Rast_allocate_c_buf();

    /* Make color table */
    make_color_cube(&out_colors);

    G_message(_("Writing raster map <%s>..."), out_name);

    for (atrow = 0; atrow < window.rows; atrow++) {
	G_percent(atrow, window.rows, 2);

	for (i = 0; i < 3; i++) {
	    struct band *b = &B[i];

	    Rast_get_row_colors(b->file, atrow, &b->colors,
				b->array[0],
				b->array[1], b->array[2], nulls);

	    if (dither) {
		short *tmp = b->floyd[0];

		b->floyd[0] = b->floyd[1];
		for (atcol = 0; atcol < window.cols + 2; atcol++)
		    tmp[atcol] = 0;
		b->floyd[1] = tmp;
	    }
	}

	for (atcol = 0; atcol < window.cols; atcol++) {
	    int val[3];

	    if (nulls[atcol]) {
		Rast_set_c_null_value(&out_array[atcol], 1);
		continue;
	    }

	    for (i = 0; i < 3; i++) {
		struct band *b = &B[i];
		int v = b->array[i][atcol];

		if (dither) {
		    int r, w, d;

		    v += b->floyd[0][atcol + 1] / 16;
		    v = (v < 0) ? 0 : (v > 255) ? 255 : v;
		    r = quantize(i, v);
		    w = r * 255 / b->maxlev;
		    d = v - w;
		    b->floyd[0][atcol + 2] += 7 * d;
		    b->floyd[1][atcol + 0] += 3 * d;
		    b->floyd[1][atcol + 1] += 5 * d;
		    b->floyd[1][atcol + 2] += 1 * d;
		    val[i] = r;
		}
		else
		    val[i] = quantize(i, v);
	    }

	    out_array[atcol] = (CELL)
		(val[2] * B[1].levels + val[1]) * B[0].levels + val[0];
	}

	Rast_put_row(out_file, out_array, CELL_TYPE);
    }
    G_percent(window.rows, window.rows, 1);

    /* Close the input files */
    for (i = 0; i < 3; i++)
	Rast_close(B[i].file);

    /* Close the output file */
    Rast_close(out_file);
    Rast_write_colors(out_name, G_mapset(), &out_colors);
    Rast_short_history(out_name, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(out_name, &history);

    G_done_msg(_("Raster map <%s> created."), out_name);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{

    struct GModule *module;
    struct Option *coord, *out_file, *min, *max, *mult;
    struct Flag *flag;
    int *int_buf;
    struct Cell_head w;
    struct History history;
    int cellfile;
    double east, north, pt[2], cur[2], row, col, fmult;
    double fmin, fmax;
    int binary;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("buffer"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("circle"));
    module->description =
	_("Creates a raster map containing concentric "
	  "rings around a given point.");

    out_file = G_define_standard_option(G_OPT_R_OUTPUT);

    coord = G_define_standard_option(G_OPT_M_COORDS);
    coord->required = YES;
    coord->description = _("The coordinate of the center (east,north)");

    min = G_define_option();
    min->key = "min";
    min->type = TYPE_DOUBLE;
    min->required = NO;
    min->description = _("Minimum radius for ring/circle map (in meters)");

    max = G_define_option();
    max->key = "max";
    max->type = TYPE_DOUBLE;
    max->required = NO;
    max->description = _("Maximum radius for ring/circle map (in meters)");

    mult = G_define_option();
    mult->key = "multiplier";
    mult->type = TYPE_DOUBLE;
    mult->required = NO;
    mult->description = _("Data value multiplier");

    flag = G_define_flag();
    flag->key = 'b';
    flag->description = _("Generate binary raster map");

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

    G_scan_easting(coord->answers[0], &east, G_projection());
    G_scan_northing(coord->answers[1], &north, G_projection());
    pt[0] = east;
    pt[1] = north;

    fmult = 1.0;

    if (min->answer)
	sscanf(min->answer, "%lf", &fmin);
    else
	fmin = 0;

    if (max->answer)
	sscanf(max->answer, "%lf", &fmax);
    else
	fmax = HUGE_VAL;

    if (fmin > fmax)
	G_fatal_error(_("Please specify a radius in which min < max"));

    if (mult->answer)
	if (1 != sscanf(mult->answer, "%lf", &fmult))
	    fmult = 1.0;

    /* nonsense test */
    if (flag->answer && (!min->answer && !max->answer))
	G_fatal_error(_("Please specify min and/or max radius when "
			"using the binary flag"));

    if (flag->answer)
	binary = 1;		/* generate binary pattern only, useful for MASK */
    else
	binary = 0;

    G_get_set_window(&w);

    cellfile = Rast_open_c_new(out_file->answer);

    int_buf = (int *)G_malloc(w.cols * sizeof(int));
    {
	int c;

	for (row = 0; row < w.rows; row++) {
	    G_percent(row, w.rows, 2);
	    cur[1] = Rast_row_to_northing(row + 0.5, &w);
	    for (col = 0; col < w.cols; col++) {
		c = col;
		cur[0] = Rast_col_to_easting(col + 0.5, &w);
		int_buf[c] =
		    (int)(distance(pt, cur, fmin, fmax, binary) * fmult);
		if (int_buf[c] == 0)
		    Rast_set_null_value(&int_buf[c], 1, CELL_TYPE);
	    }
	    Rast_put_row(cellfile, int_buf, CELL_TYPE);

	}
    }
    G_free(int_buf);
    Rast_close(cellfile);
    Rast_short_history(out_file->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(out_file->answer, &history);

    G_done_msg(_("Raster map <%s> created."),
	       out_file->answer);
    
    return (EXIT_SUCCESS);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    int partfd;
    int nrows, ncols;
    const char *drain_name;
    const char *ridge_name;
    const char *part_name;
    CELL *drain, *ridge;
    struct Cell_head window;
    int row, col, npass, tpass;
    struct GModule *module;
    struct Option *num_opt, *drain_opt, *ridge_opt, *part_opt;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    G_add_keyword(_("watershed"));
    module->description =
	_("Generates watershed subbasins raster map.");

    drain_opt = G_define_standard_option(G_OPT_R_INPUT);
    drain_opt->key = "cnetwork";
    drain_opt->description = _("Name of input coded stream network raster map");

    ridge_opt = G_define_standard_option(G_OPT_R_INPUT);
    ridge_opt->key = "tnetwork";
    ridge_opt->description = _("Name of input thinned ridge network raster map");

    part_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    
    num_opt = G_define_option();
    num_opt->key = "number";
    num_opt->type = TYPE_INTEGER;
    num_opt->required = YES;
    num_opt->description = _("Number of passes through the dataset");

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

    sscanf(num_opt->answer, "%d", &tpass);

    drain_name = drain_opt->answer;

    /* this isn't a nice thing to do. Rast_align_window() should be used first */
    Rast_get_cellhd(drain_name, "", &window);
    Rast_set_window(&window);

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    ridge_name = ridge_opt->answer;

    part_name = part_opt->answer;

    drain = read_map(drain_name, NOMASK, nrows, ncols);
    ridge = read_map(ridge_name, NOMASK, nrows, ncols);

    partfd = Rast_open_c_new(part_name);

    /* run through file and set streams to zero at locations where ridges exist */
    for (row = 0; row < nrows; row++) {
	for (col = 0; col < ncols; col++)
	    if (ridge[row * ncols + col] != 0)
		drain[row * ncols + col] = 0;
    }

    for (npass = 1; npass <= tpass; npass++) {
	for (row = 1; row < nrows - 1; row++) {
	    for (col = 1; col < ncols - 1; col++) {
		if (drain[row * ncols + col] == 0 &&
		    ridge[row * ncols + col] == 0) {
		    if (drain[(row - 1) * ncols + col] != 0 &&
			ridge[(row - 1) * ncols + col] == 0)
			drain[row * ncols + col] =
			    drain[(row - 1) * ncols + col];
		    if (drain[row * ncols + (col - 1)] != 0 &&
			ridge[row * ncols + (col - 1)] == 0)
			drain[row * ncols + col] =
			    drain[row * ncols + (col - 1)];
		}
	    }
	}
	G_message(_("Forward sweep complete"));

	for (row = nrows - 3; row > 1; --row) {
	    for (col = ncols - 3; col > 1; --col) {
		if (drain[row * ncols + col] == 0 &&
		    ridge[row * ncols + col] == 0) {
		    if (drain[(row + 1) * ncols + col] != 0 &&
			ridge[(row + 1) * ncols + col] == 0)
			drain[row * ncols + col] =
			    drain[(row + 1) * ncols + col];
		    if (drain[row * ncols + (col + 1)] != 0 &&
			ridge[row * ncols + (col + 1)] == 0)
			drain[row * ncols + col] =
			    drain[row * ncols + (col + 1)];
		}
	    }
	}
	G_message(_("Reverse sweep complete"));
    }

    /* write out partitioned watershed map */
    for (row = 0; row < nrows; row++)
	Rast_put_row(partfd, drain + (row * ncols), CELL_TYPE);

    G_message(_("Creating support files for <%s>..."), part_name);
    Rast_close(partfd);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    extern struct Cell_head window;
    union RASTER_PTR elevbuf, tmpbuf, outbuf;
    CELL min, max;
    DCELL dvalue, dvalue2, dmin, dmax;
    struct History hist;
    RASTER_MAP_TYPE data_type;
    struct Range range;
    struct FPRange fprange;
    double drow, dcol;
    int elev_fd, output_fd, zeros;
    struct
    {
	struct Option *opt1, *opt2, *opt3, *opt4, *north, *east, *year,
	    *month, *day, *hour, *minutes, *seconds, *timezone;
    } parm;
    struct Flag *flag1, *flag3, *flag4;
    struct GModule *module;
    char *name, *outname;
    double dazi, dalti;
    double azi, alti;
    double nstep, estep;
    double maxh;
    double east, east1, north, north1;
    int row1, col1;
    char OK;
    double timezone;
    int year, month, day, hour, minutes, seconds;
    long retval;
    int solparms, locparms, use_solpos;
    double sunrise, sunset, current_time;
    int sretr = 0, ssetr = 0, sretr_sec = 0, ssetr_sec = 0;
    double dsretr, dssetr;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("sun position"));
    module->label = _("Calculates cast shadow areas from sun position and elevation raster map.");
    module->description = _("Either exact sun position (A) is specified, or date/time to calculate "
			    "the sun position (B) by r.sunmask itself.");
    
    parm.opt1 = G_define_standard_option(G_OPT_R_ELEV);
    
    parm.opt2 = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.opt2->required = NO;
    
    parm.opt3 = G_define_option();
    parm.opt3->key = "altitude";
    parm.opt3->type = TYPE_DOUBLE;
    parm.opt3->required = NO;
    parm.opt3->options = "0-89.999";
    parm.opt3->description =
	_("Altitude of the sun above horizon, degrees (A)");
    parm.opt3->guisection = _("Position");

    parm.opt4 = G_define_option();
    parm.opt4->key = "azimuth";
    parm.opt4->type = TYPE_DOUBLE;
    parm.opt4->required = NO;
    parm.opt4->options = "0-360";
    parm.opt4->description =
	_("Azimuth of the sun from the north, degrees (A)");
    parm.opt4->guisection = _("Position");

    parm.year = G_define_option();
    parm.year->key = "year";
    parm.year->type = TYPE_INTEGER;
    parm.year->required = NO;
    parm.year->description = _("Year (B)");
    parm.year->options = "1950-2050";
    parm.year->guisection = _("Time");

    parm.month = G_define_option();
    parm.month->key = "month";
    parm.month->type = TYPE_INTEGER;
    parm.month->required = NO;
    parm.month->description = _("Month (B)");
    parm.month->options = "0-12";
    parm.month->guisection = _("Time");

    parm.day = G_define_option();
    parm.day->key = "day";
    parm.day->type = TYPE_INTEGER;
    parm.day->required = NO;
    parm.day->description = _("Day (B)");
    parm.day->options = "0-31";
    parm.day->guisection = _("Time");

    parm.hour = G_define_option();
    parm.hour->key = "hour";
    parm.hour->type = TYPE_INTEGER;
    parm.hour->required = NO;
    parm.hour->description = _("Hour (B)");
    parm.hour->options = "0-24";
    parm.hour->guisection = _("Time");

    parm.minutes = G_define_option();
    parm.minutes->key = "minute";
    parm.minutes->type = TYPE_INTEGER;
    parm.minutes->required = NO;
    parm.minutes->description = _("Minutes (B)");
    parm.minutes->options = "0-60";
    parm.minutes->guisection = _("Time");

    parm.seconds = G_define_option();
    parm.seconds->key = "second";
    parm.seconds->type = TYPE_INTEGER;
    parm.seconds->required = NO;
    parm.seconds->description = _("Seconds (B)");
    parm.seconds->options = "0-60";
    parm.seconds->guisection = _("Time");

    parm.timezone = G_define_option();
    parm.timezone->key = "timezone";
    parm.timezone->type = TYPE_INTEGER;
    parm.timezone->required = NO;
    parm.timezone->label =
	_("Timezone");
    parm.timezone->description = _("East positive, offset from GMT, also use to adjust daylight savings");
    parm.timezone->guisection = _("Time");

    parm.east = G_define_option();
    parm.east->key = "east";
    parm.east->key_desc = "value";
    parm.east->type = TYPE_STRING;
    parm.east->required = NO;
    parm.east->label =
	_("Easting coordinate (point of interest)");
    parm.east->description = _("Default: map center");
    parm.east->guisection = _("Position");

    parm.north = G_define_option();
    parm.north->key = "north";
    parm.north->key_desc = "value";
    parm.north->type = TYPE_STRING;
    parm.north->required = NO;
    parm.north->label =
	_("Northing coordinate (point of interest)");
    parm.north->description = _("Default: map center");
    parm.north->guisection = _("Position");

    flag1 = G_define_flag();
    flag1->key = 'z';
    flag1->description = _("Don't ignore zero elevation");

    flag3 = G_define_flag();
    flag3->key = 's';
    flag3->description = _("Calculate sun position only and exit");
    flag3->guisection = _("Print");
    
    flag4 = G_define_flag();
    flag4->key = 'g';
    flag4->description =
	_("Print the sun position output in shell script style");
    flag4->guisection = _("Print");

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

    zeros = flag1->answer;

    G_get_window(&window);

    /* if not given, get east and north: XX */
    if (!parm.north->answer || !parm.east->answer) {
	north = (window.north - window.south) / 2. + window.south;
	east = (window.west - window.east) / 2. + window.east;
	G_verbose_message(_("Using map center coordinates: %f %f"), east, north);
    }
    else {			/* user defined east, north: */

	sscanf(parm.north->answer, "%lf", &north);
	sscanf(parm.east->answer, "%lf", &east);
	if (strlen(parm.east->answer) == 0)
	    G_fatal_error(_("Empty east coordinate specified"));
	if (strlen(parm.north->answer) == 0)
	    G_fatal_error(_("Empty north coordinate specified"));
    }

    /* check which method to use for sun position:
       either user defines directly sun position or it is calculated */

    if (parm.opt3->answer && parm.opt4->answer)
	solparms = 1;		/* opt3 & opt4 complete */
    else
	solparms = 0;		/* calculate sun position */

    if (parm.year->answer && parm.month->answer && parm.day->answer &&
	parm.hour->answer && parm.minutes->answer && parm.seconds->answer &&
	parm.timezone->answer)
	locparms = 1;		/* complete */
    else
	locparms = 0;

    if (solparms && locparms)	/* both defined */
	G_fatal_error(_("Either define sun position or location/date/time parameters"));

    if (!solparms && !locparms)	/* nothing defined */
	G_fatal_error(_("Neither sun position nor east/north, date/time/timezone definition are complete"));

    /* if here, one definition was complete */
    if (locparms) {
	G_message(_("Calculating sun position... (using solpos (V. %s) from NREL)"),
		  SOLPOSVERSION);
	use_solpos = 1;
    }
    else {
	G_message(_("Using user defined sun azimuth, altitude settings (ignoring eventual other values)"));
	use_solpos = 0;
    }

    name = parm.opt1->answer;
    outname = parm.opt2->answer;
    if (!use_solpos) {
	sscanf(parm.opt3->answer, "%lf", &dalti);
	sscanf(parm.opt4->answer, "%lf", &dazi);
    }
    else {
	sscanf(parm.year->answer, "%i", &year);
	sscanf(parm.month->answer, "%i", &month);
	sscanf(parm.day->answer, "%i", &day);
	sscanf(parm.hour->answer, "%i", &hour);
	sscanf(parm.minutes->answer, "%i", &minutes);
	sscanf(parm.seconds->answer, "%i", &seconds);
	sscanf(parm.timezone->answer, "%lf", &timezone);
    }

    /* NOTES: G_calc_solar_position ()
       - the algorithm will compensate for leap year.
       - longitude, latitude: decimal degree
       - timezone: DO NOT ADJUST FOR DAYLIGHT SAVINGS TIME.
       - timezone: negative for zones west of Greenwich
       - lat/long: east and north positive
       - the atmospheric refraction is calculated for 1013hPa, 15�C 
       - time: local time from your watch

       Order of parameters:
       long, lat, timezone, year, month, day, hour, minutes, seconds 
     */

    if (use_solpos) {
	G_debug(3, "\nlat:%f  long:%f", north, east);
	retval =
	    calc_solar_position(east, north, timezone, year, month, day,
				hour, minutes, seconds);

	/* Remove +0.5 above if you want round-down instead of round-to-nearest */
	sretr = (int)floor(pdat->sretr);	/* sunrise */
	dsretr = pdat->sretr;
	sretr_sec =
	    (int)
	    floor(((dsretr - floor(dsretr)) * 60 -
		   floor((dsretr - floor(dsretr)) * 60)) * 60);
	ssetr = (int)floor(pdat->ssetr);	/* sunset */
	dssetr = pdat->ssetr;
	ssetr_sec =
	    (int)
	    floor(((dssetr - floor(dssetr)) * 60 -
		   floor((dssetr - floor(dssetr)) * 60)) * 60);

	/* print the results */
	if (retval == 0) {	/* error check */
	    if (flag3->answer) {
		if (flag4->answer) {
		    fprintf(stdout, "date=%d/%02d/%02d\n", pdat->year,
			    pdat->month, pdat->day);
		    fprintf(stdout, "daynum=%d\n", pdat->daynum);
		    fprintf(stdout, "time=%02i:%02i:%02i\n", pdat->hour,
			    pdat->minute, pdat->second);
		    fprintf(stdout, "decimaltime=%f\n",
			    pdat->hour + (pdat->minute * 100.0 / 60.0 +
					  pdat->second * 100.0 / 3600.0) /
			    100.);
		    fprintf(stdout, "longitudine=%f\n", pdat->longitude);
		    fprintf(stdout, "latitude=%f\n", pdat->latitude);
		    fprintf(stdout, "timezone=%f\n", pdat->timezone);
		    fprintf(stdout, "sunazimuth=%f\n", pdat->azim);
		    fprintf(stdout, "sunangleabovehorizon=%f\n",
			    pdat->elevref);

		    if (sretr / 60 <= 24.0) {
			fprintf(stdout, "sunrise=%02d:%02d:%02d\n",
				sretr / 60, sretr % 60, sretr_sec);
			fprintf(stdout, "sunset=%02d:%02d:%02d\n", ssetr / 60,
				ssetr % 60, ssetr_sec);
		    }
		}
		else {
		    fprintf(stdout, "%d/%02d/%02d, daynum: %d, time: %02i:%02i:%02i (decimal time: %f)\n",
			    pdat->year, pdat->month, pdat->day,
			    pdat->daynum, pdat->hour, pdat->minute,
			    pdat->second,
			    pdat->hour + (pdat->minute * 100.0 / 60.0 +
					  pdat->second * 100.0 / 3600.0) /
			    100.);
		    fprintf(stdout, "long: %f, lat: %f, timezone: %f\n",
			    pdat->longitude, pdat->latitude,
			    pdat->timezone);
		    fprintf(stdout, "Solar position: sun azimuth: %f, sun angle above horz. (refraction corrected): %f\n",
			    pdat->azim, pdat->elevref);
		    
		    if (sretr / 60 <= 24.0) {
			fprintf(stdout, "Sunrise time (without refraction): %02d:%02d:%02d\n",
				sretr / 60, sretr % 60, sretr_sec);
			fprintf(stdout, "Sunset time  (without refraction): %02d:%02d:%02d\n",
				ssetr / 60, ssetr % 60, ssetr_sec);
		    }
		}
	    }
	    sunrise = pdat->sretr / 60.;	/* decimal minutes */
	    sunset = pdat->ssetr / 60.;
	    current_time =
		pdat->hour + (pdat->minute / 60.) + (pdat->second / 3600.);
	}
	else			/* fatal error in G_calc_solar_position() */
	    G_fatal_error(_("Please correct settings"));
    }

    if (use_solpos) {
	dalti = pdat->elevref;
	dazi = pdat->azim;
    }				/* otherwise already defined */


    /* check sunrise */
    if (use_solpos) {
	G_debug(3, "current_time:%f sunrise:%f", current_time, sunrise);
	if ((current_time < sunrise)) {
	    if (sretr / 60 <= 24.0)
		G_message(_("Time (%02i:%02i:%02i) is before sunrise (%02d:%02d:%02d)"),
			  pdat->hour, pdat->minute, pdat->second, sretr / 60,
			  sretr % 60, sretr_sec);
	    else
		G_message(_("Time (%02i:%02i:%02i) is before sunrise"),
			  pdat->hour, pdat->minute, pdat->second);

	    G_warning(_("Nothing to calculate. Please verify settings."));
	}
	if ((current_time > sunset)) {
	    if (sretr / 60 <= 24.0)
		G_message(_("Time (%02i:%02i:%02i) is after sunset (%02d:%02d:%02d)"),
			  pdat->hour, pdat->minute, pdat->second, ssetr / 60,
			  ssetr % 60, ssetr_sec);
	    else
		G_message(_("Time (%02i:%02i:%02i) is after sunset"),
			  pdat->hour, pdat->minute, pdat->second);
	    G_warning(_("Nothing to calculate. Please verify settings."));
	}
    }

    if (flag3->answer && (use_solpos == 1)) {	/* we only want the sun position */
	exit(EXIT_SUCCESS);
    }
    else if (flag3->answer && (use_solpos == 0)) {
	/* are you joking ? */
	G_message(_("You already know the sun position"));
	exit(EXIT_SUCCESS);
    }

    if (!outname)
	G_fatal_error(_("Option <%s> required"), parm.opt2->key);

    elev_fd = Rast_open_old(name, "");
    output_fd = Rast_open_c_new(outname);
    
    data_type = Rast_get_map_type(elev_fd);
    elevbuf.v = Rast_allocate_buf(data_type);
    tmpbuf.v = Rast_allocate_buf(data_type);
    outbuf.v = Rast_allocate_buf(CELL_TYPE);	/* binary map */

    if (data_type == CELL_TYPE) {
	if ((Rast_read_range(name, "", &range)) < 0)
	    G_fatal_error(_("Unable to open range file for raster map <%s>"), name);
	Rast_get_range_min_max(&range, &min, &max);
	dmin = (double)min;
	dmax = (double)max;
    }
    else {
	Rast_read_fp_range(name, "", &fprange);
	Rast_get_fp_range_min_max(&fprange, &dmin, &dmax);
    }

    azi = 2 * M_PI * dazi / 360;
    alti = 2 * M_PI * dalti / 360;
    nstep = cos(azi) * window.ns_res;
    estep = sin(azi) * window.ew_res;
    row1 = 0;

    G_message(_("Calculating shadows from DEM..."));
    while (row1 < window.rows) {
	G_percent(row1, window.rows, 2);
	col1 = 0;
	drow = -1;
	Rast_get_row(elev_fd, elevbuf.v, row1, data_type);
	
	while (col1 < window.cols) {
	    dvalue = raster_value(elevbuf, data_type, col1);
	    /*              outbuf.c[col1]=1; */
	    Rast_set_null_value(&outbuf.c[col1], 1, CELL_TYPE);
	    OK = 1;
	    east = Rast_col_to_easting(col1 + 0.5, &window);
	    north = Rast_row_to_northing(row1 + 0.5, &window);
	    east1 = east;
	    north1 = north;
	    if (dvalue == 0.0 && !zeros)
		OK = 0;
	    while (OK == 1)
	    {
		east += estep;
		north += nstep;
		if (north > window.north || north < window.south
		    || east > window.east || east < window.west)
		    OK = 0;
		else {
		    maxh = tan(alti) *
			sqrt((north1 - north) * (north1 - north) +
			     (east1 - east) * (east1 - east));
		    if ((maxh) > (dmax - dvalue))
			OK = 0;
		    else {
			dcol = Rast_easting_to_col(east, &window);
			if (drow != Rast_northing_to_row(north, &window)) {
			    drow = Rast_northing_to_row(north, &window);
			    Rast_get_row(elev_fd, tmpbuf.v, (int)drow,
					 data_type);
			}
			dvalue2 = raster_value(tmpbuf, data_type, (int)dcol);
			if ((dvalue2 - dvalue) > (maxh)) {
			    OK = 0;
			    outbuf.c[col1] = 1;
			}
		    }
		}
	    }
	    G_debug(3, "Analysing col %i", col1);
	    col1 += 1;
	}
	G_debug(3, "Writing result row %i of %i", row1, window.rows);
	Rast_put_row(output_fd, outbuf.c, CELL_TYPE);
	row1 += 1;
    }
    G_percent(1, 1, 1);

    Rast_close(output_fd);
    Rast_close(elev_fd);

    /* writing history file */
    Rast_short_history(outname, "raster", &hist);
    Rast_format_history(&hist, HIST_DATSRC_1, "raster elevation map %s", name);
    Rast_command_history(&hist);
    Rast_write_history(outname, &hist);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
    int fd[NFILES];
    int outfd;
    int i;
    const char *name;
    const char *output;
    const char *mapset;
    int non_zero;
    struct Range range;
    CELL ncats, max_cats;
    int primary;
    struct Categories pcats;
    struct Colors pcolr;
    char buf[1024];
    CELL result;
    struct GModule *module;
    struct
    {
	struct Option *input, *output;
    } parm;
    struct
    {
	struct Flag *z;
    } flag;

    G_gisinit(argv[0]);

    /* Define the different options */

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Creates a cross product of the category values from "
	  "multiple raster map layers.");

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->multiple = YES;
    parm.input->gisprompt = "old,cell,raster";
    sprintf(buf, _("Names of 2-%d input raster maps"), NFILES);
    parm.input->description = G_store(buf);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    /* Define the different flags */

    flag.z = G_define_flag();
    flag.z->key = 'z';
    flag.z->description = _("Non-zero data only");

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

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    nfiles = 0;
    non_zero = flag.z->answer;

    for (nfiles = 0; (name = parm.input->answers[nfiles]); nfiles++) {
	if (nfiles >= NFILES)
	    G_fatal_error(_("More than %d files not allowed"), NFILES);
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	names[nfiles] = name;
	fd[nfiles] = Rast_open_old(name, mapset);
	Rast_read_range(name, mapset, &range);
	ncats = range.max - range.min;

	if (nfiles == 0 || ncats > max_cats) {
	    primary = nfiles;
	    max_cats = ncats;
	}
    }

    if (nfiles <= 1)
	G_fatal_error(_("Must specify 2 or more input maps"));
    output = parm.output->answer;
    outfd = Rast_open_c_new(output);

    sprintf(buf, "Cross of %s", names[0]);
    for (i = 1; i < nfiles - 1; i++) {
	strcat(buf, ", ");
	strcat(buf, names[i]);
    }
    strcat(buf, " and ");
    strcat(buf, names[i]);
    Rast_init_cats(buf, &pcats);

    /* first step is cross product, but un-ordered */
    result = cross(fd, non_zero, primary, outfd);

    /* print message STEP mesage */
    G_message(_("%s: STEP 2 ..."), G_program_name());

    /* now close all files */
    for (i = 0; i < nfiles; i++)
	Rast_close(fd[i]);
    Rast_close(outfd);

    if (result <= 0)
	exit(0);


    /* build the renumbering/reclass and the new cats file */
    qsort(reclass, result + 1, sizeof(RECLASS), cmp);
    table = (CELL *) G_calloc(result + 1, sizeof(CELL));
    for (i = 0; i < nfiles; i++) {
	mapset = G_find_raster2(names[i], "");
	Rast_read_cats(names[i], mapset, &labels[i]);
    }

    for (ncats = 0; ncats <= result; ncats++) {
	table[reclass[ncats].result] = ncats;
	set_cat(ncats, reclass[ncats].cat, &pcats);
    }

    for (i = 0; i < nfiles; i++)
	Rast_free_cats(&labels[i]);

    /* reopen the output cell for reading and for writing */
    fd[0] = Rast_open_old(output, G_mapset());
    outfd = Rast_open_c_new(output);

    renumber(fd[0], outfd);

    G_message(_("Creating support files for <%s>..."), output);
    Rast_close(fd[0]);
    Rast_close(outfd);
    Rast_write_cats(output, &pcats);
    Rast_free_cats(&pcats);
    if (result > 0) {
	Rast_make_random_colors(&pcolr, (CELL) 1, result);
	Rast_write_colors(output, G_mapset(), &pcolr);
    }

    G_message(_("%ld categories"), (long)result);
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 17
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char *argv[])
{
    int col, row;

    /* to menage start (source) raster map */
    struct Range start_range;
    CELL start_range_min, start_range_max;
    int start_is_time;  /* 0 or 1 */

    struct
    {
	struct Option *max, *dir, *base, *start,
	    *spotdist, *velocity, *mois,
	    *least, *comp_dens, *init_time,
	    *time_lag, *backdrop, *out, *x_out, *y_out;
    } parm;
    struct
    {
	/* please, remove display before GRASS 7 released */
	struct Flag *display, *spotting, *start_is_time;
    } flag;
    struct GModule *module;

    /* initialize access to database and create temporary files */

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("fire"));
    G_add_keyword(_("spread"));
    G_add_keyword(_("hazard"));
    module->label =
	_("Simulates elliptically anisotropic spread.");
    module->description =
	_("Generates a raster map of the cumulative time of spread, "
	  "given raster maps containing the rates of spread (ROS), "
	  "the ROS directions and the spread origins. "
	  "It optionally produces raster maps to contain backlink UTM "
	  "coordinates for tracing spread paths. "
	  "Usable for fire spread simulations.");

    parm.max = G_define_option();
    parm.max->key = "max";
    parm.max->type = TYPE_STRING;
    parm.max->required = YES;
    parm.max->gisprompt = "old,cell,raster";
    parm.max->guisection = _("Input maps");
    parm.max->label =
	_("Raster map containing maximal ROS (cm/min)");
	parm.max->description =
	_("Name of an existing raster map layer in the user's current "
	  "mapset search path containing the maximum ROS values (cm/minute).");

    parm.dir = G_define_option();
    parm.dir->key = "dir";
    parm.dir->type = TYPE_STRING;
    parm.dir->required = YES;
    parm.dir->gisprompt = "old,cell,raster";
    parm.dir->guisection = _("Input maps");
    parm.dir->label =
	_("Raster map containing directions of maximal ROS (degree)");
    parm.dir->description =
	_("Name of an existing raster map layer in the user's "
	  "current mapset search path containing directions of the maximum ROSes, "
	  "clockwise from north (degree)."); /* TODO: clockwise from north? see r.ros */

    parm.base = G_define_option();
    parm.base->key = "base";
    parm.base->type = TYPE_STRING;
    parm.base->required = YES;
    parm.base->gisprompt = "old,cell,raster";
    parm.base->guisection = _("Input maps");
    parm.base->label =
	_("Raster map containing base ROS (cm/min)");
    parm.base->description =
	_("Name of an existing raster map layer in the user's "
	  "current mapset search path containing the ROS values in the directions "
	  "perpendicular to maximum ROSes' (cm/minute). These ROSes are also the ones "
	  "without the effect of directional factors.");

    parm.start = G_define_option();
    parm.start->key = "start";
    parm.start->type = TYPE_STRING;
    parm.start->required = YES;
    parm.start->gisprompt = "old,cell,raster";
    parm.start->guisection = _("Input maps");
    parm.start->description =
	_("Raster map containing starting sources");
    parm.start->description =
	_("Name of an existing raster map layer in the "
	  "user's current mapset search path containing starting locations of the "
	  "spread phenomenon. Any positive integers in this map are recognized as "
	  "starting sources (seeds).");

    parm.spotdist = G_define_option();
    parm.spotdist->key = "spot_dist";
    parm.spotdist->type = TYPE_STRING;
    parm.spotdist->gisprompt = "old,cell,raster";
    parm.spotdist->guisection = _("Input maps");
    parm.spotdist->label =
	_("Raster map containing maximal spotting distance (m, required with -s)");
    parm.spotdist->description =
	_("Name of an existing raster map layer in "
	  "the user's current mapset search path containing the maximum potential "
	  "spotting distances (meters).");

    parm.velocity = G_define_option();
    parm.velocity->key = "w_speed";
    parm.velocity->type = TYPE_STRING;
    parm.velocity->gisprompt = "old,cell,raster";
    parm.velocity->guisection = _("Input maps");
    parm.velocity->label =
	_("Raster map containing midflame wind speed (ft/min, required with -s)");
    parm.velocity->description =
	_("Name of an existing raster map layer in the "
	  "user's current mapset search path containing wind velocities at half of "
	  "the average flame height (feet/minute).");

    parm.mois = G_define_option();
    parm.mois->key = "f_mois";
    parm.mois->type = TYPE_STRING;
    parm.mois->gisprompt = "old,cell,raster";
    parm.mois->guisection = _("Input maps");
    parm.mois->label =
	_("Raster map containing fine fuel moisture of the cell receiving a spotting firebrand (%, required with -s)");
    parm.mois->description =
	_("Name of an existing raster map layer in the "
	  "user's current mapset search path containing the 1-hour (<.25\") fuel "
	  "moisture (percentage content multiplied by 100).");

    parm.least = G_define_option();
    parm.least->key = "least_size";
    parm.least->type = TYPE_STRING;
    parm.least->key_desc = "odd int";
    parm.least->options = "3,5,7,9,11,13,15";
    parm.least->description =
	_("Basic sampling window size needed to meet certain accuracy (3)"); /* TODO: what is 3 here? default? */
    parm.least->description =
	_("An odd integer ranging 3 - 15 indicating "
	  "the basic sampling window size within which all cells will be considered "
	  "to see whether they will be reached by the current spread cell. The default "
	  "number is 3 which means a 3x3 window.");

    parm.comp_dens = G_define_option();
    parm.comp_dens->key = "comp_dens";
    parm.comp_dens->type = TYPE_STRING;
    parm.comp_dens->key_desc = "decimal";
    parm.comp_dens->label =
	_("Sampling density for additional computing (range: 0.0 - 1.0 (0.5))"); /* TODO: again, what is 0.5?, TODO: range not set */
    parm.comp_dens->description =
	_("A decimal number ranging 0.0 - 1.0 indicating "
	  "additional sampling cells will be considered to see whether they will be "
	  "reached by the current spread cell. The closer to 1.0 the decimal number "
	  "is, the longer the program will run and the higher the simulation accuracy "
	  "will be. The default number is 0.5.");

    parm.init_time = G_define_option();
    parm.init_time->key = "init_time";
    parm.init_time->type = TYPE_STRING;
    parm.init_time->key_desc = "int (>= 0)"; /* TODO: move to ->options */
    parm.init_time->answer = "0";
    parm.init_time->label =
	_("Initial time for current simulation (0) (min)");
    parm.init_time->description =
	_("A non-negative number specifying the initial "
	  "time for the current spread simulation (minutes). This is useful when multiple "
	  "phase simulation is conducted. The default time is 0.");

    parm.time_lag = G_define_option();
    parm.time_lag->key = "lag";
    parm.time_lag->type = TYPE_STRING;
    parm.time_lag->key_desc = "int (>= 0)"; /* TODO: move to ->options */
    parm.time_lag->description =
	_("Simulating time duration LAG (fill the region) (min)"); /* TODO: what does this mean? */
    parm.time_lag->description =
	_("A non-negative integer specifying the simulating "
	  "duration time lag (minutes). The default is infinite, but the program will "
	  "terminate when the current geographic region/mask has been filled. It also "
	  "controls the computational time, the shorter the time lag, the faster the "
	  "program will run.");

    /* TODO: what's this? probably display, so remove */
    parm.backdrop = G_define_option();
    parm.backdrop->key = "backdrop";
    parm.backdrop->type = TYPE_STRING;
    parm.backdrop->gisprompt = "old,cell,raster";
    parm.backdrop->label =
	_("Name of raster map as a display backdrop");
    parm.backdrop->description =
	_("Name of an existing raster map layer in the "
	  "user's current mapset search path to be used as the background on which "
	  "the \"live\" movement will be shown.");

    parm.out = G_define_option();
    parm.out->key = "output";
    parm.out->type = TYPE_STRING;
    parm.out->required = YES;
    parm.out->gisprompt = "new,cell,raster";
    parm.out->guisection = _("Output maps");
    parm.out->label =
	_("Raster map to contain output spread time (min)");
    parm.out->description =
	_("Name of the new raster map layer to contain "
	  "the results of the cumulative spread time needed for a phenomenon to reach "
	  "each cell from the starting sources (minutes).");

    parm.x_out = G_define_option();
    parm.x_out->key = "x_output";
    parm.x_out->type = TYPE_STRING;
    parm.x_out->gisprompt = "new,cell,raster";
    parm.x_out->guisection = _("Output maps");
    parm.x_out->label =
	_("Name of raster map to contain X back coordinates");
    parm.x_out->description =
	_("Name of the new raster map layer to contain "
	  "the results of backlink information in UTM easting coordinates for each "
	  "cell.");

    parm.y_out = G_define_option();
    parm.y_out->key = "y_output";
    parm.y_out->type = TYPE_STRING;
    parm.y_out->gisprompt = "new,cell,raster";
    parm.y_out->guisection = _("Output maps");
    parm.y_out->label =
	_("Name of raster map to contain Y back coordinates");
    parm.y_out->description =
	_("Name of the new raster map layer to contain "
	  "the results of backlink information in UTM northing coordinates for each "
	  "cell.");

    flag.display = G_define_flag();
    flag.display->key = 'd';
#if 0
    flag.display->label = _("DISPLAY 'live' spread process on screen");
    flag.display->description =
	_("Display the 'live' simulation on screen. A graphics window "
	  "must be opened and selected before using this option.");
#else
    flag.display->description = _("Live display - disabled and depreciated");
#endif

    flag.spotting = G_define_flag();
    flag.spotting->key = 's';
    flag.spotting->description = _("Consider spotting effect (for wildfires)");

    flag.start_is_time = G_define_flag();
    flag.start_is_time->key = 'i';
    flag.start_is_time->label = _("Use start raster map values in"
	" output spread time raster map");
    flag.start_is_time->description = _("Designed to be used with output"
	" of previous run of r.spread when computing spread iteratively."
	" The values in start raster map are considered as time."
	" Allowed values in raster map are from zero"
	" to the value of init_time option."
	" If not enabled, init_time is used in the area of start raster map");

    /*   Parse command line */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* FIXME - allow seed to be specified for repeatability */
    G_srand48_auto();

    display = flag.display->answer;
#if 1
    if (display)
	G_fatal_error(_("The display feature is disabled"));
#endif
    spotting = flag.spotting->answer;

    max_layer = parm.max->answer;
    dir_layer = parm.dir->answer;
    base_layer = parm.base->answer;
    start_layer = parm.start->answer;
    backdrop_layer = parm.backdrop->answer;
    out_layer = parm.out->answer;
    if (parm.x_out->answer) {
	x_out = 1;
	x_out_layer = parm.x_out->answer;
    }
    if (parm.y_out->answer) {
	y_out = 1;
	y_out_layer = parm.y_out->answer;
    }
    if (spotting) {
	if (!
	    (parm.spotdist->answer && parm.velocity->answer &&
	     parm.mois->answer)) {
	    G_warning
		("SPOTTING DISTANCE, fuel MOISTURE, or wind VELOCITY map not given w/ -s");
	    G_usage();
	    exit(EXIT_FAILURE);
	}
	else {
	    spotdist_layer = parm.spotdist->answer;
	    velocity_layer = parm.velocity->answer;
	    mois_layer = parm.mois->answer;
	}
    }
    /*Check the given the least sampling size, assign the default if needed */
    if (parm.least->answer)
	least = atoi(parm.least->answer);
    else
	least = 3;
    /*Check the given computing density, assign the default if needed */
    if (parm.comp_dens->answer) {
	comp_dens = atof(parm.comp_dens->answer);
	if (comp_dens < 0.0 || comp_dens > 1.0) {
	    G_warning("Illegal computing density <%s>",
		      parm.comp_dens->answer);
	    G_usage();
	    exit(EXIT_FAILURE);
	}
    }
    else {
	comp_dens = 0.5;
    }
    /*Check the given initial time and simulation time lag, assign the default if needed */
    init_time = atoi(parm.init_time->answer);
    if (init_time < 0) {
	G_warning("Illegal initial time <%s>", parm.init_time->answer);
	G_usage();
	exit(EXIT_FAILURE);
    }

    if (parm.time_lag->answer) {
	time_lag = atoi(parm.time_lag->answer);
	if (time_lag < 0) {
	    G_warning("Illegal simulating time lag <%s>",
		      parm.time_lag->answer);
	    G_usage();
	    exit(EXIT_FAILURE);
	}
    }
    else {
	time_lag = 99999;
    }

    /*  Get database window parameters  */

    G_get_window(&window);

    /*  find number of rows and columns in window    */

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /*transfor measurement unit from meters to centimeters due to ROS unit
     *if the input ROSs are in m/min units, cancell the following*/
    window.ns_res = 100 * window.ns_res;
    window.ew_res = 100 * window.ew_res;

    /* Initialize display screens */
#if 0
    if (display)
	display_init();
#endif

    /*  Check if input layers exists in data base  */

    if (G_find_raster2(max_layer, "") == NULL)
	G_fatal_error("Raster map <%s> not found", max_layer);

    if (G_find_raster2(dir_layer, "") == NULL)
	G_fatal_error(_("Raster map <%s> not found"), dir_layer);

    if (G_find_raster2(base_layer, "") == NULL)
	G_fatal_error(_("Raster map <%s> not found"), base_layer);

    if (G_find_raster2(start_layer, "") == NULL)
	G_fatal_error(_("Raster map <%s> not found"), start_layer);

    if (spotting) {
	if (G_find_raster2(spotdist_layer, "") == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), spotdist_layer);

	if (G_find_raster2(velocity_layer, "") == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), velocity_layer);

	if (G_find_raster2(mois_layer, "") == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), mois_layer);
    }

    /*  Open input cell layers for reading  */

    max_fd = Rast_open_old(max_layer, G_find_raster2(max_layer, ""));

    dir_fd = Rast_open_old(dir_layer, G_find_raster2(dir_layer, ""));

    base_fd = Rast_open_old(base_layer, G_find_raster2(base_layer, ""));

    if (spotting) {
	spotdist_fd =
	    Rast_open_old(spotdist_layer, G_find_raster2(spotdist_layer, ""));

	velocity_fd =
	    Rast_open_old(velocity_layer, G_find_raster2(velocity_layer, ""));

	mois_fd = Rast_open_old(mois_layer, G_find_raster2(mois_layer, ""));
    }

    /*  Allocate memories for a row  */
    cell = Rast_allocate_c_buf();
    if (x_out)
	x_cell = Rast_allocate_c_buf();
    if (y_out)
	y_cell = Rast_allocate_c_buf();

    /*  Allocate memories for a map  */
    map_max = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
    map_dir = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
    map_base = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
    map_visit = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
    map_out = (float *)G_calloc(nrows * ncols + 1, sizeof(float));
    if (spotting) {
	map_spotdist = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
	map_velocity = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
	map_mois = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
    }
    if (x_out)
	map_x_out = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));
    if (y_out)
	map_y_out = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL));


    /*   Write the input layers in the map "arrays"  */

    G_message(_("Reading inputs..."));

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	Rast_get_c_row(max_fd, cell, row);
	for (col = 0; col < ncols; col++)
	    DATA(map_max, row, col) = cell[col];
	Rast_get_c_row(dir_fd, cell, row);
	for (col = 0; col < ncols; col++)
	    DATA(map_dir, row, col) = cell[col];
	Rast_get_c_row(base_fd, cell, row);
	for (col = 0; col < ncols; col++)
	    DATA(map_base, row, col) = cell[col];
	if (spotting) {
	    Rast_get_c_row(spotdist_fd, cell, row);
	    for (col = 0; col < ncols; col++)
		DATA(map_spotdist, row, col) = cell[col];
	    Rast_get_c_row(velocity_fd, cell, row);
	    for (col = 0; col < ncols; col++)
		DATA(map_velocity, row, col) = cell[col];
	    Rast_get_c_row(mois_fd, cell, row);
	    for (col = 0; col < ncols; col++)
		DATA(map_mois, row, col) = cell[col];
	}
    }
    G_percent(row, nrows, 2);


    /*   Scan the START layer searching for starting points.
     *   Create an array of starting points (min_heap) ordered by costs.
     */

    start_fd = Rast_open_old(start_layer, G_find_raster2(start_layer, ""));

    Rast_read_range(start_layer, G_find_file("cell", start_layer, ""),
		    &start_range);
    Rast_get_range_min_max(&start_range, &start_range_min, &start_range_max);

    start_is_time = flag.start_is_time->answer;
    /* values higher than init_time are unexpected and may cause segfaults */
    if (start_is_time && start_range_max > init_time)
	G_fatal_error(_("Maximum of start raster map is grater than init_time"
			" (%d > %d)"), start_range_max, init_time);
    /* values lower then zero does not make sense for time */
    if (start_is_time && start_range_min < 0)
	G_fatal_error(_("Minimum of start raster map is less than zero"
			" (%d < 0)"), start_range_min, init_time);

    /*  Initialize the heap  */
    heap =
	(struct costHa *)G_calloc(nrows * ncols + 1, sizeof(struct costHa));
    heap_len = 0;

    G_message(_("Reading %s..."), start_layer);
    G_debug(1, "Collecting origins...");
    collect_ori(start_fd, start_is_time);
    G_debug(1, "Done");


    /* Major computation of spread time */
    G_debug(1, "Spreading...");
    spread();
    G_debug(1, "Done");


    /*  Open cumulative cost layer (and x, y direction layers) for writing */

    cum_fd = Rast_open_c_new(out_layer);
    if (x_out)
	x_fd = Rast_open_c_new(x_out_layer);
    if (y_out)
	y_fd = Rast_open_c_new(y_out_layer);

    /* prepare output -- adjust from cm to m */
    window.ew_res = window.ew_res / 100;
    window.ns_res = window.ns_res / 100;

    /* copy maps in ram to output maps */
    ram2out();

    G_free(map_max);
    G_free(map_dir);
    G_free(map_base);
    G_free(map_out);
    G_free(map_visit);
    if (x_out)
	G_free(map_x_out);
    if (y_out)
	G_free(map_y_out);
    if (spotting) {
	G_free(map_spotdist);
	G_free(map_mois);
	G_free(map_velocity);
    }

    Rast_close(max_fd);
    Rast_close(dir_fd);
    Rast_close(base_fd);
    Rast_close(start_fd);
    Rast_close(cum_fd);
    if (x_out)
	Rast_close(x_fd);
    if (y_out)
	Rast_close(y_fd);
    if (spotting) {
	Rast_close(spotdist_fd);
	Rast_close(velocity_fd);
	Rast_close(mois_fd);
    }

    /* close graphics */
#if 0
    if (display)
	display_close();
#endif

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
    MELEMENT *rowlist;
    SHORT nrows, ncols;
    SHORT datarows;
    int npoints;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *output, *npoints;
    } parm;
    struct
    {
	struct Flag *e;
    } flag;
    int n, fd, maskfd;

    /* Initialize the GIS calls                                     */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("IDW"));
    module->description =
	_("Surface interpolation utility for raster map.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.npoints = G_define_option();
    parm.npoints->key = "npoints";
    parm.npoints->type = TYPE_INTEGER;
    parm.npoints->required = NO;
    parm.npoints->description = _("Number of interpolation points");
    parm.npoints->answer = "12";

    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Output is the interpolation error");

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

    if (sscanf(parm.npoints->answer, "%d", &n) != 1 || n <= 0)
	G_fatal_error(_("Illegal value for '%s' (%s)"), parm.npoints->key,
		      parm.npoints->answer);

    npoints = n;
    error_flag = flag.e->answer;
    input = parm.input->answer;
    output = parm.output->answer;

    /*  Get database window parameters                              */
    G_get_window(&window);

    /*  find number of rows and columns in window                   */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /* create distance squared or latitude lookup tables */
    /* initialize function pointers */
    lookup_and_function_ptrs(nrows, ncols);

    /*  allocate buffers for row i/o                                */
    cell = Rast_allocate_c_buf();
    if ((maskfd = Rast_maskfd()) >= 0 || error_flag) {	/* apply mask to output */
	if (error_flag)		/* use input as mask when -e option chosen */
	    maskfd = Rast_open_old(input, "");
	mask = Rast_allocate_c_buf();
    }
    else
	mask = NULL;

    /*  Open input cell layer for reading                           */
    fd = Rast_open_old(input, "");

    /* Store input data in array-indexed doubly-linked lists and close input file */
    rowlist = row_lists(nrows, ncols, &datarows, &n, fd, cell);
    Rast_close(fd);
    if (npoints > n)
	npoints = n;


    /* open cell layer for writing output              */
    fd = Rast_open_c_new(output);

    /* call the interpolation function                              */
    interpolate(rowlist, nrows, ncols, datarows, npoints, fd, maskfd);

    /* free allocated memory */
    free_row_lists(rowlist, nrows);
    G_free(rowlook);
    G_free(collook);
    if (ll)
	free_dist_params();
    Rast_close(fd);
    /* writing history file */
    Rast_short_history(output, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(output, &history);

    G_done_msg(" ");
    
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
    /* Global variable & function declarations */
    double Thresh;
    int NumOrients;
    int inputfd, zcfd;		/* the input and output file descriptors */
    struct Cell_head window;
    CELL *cell_row;
    float Width;

    int i, j;			/* Loop control variables */
    int or, oc;			/* Original dimensions of image */
    int rows, cols;		/* Smallest powers of 2 >= number of rows & columns */
    int size;			/* the length of one side */
    long totsize;		/* the Total number of data points */
    double *data[2];		/* Data structure containing real & complex values of FFT */
    struct GModule *module;
    struct Option *input_map, *output_map, *width, *threshold, *orientations;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("edges"));
    module->description =
	_("Zero-crossing \"edge detection\" raster "
	  "function for image processing.");

    /* define options */
    input_map = G_define_option();
    input_map->key = "input";
    input_map->type = TYPE_STRING;
    input_map->required = YES;
    input_map->multiple = NO;
    input_map->gisprompt = "old,cell,raster";
    input_map->description = _("Name of input raster map");

    output_map = G_define_option();
    output_map->key = "output";
    output_map->type = TYPE_STRING;
    output_map->required = YES;
    output_map->multiple = NO;
    output_map->gisprompt = "new,cell,raster";
    output_map->description = _("Zero crossing raster map");

    width = G_define_option();
    width->key = "width";
    width->type = TYPE_INTEGER;
    width->required = NO;
    width->multiple = NO;
    width->description = _("x-y extent of the Gaussian filter");
    width->answer = "9";

    threshold = G_define_option();
    threshold->key = "threshold";
    threshold->type = TYPE_DOUBLE;
    threshold->required = NO;
    threshold->multiple = NO;
    threshold->description = _("Sensitivity of Gaussian filter");
    threshold->answer = "10";

    orientations = G_define_option();
    orientations->key = "orientations";
    orientations->type = TYPE_INTEGER;
    orientations->required = NO;
    orientations->multiple = NO;
    orientations->description = _("Number of azimuth directions categorized");
    orientations->answer = "1";

    /* call parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* open input cell map */
    inputfd = Rast_open_old(input_map->answer, "");

    sscanf(threshold->answer, "%1lf", &Thresh);
    if (Thresh <= 0.0)
	G_fatal_error(_("Threshold less than or equal to zero not allowed"));
    Thresh /= 100.0;

    sscanf(width->answer, "%f", &Width);

    if (Width <= 0.0)
	G_fatal_error(_("Width less than or equal to zero not allowed"));

    sscanf(orientations->answer, "%d", &NumOrients);
    if (NumOrients < 1)
	G_fatal_error(_("Fewer than 1 orientation classes not allowed"));


    /* get the current window for later */
    G_get_set_window(&window);

    /* get the rows and columns in the current window */
    or = Rast_window_rows();
    oc = Rast_window_cols();
    rows = G_math_max_pow2((long)or);
    cols = G_math_max_pow2((long)oc);
    size = (rows > cols) ? rows : cols;
    totsize = size * size;

    G_message(_("Power 2 values : %d rows %d columns"), rows, cols);

    /* Allocate appropriate memory for the structure containing
       the real and complex components of the FFT.  DATA[0] will
       contain the real, and DATA[1] the complex component.
     */
    data[0] = (double *)G_malloc(totsize * sizeof(double));
    data[1] = (double *)G_malloc(totsize * sizeof(double));

    /* Initialize real & complex components to zero */
    G_message(_("Initializing data..."));
    for (i = 0; i < (totsize); i++) {
	*(data[0] + i) = 0.0;
	*(data[1] + i) = 0.0;
    }

    /* allocate the space for one row of cell map data */
    cell_row = Rast_allocate_c_buf();

    /* Read in cell map values */
    G_message(_("Reading raster map..."));
    for (i = 0; i < or; i++) {
	Rast_get_c_row(inputfd, cell_row, i);

	for (j = 0; j < oc; j++)
	    *(data[0] + (i * size) + j) = (double)cell_row[j];
    }
    /* close input cell map and release the row buffer */
    Rast_close(inputfd);
    G_free(cell_row);

    /* take the del**2g of image */
    del2g(data, size, Width);

    /* find the zero crossings:  Here are several notes -
       1) this routine only uses the real values
       2) it places the zero crossings in the imaginary array */
    G_math_findzc(data[0], size, data[1], Thresh, NumOrients);

    /* open the output cell maps and allocate cell row buffers */
    G_message(_("Writing transformed data to file..."));
    zcfd = Rast_open_c_new(output_map->answer);

    cell_row = Rast_allocate_c_buf();

    /* Write out result to a new cell map */
    for (i = 0; i < or; i++) {
	for (j = 0; j < oc; j++) {
	    *(cell_row + j) = (CELL) (*(data[1] + i * cols + j));
	}
	Rast_put_row(zcfd, cell_row, CELL_TYPE);
    }
    Rast_close(zcfd);

    G_free(cell_row);

    /* Release memory resources */
    for (i = 0; i < 2; i++)
	G_free(data[i]);

    G_done_msg(_("Transform successful"));
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 20
0
static int
write_pca(double **eigmat, int *inp_fd, char *out_basename,
	  int bands, int scale, int scale_min, int scale_max)
{
    int i, j;
    void *outbuf, *outptr;
    double min = 0.;
    double max = 0.;
    double old_range = 0.;
    double new_range = 0.;
    int rows = Rast_window_rows();
    int cols = Rast_window_cols();
    int cell_mapsiz = Rast_cell_size(CELL_TYPE);
    int dcell_mapsiz = Rast_cell_size(DCELL_TYPE);
    DCELL *d_buf;

    /* 2 passes for rescale.  1 pass for no rescale */
    int PASSES = (scale) ? 2 : 1;

    /* temporary row storage */
    d_buf = (DCELL *) G_malloc(cols * sizeof(double));

    /* allocate memory for output row buffer */
    outbuf = (scale) ? Rast_allocate_buf(CELL_TYPE) :
	Rast_allocate_buf(DCELL_TYPE);

    if (!outbuf)
	G_fatal_error(_("Unable to allocate memory for raster row"));

    for (i = 0; i < bands; i++) {
	char name[100];
	int out_fd;
	int pass;

	sprintf(name, "%s.%d", out_basename, i + 1);

	G_message(_("Transforming <%s>..."), name);

	/* open a new file for output */
	if (scale)
	    out_fd = Rast_open_c_new(name);
	else {
	    out_fd = Rast_open_fp_new(name);
	    Rast_set_fp_type(DCELL_TYPE);
	}

	for (pass = 1; pass <= PASSES; pass++) {
	    void *rowbuf = NULL;
	    int row, col;

	    if (scale && (pass == PASSES)) {
		G_message(_("Rescaling <%s> to range %d,%d..."),
			  name, scale_min, scale_max);

		old_range = max - min;
		new_range = (double)(scale_max - scale_min);
	    }

	    for (row = 0; row < rows; row++) {
		void *rowptr;

		G_percent(row, rows, 2);

		/* reset d_buf */
		for (col = 0; col < cols; col++)
		    d_buf[col] = 0.;

		for (j = 0; j < bands; j++) {
		    RASTER_MAP_TYPE maptype =
			Rast_get_map_type(inp_fd[j]);

		    /* don't assume each image is of the same type */
		    if (rowbuf)
			G_free(rowbuf);
		    if (!(rowbuf = Rast_allocate_buf(maptype)))
			G_fatal_error(_("Unable allocate memory for row buffer"));

		    Rast_get_row(inp_fd[j], rowbuf, row, maptype);

		    rowptr = rowbuf;
		    outptr = outbuf;

		    /* add into the output cell eigmat[i][j] * corresp cell 
		     * of j-th band for current j */
		    for (col = 0; col < cols; col++) {
			/* handle null cells */
			if (Rast_is_null_value(rowptr, maptype)) {
			    if (scale) {
				Rast_set_null_value(outptr, 1, CELL_TYPE);
				outptr = G_incr_void_ptr(outptr, cell_mapsiz);
			    }
			    else {
				Rast_set_null_value(outptr, 1, DCELL_TYPE);
				outptr =
				    G_incr_void_ptr(outptr, dcell_mapsiz);
			    }

			    rowptr =
				G_incr_void_ptr(rowptr,
						Rast_cell_size(maptype));
			    continue;
			}

			/* corresp. cell of j-th band */
			d_buf[col] +=
			    eigmat[i][j] * Rast_get_d_value(rowptr,
								maptype);

			/* the cell entry is complete */
			if (j == (bands - 1)) {
			    if (scale && (pass == 1)) {
				if ((row == 0) && (col == 0))
				    min = max = d_buf[0];

				if (d_buf[col] < min)
				    min = d_buf[col];

				if (d_buf[col] > max)
				    max = d_buf[col];
			    }
			    else if (scale) {

				if (min == max) {
				    Rast_set_c_value(outptr, 1,
							 CELL_TYPE);
				}
				else {
				    /* map data to 0, (new_range-1) and then adding new_min */
				    CELL tmpcell =
					round_c((new_range *
						 (d_buf[col] -
						  min) / old_range) +
						scale_min);

				    Rast_set_c_value(outptr, tmpcell,
							 CELL_TYPE);
				}
			    }
			    else {	/* (!scale) */

				Rast_set_d_value(outptr, d_buf[col],
						     DCELL_TYPE);
			    }
			}

			outptr = (scale) ?
			    G_incr_void_ptr(outptr, cell_mapsiz) :
			    G_incr_void_ptr(outptr, dcell_mapsiz);

			rowptr =
			    G_incr_void_ptr(rowptr, Rast_cell_size(maptype));
		    }
		}		/* for j = 0 to bands */

		if (pass == PASSES) {
		    if (scale)
			Rast_put_row(out_fd, outbuf, CELL_TYPE);
		    else
			Rast_put_row(out_fd, outbuf, DCELL_TYPE);
		}
	    }

	    G_percent(row, rows, 2);

	    /* close output file */
	    if (pass == PASSES)
		Rast_close(out_fd);
	}
    }

    if (d_buf)
	G_free(d_buf);
    if (outbuf)
	G_free(outbuf);

    return 0;
}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
    struct GModule *module;

    int DoMap, DoFilter, MapSeed;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("random"));
    G_add_keyword(_("surface"));
    module->description =
	_("Generates random surface(s) with spatial dependence.");

    Output = G_define_option();
    Output->key = "output";
    Output->type = TYPE_STRING;
    Output->required = YES;
    Output->multiple = YES;
    Output->description = _("Name for output raster map(s)");
    Output->gisprompt = "new,cell,raster";

    Distance = G_define_option();
    Distance->key = "distance";
    Distance->type = TYPE_DOUBLE;
    Distance->required = NO;
    Distance->multiple = NO;
    Distance->description =
	_("Maximum distance of spatial correlation (value >= 0.0)");
    Distance->answer = "0.0";

    Exponent = G_define_option();
    Exponent->key = "exponent";
    Exponent->type = TYPE_DOUBLE;
    Exponent->multiple = NO;
    Exponent->required = NO;
    Exponent->description = _("Distance decay exponent (value > 0.0)");
    Exponent->answer = "1.0";

    Weight = G_define_option();
    Weight->key = "flat";
    Weight->type = TYPE_DOUBLE;
    Weight->multiple = NO;
    Weight->required = NO;
    Weight->description =
	_("Distance filter remains flat before beginning exponent");
    Weight->answer = "0.0";

    SeedStuff = G_define_option();
    SeedStuff->key = "seed";
    SeedStuff->type = TYPE_INTEGER;
    SeedStuff->required = NO;
    SeedStuff->description =
	_("Random seed (SEED_MIN >= value >= SEED_MAX), default [random]");

    range_high_stuff = G_define_option();
    range_high_stuff->key = "high";
    range_high_stuff->type = TYPE_INTEGER;
    range_high_stuff->required = NO;
    range_high_stuff->description = _("Maximum cell value of distribution");
    range_high_stuff->answer = "255";

    Uniform = G_define_flag();
    Uniform->key = 'u';
    Uniform->description = _("Uniformly distributed cell values");

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

    Init();

    if (Uniform->answer)
	GenNorm();

    CalcSD();

    for (DoMap = 0; DoMap < NumMaps; DoMap++) {
	OutFD = Rast_open_c_new(OutNames[DoMap]);

	G_message(_("Generating raster map <%s>..."), OutNames[DoMap]);

	if (Seeds[DoMap] == SEED_MIN - 1)
	    Seeds[DoMap] = (int)(ran1() * SEED_MAX);

	MapSeed = Seed = Seeds[DoMap];
	ZeroMapCells();

	for (DoFilter = 0; DoFilter < NumFilters; DoFilter++) {
	    CopyFilter(&Filter, AllFilters[DoFilter]);
	    G_debug(1,
		    "Starting filter #%d, distance: %.*lf, exponent: %.*lf, flat: %.*lf",
		    DoFilter, Digits(2.0 * Filter.MaxDist, 6),
		    2.0 * Filter.MaxDist, Digits(1.0 / Filter.Exp, 6),
		    1.0 / Filter.Exp, Digits(Filter.Mult, 6), Filter.Mult);

	    MakeBigF();
	    CalcSurface();
	}

	SaveMap(DoMap, MapSeed);
    }

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}