示例#1
0
int main (int argc, char **argv)
{
	GMT_LONG error = FALSE, set_n = FALSE, shift_xy = FALSE, offset;

	char *infile = NULL, format[BUFSIZ], unit_name[GRD_UNIT_LEN], scale_unit_name[GRD_UNIT_LEN];

	GMT_LONG i, j, unit = 0, n_read;
	
	GMT_LONG nm;
	
	float *geo = NULL, *rect = NULL;
	
	double w, e, s, n;
	double xmin, xmax, ymin, ymax, inch_to_unit, unit_to_inch, fwd_scale, inv_scale;

	struct GRD_HEADER g_head, r_head;
	struct GMT_EDGEINFO edgeinfo;
	struct GRDPROJECT_CTRL *Ctrl = NULL;

	void *New_grdproject_Ctrl (), Free_grdproject_Ctrl (struct GRDPROJECT_CTRL *C);

	argc = (int)GMT_begin (argc, argv);

	Ctrl = (struct GRDPROJECT_CTRL *)New_grdproject_Ctrl ();	/* Allocate and initialize a new control structure */
	
	infile = CNULL;
	w = e = s = n = 0.0;

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				/* Common parameters */

				case 'J':
				case 'R':
				case 'V':
				case '\0':
					error += GMT_parse_common_options (argv[i], &w, &e, &s, &n);
					break;

				/* Supplemental parameters */

				case 'C':
					Ctrl->C.active = TRUE;
					if (argv[i][2]) {	/* Also gave shifts */
	 					n_read = sscanf (&argv[i][2], "%lf/%lf", &Ctrl->C.easting, &Ctrl->C.northing);
						if (n_read != 2) {
							fprintf (stderr, "%s: GMT SYNTAX ERROR.  Expected -C[<false_easting>/<false_northing>]\n", GMT_program);
							error++;
						}
					}
					break;
				case 'D':
					Ctrl->D.active = TRUE;
					if (GMT_getinc (&argv[i][2], &Ctrl->D.xinc, &Ctrl->D.yinc)) {
						GMT_inc_syntax ('D', 1);
						error = TRUE;
					}
					break;
				case 'E':
					Ctrl->E.active = TRUE;
					Ctrl->E.dpi = atoi (&argv[i][2]);
					break;
				case 'A':
					Ctrl->A.active = TRUE;
					Ctrl->A.unit = argv[i][2];
					break;
				case 'F':
					Ctrl->F.active = TRUE;
					break;
				case 'G':
					Ctrl->G.file = strdup (&argv[i][2]);
					break;
				case 'I':
					Ctrl->I.active = TRUE;
					break;
				case 'M':	/* Directly specify units */
					Ctrl->M.active = TRUE;
					Ctrl->M.unit = argv[i][2];
					break;
				case 'N':
					sscanf (&argv[i][2], "%" GMT_LL "d/%" GMT_LL "d", &Ctrl->N.nx, &Ctrl->N.ny);
					if (Ctrl->N.ny == 0) Ctrl->N.ny = Ctrl->N.nx;
					Ctrl->N.active = TRUE;
					break;
				case 'S':
					Ctrl->S.active = TRUE;
					for (j = 2; j < 5 && argv[i][j]; j++) {
						switch (argv[i][j]) {
							case '-':
								Ctrl->S.antialias = FALSE; break;
							case 'n':
								Ctrl->S.interpolant = BCR_NEARNEIGHBOR; break;
							case 'l':
								Ctrl->S.interpolant = BCR_BILINEAR; break;
							case 'b':
								Ctrl->S.interpolant = BCR_BSPLINE; break;
							case 'c':
								Ctrl->S.interpolant = BCR_BICUBIC; break;
							case '/':
								Ctrl->S.threshold = atof (&argv[i][j+1]);
								j = 5; break;
							default:
								fprintf (stderr, "%s: Warning: The -S option has changed meaning. Use -S[-]b|c|l|n[/threshold] to specify interpolation mode.\n", GMT_program);
								j = 5; break;
						}
					}
					break;
				default:
					error = TRUE;
					GMT_default_error (argv[i][1]);
					break;
			}
		}
		else 
			infile = argv[i];
	}

	if ((Ctrl->D.active + Ctrl->E.active + Ctrl->N.active) == 0) Ctrl->N.active = set_n = TRUE;

	if (argc == 1 || GMT_give_synopsis_and_exit) {
		fprintf (stderr, "grdproject %s - Project geographical grid to/from rectangular grid\n\n", GMT_VERSION);
		fprintf (stderr, "usage: grdproject <in_grdfile> -G<out_grdfile> %s\n", GMT_J_OPT);
		fprintf (stderr, "\t[-A[k|m|n|i|c|p]] [-C[<dx/dy>]] [-D%s] [-E<dpi>] [-F]\n", GMT_inc_OPT);
		fprintf (stderr, "\t[-I] [-Mc|i|m] [-N<nx/ny>] [%s]\n", GMT_Rgeo_OPT);
		fprintf (stderr, "\t[-S[-]b|c|l|n[/<threshold>]] [-V]\n\n");

		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);

		fprintf (stderr, "\t<in_grdfile> is data set to be transformed.\n");
		fprintf (stderr, "\t-G name of output grid.\n");
		GMT_explain_option ('J');
		fprintf (stderr, "\n\tOPTIONS:\n");
		fprintf (stderr, "\t-A force projected values to be in actual meters [Default uses the given map scale].\n");
		fprintf (stderr, "\t   Specify another unit by appending k (km), m (miles), n (nautical miles), i (inch), c (cm), or p (points).\n");
		fprintf (stderr, "\t-C coordinates relative to projection center [Default is relative to lower left corner].\n");
		fprintf (stderr, "\t   Optionally append dx/dy to add (or subtract if -I) (i.e., false easting & northing) [0/0].\n");
		GMT_inc_syntax ('D', 0);
		fprintf (stderr, "\t-E sets dpi for output grid.\n");
		fprintf (stderr, "\t-F toggle between pixel and grid registration [Default is same as input].\n");
		fprintf (stderr, "\t-I Inverse transformation from rectangular to geographical.\n");
		fprintf (stderr, "\t-M Temporarily reset MEASURE_UNIT to be c (cm), i (inch), m (meter), or p (point).\n");
		fprintf (stderr, "\t   Cannot be used if -A is set.\n");
		fprintf (stderr, "\t-N sets the number of nodes for the new grid.\n");
		fprintf (stderr, "\t   Only one of -D, -E, and -N can be specified!\n");
		fprintf (stderr, "\t   If none are specified, nx,ny of the input file is used.\n");
		GMT_explain_option ('R');
		fprintf (stderr, "\t-S Determines the interpolation mode (b = B-spline, c = bicubic, l = bilinear,\n");
		fprintf (stderr, "\t   n = nearest-neighbor) [Default: bicubic].\n");
		fprintf (stderr, "\t   Optionally, prepend - to switch off antialiasing [Default: on].\n");
		fprintf (stderr, "\t   Append /<threshold> to change the minimum weight in vicinity of NaNs. A threshold of\n");
		fprintf (stderr, "\t   1.0 requires all nodes involved in interpolation to be non-NaN; 0.5 will interpolate\n");
		fprintf (stderr, "\t   about half way from a non-NaN to a NaN node [Default: 0.5].\n");
		GMT_explain_option ('V');

		exit (EXIT_FAILURE);
	}

	GMT_check_lattice (&Ctrl->D.xinc, &Ctrl->D.yinc, &Ctrl->F.active, &Ctrl->D.active);

	if (!infile) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Must specify input file\n", GMT_program);
		error++;
	}
	if (!Ctrl->G.file) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -G option:  Must specify output file\n", GMT_program);
		error++;
	}
	/*if (!project_info.region_supplied) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Must specify -R option\n", GMT_program);
		error++;
	}*/
	if ((Ctrl->M.active + Ctrl->A.active) == 2) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Can specify only one of -A and -M\n", GMT_program);
		error++;
	}
	if ((Ctrl->D.active + Ctrl->E.active + Ctrl->N.active) != 1) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Must specify only one of -D, -E, or -N\n", GMT_program);
		error++;
	}
	if (Ctrl->D.active && (Ctrl->D.xinc <= 0.0 || Ctrl->D.yinc < 0.0)) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -D option.  Must specify positive increment(s)\n", GMT_program);
		error++;
	}
	if (Ctrl->N.active && !set_n && (Ctrl->N.nx <= 0 || Ctrl->N.ny <= 0)) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -N option.  Must specify positive integers\n", GMT_program);
		error++;
	}
	if (Ctrl->E.active && Ctrl->E.dpi <= 0) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -E option.  Must specify positive dpi\n", GMT_program);
		error++;
	}
	if (Ctrl->S.active && (Ctrl->S.threshold < 0.0 || Ctrl->S.threshold > 1.0)) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -S option:  threshold must be in [0,1] range\n", GMT_program);
		error++;
	}

	if (error) exit (EXIT_FAILURE);

	if (Ctrl->M.active) GMT_err_fail (GMT_set_measure_unit (Ctrl->M.unit), "-M");
	shift_xy = !(Ctrl->C.easting == 0.0 && Ctrl->C.northing == 0.0);
	
	unit = GMT_check_scalingopt ('A', Ctrl->A.unit, scale_unit_name);
	GMT_init_scales (unit, &fwd_scale, &inv_scale, &inch_to_unit, &unit_to_inch, unit_name);

	if (Ctrl->I.active) {	/* Must flip the column types since in is Cartesian and out is geographic */
		GMT_io.out_col_type[0] = GMT_IS_LON;	GMT_io.out_col_type[1] = GMT_IS_LAT;	/* Inverse projection expects x,y and gives lon, lat */
		GMT_io.in_col_type[0] = GMT_io.in_col_type[1] = GMT_IS_FLOAT;
		project_info.degree[0] = project_info.degree[1] = FALSE;
	}

	if (!project_info.region_supplied) {
		double ww, ee, ss, nn;
		char opt_R[BUFSIZ];
		struct GRD_HEADER head;
		if (project_info.projection == GMT_UTM && project_info.utm_hemisphere == 0) {
			fprintf (stderr, "%s: GMT SYNTAX ERROR -JU|u option: When -R is not provided you have to specify the hemisphere\n", GMT_program);
			exit (EXIT_FAILURE);
		}
		GMT_err_fail (GMT_read_grd_info (infile, &head), infile);
		w = head.x_min;		e = head.x_max;
		s = head.y_min;		n = head.y_max;
		if (!Ctrl->I.active) {
			sprintf (opt_R, "-R%.12f/%.12f/%.12f/%.12f", w, e, s, n);
			GMT_parse_R_option (opt_R, &ww, &ee, &ss, &nn);
			GMT_err_fail (GMT_map_setup (w, e, s, n), "");
		}
		else {			/* Do inverse transformation */
			double x_c, y_c, lon_t, lat_t;
			/* Obtain a first crude estimation of the good -R */
			x_c = (w + e) / 2.; 		/* mid point of projected coords */
			y_c = (s + n) / 2.;
			if (project_info.projection == GMT_UTM && !project_info.north_pole && y_c > 0) y_c *= -1;
			if (y_c > 0)
				GMT_parse_R_option ("-R-180/180/0/80", &ww, &ee, &ss, &nn);
			else
				GMT_parse_R_option ("-R-180/180/-80/0", &ww, &ee, &ss, &nn);
			if (project_info.projection == GMT_UTM && !project_info.north_pole && y_c < 0) y_c *= -1;	/* Undo the *-1 (only for the UTM case) */
			if (shift_xy) {
				x_c -= Ctrl->C.easting;
				y_c -= Ctrl->C.northing;
			}
			/* Convert from 1:1 scale */ 
			if (unit) {
				x_c *= fwd_scale;
				y_c *= fwd_scale;
			}

			GMT_err_fail (GMT_map_setup (ww, ee, ss, nn), "");

			x_c *= project_info.x_scale;
			y_c *= project_info.y_scale;

			if (Ctrl->C.active) {	/* Then correct so lower left corner is (0,0) */
				x_c += project_info.x0;
				y_c += project_info.y0;
			}
			GMT_xy_to_geo (&lon_t, &lat_t, x_c, y_c);
			sprintf (opt_R, "-R%.12f/%.12f/%.12f/%.12f", lon_t-1, lon_t+1, lat_t-1, lat_t+1);
			if (gmtdefs.verbose) fprintf (stderr, "First opt_R\t %s\t%g\t%g\n", opt_R, x_c, y_c);
			GMT_parse_R_option (opt_R, &ww, &ee, &ss, &nn);
			project_info.region = 0;	/* We need to reset this to not fall into non-wanted branch deeper down */
			GMT_err_fail (GMT_map_setup (ww, ee, ss, nn), "");

			/* Finally obtain the good limits */
			if (shift_xy) {
				w -= Ctrl->C.easting;	e -= Ctrl->C.easting;
				s -= Ctrl->C.northing;	n -= Ctrl->C.northing;
			}
			if (unit) {
				w *= fwd_scale;		e *= fwd_scale;
				s *= fwd_scale;		n *= fwd_scale;
			}
			w *= project_info.x_scale;	e *= project_info.x_scale;
			s *= project_info.y_scale;	n *= project_info.y_scale;

			if (Ctrl->C.active) {
				w += project_info.x0;	e += project_info.x0;
				s += project_info.y0;	n += project_info.y0;
			}

			GMT_xy_to_geo (&ww, &ss, w, s);		/* SW corner */
			GMT_xy_to_geo (&ee, &nn, e, n);		/* NE corner */
			sprintf (opt_R, "-R%.12f/%.12f/%.12f/%.12fr", ww, ss, ee, nn);
			if (gmtdefs.verbose) fprintf (stderr, "Second opt_R\t %s\n", opt_R);
			GMT_parse_common_options (opt_R, &ww, &ee, &ss, &nn);
			w = ww;		e = ee;
			s = ss;		n = nn;
		}
	}

	GMT_err_fail (GMT_map_setup (w, e, s, n), "");

	xmin = (Ctrl->C.active) ? project_info.xmin - project_info.x0 : project_info.xmin;
	xmax = (Ctrl->C.active) ? project_info.xmax - project_info.x0 : project_info.xmax;
	ymin = (Ctrl->C.active) ? project_info.ymin - project_info.y0 : project_info.ymin;
	ymax = (Ctrl->C.active) ? project_info.ymax - project_info.y0 : project_info.ymax;
	if (Ctrl->A.active) {	/* Convert to chosen units */
		strncpy (unit_name, scale_unit_name, (size_t)GRD_UNIT_LEN);
		xmin /= project_info.x_scale;
		xmax /= project_info.x_scale;
		ymin /= project_info.y_scale;
		ymax /= project_info.y_scale;
		if (unit) {	/* Change the 1:1 unit used */
			xmin *= fwd_scale;
			xmax *= fwd_scale;
			ymin *= fwd_scale;
			ymax *= fwd_scale;
		}
	}
	else {	/* Convert inches to chosen MEASURE */
		xmin *= inch_to_unit;
		xmax *= inch_to_unit;
		ymin *= inch_to_unit;
		ymax *= inch_to_unit;
	}
	if (shift_xy) {
		xmin += Ctrl->C.easting;
		xmax += Ctrl->C.easting;
		ymin += Ctrl->C.northing;
		ymax += Ctrl->C.northing;
	}

	GMT_grd_init (&r_head, argc, argv, FALSE);
	GMT_grd_init (&g_head, argc, argv, FALSE);

	sprintf (format, "(%s/%s/%s/%s)", gmtdefs.d_format, gmtdefs.d_format, gmtdefs.d_format, gmtdefs.d_format);

	if (Ctrl->I.active) {	/* Transforming from rectangular projection to geographical */

		/* if (!project_info.region) d_swap (s, e); */  /* Got w/s/e/n, make into w/e/s/n */

		if (GMT_IS_AZIMUTHAL && project_info.polar) {	/* Watch out for polar cap grids */
			if (project_info.pole == -90.0) {	/* Covers S pole; implies 360 longitude range */
				w = -180.0;	e = +180.0;	n = MAX(s, n);	s = -90.0;
			}
			else if (project_info.pole == +90.0) {	/* Covers N pole; implies 360 longitude range */
				w = -180.0;	e = +180.0;	s = MIN(s, n);	n = +90.0;
			}
		}
		g_head.x_min = w;	g_head.x_max = e;	g_head.y_min = s;	g_head.y_max = n;

		GMT_err_fail (GMT_read_grd_info (infile, &r_head), infile);

		GMT_boundcond_init (&edgeinfo);
		nm = GMT_get_nm (4 + r_head.nx, 4 + r_head.ny);
		GMT_pad[0] = GMT_pad[1] = GMT_pad[2] = GMT_pad[3] = 2;

		rect = (float *) GMT_memory (VNULL, (size_t)nm, sizeof (float), GMT_program);
		GMT_err_fail (GMT_read_grd (infile, &r_head, rect, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), infile);
		offset = r_head.node_offset;		/* Same as input */
		if (Ctrl->F.active) offset = !offset;	/* Toggle */
		if (set_n) {
			Ctrl->N.nx = r_head.nx;
			Ctrl->N.ny = r_head.ny;
		}
		GMT_err_fail (GMT_grdproject_init (&g_head, Ctrl->D.xinc, Ctrl->D.yinc, Ctrl->N.nx, Ctrl->N.ny, Ctrl->E.dpi, offset), Ctrl->G.file);
		nm = GMT_get_nm (g_head.nx, g_head.ny);
		geo = (float *) GMT_memory (VNULL, (size_t)nm, sizeof (float), GMT_program);
		if (gmtdefs.verbose) {
			fprintf (stderr, "%s: Transform ", GMT_program);
			fprintf (stderr, format, g_head.x_min, g_head.x_max, g_head.y_min, g_head.y_max);
			fprintf (stderr, " <-- ");
			fprintf (stderr, format, xmin, xmax, ymin, ymax);
			fprintf (stderr, " [%s]\n", unit_name);
		}

		/* Modify input rect header if -A, -C, -M have been set */

		if (shift_xy) {
			r_head.x_min -= Ctrl->C.easting;
			r_head.x_max -= Ctrl->C.easting;
			r_head.y_min -= Ctrl->C.northing;
			r_head.y_max -= Ctrl->C.northing;

		}
		if (Ctrl->A.active) {	/* Convert from 1:1 scale */
			if (unit) {	/* Undo the 1:1 unit used */
				r_head.x_min *= inv_scale;
				r_head.x_max *= inv_scale;
				r_head.y_min *= inv_scale;
				r_head.y_max *= inv_scale;
			}
			r_head.x_min *= project_info.x_scale;
			r_head.x_max *= project_info.x_scale;
			r_head.y_min *= project_info.y_scale;
			r_head.y_max *= project_info.y_scale;
		}
		else if (gmtdefs.measure_unit != GMT_INCH) {	/* Convert from inch to whatever */
			r_head.x_min *= unit_to_inch;
			r_head.x_max *= unit_to_inch;
			r_head.y_min *= unit_to_inch;
			r_head.y_max *= unit_to_inch;
		}
		if (Ctrl->C.active) {	/* Then correct so lower left corner is (0,0) */
			r_head.x_min += project_info.x0;
			r_head.x_max += project_info.x0;
			r_head.y_min += project_info.y0;
			r_head.y_max += project_info.y0;
		}
		r_head.x_inc = GMT_get_inc (r_head.x_min, r_head.x_max, r_head.nx, r_head.node_offset);
		r_head.y_inc = GMT_get_inc (r_head.y_min, r_head.y_max, r_head.ny, r_head.node_offset);

		GMT_grd_project (rect, &r_head, geo, &g_head, &edgeinfo, Ctrl->S.antialias, Ctrl->S.interpolant, Ctrl->S.threshold, TRUE);

		GMT_pad[0] = GMT_pad[1] = GMT_pad[2] = GMT_pad[3] = 0;
		sprintf (g_head.x_units, "longitude [degrees_east]");
		sprintf (g_head.y_units, "latitude [degrees_north]");
		GMT_err_fail (GMT_write_grd (Ctrl->G.file, &g_head, geo, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), Ctrl->G.file);
	}
	else {	/* Forward projection from geographical to rectangular grid */

		GMT_err_fail (GMT_read_grd_info (infile, &g_head), infile);

		GMT_boundcond_init (&edgeinfo);
		nm = GMT_get_nm (4 + g_head.nx, 4 + g_head.ny);
		GMT_pad[0] = GMT_pad[1] = GMT_pad[2] = GMT_pad[3] = 2;

		geo = (float *) GMT_memory (VNULL, (size_t)nm, sizeof (float), GMT_program);
		GMT_err_fail (GMT_read_grd (infile, &g_head, geo, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), infile);

		r_head.x_min = project_info.xmin;	r_head.x_max = project_info.xmax;
		r_head.y_min = project_info.ymin;	r_head.y_max = project_info.ymax;
		if (Ctrl->A.active) {	/* Convert from 1:1 scale */
			if (unit) {	/* Undo the 1:1 unit used */
				Ctrl->D.xinc *= inv_scale;
				Ctrl->D.yinc *= inv_scale;
			}
			Ctrl->D.xinc *= project_info.x_scale;
			Ctrl->D.yinc *= project_info.y_scale;
		}
		else if (gmtdefs.measure_unit != GMT_INCH) {	/* Convert from inch to whatever */
			Ctrl->D.xinc *= unit_to_inch;
			Ctrl->D.yinc *= unit_to_inch;
		}
		if (set_n) {
			Ctrl->N.nx = g_head.nx;
			Ctrl->N.ny = g_head.ny;
		}

		if (gmtdefs.verbose) {
			fprintf (stderr, "%s: Transform ", GMT_program);
			fprintf (stderr, format, g_head.x_min, g_head.x_max, g_head.y_min, g_head.y_max);
			fprintf (stderr, " --> ");
			fprintf (stderr, format, xmin, xmax, ymin, ymax);
			fprintf (stderr, " [%s]\n", unit_name);
		}

		offset = g_head.node_offset;		/* Same as input */
		if (Ctrl->F.active) offset = !offset;	/* Toggle */

		GMT_err_fail (GMT_grdproject_init (&r_head, Ctrl->D.xinc, Ctrl->D.yinc, Ctrl->N.nx, Ctrl->N.ny, Ctrl->E.dpi, offset), Ctrl->G.file);
		nm = GMT_get_nm (r_head.nx, r_head.ny);
		rect = (float *) GMT_memory (VNULL, (size_t)nm, sizeof (float), GMT_program);
		GMT_grd_project (geo, &g_head, rect, &r_head, &edgeinfo, Ctrl->S.antialias, Ctrl->S.interpolant, Ctrl->S.threshold, FALSE);

		/* Modify output rect header if -A, -C, -M have been set */

		if (Ctrl->C.active) {	/* Change origin from lower left to projection center */
			r_head.x_min -= project_info.x0;
			r_head.x_max -= project_info.x0;
			r_head.y_min -= project_info.y0;
			r_head.y_max -= project_info.y0;
		}
		if (Ctrl->A.active) {	/* Convert to 1:1 scale */
			r_head.x_min /= project_info.x_scale;
			r_head.x_max /= project_info.x_scale;
			r_head.y_min /= project_info.y_scale;
			r_head.y_max /= project_info.y_scale;
			if (unit) {	/* Change the 1:1 unit used */
				r_head.x_min *= fwd_scale;
				r_head.x_max *= fwd_scale;
				r_head.y_min *= fwd_scale;
				r_head.y_max *= fwd_scale;
			}
		}
		else if (gmtdefs.measure_unit != GMT_INCH) {	/* Convert from inch to whatever */
			r_head.x_min /= unit_to_inch;
			r_head.x_max /= unit_to_inch;
			r_head.y_min /= unit_to_inch;
			r_head.y_max /= unit_to_inch;
		}
		if (shift_xy) {
			r_head.x_min += Ctrl->C.easting;
			r_head.x_max += Ctrl->C.easting;
			r_head.y_min += Ctrl->C.northing;
			r_head.y_max += Ctrl->C.northing;

		}
		r_head.x_inc = GMT_get_inc (r_head.x_min, r_head.x_max, r_head.nx, r_head.node_offset);
		r_head.y_inc = GMT_get_inc (r_head.y_min, r_head.y_max, r_head.ny, r_head.node_offset);

		/* rect xy values are here in GMT projected units chosen by user */

		GMT_pad[0] = GMT_pad[1] = GMT_pad[2] = GMT_pad[3] = 0;
		strcpy (r_head.x_units, unit_name);
		strcpy (r_head.y_units, unit_name);
		GMT_err_fail (GMT_write_grd (Ctrl->G.file, &r_head, rect, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), Ctrl->G.file);
	}

	GMT_free ((void *)geo);
	GMT_free ((void *)rect);

	Free_grdproject_Ctrl (Ctrl);	/* Deallocate control structure */

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}
示例#2
0
int main (int argc, char **argv)
{
	GMT_LONG i, j, ij, ij_f, n = 0;
	GMT_LONG n_expected_fields, n_args, m, n_fields, fno, n_files = 0;
	size_t n_alloc = GMT_CHUNK, nm;

	GMT_LONG error = FALSE, nofile = TRUE, done = FALSE;

	double sx, sy, cx, cy, w_min, w_max, sf = 1.0;
	double *xx = NULL, *yy = NULL, *zz = NULL, *ww = NULL, *surfd = NULL, *in = NULL;
	float *surf = NULL;

	char line[BUFSIZ], *not_used = NULL;
	FILE *fp = NULL;

	struct SPHINTERPOLATE_CTRL *Ctrl = NULL;
	struct GRD_HEADER h;
	void *New_sphinterpolate_Ctrl (), Free_sphinterpolate_Ctrl (struct SPHINTERPOLATE_CTRL *C);
	GMT_LONG get_args (char *arg, double pars[], char *msg);
	
	argc = (int)GMT_begin (argc, argv);

	Ctrl = (struct SPHINTERPOLATE_CTRL *)New_sphinterpolate_Ctrl ();	/* Allocate and initialize a new control structure */
	GMT_grd_init (&h, argc, argv, FALSE);

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
        
				/* Common parameters */
        
				case 'H':
				case 'M':
				case 'R':
				case 'V':
				case ':':
				case 'b':
				case 'm':
				case '\0':
					error += GMT_parse_common_options (argv[i], &h.x_min, &h.x_max, &h.y_min, &h.y_max);
					break;
        
				/* Supplemental parameters */
        
				case 'F':
					Ctrl->F.active = TRUE;
					break;
				case 'G':
					Ctrl->G.active = TRUE;
					Ctrl->G.file = strdup (&argv[i][2]);
					break;
				case 'I':
					Ctrl->I.active = TRUE;
					if (GMT_getinc (&argv[i][2], &Ctrl->I.xinc, &Ctrl->I.yinc)) {
						GMT_inc_syntax ('I', 1);
						error = TRUE;
					}
					break;
				case 'Q':
					Ctrl->Q.active = TRUE;
					switch (argv[i][2]) {
						case '0':	/* Linear */
							Ctrl->Q.mode = 0;
							break;
						case '1':
							Ctrl->Q.mode = 1;
							break;
						case '2':
							Ctrl->Q.mode = 2;
							if (argv[i][3] == '/') {	/* Gave optional n/m/dgmx */
								if ((m = get_args (&argv[i][4], Ctrl->Q.value, "-Q3/N[/M[/U]]")) < 0) error = TRUE;
							}
							break;
						case '3':
							Ctrl->Q.mode = 3;
							if (argv[i][3] == '/') {	/* Gave optional e/sm/niter */
								if ((m = get_args (&argv[i][4], Ctrl->Q.value, "-Q3/E[/U[/niter]]")) < 0) error = TRUE;
							}
							break;
						default:
							error = TRUE;
							fprintf (stderr, "GMT ERROR %s: -%c Mode must be in 0-3 range\n", GMT_program, argv[i][1]);
							break;
					}
					break;
				case 'T':
					Ctrl->T.active = TRUE;
					break;
				case 'Z':
					Ctrl->Z.active = TRUE;
					break;
				default:
					error = TRUE;
					GMT_default_error (argv[i][1]);
					break;
			}
		}
		else
			n_files++;
	}

	if (argc == 1 || GMT_give_synopsis_and_exit) {
		fprintf (stderr, "sphinterpolate %s - Spherical gridding in tension of data on a sphere\n", GMT_VERSION);
		fprintf (stderr, "==> The hard work is done by algorithms 772 (STRIPACK) & 773 (SSRFPACK) by R. J. Renka [1997] <==\n\n");
		fprintf (stderr, "usage: sphinterpolate [<infiles>] -G<grdfile> %s [-F] [%s]\n", GMT_I_OPT, GMT_H_OPT);
		fprintf (stderr, "\t[-Q<mode>][/args] [-T] [-V] [-Z] [%s] [%s] [%s]\n\n", GMT_t_OPT, GMT_b_OPT, GMT_m_OPT);
                
		fprintf (stderr, "\t-G Specify file name for the final gridded solution.\n");
		GMT_inc_syntax ('I', 0);
		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);
                
		fprintf (stderr, "\n\tOPTIONS:\n");
		fprintf (stderr, "\tinfiles (in ASCII) has 3 or more columns.  If no file(s) is given, standard input is read.\n");
		fprintf (stderr, "\t-F Force pixel registration for output grid [Default is gridline orientation]\n");
		GMT_explain_option ('H');
		fprintf (stderr, "\t-Q Select tension factors to achive the following [Default is no tension]:\n");
		fprintf (stderr, "\t   0: Piecewise linear interpolation ; no tension [Default]\n");
		fprintf (stderr, "\t   1: Smooth interpolation with local gradient estimates.\n");
		fprintf (stderr, "\t   2: Smooth interpolation with global gradient estimates and tension.  Optionally append /N/M/U:\n");
		fprintf (stderr, "\t      N = Number of iterations to converge solutions for gradients and variable tensions (-T only) [3]\n");
		fprintf (stderr, "\t      M = Number of Gauss-Seidel iterations when determining gradients [10]\n");
		fprintf (stderr, "\t      U = Maximum change in a gradient at the last iteration [0.01]\n");
		fprintf (stderr, "\t   3: Smoothing.  Optionally append /E/U/N, where\n");
		fprintf (stderr, "\t      E = Expected squared error in a typical (scaled) data value [0.01]\n");
		fprintf (stderr, "\t      U = Upper bound on  weighted sum of squares of deviations from data [npoints]\n");
		fprintf (stderr, "\t      N = Number of iterations to converge solutions for gradients and variable tensions (-T only) [3]\n");
		GMT_explain_option ('R');
		fprintf (stderr, "\t   If no region is specified we default to the entire world [-Rg]\n");
		fprintf (stderr, "\t-T Use variable tension (ignored for -Q0) [constant]\n");
		GMT_explain_option ('V');
		fprintf (stderr, "\t-Z Scale data by 1/(max-min) prior to gridding [no scaling]\n");
		GMT_explain_option (':');
		GMT_explain_option ('i');
		GMT_explain_option ('n');
		fprintf (stderr, "\t   Default is 3 input columns\n");
		GMT_explain_option ('m');
		GMT_explain_option ('.');
		exit (EXIT_FAILURE);
	}

	GMT_check_lattice (&Ctrl->I.xinc, &Ctrl->I.yinc, &Ctrl->F.active, &Ctrl->I.active);

	if (GMT_io.binary[GMT_IN] && GMT_io.io_header[GMT_IN]) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR.  Binary input data cannot have header -H\n", GMT_program);
		error++;
	}
	if (GMT_io.binary[GMT_IN] && GMT_io.ncol[GMT_IN] == 0) GMT_io.ncol[GMT_IN] = 3;
	if (GMT_io.binary[GMT_IN] && GMT_io.ncol[GMT_IN] < 3) {
            fprintf (stderr, "%s: GMT SYNTAX ERROR.  Binary input data (-bi) must have at least 3 columns\n", GMT_program);
		error++;
	}
	if (Ctrl->I.xinc <= 0.0 || Ctrl->I.yinc <= 0.0) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -I option.  Must specify positive increment(s)\n", GMT_program);
		error = TRUE;
	}
	if (!Ctrl->G.file) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -G:  Must specify output file\n", GMT_program);
		error = TRUE;
	}
	if (Ctrl->Q.mode < 0 || Ctrl->Q.mode > 3) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -T:  Must specify a mode in the 0-3 range\n", GMT_program);
		error = TRUE;
	}
	if (error) exit (EXIT_FAILURE);

	if (GMT_io.binary[GMT_IN] && gmtdefs.verbose) {
		char *type[2] = {"double", "single"};
		fprintf (stderr, "%s: Expects %ld-column %s-precision binary data\n", GMT_program, GMT_io.ncol[GMT_IN], type[GMT_io.single_precision[GMT_IN]]);
	}
	if (!project_info.region_supplied) {	/* Default is global region */
		h.x_min = 0.0;	h.x_max = 360.0;	h.y_min = -90.0;	h.y_max = 90.0;
	}

#ifdef SET_IO_MODE
	GMT_setmode (GMT_OUT);
#endif

	/* Now we are ready to take on some input values */

	if (n_files > 0)
		nofile = FALSE;
	else
		n_files = 1;
	n_args = (argc > 1) ? argc : 3;
	n_expected_fields = (GMT_io.ncol[GMT_IN]) ? GMT_io.ncol[GMT_IN] : 3;

	n_alloc = GMT_CHUNK;
	xx = (double *) GMT_memory (VNULL, (size_t)n_alloc, sizeof (double), GMT_program);
	yy = (double *) GMT_memory (VNULL, (size_t)n_alloc, sizeof (double), GMT_program);
	zz = (double *) GMT_memory (VNULL, (size_t)n_alloc, sizeof (double), GMT_program);
	ww = (double *) GMT_memory (VNULL, (size_t)n_alloc, sizeof (double), GMT_program);
	n = 0;
	w_min = DBL_MAX;	w_max = -DBL_MAX;
	for (fno = 1; !done && fno < n_args; fno++) {	/* Loop over input files, if any */
		if (!nofile && argv[fno][0] == '-') continue;

		if (nofile) {	/* Just read standard input */
			fp = GMT_stdin;
			done = TRUE;
#ifdef SET_IO_MODE
			GMT_setmode (GMT_IN);
#endif
		}
		else if ((fp = GMT_fopen (argv[fno], GMT_io.r_mode)) == NULL) {
			fprintf (stderr, "%s: Cannot open file %s\n", GMT_program, argv[fno]);
			continue;
		}

		if (!nofile && gmtdefs.verbose) fprintf (stderr, "%s: Reading file %s\n", GMT_program, argv[fno]);

		if (GMT_io.io_header[GMT_IN]) for (i = 0; i < GMT_io.n_header_recs; i++) not_used = GMT_fgets (line, BUFSIZ, fp);

		while ((n_fields = GMT_input (fp, &n_expected_fields, &in)) >= 0 && !(GMT_io.status & GMT_IO_EOF)) {	/* Not yet EOF */

			if (GMT_io.status & GMT_IO_MISMATCH) {
				fprintf (stderr, "%s: Mismatch between actual (%ld) and expected (%ld) fields near line %ld\n", GMT_program, n_fields, n_expected_fields, n);
				exit (EXIT_FAILURE);
			}
			while (GMT_io.status & GMT_IO_SEGMENT_HEADER) {	/* Segment header, get next record */
				n_fields = GMT_input (fp, &n_expected_fields, &in);
			}
			sincosd (in[GMT_Y], &sy, &cy);
			sincosd (in[GMT_X], &sx, &cx);
			xx[n] = cy * cx;
			yy[n] = cy * sx;
			zz[n] = sy;
			ww[n] = in[GMT_Z];
			if (Ctrl->Z.active) {
				if (ww[n] < w_min) w_min = ww[n];
				if (ww[n] > w_max) w_max = ww[n];
			}
			n++;

			if (n == (int)n_alloc) {	/* Get more memory */
				n_alloc <<= 1;
				xx = (double *) GMT_memory ((void *)xx, (size_t)n_alloc, sizeof (double), GMT_program);
				yy = (double *) GMT_memory ((void *)yy, (size_t)n_alloc, sizeof (double), GMT_program);
				zz = (double *) GMT_memory ((void *)zz, (size_t)n_alloc, sizeof (double), GMT_program);
				ww = (double *) GMT_memory ((void *)ww, (size_t)n_alloc, sizeof (double), GMT_program);
			}
		}

		if (fp != GMT_stdin) GMT_fclose (fp);
	}

	xx = (double *) GMT_memory ((void *)xx, (size_t)n, sizeof (double), GMT_program);
	yy = (double *) GMT_memory ((void *)yy, (size_t)n, sizeof (double), GMT_program);
	zz = (double *) GMT_memory ((void *)zz, (size_t)n, sizeof (double), GMT_program);
	ww = (double *) GMT_memory ((void *)ww, (size_t)n, sizeof (double), GMT_program);

	if (gmtdefs.verbose) fprintf (stderr, "%s: Do Delaunay triangulation using %ld points\n", GMT_program, n);

	if (Ctrl->Z.active && w_max > w_min) {	/* Scale the data */
		sf = 1.0 / (w_max - w_min);
		for (i = 0; i < n; i++) ww[i] *= sf;
	}
	
	/* Set up output grid */
	
	if (gmtdefs.verbose) fprintf (stderr, "%s: Evaluate output grid\n", GMT_program);
	h.node_offset = (int)Ctrl->F.active;
	h.x_inc = Ctrl->I.xinc;
	h.y_inc = Ctrl->I.yinc;
	GMT_RI_prepare (&h);	/* Ensure -R -I consistency and set nx, ny */
	GMT_err_fail (GMT_grd_RI_verify (&h, 1), Ctrl->G.file);

	h.xy_off = 0.5 * h.node_offset;
	nm = GMT_get_nm (h.nx, h.ny);
	surfd = (double *) GMT_memory (VNULL, (size_t)nm, sizeof(double), GMT_program);
	
	/* Do the interpolation */
	
	ssrfpack_grid (xx, yy, zz, ww, n, Ctrl->Q.mode, Ctrl->Q.value, Ctrl->T.active, gmtdefs.verbose, &h, surfd);
	GMT_free ((void *)xx);
	GMT_free ((void *)yy);
	GMT_free ((void *)zz);
	GMT_free ((void *)ww);
	
	/* Convert the doubles to float and unto the Fortran transpose order */
	
	sf = (w_max - w_min);
	surf = (float *) GMT_memory (VNULL, (size_t)nm, sizeof(float), GMT_program);
	for (j = ij = 0; j < h.ny; j++) {
		for (i = 0; i < h.nx; i++, ij++) {
			ij_f = i * h.ny + j;
			surf[ij] = (float)surfd[ij_f];
			if (Ctrl->Z.active) surf[ij] *= (float)sf;
		}
	}
	GMT_free ((void *)surfd);
	
	/* Write solution */
	
	GMT_err_fail (GMT_write_grd (Ctrl->G.file, &h, surf, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), Ctrl->G.file);
	
	/* Free variables */
	
	GMT_free ((void *)surf);

	if (gmtdefs.verbose) fprintf (stderr, "%s: Done!\n", GMT_program);

	Free_sphinterpolate_Ctrl (Ctrl);	/* Deallocate control structure */

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}
示例#3
0
int main (int argc, char **argv)
{
	GMT_LONG	error = FALSE;

	GMT_LONG	i, k, nx_old, ny_old, nx_new, ny_new, one_or_zero;
	
	GMT_LONG	nm;

	char *grd_in, format[BUFSIZ], za[GMT_TEXT_LEN], zb[GMT_TEXT_LEN];

	float	*grd = NULL;

	double	w_new = 0.0, e_new = 0.0, s_new = 0.0, n_new = 0.0;
	double	w_old, e_old, s_old, n_old;

	struct GRD_HEADER header, test_header;
	struct GRDCUT_CTRL *Ctrl = NULL;

	void *New_grdcut_Ctrl (), Free_grdcut_Ctrl (struct GRDCUT_CTRL *C);
	
	argc = (int)GMT_begin (argc, argv);

	Ctrl = (struct GRDCUT_CTRL *) New_grdcut_Ctrl ();	/* Allocate and initialize a new control structure */

	grd_in = CNULL;
	za[0] = zb[0] = '\0';

	/* Check and interpret the command line arguments */

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch(argv[i][1]) {
				/* Common parameters */

				case 'R':
				case 'V':
				case 'f':
				case '\0':
					error += GMT_parse_common_options (argv[i], &w_new, &e_new, &s_new, &n_new);
					break;

	 			case 'G':
					Ctrl->G.active = TRUE;
					Ctrl->G.file = strdup (&argv[i][2]);
					break;
					
	 			case 'Z':
					Ctrl->Z.active = TRUE;
					k = 2;
					if (argv[i][k] == 'n') {
						Ctrl->Z.mode = NAN_IS_OUTSIDE;
						k = 3;
					}
					if (sscanf (&argv[i][k], "%[^/]/%s", za, zb) == 2) {
						if (!(za[0] == '-' && za[1] == '\0')) error += GMT_verify_expectations (GMT_io.in_col_type[GMT_Z], GMT_scanf_arg (za, GMT_io.in_col_type[GMT_Z], &Ctrl->Z.min), za);
						if (!(zb[0] == '-' && zb[1] == '\0')) error += GMT_verify_expectations (GMT_io.in_col_type[GMT_Z], GMT_scanf_arg (zb, GMT_io.in_col_type[GMT_Z], &Ctrl->Z.max), zb);
					}
					break;
	
				default:		/* Options not recognized */
					error = TRUE;
					GMT_default_error (argv[i][1]);
					break;
			}
		}
		else
	 		grd_in = argv[i];
	}

	if (argc == 1 || GMT_give_synopsis_and_exit) {
		fprintf (stderr,"grdcut %s - Extract subsets from grid files\n\n", GMT_VERSION);
		fprintf (stderr, "usage: grdcut <input_grd> -G<output_grd> %s [-V] [-Z[n][min/max]] [%s]\n", GMT_Rgeo_OPT, GMT_f_OPT);

		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);

		fprintf (stderr, "\t<input_grd> is file to extract a subset from.\n");
		fprintf (stderr, "\t-G specifies output grid file.\n");
		GMT_explain_option ('R');
		fprintf (stderr, "\t   Obviously, the WESN you specify must be within the WESN of the input file.\n");
		fprintf (stderr, "\t   If in doubt, run grdinfo first and check range of old file.\n");
		fprintf (stderr, "\n\tOPTIONS:\n");
		GMT_explain_option ('V');
		fprintf (stderr, "\t-Z Specify a range and determine the corresponding rectangular region so that\n");
		fprintf (stderr, "\t   all values outside this region are outside the range [-inf/+inf].\n");
		fprintf (stderr, "\t   Use -Zn to consider NaNs outside as well [Default just ignores NaNs].\n");
		GMT_explain_option ('f');
		exit (EXIT_FAILURE);
	}

	/* Check that the options selected make sense */

	if ((project_info.region_supplied + Ctrl->Z.active) != 1) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Must specify either the -R or the -Z options\n", GMT_program);
		error++;
	}
	if (!Ctrl->G.file) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -G option:  Must specify output file\n", GMT_program);
		error++;
	}
	if (!grd_in) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Must specify input file\n", GMT_program);
		error++;
	}
	if (error) exit (EXIT_FAILURE);

	GMT_err_fail (GMT_read_grd_info (grd_in, &header), grd_in);

	if (Ctrl->Z.active) {	/* Must determine new region via -Z */
		GMT_LONG i0, i1, j0, j1, j, ij;
		
		nm = GMT_get_nm (header.nx, header.ny);
		grd = (float *) GMT_memory (VNULL, (size_t)nm, sizeof (float), GMT_program);
		GMT_err_fail (GMT_read_grd (grd_in, &header, grd, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), grd_in);
		for (i = 0, i0 = -1; i0 == -1 && i < header.nx; i++) {	/* Scan from xmin towards xmax */
			for (j = 0, ij = i; i0 == -1 && j < header.ny; j++, ij += header.ny) {
				if (GMT_is_fnan (grd[ij])) {
					if (Ctrl->Z.mode == NAN_IS_OUTSIDE) i0 = i;	/* Must stop since this value defines the inner box */
				}
				else if (grd[ij] >= Ctrl->Z.min && grd[ij] <= Ctrl->Z.max)
					i0 = i;
			}
		}
		if (i0 == -1) {
			fprintf (stderr, "%s: The sub-region is empty - no file written\n", GMT_program);
			GMT_free ((void *)grd);
			exit (EXIT_FAILURE);
		}
		for (i = header.nx-1, i1 = -1; i1 == -1 && i > i0; i--) {	/* Scan from xmax towards xmin */
			for (j = 0, ij = i; i1 == -1 && j < header.ny; j++, ij += header.ny) {
				if (GMT_is_fnan (grd[ij])) {
					if (Ctrl->Z.mode == NAN_IS_INSIDE) i1 = i;	/* Must stop since this value defines the inner box */
				}
				else if (grd[ij] >= Ctrl->Z.min && grd[ij] <= Ctrl->Z.max)
					i1 = i;
			}
		}
		for (j = 0, j0 = -1; j0 == -1 && j < header.ny; j++) {	/* Scan from ymin towards ymax */
			for (i = i0, ij = GMT_IJ(j,i0,header.nx); j0 == -1 && i < i1; i++, ij++) {
				if (GMT_is_fnan (grd[ij])) {
					if (Ctrl->Z.mode == NAN_IS_INSIDE) j0 = j;	/* Must stop since this value defines the inner box */
				}
				else if (grd[ij] >= Ctrl->Z.min && grd[ij] <= Ctrl->Z.max)
					j0 = j;
			}
		}
		for (j = header.ny-1, j1 = -1; j1 == -1 && j >= j0; j--) {	/* Scan from ymax towards ymin */
			for (i = i0, ij = GMT_IJ(j,i0,header.nx); j1 == -1 && i < i1; i++, ij++) {
				if (GMT_is_fnan (grd[ij])) {
					if (Ctrl->Z.mode == NAN_IS_INSIDE) j1 = j;	/* Must stop since this value defines the inner box */
				}
				else if (grd[ij] >= Ctrl->Z.min && grd[ij] <= Ctrl->Z.max)
					j1 = j;
			}
		}
		if (i0 == 0 && j0 == 0 && i1 == (header.nx-1) && j1 == (header.ny-1)) {
			fprintf (stderr, "%s: Your -Z limits produced no subset - output grid is identical to input grid\n", GMT_program);
			w_new = header.x_min;	e_new = header.x_max;
			s_new = header.y_min;	n_new = header.y_max;
		}
		else {	/* Adjust boundaries inwards */
			w_new = header.x_min + i0 * header.x_inc;
			e_new = header.x_max - (header.nx - 1 - i1) * header.x_inc;
			s_new = header.y_min + (header.ny - 1 - j1) * header.y_inc;
			n_new = header.y_max - j0 * header.y_inc;
		}
		GMT_free ((void *)grd);
	}
	
	if (s_new < header.y_min || s_new > header.y_max) error = TRUE;
	if (n_new < header.y_min || n_new > header.y_max) error = TRUE;

	if (GMT_io.in_col_type[GMT_X] == GMT_IS_LON) {	/* Geographic data */
		if (w_new < header.x_min && e_new < header.x_min) {
			header.x_min -= 360.0;
			header.x_max -= 360.0;
		}
		if (w_new > header.x_max && e_new > header.x_max) {
			header.x_min += 360.0;
			header.x_max += 360.0;
		}
		if (!GMT_grd_is_global (&header) && (w_new < header.x_min || e_new > header.x_max)) error = TRUE;
	}
	else if (w_new < header.x_min || e_new > header.x_max)
		error = TRUE;

	if (error) {
		fprintf (stderr, "%s: Subset exceeds data domain!\n", GMT_program);
		exit (EXIT_FAILURE);
	}

	/* Make sure output grid is kosher */

	GMT_adjust_loose_wesn (&w_new, &e_new, &s_new, &n_new, &header);

	test_header.x_min = w_new;	test_header.x_max = e_new;	test_header.x_inc = header.x_inc;
	test_header.y_min = s_new;	test_header.y_max = n_new;	test_header.y_inc = header.y_inc;
	GMT_err_fail (GMT_grd_RI_verify (&test_header, 1), Ctrl->G.file);

	/* OK, so far so good. Check if new wesn differs from old wesn by integer dx/dy */

	if (GMT_minmaxinc_verify (header.x_min, w_new, header.x_inc, GMT_SMALL) == 1) {
		fprintf (stderr, "%s: Old and new x_min do not differ by N * dx\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	if (GMT_minmaxinc_verify (e_new, header.x_max, header.x_inc, GMT_SMALL) == 1) {
		fprintf (stderr, "%s: Old and new x_max do not differ by N * dx\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	if (GMT_minmaxinc_verify (header.y_min, s_new, header.y_inc, GMT_SMALL) == 1) {
		fprintf (stderr, "%s: Old and new y_min do not differ by N * dy\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	if (GMT_minmaxinc_verify (n_new, header.y_max, header.y_inc, GMT_SMALL) == 1) {
		fprintf (stderr, "%s: Old and new y_max do not differ by N * dy\n", GMT_program);
		exit (EXIT_FAILURE);
	}

	GMT_grd_init (&header, argc, argv, TRUE);

	w_old = header.x_min;	e_old = header.x_max;
	s_old = header.y_min;	n_old = header.y_max;
	nx_old = header.nx;	ny_old = header.ny;
	one_or_zero = (header.node_offset) ? 0 : 1;
	nx_new = irint ((e_new - w_new) / header.x_inc) + one_or_zero;
	ny_new = irint ((n_new - s_new) / header.y_inc) + one_or_zero;

	nm = GMT_get_nm (nx_new, ny_new);
	
	grd = (float *) GMT_memory (VNULL, (size_t)nm, sizeof (float), GMT_program);
	GMT_err_fail (GMT_read_grd (grd_in, &header, grd, w_new, e_new, s_new, n_new, GMT_pad, FALSE), grd_in);

	if (gmtdefs.verbose) {
		sprintf (format, "\t%s\t%s\t%s\t%s\t%s\t%s\t%%ld\t%%ld\n", gmtdefs.d_format, gmtdefs.d_format,
			gmtdefs.d_format, gmtdefs.d_format, gmtdefs.d_format, gmtdefs.d_format);
		fprintf (stderr, "%s: File spec:\tW E S N dx dy nx ny:\n", GMT_program);
		fprintf (stderr, "%s: Old:", GMT_program);
		fprintf (stderr, format, w_old, e_old, s_old, n_old, header.x_inc, header.y_inc, nx_old, ny_old);
		fprintf (stderr, "%s: New:", GMT_program);
		fprintf (stderr, format, w_new, e_new, s_new, n_new, header.x_inc, header.y_inc, nx_new, ny_new);
	}

	GMT_err_fail (GMT_write_grd (Ctrl->G.file, &header, grd, 0.0, 0.0, 0.0, 0.0, GMT_pad, FALSE), Ctrl->G.file);

	GMT_free ((void *) grd);

	Free_grdcut_Ctrl (Ctrl);	/* Deallocate control structure */

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}
示例#4
0
int main (int argc, char **argv)
{
    GMT_LONG     i, symbol = 0, n, n_files = 0, fno;
    GMT_LONG     n_args;
    GMT_LONG     form_s = 0, justify_s = 5;
    
    GMT_LONG error = FALSE, nofile = TRUE;
    GMT_LONG done, greenwich, label_s = FALSE;
    GMT_LONG change_position = FALSE;
    GMT_LONG get_position = FALSE, get_size = FALSE, get_symbol = FALSE;
    GMT_LONG outline_E = FALSE, outline_G = FALSE, outline_F = FALSE;
    GMT_LONG old_GMT_world_map, skip_if_outside = TRUE;
    GMT_LONG plot_polS = FALSE, vecS = FALSE, scolor = FALSE, outline_s = FALSE;
    GMT_LONG def_cpen = FALSE, def_fpen = FALSE, def_tpen = FALSE;
    GMT_LONG def_gpen = FALSE, def_epen = FALSE, def_spen = FALSE;
    GMT_LONG hypo = FALSE;
    
    double west = 0.0, east = 0.0, south = 0.0, north = 0.0;
    double plot_x, plot_y, symbol_size = 0.0, symbol_size2;
    double lon, lat, plot_x0, plot_y0;
    double new_lon, new_lat, new_plot_x0, new_plot_y0;
    double radius, ech = 0., azimut, ih, plongement;
    double c_pointsize = 0.015, fontsize_s = 12.0;
    double angle_s = 0.0;
    double azS, sizeS = GMT_d_NaN;
    double v_width = GMT_d_NaN, h_length = GMT_d_NaN, h_width = GMT_d_NaN, shape;
    double si, co;

    char line[BUFSIZ], symbol_type, col[4][GMT_TEXT_LEN];
    char pol, *not_used = NULL;
    char txt_a[GMT_TEXT_LEN],txt_b[GMT_TEXT_LEN],txt_c[GMT_TEXT_LEN], txt_d[GMT_TEXT_LEN];
    char stacode[GMT_TEXT_LEN];
    
    FILE *fp = NULL;
    
    struct GMT_PEN pen, cpen, fpen, gpen, epen, spen, tpen;
    struct GMT_FILL fill, ffill, gfill, efill, sfill;
    struct GMT_FILL black, nofill;
    
    argc = (int)GMT_begin (argc, argv);
    
    GMT_init_pen (&pen, GMT_PENWIDTH);
    GMT_init_fill (&nofill, -1, -1, -1); 
    GMT_init_fill (&black, 0, 0, 0);     
    GMT_init_fill (&efill, 250, 250, 250);
    
    fill = nofill;
    ffill = nofill;
    sfill = nofill;
    gfill = black;

    /* Check and interpret the command line arguments */
    
    for (i = 1; !error && i < argc; i++) {
        if (argv[i][0] == '-') {
            switch(argv[i][1]) {
        
                /* Common parameters */
            
                case 'B':
                case 'H':
                case 'J':
                case 'K':
                case 'O':
                case 'P':
                case 'R':
                case 'U':
                case 'V':
                case 'X':
                case 'x':
                case 'Y':
                case 'y':
                case 'c':
                case '\0':
                    error += GMT_parse_common_options (argv[i], &west, &east, &south, &north);
                    break;
                
                /* Supplemental parameters */
            
                case 'C':       /* New coordinates */
                         change_position = TRUE;
                         sscanf(&argv[i][2], "%lf/%lf", &new_lon, &new_lat);
                         if(strchr(argv[i], 'W')) {
                             GMT_getpen (strchr(argv[i]+1, 'W')+1, &cpen);
                             def_cpen = TRUE;
                         }
                         if(strchr(argv[i], 'P')) {
                             sscanf(strchr(argv[i]+1, 'P')+1, "%lf", &c_pointsize);
                         }
                         break;
                case 'D':       /* Coordinates */
                         get_position = TRUE;
                         sscanf(&argv[i][2], "%lf/%lf", &lon, &lat);
                         break;
                case 'E':        /* Set color for station in extensive part */
                         GMT_getfill (&argv[i][2], &efill);
                         break;
                case 'e':        /* Outline station symbol in extensive part */
                         outline_E = TRUE;
                         if(strlen(argv[i]) > 2) {
                             GMT_getpen (&argv[i][2], &epen);
                             def_epen = TRUE;
                         }
                         break;
                case 'F':        /* Set background color of beach ball */
                         GMT_getfill (&argv[i][2], &ffill);
                         break;
                case 'f':        /* Outline beach ball */
                         outline_F = TRUE;
                         if(strlen(argv[i]) > 2) {
                             GMT_getpen (&argv[i][2], &fpen);
                             def_fpen = TRUE;
                         }
                         break;
                case 'G':        /* Set color for station in compressive part */
                         GMT_getfill (&argv[i][2], &gfill);
                         break;
                case 'g':        /* Outline station symbol in compressive part */
                         outline_G = TRUE;
                         if(strlen(argv[i]) > 2) {
                             GMT_getpen (&argv[i][2], &gpen);
                             def_gpen = TRUE;
                         }
                         break;
                case 'h':    /* Use HYPO71 format */
                         hypo = TRUE;
                         break;
                case 'M':    /* Focal sphere size */
                         get_size = TRUE;
                         sscanf(&argv[i][2], "%s", txt_a);
                         ech = GMT_convert_units (txt_a, GMT_INCH);
                         break;
                case 'N':        /* Do not skip points outside border */
                         skip_if_outside = FALSE;
                         break;
                case 'S':        /* Get symbol [and size] */
                         symbol_type = argv[i][2];
                         symbol_size = GMT_convert_units (&argv[i][3], GMT_INCH);
                         get_symbol = TRUE;
                         switch (symbol_type) {
                             case 'a':
                                 symbol = STAR;
                                 break;
                             case 'c':
                                 symbol = CIRCLE;
                                 break;
                             case 'd':
                                 symbol = DIAMOND;
                                 break;
                             case 'h':
                                 symbol = HEXAGON;
                                 break;
                             case 'i':
                                 symbol = ITRIANGLE;
                                 break;
                             case 'p':
                                 symbol = POINT;
                                 break;
                             case 's':
                                 symbol = SQUARE;
                                 break;
                             case 't':
                                 symbol = TRIANGLE;
                                 break;
                             case 'x':
                                 symbol = CROSS;
                                 break;
                             default:
                                 error = TRUE;
                                 fprintf (stderr, "%s: GMT SYNTAX ERROR -S option:  Unrecognized symbol type %c\n", argv[0], symbol_type);
                                 break;
                         }
                         break;
                case 's':        /* Get S polarity */
                         plot_polS = TRUE;
                         strcpy(txt_a, &argv[i][3]);
                         n=0; while (txt_a[n] && txt_a[n] != '/' && txt_a[n] != 'V' && txt_a[n] != 'G' && txt_a[n] != 'L') n++; txt_a[n]=0;
                         sizeS = GMT_convert_units (txt_a, GMT_INCH);

                         if(strchr(argv[i], 'V')) {
                             vecS = TRUE;
                             strcpy(txt_a,strchr(argv[i], 'V'));
                             if(strncmp(txt_a,"VG",(size_t)2) == 0 || strncmp(txt_a,"VL",(size_t)2) == 0 || strlen(txt_a) == 1) {
                                 v_width = 0.03; h_length = 0.12; h_width = 0.1; shape = gmtdefs.vector_shape;
                                 if (!gmtdefs.measure_unit) {
                                     v_width = 0.075; h_length = 0.3; h_width = 0.25; shape = gmtdefs.vector_shape;
                                 }
                             }
                             else {
                                strcpy(txt_a, strchr(argv[i], 'V')+1);
                                strcpy(txt_b, strchr(txt_a+1, '/')+1);
                                strcpy(txt_c, strchr(txt_b+1, '/')+1);
                                strcpy(txt_d, strchr(txt_c+1, '/')+1);
                                n=0; while (txt_a[n] && txt_a[n] != '/') n++; txt_a[n]=0;
                                n=0; while (txt_b[n] && txt_b[n] != '/') n++; txt_b[n]=0;
                                n=0; while (txt_c[n] && txt_c[n] != '/') n++; txt_c[n]=0;
                                n=0; while (txt_d[n] && txt_d[n] != '/' && txt_d[n] != 'L' && txt_d[n] != 'G') n++; txt_d[n]=0;
                                v_width = GMT_convert_units (txt_a, GMT_INCH);
                                h_length = GMT_convert_units (txt_b, GMT_INCH);
                                h_width = GMT_convert_units (txt_c, GMT_INCH);
                                shape = atof(txt_d);
                             }
                         }
                         if(strchr(argv[i], 'G')) {
                             sscanf (strchr(argv[i]+1,'G')+1,"%d/%d/%d",&sfill.rgb[0],&sfill.rgb[1],&sfill.rgb[2]);
                             sprintf(txt_a, "%d/%d/%d",sfill.rgb[0],sfill.rgb[1],sfill.rgb[2]);
                             GMT_getfill (txt_a, &sfill);
                             scolor = TRUE;
                         }
                         if(strchr(argv[i], 'L')) outline_s = TRUE;
                         break;
                case 'T':       /* Information about label printing */
                        label_s = TRUE;
                        if (strlen(argv[i]) > 2) {
                             sscanf (&argv[i][2], "%lf/%" GMT_LL "d/%" GMT_LL "d/%lf/", &angle_s,
                                     &form_s, &justify_s, &fontsize_s);
                        }
                        break;
                case 't':       /* Set color for station label */
                         GMT_getpen (&argv[i][2], &tpen);
                         def_tpen = TRUE;
                         break;

                case 'W':        /* Set line attributes */
                         GMT_getpen (&argv[i][2], &pen);
                         break;
                    
                /* Illegal options */
            
                default:        /* Options not recognized */
                         error = TRUE;
                         GMT_default_error (argv[i][1]);
                         break;
            }
        }
        else
            n_files++;
    }

    /* Check that the options selected are consistent */
    
    if (!project_info.region_supplied) {
        error++;
    }
    if(ech <= 0.) {
        error++;
    }
    if(get_position + get_size + get_symbol < 3) {
        error++;
    }
    
    if (argc == 1 || GMT_give_synopsis_and_exit || error) {    /* Display usage */
        fprintf (stderr,"%s %s - Plot polarities on the inferior focal half-sphere on maps\n\n",argv[0], GMT_VERSION);
        fprintf (stderr,"usage: argv[0] <infiles> %s %s\n", GMT_J_OPT, GMT_Rgeo_OPT);
        fprintf (stderr, " -Dlongitude/latitude -Msize[i/c] -S<symbol><size>[i/c]\n");
        fprintf (stderr, " [-A] [%s] [-Clongitude/latitude[W<pen>][Ppointsize]] [-E<fill>]\n", GMT_B_OPT);
        fprintf (stderr, " [-e[<pen>]] [-F<fill>] [-f[<pen>]] [-G<fill>] [-g[<pen>]] [%s] [-K] [-N] [-O] [-P]\n", GMT_Ho_OPT);
        fprintf (stderr, " [-s<half-size>/[V[<v_width/h_length/h_width/shape]][G<r/g/b>][L]\n");
        fprintf (stderr, " [-T[<labelinfo>]] [-t<pen>] [%s] [-V] [-W<pen>]\n", GMT_U_OPT);
        fprintf (stderr, " [%s] [%s] [%s]\n", GMT_X_OPT, GMT_Y_OPT, GMT_c_OPT);
        
        if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);
        
        fprintf (stderr, "    <infiles> is one or more files.  If no, read standard input\n");
        GMT_explain_option ('j');
        GMT_explain_option ('R');
        fprintf (stderr, "        -D Set longitude/latitude\n");
        fprintf (stderr, "        -M Set size of beach ball in %s\n", GMT_unit_names[gmtdefs.measure_unit]);
        fprintf (stderr, "        -S to select symbol type and symbol size (in %s).  Choose between\n", GMT_unit_names[gmtdefs.measure_unit]);
        fprintf (stderr, "           st(a)r, (c)ircle, (d)iamond, (h)exagon, (i)nvtriangle\n");
        fprintf (stderr, "           (p)oint, (s)quare, (t)riangle, (x)cross\n");
        fprintf (stderr, "\n\tOPTIONS:\n");
        GMT_explain_option ('B');
        GMT_explain_option ('b');
        fprintf (stderr, "        -C Set new_longitude/new_latitude[W<pen>][Ppointsize]\n");
        fprintf (stderr, "           A line will be plotted between both positions\n");
        fprintf (stderr, "           Default is width = 3, color = current pen and pointsize = 0.015\n");
        fprintf (stderr, "        -E Specify color symbol for station in extensive part.\n");
        fprintf (stderr, "           Fill can be either <r/g/b> (each 0-255) for color \n");
        fprintf (stderr, "           or <gray> (0-255) for gray-shade [0].\n");
        fprintf (stderr, "           Default is light gray.\n");
        fprintf (stderr, "        -e Outline of station symbol in extensive part.\n");
        fprintf (stderr, "           Default is current pen.\n");
        fprintf (stderr, "        -F Specify background color of beach ball. It can be\n");
        fprintf (stderr, "           <r/g/b> (each 0-255) for color or <gray> (0-255) for gray-shade [0].\n");
        fprintf (stderr, "           Default is no fill\n");
        fprintf (stderr, "        -f Outline beach ball\n");
        fprintf (stderr, "           Add <pen attributes> if not current pen.\n");
        fprintf (stderr, "        -G Specify color symbol for station in compressive part. Fill can be either\n");
        fprintf (stderr, "           Fill can be either <r/g/b> (each 0-255) for color\n");
        fprintf (stderr, "           or <gray> (0-255) for gray-shade [0].\n");
        fprintf (stderr, "           Add L[<pen>] to outline\n");
        fprintf (stderr, "           Default is black.\n");
        fprintf (stderr, "        -g Outline of station symbol in compressive part.\n");
        fprintf (stderr, "           Add <pen attributes> if not current pen.\n");
        fprintf (stderr, "        -h Use special format derived from HYPO71 output.\n");
        GMT_explain_option ('H');
        GMT_explain_option ('K');
        fprintf (stderr, "        -N Do Not skip/clip symbols that fall outside map border\n");
        fprintf (stderr, "           [Default will ignore those outside]\n");
        GMT_explain_option ('O');
        GMT_explain_option ('P');
        fprintf (stderr, "        -s to plot S polarity azimuth.\n");
        fprintf (stderr, "           Azimuth of S polarity is in last column.\n");
        fprintf (stderr, "           It may be a vector (V option) or a segment. Give half-size in cm.\n");
        fprintf (stderr, "           L option is for outline\n");
        fprintf (stderr, "           -s<half-size>/[V[<v_width/h_length/h_width/shape>]][G<r/g/b>][L]\n");
        fprintf (stderr, "           Default definition of v is 0.075/0.3/0.25/1\n");
        fprintf (stderr, "           Outline is current pen\n");
        fprintf (stderr, "        -T[<info about labal printing>] to write station code.\n");
        fprintf (stderr, "           <angle/form/justify/fontsize in points>\n");
        fprintf (stderr, "           Default is 0.0/0/5/12\n");
        fprintf (stderr, "        -t sets pen attributes to write station codes [default is current pen]\n");
        GMT_explain_option ('U');
        GMT_explain_option ('V');
        fprintf (stderr, "        -W sets current pen attributes [width = %gp, color = (%d/%d/%d), texture = solid line].\n", pen.width, pen.rgb[0], pen.rgb[1], pen.rgb[2]);
        GMT_explain_option ('X');
        GMT_explain_option ('c');
        GMT_explain_option ('.');
        exit (EXIT_FAILURE);
    }
    
    if(!def_cpen) {
        cpen = pen; cpen.width = 3;
    }                                         /* pen for change position */
    if(!def_fpen) fpen = pen;                 /* outline beach ball */
    if(!def_gpen) gpen = pen;                 /* outline compressive stations */
    if(!def_epen) epen = pen;                 /* outline extensive stations */
    if(!def_spen) spen = pen;                 /* outline S_pol segment */
    if(!def_tpen) tpen = pen;                 /* pen to print station name */

    if (n_files > 0)
        nofile = FALSE;
    else
        n_files = 1;
    n_args = (argc > 1) ? argc : 2;
    
    greenwich = (west < 0.0 || east <= 0.0);
    
    GMT_err_fail (GMT_map_setup (west, east, south, north), "");

    GMT_plotinit (argc, argv);
    
    if (label_s) ps_setfont (gmtdefs.annot_font[0]);

    if (symbol > 0 && skip_if_outside) GMT_map_clip_on (GMT_no_rgb, 3);
    
    old_GMT_world_map = GMT_world_map;
    
    done = FALSE;


    for (fno = 1; !done && fno < n_args; fno++) {    /* Loop over all input files */
        if (!nofile && argv[fno][0] == '-') continue;
        if (nofile) {
            fp = GMT_stdin;
            done = TRUE;
        }
        else if ((fp = GMT_fopen (argv[fno], "r")) == NULL) {
            fprintf (stderr, "%s: Cannot open file %s\n", argv[0], argv[fno]);
            continue;
        }

        if (!nofile && gmtdefs.verbose) {
            fprintf (stderr, "%s: Working on file %s\n", argv[0], argv[fno]);
            sprintf (line, "File: %s", argv[fno]);
            ps_comment (line);
        }
        if (GMT_io.io_header[GMT_IN]) for (i = 0; i < GMT_io.n_header_recs; i++) not_used = GMT_fgets (line, 512, fp);
        
        GMT_world_map = TRUE;
        
        GMT_geo_to_xy(lon, lat, &plot_x0, &plot_y0);
        if(change_position) {
            GMT_setpen (&cpen);
            GMT_geo_to_xy(new_lon, new_lat, &new_plot_x0, &new_plot_y0);
            ps_circle(plot_x0, plot_y0, c_pointsize, cpen.rgb, 1);
            ps_plot(plot_x0, plot_y0, PSL_PEN_MOVE);
            ps_plot(new_plot_x0, new_plot_y0, PSL_PEN_DRAW_AND_STROKE);
            plot_x0 = new_plot_x0;
            plot_y0 = new_plot_y0;
        }
        if (skip_if_outside) {
            GMT_map_outside (lon, lat);
            if (GMT_abs (GMT_x_status_new) > 1 || GMT_abs (GMT_y_status_new) > 1) continue;
        }

        GMT_setpen (&fpen);
        ps_circle (plot_x0, plot_y0, ech, ffill.rgb, outline_F);

        while (GMT_fgets (line, BUFSIZ, fp)) {
            switch (hypo) {
                case 0 :
                    if(!plot_polS) {
                        sscanf (line, "%s %lf %lf %c", stacode, &azimut, &ih, &pol);
                    }
                    else {
                        n = sscanf (line, "%s %lf %lf %c %lf", stacode, &azimut, &ih, &pol, &azS);
                        if(n == 4) azS = -1.;
                    }
                    break;
                case 1 :
 	    	    memset ((void *)col, 0, 4 * GMT_TEXT_LEN * sizeof (char));
                   if(!plot_polS) {
                        sscanf (line, "%s %s %s %s %lf %lf %c", col[0], col[1], col[2], stacode, &azimut, &ih, col[3]);
                        pol = col[3][2];
                    }
                    else {
                        n = sscanf (line, "%s %s %s %s %lf %lf %c %lf", col[0], col[1], col[2], stacode, &azimut, &ih, col[3], &azS);
                        pol = col[3][2];
                        if(n == 7) azS = -1.;
                    }
                    break;
            }
        
            if(strcmp(col[0],"000000")!=0) {
                plongement = (ih - 90.) * M_PI / 180.;
                if(plongement  < 0.) {
                    plongement = -plongement;
                    azimut += 180 ;
                    symbol_size2 = symbol_size * 0.8;
                }
                else symbol_size2 = symbol_size;
                radius = sqrt(1. - sin(plongement));
                if(radius >= 0.97) radius = 0.97;
                azimut += 180;
                azimut *= M_PI / 180.;
                sincos (azimut, &si, &co);
                plot_x = radius * si * ech / 2. + plot_x0;
                plot_y = radius * co * ech / 2. + plot_y0;
                if (symbol == CROSS || symbol == POINT) ps_setpaint (fill.rgb);
            
                if(label_s) {
                    GMT_setpen (&tpen);
                    switch (justify_s) {
                        case 11 :
                            ps_text(plot_x-symbol_size2-0.1, plot_y-symbol_size2-0.1, fontsize_s, stacode, angle_s, 11, form_s);
                            break;
                        case 10 :
                            ps_text(plot_x, plot_y-symbol_size2-0.1, fontsize_s, stacode, angle_s, 10, form_s);
                            break;
                        case 9 :
                            ps_text(plot_x+symbol_size2+0.1, plot_y-symbol_size2-0.1, fontsize_s, stacode, angle_s, 9, form_s);
                            break;
                        case 7:
                            ps_text(plot_x-symbol_size2-0.1, plot_y, fontsize_s, stacode, angle_s, 7, form_s);
                            break;
                        case 6:
                            ps_text(plot_x, plot_y, fontsize_s, stacode, angle_s, 6, form_s);
                            break;
                        case 5:
                            ps_text(plot_x+symbol_size2+0.1, plot_y, fontsize_s, stacode, angle_s, 5, form_s);
                            break;
                        case 3:
                            ps_text(plot_x-symbol_size2-0.1, plot_y+symbol_size2+0.1, fontsize_s, stacode, angle_s, 3, form_s);
                            break;
                        case 2:
                            ps_text(plot_x, plot_y+symbol_size2+0.1, fontsize_s, col[3], angle_s, 2, form_s);
                            break;
                        case 1:
                            ps_text(plot_x+symbol_size2+0.1, plot_y+symbol_size2+0.1, fontsize_s, stacode, angle_s, 1, form_s);
                            break;
                    }
                }
    
                switch (symbol) {
                    case STAR:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_star (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_star (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                    case CROSS:
                              GMT_setpen (&pen);
                              ps_cross (plot_x, plot_y, symbol_size2);
                              break;
                    case POINT:
                              GMT_setpen (&pen);
                              ps_cross (plot_x, plot_y, POINTSIZE);
                              break;
                    case CIRCLE:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_circle (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_circle (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                    case SQUARE:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_square (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_square (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                    case HEXAGON:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_hexagon (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_hexagon (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                    case TRIANGLE:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_triangle (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_triangle (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                    case ITRIANGLE:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_itriangle (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_itriangle (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                    case DIAMOND:
                              if(pol == 'u' || pol == 'U' || pol == 'c' || pol == 'C' || pol == '+') {
                                  GMT_setpen (&gpen);
                                  ps_diamond (plot_x, plot_y, symbol_size2, gfill.rgb, outline_G);
                              }
                              else if(pol == 'r' || pol == 'R' || pol == 'd' || pol == 'D' || pol == '-') {
                                  GMT_setpen (&epen);
                                  ps_diamond (plot_x, plot_y, symbol_size2, efill.rgb, outline_E);
                              }
                              else {
                                  GMT_setpen (&pen);
                                  ps_cross (plot_x, plot_y, symbol_size2);
                              }
                              break;
                }
                if(plot_polS && azS >= 0.) {
                    GMT_setpen (&spen);
                    sincos (azS*M_PI/180., &si, &co);
                    if(vecS) {
                        ps_vector(plot_x - sizeS*si, plot_y - sizeS*co, 
                            plot_x + sizeS*si, plot_y + sizeS*co, v_width, 
                            h_length, h_width, gmtdefs.vector_shape, sfill.rgb, outline_s);
                    }
                    else { 
                        if(scolor) ps_setpaint (sfill.rgb);
                        else ps_setpaint (pen.rgb);
                        ps_plot(plot_x - sizeS*si, plot_y - sizeS*co, PSL_PEN_MOVE);
                        ps_plot(plot_x + sizeS*si, plot_y + sizeS*co, PSL_PEN_DRAW_AND_STROKE); 
                    }
                }
            }
        }
        if (fp != stdin) GMT_fclose (fp);
    }
    
    if (skip_if_outside) GMT_map_clip_off ();

    GMT_world_map = old_GMT_world_map;
    
    if (pen.texture[0]) ps_setdash (CNULL, 0);

    GMT_map_basemap ();

    GMT_plotend ();
    
    GMT_end (argc, argv);

    exit (EXIT_SUCCESS);
}
示例#5
0
int read_esri_info (struct GMT_CTRL *GMT, FILE *fp, struct GMT_GRID_HEADER *header)
{
	int c;
	char record[GMT_BUFSIZ];
	FILE *fp2 = NULL, *fpBAK = NULL;

	header->registration = GMT_GRID_NODE_REG;
	header->z_scale_factor = 1.0;
	header->z_add_offset   = 0.0;

	if (header->flags[0] == 'M' || header->flags[0] == 'I') {	/* We are dealing with a ESRI .hdr file */
		int error;
		if ((error = read_esri_info_hdr (GMT, header))) 		/* Continue the work someplace else */
			return (error);
		else
			return (GMT_NOERROR);
	}
	else if (header->flags[0] == 'B' && header->flags[1] == '0') {	/* A GTOPO30 or SRTM30 file */
		size_t len = strlen (header->title);

		header->inc[GMT_X] = header->inc[GMT_Y] = 30.0 * GMT_SEC2DEG;	/* 30 arc seconds */
		header->wesn[YHI] = atof (&header->title[len-2]);
		if ( header->title[len-3] == 'S' || header->title[len-3] == 's' ) header->wesn[YHI] *= -1; 
		c = header->title[len-3];
		header->title[len-3] = '\0';
		header->wesn[XLO] = atof (&header->title[len-6]);
		header->title[len-3] = (char)c;		/* Reset because this function is called at least twice */
		if ( header->title[len-7] == 'W' || header->title[len-7] == 'w' ) header->wesn[XLO] *= -1; 
		if (header->wesn[YHI] > -60) {
			header->wesn[YLO] = header->wesn[YHI] - 50; 
			header->wesn[XHI] = header->wesn[XLO] + 40; 
			header->nx = 4800;
			header->ny = 6000;
		}
		else {	/* Antarctica tiles cover 30 degrees of latitude and 60 degrees of longitude each have 3,600 rows and 7,200 columns */
			header->wesn[YLO] = -90; 
			header->wesn[XHI] = header->wesn[XLO] + 60; 
			header->nx = 7200;
			header->ny = 3600;
		}
		header->registration = GMT_GRID_PIXEL_REG;
		GMT_set_geographic (GMT, GMT_IN);
		gmt_grd_set_units (GMT, header);
		
		/* Different sign of NaN value between GTOPO30 and SRTM30 grids */
		if (strstr (header->name, ".DEM") || strstr (header->name, ".dem"))
			header->nan_value = -9999.0f;
		else
			header->nan_value = 9999.0f;
		header->bits = 16;		/* Temp pocket to store number of bits */
		return (GMT_NOERROR);
	}
	else if (header->flags[0] == 'B' && header->flags[1] == '1') {	/* A SRTM3 or SRTM1 file */
		size_t len = strlen (header->title);
		struct stat F;

		header->wesn[XLO] = atof (&header->title[len-3]);
		if ( header->title[len-4] == 'W' || header->title[len-4] == 'W' ) header->wesn[XLO] *= -1; 
		c = header->title[len-4];
		header->title[len-4] = '\0';
		header->wesn[YLO] = atof (&header->title[len-6]);
		header->title[len-4] = (char)c;		/* Reset because this function is called at least twice */
		if ( header->title[len-7] == 'S' || header->title[len-7] == 's' ) header->wesn[YLO] *= -1; 
		header->wesn[YHI] = header->wesn[YLO] + 1; 
		header->wesn[XHI] = header->wesn[XLO] + 1; 
		header->nan_value = -32768.0f;
		header->bits = 16;		/* Temp pocket to store number of bits */
		stat (header->name, &F);	/* Must finally find out if it is a 1 or 3 arcseconds file */
		if (F.st_size < 3e6) {		/* Actually the true size is 2884802 */
			header->inc[GMT_X] = header->inc[GMT_Y] = 3.0 * GMT_SEC2DEG;	/* 3 arc seconds */
			strcpy (header->remark, "Assumed to be a SRTM3 tile");
		}
		else {
			header->inc[GMT_X] = header->inc[GMT_Y] = 1.0 * GMT_SEC2DEG;	/* 1 arc second  */
			strcpy (header->remark, "Assumed to be a SRTM1 tile");
		}
		GMT_set_geographic (GMT, GMT_IN);
		gmt_grd_set_units (GMT, header);
		return (GMT_NOERROR);
	}
	else if ((header->flags[0] == 'L' || header->flags[0] == 'B') && header->flags[1] == '2') {	/* A Arc/Info BINARY file */
		if ((fp2 = GMT_fopen (GMT, header->title, "r")) == NULL) return (GMT_GRDIO_OPEN_FAILED);
		/* To use the same parsing header code as in the ASCII file case where header and data are in the
		   same file, we will swap the file pointers and undo the swap at the end of this function */
		fpBAK = fp;	/* Copy of the input argument '*fp' */
		fp = fp2;
	}

	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %d", &header->nx) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding ncols record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %d", &header->ny) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding nrows record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->wesn[XLO]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding xll record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_str_tolower (record);
	if (!strncmp (record, "xllcorner", 9U)) header->registration = GMT_GRID_PIXEL_REG;	/* Pixel grid */
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->wesn[YLO]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding yll record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_str_tolower (record);
	if (!strncmp (record, "yllcorner", 9U)) header->registration = GMT_GRID_PIXEL_REG;	/* Pixel grid */
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->inc[GMT_X]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding cellsize record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	/* Handle the optional nodata_value record */
	c = fgetc (fp);	/* Get first char of next line... */
	ungetc (c, fp);	/* ...and put it back where it came from */
	if (c == 'n' || c == 'N') {	/*	Assume this is a nodata_value record since we found an 'n|N' */
		GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
		if (sscanf (record, "%*s %f", &header->nan_value) != 1) {
			GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding nan_value_value record\n");
			return (GMT_GRDIO_READ_FAILED);
		}
	}
	header->inc[GMT_Y] = header->inc[GMT_X];
	header->wesn[XHI] = header->wesn[XLO] + (header->nx - 1 + header->registration) * header->inc[GMT_X];
	header->wesn[YHI] = header->wesn[YLO] + (header->ny - 1 + header->registration) * header->inc[GMT_Y];

	GMT_err_fail (GMT, GMT_grd_RI_verify (GMT, header, 1), header->name);

	if (fpBAK) {		/* Case of Arc/Info binary file with a separate header file. We still have things to do. */
		char tmp[16];
		/* Read an extra record containing the endianness info */
		GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
		if (sscanf (record, "%*s %s", tmp) != 1) {
			GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info BINARY Grid: Error decoding endianness record\n");
			return (GMT_GRDIO_READ_FAILED);
		}
		header->flags[0] = (tmp[0] == 'L') ? 'L' : 'B';

		header->bits = 32;	/* Those float binary files */
		/* Ok, now as mentioned above undo the file pointer swapping (point again to data file) */
		fp = fpBAK;
		GMT_fclose (GMT, fp2);
	}

	return (GMT_NOERROR);
}
示例#6
0
int read_esri_info_hdr (struct GMT_CTRL *GMT, struct GMT_GRID_HEADER *header) {
	/* Parse the contents of a .HDR file */
	int nB;
	char record[GMT_BUFSIZ];
	FILE *fp = NULL;

	if ((fp = GMT_fopen (GMT, header->title, "r")) == NULL) return (GMT_GRDIO_OPEN_FAILED);

	header->registration = GMT_GRID_NODE_REG;
	header->z_scale_factor = 1.0;
	header->z_add_offset   = 0.0;

	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);		/* BYTEORDER */ 
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);		/* LAYOUT */
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %d", &header->ny) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding NROWS record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %d", &header->nx) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding NCOLS record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %d", &nB) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding NBANDS record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	if (nB != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Cannot read file with number of Bands != 1 \n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %d", &header->bits) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding NBITS record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	if ( header->bits != 16 && header->bits != 32 ) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: This data type (%d bits) is not supported\n", header->bits);
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);		/* BANDROWBYTES  */ 
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);		/* TOTALROWBYTES */
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);		/* BANDGAPBYTES  */
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	while (strncmp (record, "NODATA", 4) )		/* Keep reading till find this keyword */
		GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %f", &header->nan_value) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding nan_value_value record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->wesn[XLO]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding ULXMAP record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->wesn[YHI]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding ULYMAP record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->inc[GMT_X]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding XDIM record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
	GMT_fgets (GMT, record, GMT_BUFSIZ, fp);
	if (sscanf (record, "%*s %lf", &header->inc[GMT_Y]) != 1) {
		GMT_Report (GMT->parent, GMT_MSG_NORMAL, "Arc/Info ASCII Grid: Error decoding YDIM record\n");
		return (GMT_GRDIO_READ_FAILED);
	}
			
	GMT_fclose (GMT, fp);

	header->wesn[XHI] = header->wesn[XLO] + (header->nx - 1 + header->registration) * header->inc[GMT_X];
	header->wesn[YLO] = header->wesn[YHI] - (header->ny - 1 + header->registration) * header->inc[GMT_Y];

	GMT_err_fail (GMT, GMT_grd_RI_verify (GMT, header, 1), header->name);

	return (GMT_NOERROR);
}
示例#7
0
int main (int argc, char **argv)
{
	GMT_LONG error = FALSE;
	int xplot_cdp = FALSE, xplot_offset = FALSE, fix_x = FALSE, byte_x = 0; /* parameters for location plot */
	int yplot_cdp = FALSE, yplot_offset = FALSE, fix_y = FALSE, byte_y = 0;
	int doclip = FALSE;
	int normalize = FALSE, do_fill = FALSE, negative = FALSE, plot_wig = FALSE;
	int no_zero = FALSE, polarity=1;
#ifdef WORDS_BIGENDIAN
	int swap_bytes = FALSE;
#else
	int swap_bytes = TRUE;
#endif

	int i, nm;
	int ix, iz, n_traces=10000, n_samp=0, n_sampr=0, shade[3]={0,0,0}, trans[3]={-1,-1,-1};

	int check;

	double w, e, s, n, dx = 1.0, dz = 0.0; /* dx, dz are trace and sample interval */
	double xlen, ylen, xpix, ypix;
	double x0 = 0.0 , y0 = 0.0;


	float bias = 0.0, scale = 1.0, clip = 0.0, dev_x = 0.0, dev_y = 0.0;
	double redvel=0.0;
	float toffset=0.0;

	char input[512];
	char *text = NULL;
	char *head = NULL;
	int head2;


	char reelhead[3200];
	float *data = NULL;
	SEGYHEAD *header = NULL;
	SEGYREEL binhead;

	FILE *fpi = NULL;


	input[0] = 0;
	w = e = s = n = 0.0;

	argc = (int)GMT_begin (argc, argv);

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				/* Common parameters */

				case 'V':
				case 'R':
				case 'J':
				case 'O':
				case 'K':
				case 'P':
				case '\0':
					error += GMT_parse_common_options (argv[i], &w, &e, &s, &n);
					break;
                                case 'E':
					error += GMT_get_proj3D (&argv[i][2], &z_project.view_azimuth, &z_project.view_elevation);
					break;
				/* parameters for wiggle mode */
				case 'F':
					do_fill = TRUE;
					if (GMT_getrgb (&argv[i][2], shade)) {
						++error;
						GMT_rgb_syntax ('F', " ");
					}
					break;
				case 'I':
					negative = TRUE;
					break;
				case 'W':
					plot_wig = TRUE;
					break;
				/* trace norm., clip and bias */
				case 'N':
					normalize = TRUE;
					break;
				case 'C':
					doclip = TRUE;
					clip = (float) atof (&argv[i][2]);
 					break;
				case 'B':
					bias = (float) atof (&argv[i][2]);
					break;
				case 'Z':
					no_zero = TRUE;
					break;
				/* variable spacing */
				case 'S':
				  if ((text = strstr(&argv[i][2], "/")) != NULL) {
				    	text = strtok(&argv[i][2], "/");
				    	if ((text[0] >='0' && text[0]<='9') || text[0] == '-'){
				      		fix_x = TRUE;
				      	x0 = (double) atof(text);
				    	}
				    	else{
						switch(text[0]){
							case 'o':
								xplot_offset = TRUE;
								break;
							case 'c':
								xplot_cdp = TRUE;
								break;
							case 'b':
					  			byte_x = atoi(&text[1]);
					  			break;
						}
				    	} /* now parameters for y */
				  	text = strtok(CNULL, "/");
				  	if (text != NULL){
				    		if ((text[0] >='0' && text[0]<='9') || text[0] == '-'){
				      			fix_y = TRUE;
				      			y0 = (double) atof(text);
				    		}
				    		else{
							switch(text[0]){
								case 'o':
									yplot_offset = TRUE;
									break;
								case 'c':
									yplot_cdp = TRUE;
									break;
								case 'b':
							  	byte_y = atoi(&text[1]);
							  	break;
							}
				    		}
				  	}
				  	else{
				    		fprintf(stderr,"%s:  Must specify parameters for x and y \n", GMT_program);
				    		++error;
				  	}
				}
				else{
					fprintf(stderr,"%s:  Must specify parameters for x and y \n", GMT_program);
					++error;
			 	}
				/*error += (!xplot_cdp && !xplot_offset && !byte_x && !fix_x);
				error += (!yplot_cdp && !yplot_offset && !byte_x && !fix_y);*/
				break;
				/* trace scaling */
				case 'D':
				  	if ((text = strstr(&argv[i][2], "/")) != NULL) {
				   	 	text = strtok(&argv[i][2], "/");
						dev_x = (float) atof (text);
				  		text = strtok(CNULL, "/");
						dev_y = (float) atof (text);
					}
					else
						dev_x = (float) atof (&argv[i][2]);
					/*error += ((dev_x < 0.0) && (dev_y < 0.0));*/
					error += (!dev_x && !dev_y);
			/*fprintf (stderr, "dev_x %f \t dev_y %f \n",dev_x, dev_y);*/
					break;
				/* over-rides of header info */
				case 'X': /* -X and -Y can be changed in gmt routines to lower case...*/
				case 'x':
					dx = atof (&argv[i][2]);
					break;
				case 'Y':
				case 'y':
					dz = atof (&argv[i][2]);
					break;
				case 'L':
					n_sampr = atoi (&argv[i][2]);
					break;
				case 'M':
					n_traces = atoi (&argv[i][2]);
					break;
				/* reduction velocity application */
				case 'U':
					redvel = atof (&argv[i][2]);
					break;
				case 'A':
					swap_bytes = !swap_bytes;
					break;
				default:
					error = TRUE;
					break;
			}
			}
		else if ((fpi = fopen (argv[i], "rb")) == NULL) {
			fprintf (stderr, "%s: Cannot find segy file %s\n",  GMT_program, argv[i]);
			exit (EXIT_FAILURE);
		}
	}


	if (argc == 1 || GMT_give_synopsis_and_exit) {
		fprintf (stderr, "pssegyz %s - Plot a segy file in PostScript\n\n", GMT_VERSION);
		fprintf (stderr, "usage: pssegyz [<segyfile>] %s %s -D<dev>\n", GMT_Jx_OPT, GMT_Rx_OPT);
		fprintf (stderr, "	[%s] [-C<clip>] [-B<bias>] [-N] [-Z]\n", GMT_E_OPT);
		fprintf (stderr, "	[-F<gray>|<r/g/b>] [-I] [-W] [-S<x>/<y>]\n");
		fprintf (stderr, "	[-X<dx>] [-Y<dz>] [-L<nsamp>] [-M<ntraces>] \n");
		fprintf (stderr, "	[-U<redvel>] [-A] [-O] [-K] [-P]\n");




		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);

		fprintf (stderr, 
			"\n\t-Jx for projection.  Scale in INCH/units.  Specify one:\n\t -Jx<x-scale>              Linear projection\n\t-Jx<x-scale>l             Log10 projection\n\t  -Jx<x-scale>p<power>      x^power projection\n\tUse / to specify separate x/y scaling.\n\t If -JX is used then give axes lengths rather than scales\n\t regular map projections may not work!\n");
		GMT_explain_option ('R');
		fprintf (stderr, "	NB units for y are s or km\n");
		fprintf (stderr, "	-D<dev> to give deviation in X units of plot for 1.0 on scaled trace.\n");
		fprintf (stderr, "	<dev> is single number (applied equally in X and Y directions or <devX>/<devY>.\n");
		fprintf (stderr, "	 IEEE SEGY file [or standard input] \n\n");
		fprintf (stderr, "\n\tOPTIONS:\n");
		GMT_explain_option ('E');
		GMT_explain_option ('V');
		fprintf (stderr, "	-C<clip> to clip scaled trace excursions at <clip>, applied after bias\n");
		fprintf (stderr, "	-B<bias> to bias scaled traces (-B-0.1 subtracts 0.1 from values)\n");
		fprintf (stderr,"	-N to trace normalize the plot\n");
		fprintf (stderr,"		order of operations: [normalize][bias][clip](deviation)\n");
		fprintf (stderr,"	-Z to suppress plotting traces whose rms amplitude is 0 \n");
		fprintf (stderr,"	-F<gray>|<r/g/b> to fill variable area with shade\n");
		fprintf (stderr,"		only single color for the bitmap though\n");
		fprintf (stderr,"	-I to fill negative rather than positive excursions\n");
		fprintf (stderr,"	-W to plot wiggle trace\n");
		fprintf (stderr,"	must specify either -W or -F\n");
		fprintf (stderr,"	-X<mult> multiply trace locations by <mult>\n");
		fprintf (stderr,"	-Y<dz> to override sample interval\n");
		fprintf (stderr,"	-S<x/y> to set variable spacing\n");
		fprintf (stderr,"		x,y are (number) for fixed location, c for cdp, o for offset, b<n> for long int at byte n\n");
		fprintf (stderr,"	-L<nsamp> to override number of samples\n");
		fprintf (stderr,"	-M<ntraces> to fix number of traces. Default reads all traces.\n\t\t-M0 will read number in binary header, -Mn will attempt to read only n traces.\n");
		fprintf (stderr,"	-U<redvel> to apply reduction velocity (-ve removes reduction alreadz present)\n");
		fprintf (stderr,"	-A flips the default byte-swap state (default assumes data have a bigendian byte-order)\n");
		GMT_explain_option ('O');
		GMT_explain_option ('K');
		GMT_explain_option ('P');
		exit (EXIT_FAILURE);
	}

	if (negative && !do_fill){ /* negative with no fill */
		error++;
		fprintf(stderr,"%s: SYNTAX ERROR: Must specify -F with -I\n", GMT_program);
	}
	if (!do_fill && !plot_wig){ /* no plotting specified */
 		error++;
 		fprintf(stderr,"%s: SYNTAX ERROR: Must specify -F or -W\n", GMT_program);
 	}
 	if (dev_x < 0.0 || dev_y < 0.0){
 		error++;
 		fprintf(stderr,"%s: SYNTAX ERROR: Must specify a positive deviation\n",GMT_program);
 	}
 	if (!GMT_IS_LINEAR){
 		fprintf(stderr,"%s: WARNING: you asked for a non-rectangular projection. \n It will probably still work, but be prepared for problems\n",GMT_program);
 	}
  	if (!project_info.z_bottom && !project_info.z_top){ /* no z range in the -R parameter */
 		error++;
 		fprintf(stderr,"%s: ERROR: must specify z range in -R option.",GMT_program);
 	}
  	if (!project_info.region_supplied){ /* no -R parameter */
 		error++;
 		fprintf(stderr,"%s: ERROR: must specify -R option.",GMT_program);
 	}
	if (z_project.view_azimuth > 360.0 || z_project.view_elevation <= 0.0 || z_project.view_elevation > 90.0) {
                fprintf (stderr, "%s: GMT SYNTAX ERROR -E option:  Enter azimuth in 0-360 range, elevation in 0-90 range\n", GMT_program);
                error++;
        }

 	if ((xplot_cdp && xplot_offset) || (yplot_cdp && yplot_offset) || (xplot_cdp && byte_x) || (yplot_cdp && byte_y) || (byte_x && xplot_offset) || (byte_y && yplot_offset)){
 		fprintf(stderr,"%s: SYNTAX ERROR: Can't specify more than one trace location key\n",GMT_program);
 		error++;
 	}
 
 	if (error) exit (EXIT_FAILURE);

	if (fpi == NULL) fpi = stdin;

/* set up map projection and PS plotting */
	GMT_err_fail (GMT_map_setup (w, e, s, n), "");
	GMT_plotinit (argc, argv);

        /*if (project_info.three_D) ps_transrotate (-z_project.xmin, -z_project.ymin, 0.0);*/


/* define area for plotting and size of array for bitmap */
	xlen = z_project.xmax-z_project.xmin;
	xpix = xlen*gmtdefs.dpi; /* pixels in x direction */
	/*xpix /= 8.0;
	bm_nx = 1 +(int) xpix;*/
	bm_nx = (int) ceil (xpix/8.0); /* store 8 pixels per byte in x direction but must have
				whole number of bytes per scan */
	ylen = z_project.ymax-z_project.ymin;
	ypix = ylen*gmtdefs.dpi; /* pixels in y direction */
	bm_ny = (int) ypix;
	nm = bm_nx*bm_ny;


/* read in reel headers from segy file */
	if ((check = get_segy_reelhd (fpi, reelhead)) != TRUE) exit(1);
	if ((check = get_segy_binhd (fpi, &binhead)) != TRUE) exit(1);

	if(swap_bytes){
/* this is a little-endian system, and we need to byte-swap ints in the reel header - we only
use a few of these*/
		if (gmtdefs.verbose) fprintf(stderr, "%s: swapping bytes for ints in the headers\n", GMT_program);
		binhead.num_traces = GMT_swab2(binhead.num_traces);
		binhead.nsamp = GMT_swab2(binhead.nsamp);
		binhead.dsfc = GMT_swab2(binhead.dsfc);
		binhead.sr = GMT_swab2(binhead.sr);
	}

/* set parameters from the reel headers */
	if (!n_traces)
		n_traces = binhead.num_traces;

	if (gmtdefs.verbose) fprintf(stderr, "%s: Number of traces in header is %d\n", GMT_program, n_traces);


	if (!n_sampr){/* number of samples not overridden*/
		n_sampr = binhead.nsamp;
		fprintf(stderr,"%s: Number of samples per trace is %d\n", GMT_program, n_sampr);
	}
	else if ((n_sampr != binhead.nsamp) && (binhead.nsamp))
		fprintf(stderr,"%s: warning nsampr input %d, nsampr in header %d\n", GMT_program, n_sampr, binhead.nsamp);

	if (!n_sampr){ /* no number of samples still - a problem! */
		fprintf(stderr, "%s: Error, number of samples per trace unknown\n", GMT_program);
		exit (EXIT_FAILURE);
	}

	if(gmtdefs.verbose) 
		fprintf(stderr, "%s: Number of samples is %dl\n", GMT_program, n_samp);

	if(binhead.dsfc != 5) fprintf(stderr, "%s: WARNING data not in IEEE format\n", GMT_program);

	if (!dz){
		dz = binhead.sr; /* sample interval of data (microseconds) */
		dz /= 1000000.0;
		fprintf(stderr,"%s: Sample interval is %f s\n", GMT_program, dz);
	}
	else if ((dz != binhead.sr) && (binhead.sr)) /* value in header overridden by input */
		fprintf(stderr, "%s: Warning dz input %f, dz in header %f\n", GMT_program, dz, (float)binhead.sr);

	if (!dz){ /* still no sample interval at this point is a problem! */
		fprintf(stderr, "%s: Error, no sample interval in reel header\n", GMT_program);
		exit (EXIT_FAILURE);
	}


	bitmap = (unsigned char *) GMT_memory (NULL, (size_t)nm, sizeof (char), "pssegyz");

	ix=0;
	while ((ix<n_traces) && (header = get_segy_header(fpi))){   /* read traces one by one */
	/* check true location header for x */
		if (xplot_offset){ /* plot traces by offset, cdp, or input order */
			int32_t offset = ((swap_bytes)? GMT_swab4(header->sourceToRecDist): header->sourceToRecDist);
			x0 = (double) offset;
		}
		else if (xplot_cdp){
			int32_t cdpval = ((swap_bytes)? GMT_swab4(header->cdpEns): header->cdpEns);
			x0 = (double) cdpval;
		}
		else if (byte_x){ /* ugly code - want to get value starting at byte_x of header into a double... */
		   	head = (char *) header;
			memcpy(&head2, &head[byte_x], 4); /* edited to fix bug where 8bytes were copied from head.
                                                Caused by casting to a long directly from char array*/ 
			x0 = (double) ((swap_bytes)? GMT_swab4(head2): head2);
		}
		else if (fix_x)
			x0 /= dx;
		else
			x0 = (1.0 + (double) ix); /* default x to input trace number */

	/* now do same for y */
		if (yplot_offset){ /* plot traces by offset, cdp, or input order */
			int32_t offset = ((swap_bytes)? GMT_swab4(header->sourceToRecDist): header->sourceToRecDist);
			y0 = (double) offset;
		}
		else if (yplot_cdp){
			int32_t cdpval = ((swap_bytes)? GMT_swab4(header->cdpEns): header->cdpEns);
			y0 = (double) cdpval;
		}
		else if (byte_y){
			head =  (char *) header;
			memcpy(&head2, &head[byte_y], 4); /* edited to fix bug where 8bytes were copied from head.
                                                Caused by casting to a long directly from char array*/ 
			y0 = (double) ((swap_bytes)? GMT_swab4(head2): head2);
		}
		else if (fix_y)
			y0 /= dx;
		else
			y0 = s / dx; /* default y to s edge of projection */

		x0 *= dx;
		y0 *= dx; /* scale x and y by the input dx scalar */

		if (swap_bytes){
/* need to permanently byte-swap some things in the trace header 
do this after getting the location of where traces are plotted in case the general byte_x case
overlaps a defined header in a strange way */
			 header->sourceToRecDist=GMT_swab4(header->sourceToRecDist);
			 header->sampleLength=GMT_swab2(header->sampleLength);
			 header->num_samps=GMT_swab4(header->num_samps);
		}

		if (gmtdefs.verbose) 
			fprintf(stderr, "%s: trace %d at x=%f, y=%f \n", GMT_program, ix+1, x0, y0);

		if (redvel){
			toffset = (float) -(fabs((double)(header->sourceToRecDist))/redvel);
			if (gmtdefs.verbose)
				fprintf(stderr, "%s: time shifted by %f\n", GMT_program, toffset);
		}

		data = (float *) get_segy_data(fpi, header); /* read a trace */
	/* get number of samples in _this_ trace (e.g. OMEGA has strange ideas about SEGY standard)
                or set to number in reel header */
                if ( !(n_samp = samp_rd(header)) ) n_samp = n_sampr;

		if(swap_bytes){ /* need to swap the order of the bytes in the data even though assuming IEEE format */
			int *intdata = (int *) data;
			for (iz=0; iz<n_samp; iz++){
				intdata[iz]=GMT_swab4(intdata[iz]);
			}
		}

		if(normalize || no_zero){
			scale= (float) rms(data, n_samp);
			if (gmtdefs.verbose) 
				fprintf(stderr, "%s: \t\t rms value is %f\n", GMT_program, scale);
		}
		for (iz=0; iz<n_samp; iz++){ /* scale bias and clip each sample in the trace */
			if (normalize) data[iz] /= scale;
			data[iz] += bias; 
			if(doclip && (fabs(data[iz]) > clip)) data[iz] = (float)(clip*data[iz]/fabs(data[iz])); /* apply bias and then clip */
		}

		if (!no_zero || scale)
			plot_trace (data, dz, x0, y0, n_samp, do_fill, negative, plot_wig, toffset, dev_x, dev_y);
		free (data);
		free (header);
		ix++;
	}

	/* map_clip_on (-1, -1, -1, 3); */
	/* set a clip at the map boundary since the image space overlaps a little */
	ps_bitimage (0.0,0.0,xlen, ylen, bitmap, 8*bm_nx, bm_ny, polarity, shade, trans);

	/* map_clip_off ();*/

	if (fpi != stdin) fclose (fpi);

	/*ps_rotatetrans (z_project.xmin, z_project.ymin, 0.0);*/
	GMT_plotend ();

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}
示例#8
0
int main (int argc, char **argv)
{
#include "grdreformat.h"	/* Defines N_GRDTXT_LINES and char *grd_formats[N_GRDTXT_LINES] array used in usage message */
	GMT_LONG error = FALSE, global = FALSE, no_header;

	GMT_LONG i, nfiles = 0, nx, ny, type[2];

	size_t nm;
	
	double w, e, s, n;

	float *z = NULL;

	char *file[2], fname[2][BUFSIZ];

	struct GRD_HEADER grd;
	struct GRDREFORMAT_CTRL *Ctrl = NULL;

	void *New_grdreformat_Ctrl (), Free_grdreformat_Ctrl (struct GRDREFORMAT_CTRL *C);

	argc = (int)GMT_begin (argc, argv);

	Ctrl = (struct GRDREFORMAT_CTRL *)New_grdreformat_Ctrl ();	/* Allocate and initialize a new control structure */
	
	file[0] = file[1] = CNULL;
	w = e = s = n = 0.0;

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				/* Common parameters */

				case 'R':
				case 'V':
				case 'f':
				case '\0':
					error += GMT_parse_common_options (argv[i], &w, &e, &s, &n);
					break;

				case 'N':
					Ctrl->N.active = TRUE;
					break;
				default:
					error = TRUE;
					GMT_default_error (argv[i][1]);
					break;
			}
		}
		else if (nfiles < 2) {
			file[nfiles] = argv[i];
			nfiles++;
		}
		else
			nfiles++;
	}

	if (argc == 1 || GMT_give_synopsis_and_exit) {	/* Display usage */
		fprintf (stderr, "grdreformat %s - Converting between different grid file formats\n\n", GMT_VERSION);
		fprintf( stderr, "usage: grdreformat ingrdfile[=id[/scale/offset]] outgrdfile[=id[/scale/offset]] [-N]\n\t[%s] [%s] [-V]\n", GMT_Rgeo_OPT, GMT_f_OPT);

		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);

		fprintf (stderr, "\tingrdfile is the grid file to convert.\n");
		fprintf (stderr, "\toutgrdfile is the new converted grid file.\n");
		fprintf( stderr, "\tscale and offset, if given, will multiply data by scale and add offset.\n");
		fprintf (stderr, "\n\tOPTIONS:\n");
		fprintf (stderr, "\t-N  Do NOT write the header (native grids only - ignored otherwise).\n");
		fprintf (stderr, "\t\t  Useful when creating files to be used by grdraster.\n");
		GMT_explain_option ('r');
		GMT_explain_option ('f');
		GMT_explain_option ('V');

		fprintf (stderr, "\n	The following grid file formats are supported:\n\n");
#ifdef USE_GDAL
		for (i = 0; i < N_GRDTXT_LINES; i++) fprintf (stderr, "\t%s\n", grd_formats[i]);
#else
		for (i = 0; i < N_GRDTXT_LINES; i++) if (i != 33) fprintf (stderr, "\t%s\n", grd_formats[i]);
#endif
		exit (EXIT_FAILURE);
	}

	if (nfiles != 2) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR: Must specify both input and output file names.\n", GMT_program);
		error++;
	}

	if (error) exit (EXIT_FAILURE);

	GMT_grd_init (&grd, argc, argv, FALSE);
	no_header = (Ctrl->N.active) ? 64 : 0;
	GMT_err_fail (GMT_grd_get_format (file[0], &grd, TRUE), file[0]);
	type[0] = grd.type;
	strcpy (fname[0], grd.name);
	GMT_err_fail (GMT_grd_get_format (file[1], &grd, FALSE), file[1]);
	type[1] = grd.type;
	strcpy (fname[1], grd.name);

	if (type[1] == 20) {	/* Golden Surfer format 7 (double) is read-only */
		fprintf (stderr, "%s: Grid format sd (Golden Software Surfer format 7 (double)) is read-only!\n", GMT_program);
		exit (EXIT_FAILURE);
	}
#ifdef USE_GDAL
	if (type[1] == 22) {	/* GDAL format is read-only */
		fprintf (stderr, "%s: Grid format gd (GDAL) is read-only!\n", GMT_program);
		exit (EXIT_FAILURE);
	}
#endif	
	if (gmtdefs.verbose) {
		if (file[0][0] == '=') strcpy (fname[0], "<stdin>");
		if (file[1][0] == '=') strcpy (fname[1], "<stdout>");
		fprintf (stderr, "%s: Translating file %s (format = %ld) to file %s (format = %ld)\n", GMT_program, fname[0], type[0], fname[1], type[1]);
		if (no_header && GMT_grdformats[type[1]][0] != 'c' && GMT_grdformats[type[1]][0] != 'n') fprintf (stderr, "%s: No grd header will be written\n", GMT_program);
	}

	GMT_err_fail (GMT_read_grd_info (file[0], &grd), fname[0]);

	if (e > w && n > s) {
		global = GMT_grd_is_global (&grd);
		if (!global && (w < grd.x_min || e > grd.x_max)) error = TRUE;
		if (s < grd.y_min || n > grd.y_max) error = TRUE;
		if (error) {
			fprintf (stderr, "%s: Subset exceeds data domain!\n", GMT_program);
			exit (EXIT_FAILURE);
		}
		nx = GMT_get_n (w, e, grd.x_inc, grd.node_offset);
		ny = GMT_get_n (s, n, grd.y_inc, grd.node_offset);
		nm = GMT_get_nm (nx, ny);
	}
	else
		nm = GMT_get_nm (grd.nx, grd.ny);

	z = (float *) GMT_memory (VNULL, nm, sizeof (float), GMT_program);
	GMT_err_fail (GMT_read_grd (file[0], &grd, z, w, e, s, n, GMT_pad, FALSE), fname[0]);

	grd.type = type[1];

	GMT_grd_init (&grd, argc, argv, TRUE);

	GMT_err_fail (GMT_write_grd (file[1], &grd, z, 0.0, 0.0, 0.0, 0.0, GMT_pad, no_header), fname[1]);

	GMT_free ((void *)z);

	Free_grdreformat_Ctrl (Ctrl);	/* Deallocate control structure */

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}