Example #1
0
/*!
 * \brief Creates system of linear equations from interpolated points
 *
 * Creates system of linear equations represented by matrix using given
 * points and interpolating function interp()
 *
 * \param params struct interp_params *
 * \param points points for interpolation as struct triple
 * \param n_points number of points
 * \param[out] matrix the matrix
 * \param indx
 *
 * \return -1 on failure, 1 on success
 */
int IL_matrix_create(struct interp_params *params,
		     struct triple *points,	/* points for interpolation */
		     int n_points,	/* number of points */
		     double **matrix,	/* matrix */
		     int *indx)
{
    double xx, yy;
    double rfsta2, r;
    double d;
    int n1, k1, k2, k, i1, l, m, i, j;
    double fstar2 = params->fi * params->fi / 4.;
    static double *A = NULL;
    double RO, amaxa;
    double rsin = 0, rcos = 0, teta, scale = 0;	/*anisotropy parameters - added by JH 2002 */
    double xxr, yyr;

    if (params->theta) {
	teta = params->theta * (M_PI / 180);	/* deg to rad */
	rsin = sin(teta);
	rcos = cos(teta);
    }
    if (params->scalex)
	scale = params->scalex;


    n1 = n_points + 1;

    if (!A) {
	if (!
	    (A =
	     G_alloc_vector((params->KMAX2 + 2) * (params->KMAX2 + 2) + 1))) {
	    fprintf(stderr, "Cannot allocate memory for A\n");
	    return -1;
	}
    }

    /*
       C      GENERATION OF MATRIX
       C      FIRST COLUMN
     */
    A[1] = 0.;
    for (k = 1; k <= n_points; k++) {
	i1 = k + 1;
	A[i1] = 1.;
    }
    /*
       C      OTHER COLUMNS
     */
    RO = -params->rsm;
    /* fprintf (stderr, "sm[%d] = %f,  ro=%f\n", 1, points[1].smooth, RO); */
    for (k = 1; k <= n_points; k++) {
	k1 = k * n1 + 1;
	k2 = k + 1;
	i1 = k1 + k;
	if (params->rsm < 0.) {	/*indicates variable smoothing */
	    A[i1] = -points[k - 1].sm;	/* added by Mitasova nov. 96 */
	    /* G_debug(5, "sm[%d]=%f, a=%f", k, points[k-1].sm, A[i1]); */
	}
	else {
	    A[i1] = RO;		/* constant smoothing */
	}
	/* if (i1 == 100) fprintf (stderr,i "A[%d] = %f\n", i1, A[i1]); */

	/* A[i1] = RO; */
	for (l = k2; l <= n_points; l++) {
	    xx = points[k - 1].x - points[l - 1].x;
	    yy = points[k - 1].y - points[l - 1].y;

	    if ((params->theta) && (params->scalex)) {
		/* re run anisotropy */
		xxr = xx * rcos + yy * rsin;
		yyr = yy * rcos - xx * rsin;
		xx = xxr;
		yy = yyr;
		r = scale * xx * xx + yy * yy;
		rfsta2 = fstar2 * (scale * xx * xx + yy * yy);
	    }
	    else {
		r = xx * xx + yy * yy;
		rfsta2 = fstar2 * (xx * xx + yy * yy);
	    }

	    if (rfsta2 == 0.) {
		fprintf(stderr, "ident. points in segm.\n");
		fprintf(stderr, "x[%d]=%f, x[%d]=%f, y[%d]=%f, y[%d]=%f\n",
			k - 1, points[k - 1].x, l - 1, points[l - 1].x, k - 1,
			points[k - 1].y, l - 1, points[l - 1].y);
		return -1;
	    }
	    i1 = k1 + l;
	    A[i1] = params->interp(r, params->fi);
	}
    }

    /* C       SYMMETRISATION */
    amaxa = 1.;
    for (k = 1; k <= n1; k++) {
	k1 = (k - 1) * n1;
	k2 = k + 1;
	for (l = k2; l <= n1; l++) {
	    m = (l - 1) * n1 + k;
	    A[m] = A[k1 + l];
	    amaxa = amax1(A[m], amaxa);
	}
    }
    m = 0;
    for (i = 0; i <= n_points; i++) {
	for (j = 0; j <= n_points; j++) {
	    m++;
	    matrix[i][j] = A[m];
	}
    }

    G_debug(3, "calling G_ludcmp()  n=%d indx=%d", n_points, *indx);
    if (G_ludcmp(matrix, n_points + 1, indx, &d) <= 0) {
	/* find the inverse of the matrix */
	fprintf(stderr, "G_ludcmp() failed! n=%d  d=%.2f\n", n_points, d);
	return -1;
    }

    /* G_free_vector(A); */
    return 1;
}
Example #2
0
void rdcircsum(float *outpsf, osm_ds *head, int bin,
		float distance, float size, int tandem)
{
int 		Nxy,Nz,Nr;
int		ovrsmp;
int		symmetric;
FILE		*logfp,*infofp;

float		*pupil; 	/*   Pupil function and its Fourier transform */
fcomplex	*Cpupil;
float		*psfobj; 	/*   One (xy) plane of the objective's PSF    */
float		*psfbin1; 	/*   One plane (xy) of the intermediate PSF   */
float		*psfbin; 	/*   One plane (xy) of the final PSF          */
float		*psfcond; 	/*   One plane of the condenser PSF           */
fcomplex	*otfcond;
float		peak;		/*   Max. value of arrays (normalization)     */
float		illum; 		/*   One sample of the illumination patern    */
float		tmp;
float		alpha;
float		*radpsf; 	/*   PSF intensity image XY crossection       */
float		*psfxz;
float		Vxx, Vyx, 	/*   Elements of the sampling matrix          */
		Vxy, Vyy; 
int		iz, ir, ix, 	/*   indices for depth, radial distance,      */
		iy, jx, jy; 	/*    and the two lateral coordinates 	      */
int		n1, n2; 	/*   indices for periodic sampling in the PSF */
int		Maxn1, Maxn2, 
		Minn1, Minn2;
int		Maxir;

/* __Stuff to calculte min and max index values */
float		Sxmin, Sxmax, xmax, Maxxprime;
float		Symin, Symax, ymax, Maxyprime;
float		Maxrprime;
int		sMinn1, lMaxn1;
float		mytemp;

/*   Number of samples in (x, y), in z and radially (= Nxy*sqrt(2))*/
int		HalfNxy, Zup;
/*   Number of samples radially on the convolution of psfcond and pupil */
int		NetNr;
/*   Number of samples in (x,y) before binning  */
int		Lxy;
/*   Number of samples in (x,y) before binning and after 
     oversampling for the summation*/
int		Mxy, Halfway;
/*   Pupil function region of support */
int		Pxy;
/*   normalized radial or lateral sampling rate */
float		nrm_deltar, nrm_deltaxy=1.0;
/*   new lateral sampling rate based on oversampling */
float		deltaxy1;
/*   oversampling rate for the xy plane */
int		osamp;
/*   Floating point version of the above */
float		ratio;
/*   Weigth factors for apodization */
float		weight, appod;
/*   Distances in the detector plane (mm) */
float		rd, x, y, ysq;
/*   Shifted coordinates  */
float		xprime, yprime, rprime;
/*   Shifting of coodrinates */
float		dx, dy;
/*   Shifted radial coordinate normalized by deltar */
float		normRprime;
    
/*   ..To prompt for things */
char	temp_string[255];
char	answer[255];

/* --------------------- BEGIN EXECUTABLE CODE -------------------- */


/* __Initialize whatever paremeters here */
/*   ..Periodicity matrix */
Vxx = 1.0;
Vyx = 0.0;
Vxy = -0.5;
Vyy = (float)sqrt(3.0)*0.5;

/*   ..Prompt for all data */

Nr	  = head->nx;
Nz	  = head->ny;
psfxz     = (float*)head->data;
ovrsmp    = head->xstart;
Nxy       = head->ystart;
symmetric = head->zstart;
/* leave at 1.0
nrm_deltar    = head->xlength;
nrm_deltaxy   = head->ylength;
*/


HalfNxy = Nxy/2;
Lxy = Nxy*bin; 			/* Number of pixels before binning */
Halfway = (HalfNxy+1)*bin; 
NetNr = Nr; 			/* Number of pixels in convolution of psfcond and pupil */

nrm_deltar = nrm_deltaxy/((float)ovrsmp);

/* oversampling rate    */
/* make it beat nyquist */
osamp = (int)(deltaxy/deltaxy_nyq) + 1;

if(osamp < 5) osamp = 5;

/* make odd */
if(!(osamp & 1)) osamp++;

/* New deltaxy for oversampling */
deltaxy1 = deltaxy/((float)osamp);
ratio = (float) deltaxy1 / deltar;

printf("DXY: %.4f DXY_NYQ: %.4f SAMP = %d NEW_DXY: %.4f\n",
		deltaxy,deltaxy_nyq,osamp,deltaxy1);

Mxy = Lxy * osamp; /* number of pixels after oversampling */
Halfway = (HalfNxy+1)*bin*osamp; 
printf("ratio = %f Mxy = %d \n", ratio,Mxy);

/* check for single aperture */
if(distance <= 0.0) distance = 1E20;

distance = distance*nrm_deltaxy; 	/* Scale by pre-binning pixel size */

Zup = Nz; 			/* Limit for z index */
if (symmetric) Zup = (Nz/2) + 1;

/*   ..Maximum values for row sampling index 
	(NOTE: Assumes Vyy != 0 <--) */
Minn2 = ((float)-Mxy)/(Vyy*distance);
Maxn2 = ((float)(2*Mxy))/(Vyy*distance);

/* __Calculate a conservative extimate of the maximum value if the 'ir'
index that is expected to be used.  The estimate is calculated
with the following assumptions:
Vxx > 0, Vyy > 0 (strictly greater)
Vxy < 0 	 (Striclty less than)
Vyx = 0		 (exactly)
..Most negative value of n1 expected */

sMinn1 = ((float)-Mxy)/distance - (float)Minn2*Vxy/Vxx;
/*   ..Most positive value of n1 expected  */
lMaxn1 =  (((float)(2*Mxy))/distance - (float)Maxn2*Vxy)/Vxx;
/*   ..most negative value of term subtracted from xprime */
Sxmin = Vxx*(float)sMinn1 + Vyx*(float)Maxn2;
/*   ..Most positive value of term subtracted from xprime */
Sxmax = Vxx*(float)lMaxn1 + Vyx*(float)Minn2;
/*   ..Largest value of x */
xmax = (float)(Halfway-1) * nrm_deltaxy;
/*   ..Largest absolute value of xprime  */
Maxxprime = amax1(Sxmax*distance, xmax - Sxmin*distance);
/*   ..Most negative value of the term subtracted 
	from yprime (with Vyx=0,Vyy>0) */
Symin = Vyy*(float)Minn2;
/*   ..Most positive value of the term subtracted 
	from yprime (with Vyx=0,Vyy>0) */
/* In the original fortran code, Maxn1 is used in the next line
without being initialized first. I suspect it's a bug, and should
really be Maxn2. */
Symax = Vyy*(float)Maxn2;
/*   ..largest value of y  */
ymax = (float)(Halfway-1) * nrm_deltaxy;
/*   ..Largest absolute value of yprime */
Maxyprime=amax1(Vyy*(float)Maxn2*distance,ymax-Vyy*(float)Minn2*distance);
/*   ..Largest value of rprime we can conservativelly expect */
Maxrprime = (float) sqrt (Maxxprime*Maxxprime + Maxyprime*Maxyprime);
/*   ..Largetst index ir expected */
Maxir = (int) ((Maxrprime + 1.0)/nrm_deltar);
/*   ..Factor to be used in linear interpolation used as apodization */
appod = 1.0;
if (Maxir > Nr) appod = 1.0/(float)(Maxir - Nr) ;

/*   ..Calculate size of pupil function array at the higher resolution*/
Pxy = Nxy*ovrsmp*bin;
/*   ..Calculate the least power of 2 that will fit */
Pxy = intlog2(Pxy-1);
Pxy = (int) pow(2.0 , Pxy+1);

/*   ..Make sure that the log file exists */
if((logfp=fopen(lognm,"a"))==(FILE *)NULL) {
   fprintf(stderr,"WARNING: (rotdiskcirc) can't open logfile `%s' for write.\n",lognm);
   logfp = stderr;
   }
fprintf(logfp,"         Number of slices or planes: %d\n", Nz);
fprintf(logfp," Number of xy-samples after binning: %d\n", Nxy);
fprintf(logfp," Number of radial samples available: %d\n", Nr);
fprintf(logfp,"   Oversampling (before binning) by: %d\n", ovrsmp);
fprintf(logfp,"                     binning factor: %d\n", bin);
fprintf(logfp,"         distance between apertures: %E\n", distance);
fprintf(logfp,"   aperture size(prebin,oversmpled): %f\n", size);
fprintf(logfp,"   pupil support(prebin,oversmpled): %d\n", Pxy);
fprintf(logfp,"                      sample matrix:\n");
fprintf(logfp,"                                Vxx: %f\n",Vxx);
fprintf(logfp,"                                Vxy: %f\n",Vxy);
fprintf(logfp,"                                Vyx: %f\n",Vyx);
fprintf(logfp,"                                Vyy: %f\n",Vyy);
fprintf(logfp,"even symmetry in z is %s assumed.\n", symmetric ? "":"NOT");


   sprintf(temp_string,"%s.info",psfnm);
   if((infofp=fopen(temp_string,"a"))==(FILE *)NULL) 
      fprintf(stderr,"WARNING: can't open info file %s for write.\n",temp_string);
   else {
        fprintf(infofp,"                    binning factor: %d\n", bin);
        fprintf(infofp,"        Distance between apertures: %E\n", distance);
        fprintf(infofp,"aperture diameter(prebin,oversamp): %f\n", size);
        fprintf(infofp,"                     sample matrix:\n");
        fprintf(infofp,"                               Vxx: %f\n",Vxx);
        fprintf(infofp,"                               Vxy: %f\n",Vxy);
        fprintf(infofp,"                               Vyx: %f\n",Vyx);
        fprintf(infofp,"                               Vyy: %f\n",Vyy);
        fclose(infofp);
         }


fprintf(stderr,"check file %s for progress report.\n",lognm);

if (size >= 1.0) {
   keeplog (logfp, "sampling pupil function ");

   /* first allocate memory for array pupil */
   if((pupil=(float *)calloc(sizeof(float),((Pxy+2)*Pxy)))==
      (float *)NULL) {
      fprintf(stderr,"out of memory in %s\n",prognm);
      exit(1);
      }
   ZeroOut(pupil,(Pxy+2)*Pxy);

   /* Get pupil function */
   getpupil(pupil, size, Pxy, Pxy);
   add2columns(pupil,Pxy,Pxy);

   /* Fourier transform pupil function */
   real_fft3d(pupil,Pxy,Pxy,1,Pxy+2,Pxy,FORWARD);
   Cpupil=(fcomplex *)pupil;

   /* If tandem scanning, the equivalent pinhole function is the
      convolution of the pinhole with itself */
   if (tandem) mult3dcm (Cpupil, Cpupil, (Pxy+2)*Pxy/2);

   /* Normalize Cpupil array to avoid handling very small numbers */
   peak = 0.0;
   norm3dcm (Cpupil, &peak, Pxy*(Pxy+2)/2);
   }
     
/* allocate memory for psfobj. Notice size of array   */
if((psfobj=(float *)calloc(sizeof(float),Mxy*Mxy))==(float *)NULL) {
   fprintf(stderr,"out of memory in %s\n",prognm);
   exit(1);
   }
ZeroOut(psfobj,Mxy*Mxy);

printf("Mxy = %d and Pxy=%d\n",Mxy,Pxy);
fflush(stdout);
/* allocate memory for psfcond. Notice size of array   */
if (Mxy > Pxy){  /* when ovrsmp < 5 then this is true */
  printf("Mxy >Pxy\n");
  if((psfcond=(float *)calloc(sizeof(float),(Mxy+2)*Mxy))==(float *)NULL) {
     fprintf(stderr,"out of memory in %s\n",prognm);
     exit(1);
     }
}
else
  if((psfcond=(float *)calloc(sizeof(float),(Pxy+2)*Pxy))==(float *)NULL) {
     fprintf(stderr,"out of memory in %s\n",prognm);
     exit(1);
     }

ZeroOut(psfcond,(Pxy+2)*Pxy);
otfcond=(fcomplex *)psfcond;

/* allocate memory for psfbin. Notice size of array   */
if((psfbin=(float *)calloc(sizeof(float),Nxy*Nxy))==(float *)NULL) {
   fprintf(stderr,"out of memory in %s\n",prognm);
   exit(1);
   }
ZeroOut(psfbin,Nxy*Nxy);

/* allocate memory for psfbi1. Notice size of array */
if((psfbin1=(float *)calloc(sizeof(float),Lxy*Lxy))==(float *)NULL) {
   fprintf(stderr,"out of memory in %s\n",prognm);
   exit(1);
}
ZeroOut(psfbin1,Lxy*Lxy);


for(iz=1;iz<=Zup;iz++){
   if ( (iz-1)%1 == 0) {
      sprintf(temp_string,"iz = %d",iz);
      keeplog(logfp, temp_string);
      }

   /*      ..Read on row of the rz or xz cross-section */
   /* first have to go to the right place in file */

   radpsf = (psfxz + (iz-1)*Nr);

   /* Calculate the objective PSF (iterpolate rz section into xyz sect)*/
   r2xy(psfobj, radpsf, Mxy, Mxy, Nr, ratio);

   if (size >= 1.0) {
      /* Convolve condenser PSF and aperture */
      /* interpolate w/o subsampling */
      r2xy(psfcond, radpsf, Pxy, Pxy, Nr, 1.0);
      add2columns(psfcond,Pxy,Pxy);

      /*  Fourier transform, multiply, inverse Fourier transform */
      real_fft3d(psfcond,Pxy,Pxy,1,Pxy+2,Pxy,FORWARD);
      mult3dcm(otfcond, Cpupil, (Pxy+2)*Pxy/2);
      real_fft3d(psfcond,Pxy,Pxy,1,Pxy+2,Pxy,REVERSE);

      /* Copy first line of convolution to radpsf to use for illumination */
      NetNr = Pxy/2+1;
      cp3dr(radpsf, psfcond, NetNr);
      
   }


   /* The following loops are based on the PSF's even symmetry 
       in x and y */
   /* Calculate the illumination distribution */

   for(iy=1;iy<=Halfway;iy++){
      y = (float)(iy-1)*nrm_deltaxy;
      for(ix=1;ix<=Halfway;ix++){
         x = (float)(ix-1)*nrm_deltaxy;
         /*Initialize to use as accumulator */
	 illum = 0.0;
         /*  ..Index n2 is for columns  */
         for(n2=Minn2;n2<=Maxn2;n2++){
            dx = Vxy*n2;
            dy = Vyy*n2;
            
            /* ..These two lines assume Vxx is not zero */
            Minn1=(int)(((float)-Mxy/distance-dx)/Vxx);
            Maxn1=(int)((2.0*(float)Mxy/distance-dx)/Vxx);

            /*  ..Index n1 involves rows and columns */
            for(n1=Minn1;n1<=Maxn1;n1++){
               xprime = x - distance*(Vxx*(float)n1+dx);
               yprime = y - distance*(Vyx*(float)n1+dy);

               /* Rectangular sampling to check what's going on here */
               /*
                          xprime = x - distance*float(n2)
                          yprime = y - distance*float(n1)
               */
               rprime = (float)sqrt((double)(xprime*xprime) + (double)(yprime*yprime));
               /*  ..Normalize to the subsampled grid */
               normRprime = rprime*ratio;
               ir = (int)normRprime + 1;

               /*     ..Interpolate and accumulate */
               if (ir < NetNr) {

                  /*  ..Interpolate between adjacent samples */
                  alpha = ir - normRprime;

                  /*tmp = radpsf(ir)*alpha + radpsf(ir+1)*(1.0-alpha)*/
                  tmp = *(radpsf+ir-1) * ((float)ir-normRprime)
                        + *(radpsf+ir+1-1) * (normRprime+1.0-(float)ir);
                  }
               else {
                  /*This should disapear when we become confident
                    that the conservative guess for Maxir is OK */
                  if (ir > Maxir) {
                     Maxir = ir;
                     fprintf(stderr,"Found an ir > Maxir. \n");
                     fprintf(stderr,"Maxir set to %d\n",ir);
                     fprintf(stderr,"check the code that guesses Maxir again.\n");
	             appod = 1.0/(Maxir-Nr);
                     }

                  /*..Apodize from last available sample to zero 
            		to avoid sharp edges in the PSF */
                  /* ..Apodize by linear interpolation to zero at ir = Maxir */
                  weight = (Maxir-(float)ir)*appod;

                  tmp = *(radpsf+NetNr-1) * weight;
                  }  

               illum = illum + tmp;
            }   /*           end loop for n1 */
         }   /*           end loop for n2 */

         /* IMPORTANT
            The dimension of the array psfcond is now Mxy by Mxy,
            instead of (Pxy+2) by Pxy. */

         /* psfcond(ix,iy) = illum */
         *(psfcond+(ix-1)+(iy-1)*Mxy) = illum;

      } /*         end loop for ix */
   } /*         end loop for iy */

   /* ..Even symmetric replication into the other three quadrants */

   /* IMPORTANT
      The dimension of the array psfcond is now Mxy by Mxy,
      instead of (Pxy+2) by Pxy. 
   */

   evenrepr(psfcond, Mxy, Mxy);

   /*  ..Multiply illumination and objective psf (into psfobj) */
   mult3drm(psfobj, psfcond, Mxy*Mxy);
     
   /* sum neighboring pixels to downsample the BIG PSF */
   /* note dimension goes from Mxy to Lxy = Nxy*bin */
   Sum4N4NToNN(psfobj,psfbin1,Lxy,osamp); /* routine is in rotsum.c */

   /* Bin here */
   /* If binning by 1 copy psf to psfbin  */
   if (bin == 1) /* Lxy = Nxy */
     cp3dr (psfbin, psfbin1, Nxy*Nxy);
   else {
      /* Add pixels together */
      /* Clean psfbin array to use as accumulator */
      init3dr(psfbin, 0.0, Nxy*Nxy);

      /* binning  */
      for(ix=1;ix<=Lxy;ix++){
         jx = ((ix-1)/bin) + 1;
         for(iy=1;iy<=Lxy;iy++){
            jy = ((iy-1)/bin) + 1;
	    *(psfbin+(jx-1)+(jy-1)*Nxy) += *(psfbin1+(ix-1)+(iy-1)*Lxy);
            }
         }
      }

   WritePlane(iz-1,outpsf,psfbin,Nxy,Nxy,Nxy,Nxy);
   if(symmetric && (iz > 1))
       WritePlane(Nz-iz+1,outpsf,psfbin,Nxy,Nxy,Nxy,Nxy);


}  /* end of "for(iz=1;iz<=Zup;iz++)" */


keeplog (logfp, "DONE");
if(logfp != stderr) fclose(logfp);

printf("don't free up the memory\n");
/*free(radpsf);
free(psfbin);
free(psfobj);
free(psfcond);
free(pupil);*/

}
Example #3
0
/* data preparations, sigma, shear, etc. */
int grad_check(void)
{
    int k, l;
    double zx, zy, zd2, zd4, sinsl;
    double cc, cmul2;
    double sheer;
    double vsum = 0.;
    double vmax = 0.;
    double chsum = 0.;
    double zmin = 1.e12;
    double zmax = -1.e12;
    double zd2min = 1.e12;
    double zd2max = -1.e12;
    double smin = 1.e12;
    double smax = -1.e12;
    double infmin = 1.e12;
    double infmax = -1.e12;
    double sigmax = -1.e12;
    double cchezmax = -1.e12;
    double rhow = 1000.;
    double gacc = 9.81;
    double hh = 1.;
    double deltaw = 1.e12;

    sisum = 0.;
    infsum = 0.;
    cmul2 = rhow * gacc;

    for (k = 0; k < my; k++) {
	for (l = 0; l < mx; l++) {
	    if (zz[k][l] != UNDEF) {
		zx = v1[k][l];
		zy = v2[k][l];
		zd2 = zx * zx + zy * zy;
		sinsl = sqrt(zd2) / sqrt(zd2 + 1);	/* sin(terrain slope) */
		/* Computing MIN */
		zd2 = sqrt(zd2);
		zd2min = amin1(zd2min, zd2);
		/* Computing MAX */
		zd2max = amax1(zd2max, zd2);
		zd4 = sqrt(zd2);	/* ^.25 */
		if (cchez[k][l] != 0.) {
		    cchez[k][l] = 1. / cchez[k][l];	/* 1/n */
		}
		else {
		    G_fatal_error(_("Zero value in Mannings n"));
		}
		if (zd2 == 0.) {
		    v1[k][l] = 0.;
		    v2[k][l] = 0.;
		    slope[k][l] = 0.;
		}
		else {
		    if (wdepth)
			hh = pow(gama[k][l], 2. / 3.);
		    /* hh = 1 if there is no water depth input */
		    v1[k][l] = (double)hh *cchez[k][l] * zx / zd4;
		    v2[k][l] = (double)hh *cchez[k][l] * zy / zd4;

		    slope[k][l] =
			sqrt(v1[k][l] * v1[k][l] + v2[k][l] * v2[k][l]);
		}
		if (wdepth) {
		    sheer = (double)(cmul2 * gama[k][l] * sinsl);	/* shear stress */
		    /* if critical shear stress >= shear then all zero */
		    if ((sheer <= tau[k][l]) || (ct[k][l] == 0.)) {
			si[k][l] = 0.;
			sigma[k][l] = 0.;
		    }
		    else {
			si[k][l] = (double)(dc[k][l] * (sheer - tau[k][l]));
			sigma[k][l] = (double)(dc[k][l] / ct[k][l]) * (sheer - tau[k][l]) / (pow(sheer, 1.5));	/* rill erosion=1.5, sheet = 1.1 */
		    }
		}
		sisum += si[k][l];
		smin = amin1(smin, si[k][l]);
		smax = amax1(smax, si[k][l]);
		if (inf) {
		    infsum += inf[k][l];
		    infmin = amin1(infmin, inf[k][l]);
		    infmax = amax1(infmax, inf[k][l]);
		}
		vmax = amax1(vmax, slope[k][l]);
		vsum += slope[k][l];
		chsum += cchez[k][l];
		zmin = amin1(zmin, (double)zz[k][l]);
		zmax = amax1(zmax, (double)zz[k][l]);	/* not clear were needed */
		if (wdepth)
		    sigmax = amax1(sigmax, sigma[k][l]);
		cchezmax = amax1(cchezmax, cchez[k][l]);
		/* saved sqrt(sinsl)*cchez to cchez array for output */
		cchez[k][l] *= sqrt(sinsl);
	    }			/* DEFined area */
	}
    }
    if (inf != NULL && smax < infmax)
	G_warning(_("Infiltration exceeds the rainfall rate everywhere! No overland flow."));

    cc = (double)mx *my;

    si0 = sisum / cc;
    vmean = vsum / cc;
    chmean = chsum / cc;

    if (inf)
	infmean = infsum / cc;

    if (wdepth)
	deltaw = 0.8 / (sigmax * vmax);	/*time step for sediment */
    deltap = 0.25 * sqrt(stepx * stepy) / vmean;	/*time step for water */

    if (deltaw > deltap)
	timec = 4.;
    else
	timec = 1.25;

    miter = (int)(timesec / (deltap * timec));	/* number of iterations = number of cells to pass */
    iterout = (int)(iterout / (deltap * timec));	/* number of cells to pass for time series output */

    fprintf(stderr, "\n");
    G_message(_("Min elevation \t= %.2f m\nMax elevation \t= %.2f m\n"), zmin,
	      zmax);
    G_message(_("Mean Source Rate (rainf. excess or sediment) \t= %f m/s or kg/m2s \n"),
	      si0);
    G_message(_("Mean flow velocity \t= %f m/s\n"), vmean);
    G_message(_("Mean Mannings \t= %f\n"), 1.0 / chmean);

    deltap = amin1(deltap, deltaw);

    G_message(_("Number of iterations \t= %d cells\n"), miter);
    G_message(_("Time step \t= %.2f s\n"), deltap);
    if (wdepth) {
	G_message(_("Sigmax \t= %f\nMax velocity \t= %f m/s\n"), sigmax,
		  vmax);
	G_message(_("Time step used \t= %.2f s\n"), deltaw);
    }
    /*    if (wdepth) deltap = 0.1; 
     *    deltap for sediment is ar. average deltap and deltaw */
    /*    if (wdepth) deltap = (deltaw+deltap)/2.; 
     *    deltap for sediment is ar. average deltap and deltaw */


    /*! For each cell (k,l) compute the length s=(v1,v2) of the path 
     *  that the particle will travel per one time step
     *  \f$ s(k,l)=v(k,l)*dt \f$, [m]=[m/s]*[s]
     *  give warning if there is a cell that will lead to path longer than 2 cells 
     *
     *  if running erosion, compute sediment transport capacity for each cell si(k,l)
     *  \f$
     * T({\bf r})=K_t({\bf r}) \bigl[\tau({\bf r})\bigr]^p
     * =K_t({\bf r}) \bigl[\rho_w\, g h({\bf r}) \sin \beta ({\bf r}) \bigr]^p
     * \f$
     * [kg/ms]=...
     */
    for (k = 0; k < my; k++) {
	for (l = 0; l < mx; l++) {
	    if (zz[k][l] != UNDEF) {
		v1[k][l] *= deltap;
		v2[k][l] *= deltap;
		/*if(v1[k][l]*v1[k][l]+v2[k][l]*v2[k][l] > cellsize, warning, napocitaj
		 *ak viac ako 10%a*/
		/* THIS IS CORRECT SOLUTION currently commented out */
		if (inf)
		    inf[k][l] *= timesec;
		if (wdepth)
		    gama[k][l] = 0.;
		if (et) {
		    if (sigma[k][l] == 0. || slope[k][l] == 0.)
			si[k][l] = 0.;
		    else
			/* temp for transp. cap. erod */
			si[k][l] = si[k][l] / (slope[k][l] * sigma[k][l]);
		}
	    }			/* DEFined area */
	}
    }

    /*! compute transport capacity limted erosion/deposition et 
     *   as a divergence of sediment transport capacity
     *   \f$
     D_T({\bf r})= \nabla\cdot {\bf T}({\bf r})
     *   \f$
     */
    if (et) {
	erod(si);		/* compute divergence of t.capc */
	if (output_et() != 1)
	    G_fatal_error(_("Unable to write et file"));
    }

    /*! compute the inversion operator and store it in sigma - note that after this
     *   sigma does not store the first order reaction coefficient but the operator
     *   WRITE the equation here
     */
    if (wdepth) {
	for (k = 0; k < my; k++) {
	    for (l = 0; l < mx; l++) {
		if (zz[k][l] != UNDEF) {
		    /* get back from temp */
		    if (et)
			si[k][l] = si[k][l] * slope[k][l] * sigma[k][l];
		    if (sigma[k][l] != 0.)
			/* rate of weight loss - w=w*sigma ,
			 * vaha prechadzky po n-krokoch je sigma^n */

			/*!!!!! not clear what's here :-\ !!!!!*/

			sigma[k][l] =
			    exp(-sigma[k][l] * deltap * slope[k][l]);
		    /* if(sigma[k][l]<0.5) warning, napocitaj, 
		     * ak vacsie ako 50% skonci, zmensi deltap)*/
		}
	    }			/*DEFined area */
	}
    }
    return 1;
}
Example #4
0
int POINT(int n_points, struct quadruple *points, struct point_3d skip_point)

/*
   c  interpolation check of z-values in given points
   c
 */
{
    double errmax, h, xx, yy, r2, hz, zz, ww, err, xmm, ymm,
	zmm, wmm, r, etar;
    int n1, mm, m, mmax, inside;

    errmax = .0;
    n1 = n_points + 1;
    if (!cv) {
	for (mm = 1; mm <= n_points; mm++) {
	    h = b[n1];
	    for (m = 1; m <= n_points; m++) {
		xx = points[mm - 1].x - points[m - 1].x;
		yy = points[mm - 1].y - points[m - 1].y;
		zz = points[mm - 1].z - points[m - 1].z;
		r2 = yy * yy + xx * xx + zz * zz;
		r = sqrt(r2);
		etar = (fi * r) / 2.;
		h = h + b[m] * crs(etar);
	    }
	    hz = h + wmin;
	    ww = points[mm - 1].w + wmin;
	    err = hz - ww;

	    xmm = (points[mm - 1].x * dnorm) + xmn + current_region.west;
	    ymm = (points[mm - 1].y * dnorm) + ymn + current_region.south;
	    zmm =
		(points[mm - 1].z * dnorm) / zmult + zmn / zmult +
		current_region.bottom;

	    if ((xmm >= xmn + current_region.west) &&
		(xmm <= xmx + current_region.west) &&
		(ymm >= ymn + current_region.south) &&
		(ymm <= ymx + current_region.south) &&
		(zmm >= zmn / zmult + current_region.bottom) &&
		(zmm <= zmx / zmult + current_region.bottom))
		inside = 1;
	    else
		inside = 0;
	    if (devi != NULL && inside == 1)
		point_save(xmm, ymm, zmm, err);

	    if (err < 0) {
		err = -err;
	    }
	    if (err >= errmax) {
		errmax = err;
		mmax = mm;
	    }
	}

	ertot = amax1(errmax, ertot);
	if (errmax > ertre) {
	    xmm = (points[mmax - 1].x * dnorm) +
		((struct octdata *)(root->data))->x_orig;
	    ymm = (points[mmax - 1].y * dnorm) +
		((struct octdata *)(root->data))->y_orig;
	    zmm = (points[mmax - 1].z * dnorm) +
		((struct octdata *)(root->data))->z_orig;
	    wmm = points[mmax - 1].w + wmin;
	    /*      printf (" max. error = %f at point i = %d \n", errmax, mmax);
	       printf (" x(i) = %f  y(i) = %f \n", xmm, ymm);
	       printf (" z(i) = %f  w(i) = %f \n", zmm, wmm); */
	}
    }

    /* cv stuff */
    if (cv) {

	h = b[n1];		/* check this if h=b[0] used in 2d should be applied here */
	for (m = 1; m <= n_points; m++) {	/* number of points is already 1 less (skip_point) */
	    xx = points[m - 1].x - skip_point.x;
	    yy = points[m - 1].y - skip_point.y;
	    zz = points[m - 1].z - skip_point.z;

	    r2 = yy * yy + xx * xx + zz * zz;
	    if (r2 != 0.) {
		r = sqrt(r2);
		etar = (fi * r) / 2.;
		h = h + b[m] * crs(etar);
	    }
	}
	hz = h + wmin;
	ww = skip_point.w + wmin;
	err = hz - ww;
	xmm = (skip_point.x * dnorm) + xmn + current_region.west;
	ymm = (skip_point.y * dnorm) + ymn + current_region.south;
	zmm =
	    (skip_point.z * dnorm) / zmult + zmn / zmult +
	    current_region.bottom;

	if ((xmm >= xmn + current_region.west) &&
	    (xmm <= xmx + current_region.west) &&
	    (ymm >= ymn + current_region.south) &&
	    (ymm <= ymx + current_region.south) &&
	    (zmm >= zmn / zmult + current_region.bottom) &&
	    (zmm <= zmx / zmult + current_region.bottom))
	    inside = 1;
	else
	    inside = 0;

	if (inside == 1)
	    point_save(xmm, ymm, zmm, err);

    }				/* cv */


    return 1;
}
Example #5
0
int secpar_loop(int ngstc, int nszc, int i)
{
    double dnorm1, ro, dx2, dy2, dz2, grad1, grad2, slp, grad, oor1, oor2,
	curn, curm, curg, dxy2, dxz2, dyz2;
    double dg1, dg2, dg3, dg4, dg5, dg6, h11, h12, h22, h13, h23, h33,
	dm1, dm2, dm3, dm4, dm5, dm6, dnorm5;
    double gradmin;
    int bmask = 1;
    static int first_t = 1;

    ro = M_R2D;
    gradmin = 0.0;
    /*
       for (i = ngstc; i <= nszc; i++)
       { */
    /*      
       if(maskmap != NULL)
       {
       bmask = BM_get(bitmask, i, k);
       } */
    if (bmask == 1) {
	dx2 = adx[i] * adx[i];
	dy2 = ady[i] * ady[i];
	dz2 = adz[i] * adz[i];
	grad1 = dx2 + dy2;
	grad2 = dx2 + dy2 + dz2;
	grad = sqrt(grad2);	/* gradient */
	/* slope in %        slp = 100. * grad; */
	/* slope in degrees
	   slp = ro * atan (grad); */
	slp = atan(grad);
	if ((aspect1 != NULL) || (aspect2 != NULL)) {
	    if (grad <= gradmin) {
		oor1 = 0.;	/* horiz. angle */
		oor2 = 0.;	/* vertical angle */
	    }
	}

/***********aspect from r.slope.aspect, with adx, ady computed
	from interpol. function RST **************************/

	if (aspect1 != NULL) {
	    if (adx[i] == 0) {
		/*       if (ady[i] > 0) oor1 = M_PI / 2;
		   else oor1 = M_PI + M_PI / 2; */
		if (ady[i] > 0)
		    oor1 = 90.;
		else
		    oor1 = 270.;
	    }
	    else {
		/*                       oor1 = atan2(ady[i],adx[i]);
		   if(oor1 <= 0) oor1 = 2 * M_PI + oor1; */
		oor1 = ro * atan2(ady[i], adx[i]);
		if (oor1 <= 0)
		    oor1 = 360. + oor1;
	    }
	}

 /** vertical angle */
	if (aspect2 != NULL) {
	    if (adz[i] == 0) {
		oor2 = 0.;
	    }
	    else {
		/*                      oor2 = atan2( adz[i], sqrt(grad1) ); */
		oor2 = ro * atan2(adz[i], sqrt(grad1));
	    }
	}
	dnorm1 = sqrt(grad2 + 1.);
	dnorm5 = dnorm1 * dnorm1 * dnorm1 * dnorm1 * dnorm1;
	if (ncurv != NULL) {
	    dxy2 = 2. * adxy[i] * adx[i] * ady[i];
	    dxz2 = 2. * adxz[i] * adx[i] * adz[i];
	    dyz2 = 2. * adyz[i] * ady[i] * adz[i];
	    curn =
		-(adxx[i] * dx2 + dxy2 + dxz2 + dyz2 + adzz[i] * dz2 +
		  adyy[i] * dy2) / grad2;
	}
	if (gcurv != NULL) {
	    dg1 = -adxx[i] * adyy[i] * adzz[i];
	    dg2 = -adxy[i] * adxz[i] * adyz[i];
	    dg3 = -adxz[i] * adxy[i] * adyz[i];
	    dg4 = adyz[i] * adyz[i] * adxx[i];
	    dg5 = adxy[i] * adxy[i] * adzz[i];
	    dg6 = adxz[i] * adxz[i] * adyy[i];
	    curg = (dg1 + dg2 + dg3 + dg4 + dg5 + dg6) / dnorm5;
	}
	if (mcurv != NULL) {
	    h11 = -adxx[i] / dnorm1 + 2 * (1 + dx2);
	    h12 = -adxy[i] / dnorm1 + 2 * (adx[i] * ady[i]);
	    h22 = -adyy[i] / dnorm1 + 2 * (1 + dy2);
	    h13 = -adxz[i] / dnorm1 + 2 * (adx[i] * adz[i]);
	    h23 = -adyz[i] / dnorm1 + 2 * (ady[i] * adz[i]);
	    h33 = -adzz[i] / dnorm1 + 2 * (1 + dz2);
	    dm1 = h11 * h22 * h33;
	    dm2 = -h23 * h11 * h23;
	    dm3 = -h12 * h33 * h12;
	    dm4 = -h13 * h13 * h22;
	    dm5 = h12 * h23 * h13;
	    dm6 = h13 * h12 * h23;
	    curm = (dm1 + dm2 + dm3 + dm4 + dm5 + dm6) / (3. * (grad2 + 1.));
	}
	/*   temp = grad2 + 1.; */
	if (first_t) {
	    first_t = 0;
	    if (gradient != NULL)
		gmax = gmin = slp;
	    if (aspect1 != NULL)
		a1max = a1min = oor1;
	    if (aspect2 != NULL)
		a2max = a2min = oor2;
	    if (ncurv != NULL)
		c1max = c1min = curn;
	    if (gcurv != NULL)
		c2max = c2min = curg;
	    if (mcurv != NULL)
		c3max = c3min = curm;
	}

	if (gradient != NULL) {
	    gmin = amin1(gmin, slp);
	    gmax = amax1(gmax, slp);
	}
	if (aspect1 != NULL) {
	    a1min = amin1(a1min, oor1);
	    a1max = amax1(a1max, oor1);
	}
	if (aspect2 != NULL) {
	    a2min = amin1(a2min, oor2);
	    a2max = amax1(a2max, oor2);
	}
	if (ncurv != NULL) {
	    c1min = amin1(c1min, curn);
	    if (curn < 10.)
		c1max = amax1(c1max, curn);
	}
	if (gcurv != NULL) {
	    c2min = amin1(c2min, curg);
	    if (curg < 10.)
		c2max = amax1(c2max, curg);
	}
	if (mcurv != NULL) {
	    c3min = amin1(c3min, curm);
	    if (curn < 10.)
		c3max = amax1(c3max, curm);
	}

	if (gradient != NULL)
	    adx[i] = slp;
	if (aspect1 != NULL)
	    ady[i] = oor1 / ro;
	if (aspect2 != NULL)
	    adz[i] = oor2 / ro;
	if (ncurv != NULL)
	    adxx[i] = curn;	/* change of gradient */
	if (gcurv != NULL)
	    adyy[i] = curg;	/* Gaussian curvature */
	if (mcurv != NULL)
	    adxy[i] = curm;	/* Mean curvature */
	/*printf(" parametre grad %lf\n", slp); */
    }
    /*      } secapr loop */

    return 1;
}
Example #6
0
int
COGRR1(double x_or, double y_or, double z_or, int n_rows, int n_cols,
       int n_levs, int n_points, struct quadruple *points,
       struct point_3d skip_point)

/*C
   C       INTERPOLATION BY FUNCTIONAL METHOD : TPS + complete regul.
   c
 */
{
    int secpar_loop();
    static double *w2 = NULL;
    static double *wz2 = NULL;
    static double *wz1 = NULL;
    double amaxa;
    double stepix, stepiy, stepiz, RO, xx, yy, zz, xg, yg, zg, xx2;
    double wm, dx, dy, dz, dxx, dyy, dxy, dxz, dyz, dzz, h, bmgd1,
	bmgd2, etar, zcon, r, ww, wz, r2, hcell, zzcell2,
	etarcell, rcell, wwcell, zzcell;
    double x_crs,x_crsd,x_crsdd,x_crsdr2;
    int n1, k1, k2, k, i1, l, l1, n4, n5, m, i;
    int NGST, LSIZE, ngstc, nszc, ngstr, nszr, ngstl, nszl;
    int POINT();
    int ind, ind1;
    static int first_time_z = 1;
    off_t offset, offset1, offset2;
    int bmask = 1;
    static FCELL *cell = NULL;

    int cond1 = (gradient != NULL) || (aspect1 != NULL) || (aspect2 != NULL);
    int cond2 = (ncurv != NULL) || (gcurv != NULL) || (mcurv != NULL);

#define CEULER .57721566
    /*
       C
       c        character*32 fncdsm
       c normalization
       c
     */
    offset1 = nsizr * nsizc;

    stepix = ew_res / dnorm;
    stepiy = ns_res / dnorm;
    stepiz = tb_res / dnorm;

    if (!w2) {
	if (!(w2 = (double *)G_malloc(sizeof(double) * (KMAX2 + 1)))) {
	    clean();
	    G_fatal_error(_("Not enough memory for %s"), "w2");
	}
    }
    if (!wz2) {
	if (!(wz2 = (double *)G_malloc(sizeof(double) * (KMAX2 + 1)))) {
	    clean();
	    G_fatal_error(_("Not enough memory for %s"), "wz2");
	}
    }
    if (!wz1) {
	if (!(wz1 = (double *)G_malloc(sizeof(double) * (KMAX2 + 1)))) {
	    clean();
	    G_fatal_error(_("Not enough memory for %s"), "wz1");
	}
    }

    if (cell == NULL)
	cell = Rast_allocate_f_buf();

    for (i = 1; i <= n_points; i++) {
	points[i - 1].x = (points[i - 1].x - x_or) / dnorm;
	points[i - 1].y = (points[i - 1].y - y_or) / dnorm;
	points[i - 1].z = (points[i - 1].z - z_or) / dnorm;
    }
    if (cv) {
	skip_point.x = (skip_point.x - x_or) / dnorm;
	skip_point.y = (skip_point.y - y_or) / dnorm;
	skip_point.z = (skip_point.z - z_or) / dnorm;
    }
    n1 = n_points + 1;
    /*
       C
       C      GENERATION OF MATRIX
       C
       C      FIRST COLUMN
       C
     */
    A[1] = 0.;
    for (k = 1; k <= n_points; k++) {
	i1 = k + 1;
	A[i1] = 1.;
    }
    /*
       C
       C      OTHER COLUMNS
       C
     */
    RO = rsm;
    for (k = 1; k <= n_points; k++) {
	k1 = k * n1 + 1;
	k2 = k + 1;
	i1 = k1 + k;
	if (rsm < 0.) {		/*indicates variable smoothing */
	    A[i1] = points[k - 1].sm;
	}
	else {
	    A[i1] = RO;		/* constant smoothing */
	}
	for (l = k2; l <= n_points; l++) {
	    xx = points[k - 1].x - points[l - 1].x;
	    yy = points[k - 1].y - points[l - 1].y;
	    zz = points[k - 1].z - points[l - 1].z;
	    r = sqrt(xx * xx + yy * yy + zz * zz);
	    etar = (fi * r) / 2.;
	    if (etar == 0.) {
		/*              printf ("ident. points in segm.  \n");
		   printf ("x[%d]=%lf,x[%d]=%lf,y[%d]=%lf,y[%d]=%lf\n",
		   k - 1, points[k - 1].x, l - 1, points[l - 1].x, k - 1, points[k - 1].y, l - 1, points[l - 1].y); */
	    }
	    i1 = k1 + l;
	    A[i1] = crs(etar);
	}
    }
    /*
       C
       C       SYMMETRISATION
       C
     */
    amaxa = 1.;
    for (k = 1; k <= n1; k++) {
	k1 = (k - 1) * n1;
	k2 = k + 1;
	for (l = k2; l <= n1; l++) {
	    m = (l - 1) * n1 + k;
	    A[m] = A[k1 + l];
	    amaxa = amax1(A[m], amaxa);
	}
    }

    /*
       C        RIGHT SIDE
       C
     */
    n4 = n1 * n1 + 1;
    A[n4] = 0.;
    for (l = 1; l <= n_points; l++) {
	l1 = n4 + l;
	A[l1] = points[l - 1].w;
    }
    n5 = n1 * (n1 + 1);
    for (i = 1; i <= n5; i++)
	A[i] = A[i] / amaxa;

    /*
       SOLVING OF SYSTEM
     */

    if (LINEQS(n1, n1, 1, &NERROR, &DETERM)) {

	for (k = 1; k <= n_points; k++) {
	    l = n4 + k;
	    b[k] = A[l];
	}
	b[n_points + 1] = A[n4];

	POINT(n_points, points, skip_point);
	if (cv)
	    return 1;
	if (devi != NULL && sig1 == 1)
	    return 1;
	/*
	   C
	   C         INTERPOLATION   *  MOST INNER LOOPS !
	   C
	 */
	NGST = 1;
	LSIZE = 0;

	ngstc = (int)(x_or / ew_res + 0.5) + 1;
	nszc = ngstc + n_cols - 1;
	ngstr = (int)(y_or / ns_res + 0.5) + 1;
	nszr = ngstr + n_rows - 1;
	ngstl = (int)(z_or / tb_res + 0.5) + 1;
	nszl = ngstl + n_levs - 1;

	/*        fprintf(stderr," Progress percentage for each segment ..." ); */
	/*fprintf(stderr,"Before loops,ngstl = %d,nszl =%d\n",ngstl,nszl); */
	for (i = ngstl; i <= nszl; i++) {
	    /*fprintf(stderr,"level=%d\n",i); */
	    /*      G_percent(i, nszl, 2); */
	    offset = offset1 * (i - 1);	/* levels offset */
	    zg = (i - ngstl) * stepiz;
	    for (m = 1; m <= n_points; m++) {
		wz = zg - points[m - 1].z;
		wz1[m] = wz;
		wz2[m] = wz * wz;
	    }
	    for (k = ngstr; k <= nszr; k++) {
		yg = (k - ngstr) * stepiy;
		for (m = 1; m <= n_points; m++) {
		    wm = yg - points[m - 1].y;
		    w[m] = wm;
		    w2[m] = wm * wm;
		}
		if ((cellinp != NULL) && (cellout != NULL) && (i == ngstl))
		    Rast_get_f_row(fdcell, cell, n_rows_in - k);

		for (l = ngstc; l <= nszc; l++) {
		    LSIZE = LSIZE + 1;
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, l - 1, k - 1);	/*bug fix 02/03/00 jh */
		    xg = (l - ngstc) * stepix;
		    ww = 0.;
		    wwcell = 0.;
		    dx = 0.;
		    dy = 0.;
		    dz = 0.;
		    dxx = 0.;
		    dxy = 0.;
		    dxz = 0.;
		    dyy = 0.;
		    dyz = 0.;
		    dzz = 0.;
		    /* compute everything for area which is not masked out
		       and where cross_input map doesn't have nulls */
		    if (bmask == 1 && !(cell && Rast_is_f_null_value(&cell[l - 1]))) {
			h = b[n1];
			hcell = b[n1];
			for (m = 1; m <= n_points; m++) {
			    xx = xg - points[m - 1].x;
			    xx2 = xx * xx;
			    if ((cellinp != NULL) && (cellout != NULL) &&
				(i == ngstl)) {
				zcon = (double)(cell[l - 1] * zmult - z_or) - z_orig_in * zmult;	/* bug fix 02/03/00 jh */
				zcon = zcon / dnorm;
				zzcell = zcon - points[m - 1].z;
				zzcell2 = zzcell * zzcell;
				rcell = sqrt(xx2 + w2[m] + zzcell2);
				etarcell = (fi * rcell) / 2.;
				hcell = hcell + b[m] * crs(etarcell);
			    }
			    r2 = xx2 + w2[m] + wz2[m];
			    r = sqrt(r2);
			    etar = (fi * r) / 2.;

                            crs_full(
                              etar,fi,
                              &x_crs,
                              cond1?&x_crsd:NULL,
                              cond2?&x_crsdr2:NULL,
                              cond2?&x_crsdd:NULL
                            );
                            h = h + b[m] * x_crs;
                            if(cond1)
                            {
                                   bmgd1 = b[m] * x_crsd;
			    dx = dx + bmgd1 * xx;
			    dy = dy + bmgd1 * w[m];
			    dz = dz + bmgd1 * wz1[m];
                            }
                            if(cond2)
                            {
                                   bmgd2 = b[m] * x_crsdd;
                                   bmgd1 = b[m] * x_crsdr2;
			    dyy = dyy + bmgd2 * w2[m] + bmgd1 * w2[m];
			    dzz = dzz + bmgd2 * wz2[m] + bmgd1 * wz2[m];
			    dxy = dxy + bmgd2 * xx * w[m] + bmgd1 * xx * w[m];
                                   dxz = dxz + bmgd2 * xx * wz1[m] + bmgd1 * xx * wz1[m];
                                   dyz = dyz + bmgd2 * w[m] * wz1[m] + bmgd1 * w[m] * wz1[m];
                            }                            
			}
			ww = h + wmin;
			if ((cellinp != NULL) && (cellout != NULL) &&
			    (i == ngstl))
			    wwcell = hcell + wmin;
			az[l] = ww;
			if (first_time_z) {
			    first_time_z = 0;
			    zmaxac = zminac = ww;
			    if ((cellinp != NULL) && (cellout != NULL) &&
				(i == ngstl))
				zmaxacell = zminacell = wwcell;
			}
			zmaxac = amax1(ww, zmaxac);
			zminac = amin1(ww, zminac);
			if ((cellinp != NULL) && (cellout != NULL) &&
			    (i == ngstl)) {
			    zmaxacell = amax1(wwcell, zmaxacell);
			    zminacell = amin1(wwcell, zminacell);
			}
			if ((ww > wmax + 0.1 * (wmax - wmin))
			    || (ww < wmin - 0.1 * (wmax - wmin))) {
			    static int once = 0;

			    if (!once) {
				once = 1;
				fprintf(stderr, "WARNING:\n");
				fprintf(stderr,
					"Overshoot -- increase in tension suggested.\n");
				fprintf(stderr,
					"Overshoot occurs at (%d,%d,%d) cell\n",
					l, k, i);
				fprintf(stderr,
					"The w-value is %lf, wmin is %lf,wmax is %lf\n",
					ww, wmin, wmax);
			    }
			}
		    }		/* skip here if you are in masked area, ww should be 0 */
		    az[l] = ww;
		    adx[l] = dx;
		    ady[l] = dy;
		    adz[l] = dz;
		    /*              printf("\n %f", ww); */
		    adxx[l] = dxx;
		    adxy[l] = dxy;
		    adxz[l] = dxz;
		    adyy[l] = dyy;
		    adyz[l] = dyz;
		    adzz[l] = dzz;
		    if ((gradient != NULL) || (aspect1 != NULL) ||
			(aspect2 != NULL)
			|| (ncurv != NULL) || (gcurv != NULL) ||
			(mcurv != NULL))
			if (!(secpar_loop(ngstc, nszc, l))) {
			    clean();
			    G_fatal_error(_("Secpar_loop failed"));
			}
		    if ((cellinp != NULL) && (cellout != NULL) &&
			(i == ngstl)) {
			zero_array_cell[l - 1] = (FCELL) (wwcell);
		    }
		    if (outz != NULL) {
			zero_array1[l - 1] = (float)(az[l] * sciz);
		    }
		    if (gradient != NULL) {
			zero_array2[l - 1] = (float)(adx[l]);
		    }
		    if (aspect1 != NULL) {
			zero_array3[l - 1] = (float)(ady[l]);
		    }
		    if (aspect2 != NULL) {
			zero_array4[l - 1] = (float)(adz[l]);
		    }
		    if (ncurv != NULL) {
			zero_array5[l - 1] = (float)(adxx[l]);
		    }
		    if (gcurv != NULL) {
			zero_array6[l - 1] = (float)(adyy[l]);
		    }
		    if (mcurv != NULL) {
			zero_array7[l - 1] = (float)(adxy[l]);
		    }
		}		/* columns */
		ind = nsizc * (k - 1) + (ngstc - 1);
		ind1 = ngstc - 1;
		offset2 = offset + ind;	/* rows*cols offset */

		if ((cellinp != NULL) && (cellout != NULL) && (i == ngstl)) {
		    G_fseek(Tmp_fd_cell, ((off_t)ind * sizeof(FCELL)), 0);
		    if (!
			(fwrite
			 (zero_array_cell + ind1, sizeof(FCELL),
			  nszc - ngstc + 1, Tmp_fd_cell))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (outz != NULL) {
		    G_fseek(Tmp_fd_z, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array1 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_z))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (gradient != NULL) {
		    G_fseek(Tmp_fd_dx, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array2 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_dx))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (aspect1 != NULL) {
		    G_fseek(Tmp_fd_dy, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array3 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_dy))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (aspect2 != NULL) {
		    G_fseek(Tmp_fd_dz, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array4 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_dz))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (ncurv != NULL) {
		    G_fseek(Tmp_fd_xx, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array5 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_xx))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (gcurv != NULL) {
		    G_fseek(Tmp_fd_yy, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array6 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_yy))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (mcurv != NULL) {
		    G_fseek(Tmp_fd_xy, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array7 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_xy))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}

	    }
	}
    }				/* falls here if LINEQS() returns 0 */
    /*    total++; */
    /*fprintf(stderr,"wminac=%lf,wmaxac=%lf\n",zminac,zmaxac); */
    return 1;

}
Example #7
0
int INPUT(struct Map_info *In, char *column, char *scol, char *wheresql)
{
    struct quadruple *point;
    double x, y, z, w, nz = 0., sm;
    double c1, c2, c3, c4, c5, c6, nsg;
    int i, j, k = 0, a, irev, cfmask;
    int ddisk = 0;
    double deltx, delty, deltz;
    int first_time = 1;
    CELL *cellmask;
    const char *mapsetm;
    char buf[500];
    int cat, intval;
    struct field_info *Fi;
    dbDriver *Driver;
    dbCatValArray cvarr, sarray;
    int nrec, nrec1, ctype, sctype;
    struct line_pnts *Points;
    struct line_cats *Cats;

    OUTRANGE = 0;
    NPOINT = 0;
    dmin = dmin * dmin;

    /* Read attributes */
    db_CatValArray_init(&cvarr);
    if (scol != NULL)
	db_CatValArray_init(&sarray);
    Fi = Vect_get_field(In, 1);
    if (Fi == NULL)
	G_fatal_error(_("Unable to get layer info for vector map"));

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

    nrec =
	db_select_CatValArray(Driver, Fi->table, Fi->key, column, wheresql,
			      &cvarr);
    ctype = cvarr.ctype;
    G_debug(3, "nrec = %d", nrec);

    if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE)
	G_fatal_error(_("Column type of wcolumn is not supported (must be integer or double)"));

    if (nrec < 0)
	G_fatal_error(_("Unable to select data from table"));
    G_message("%d records selected from table", nrec);

    if (scol != NULL) {

	nrec1 =
	    db_select_CatValArray(Driver, Fi->table, Fi->key, scol, wheresql,
				  &sarray);
	sctype = cvarr.ctype;

	if (sctype == -1)
	    G_fatal_error(_("Cannot read column type of smooth column"));
	if (sctype == DB_C_TYPE_DATETIME)
	    G_fatal_error
		(_("Column type of smooth column (datetime) is not supported"));
	if (sctype != DB_C_TYPE_INT && sctype != DB_C_TYPE_DOUBLE)
	    G_fatal_error(_("Column type of smooth column is not supported (must be integer or double)"));
    }

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    Vect_rewind(In);

    while (1) {
	int ival, type, ret;

	if (-1 == (type = Vect_read_next_line(In, Points, Cats)))
	    G_fatal_error(_("Unable to read vector map"));

	if (type == -2)
	    break;		/* EOF */

	if (!(type & GV_POINTS))
	    continue;

	Vect_cat_get(Cats, 1, &cat);
	if (cat < 0) {
	    G_warning(_("Point without category"));
	    continue;
	}

	x = Points->x[0];
	y = Points->y[0];
	z = Points->z[0];

	if (ctype == DB_C_TYPE_INT) {
	    ret = db_CatValArray_get_value_int(&cvarr, cat, &ival);
	    w = ival;
	}
	else {			/* DB_C_TYPE_DOUBLE */
	    ret = db_CatValArray_get_value_double(&cvarr, cat, &w);
	}

	if (ret != DB_OK) {
	    if (wheresql != NULL)
		/* G_message(_("Database record for cat %d not used due to SQL statement")); */
		/* do nothing in this case to not confuse user. Or implement second cat list */
		;
	    else
		G_warning(_("No record for category %d in table <%s>"), cat,
			  Fi->table);
	    continue;
	}

	if (rsm == -1 && scol != NULL) {

	    if (sctype == DB_C_TYPE_INT) {
		ret = db_CatValArray_get_value_int(&sarray, cat, &intval);
		sm = intval;
	    }
	    else {		/* DB_C_TYPE_DOUBLE */
		ret = db_CatValArray_get_value_double(&sarray, cat, &sm);
	    }
	}


	G_debug(3, "%f %f %f %f", x, y, z, w);

	k++;
	w = w * wmult;
	z = z * zmult;
	c1 = x - ((struct octdata *)(root->data))->x_orig;
	c2 = ((struct octdata *)(root->data))->x_orig +
	    ((struct octdata *)(root->data))->n_cols * ew_res - x;
	c3 = y - ((struct octdata *)(root->data))->y_orig;
	c4 = ((struct octdata *)(root->data))->y_orig +
	    ((struct octdata *)(root->data))->n_rows * ns_res - y;
	c5 = z - ((struct octdata *)(root->data))->z_orig;
	c6 = ((struct octdata *)(root->data))->z_orig +
	    ((struct octdata *)(root->data))->n_levs * tb_res - z;

	if (!
	    ((c1 >= 0) && (c2 >= 0) && (c3 >= 0) && (c4 >= 0) && (c5 >= 0) &&
	     (c6 >= 0))) {
	    if (!OUTRANGE) {
		G_warning(_("Some points outside of region -- will ignore..."));
	    }
	    OUTRANGE++;
	}
	else {
	    if (!(point = point_new(x, y, z, w, sm))) {
		clean();
		G_fatal_error(_("Cannot allocate memory for point"));
	    }

	    a = OT_insert_oct(point, root);
	    if (a == 0) {
		NPOINT++;
	    }
	    if (a < 0) {
		G_warning(_("Can't insert %lf,%lf,%lf,%lf,%lf a=%d"), x, y, z,
			  w, sm, a);
		return -1;
	    }

	    if (first_time) {
		first_time = 0;
		xmin = x;
		ymin = y;
		zmin = z;
		wmin = w;
		xmax = x;
		ymax = y;
		zmax = z;
		wmax = w;
	    }

	    xmin = amin1(xmin, x);
	    ymin = amin1(ymin, y);
	    zmin = amin1(zmin, z);
	    wmin = amin1(wmin, w);
	    xmax = amax1(xmax, x);
	    ymax = amax1(ymax, y);
	    zmax = amax1(zmax, z);
	    wmax = amax1(wmax, w);
	}
    }				/* while */

    db_CatValArray_free(&cvarr);

    c1 = xmin - ((struct octdata *)(root->data))->x_orig;
    c2 = ((struct octdata *)(root->data))->x_orig +
	((struct octdata *)(root->data))->n_cols * ew_res - xmax;
    c3 = ymin - ((struct octdata *)(root->data))->y_orig;
    c4 = ((struct octdata *)(root->data))->y_orig +
	((struct octdata *)(root->data))->n_rows * ns_res - ymax;
    c5 = zmin - ((struct octdata *)(root->data))->z_orig;
    c6 = ((struct octdata *)(root->data))->z_orig +
	((struct octdata *)(root->data))->n_levs * tb_res - zmax;

    if ((c1 > 5 * ew_res) || (c2 > 5 * ew_res) ||
	(c3 > 5 * ns_res) || (c4 > 5 * ns_res) ||
	(c5 > 5 * tb_res) || (c6 > 5 * tb_res)) {
	static int once = 0;

	if (!once) {
	    once = 1;
	    G_warning(_("Strip exists with insufficient data"));
	}
    }

    nz = wmin;
    totsegm = translate_oct(root, ((struct octdata *)(root->data))->x_orig,
			    ((struct octdata *)(root->data))->y_orig,
			    ((struct octdata *)(root->data))->z_orig, nz);
    if (!totsegm) {
	clean();
	G_fatal_error(_("Zero segments!"));
    }

    ((struct octdata *)(root->data))->x_orig = 0;
    ((struct octdata *)(root->data))->y_orig = 0;
    ((struct octdata *)(root->data))->z_orig = 0;	/* was commented out */

    if (outz != NULL)
	ddisk += disk;
    if (gradient != NULL)
	ddisk += disk;
    if (aspect1 != NULL)
	ddisk += disk;
    if (ncurv != NULL)
	ddisk += disk;
    if (gcurv != NULL)
	ddisk += disk;
    if (mcurv != NULL)
	ddisk += disk;

    G_message
	("Processing all selected output files will require %d bytes of disk space for temp files",
	 ddisk);

    /*
       fprintf(stderr,"xmin=%lf,xmax=%lf,ymin=%lf,ymax=%lf,zmin=%lf,zmax=%lf,wmin=%lf,wmax=%lf\n",xmin,xmax,ymin,ymax,zmin,zmax,wmin,wmax);
     */

    fprintf(stderr, "\n");
    if (OUTRANGE > 0)
	G_warning
	    (_("There are points outside specified 2D/3D region--ignored %d points (total points: %d)"),
	     OUTRANGE, k);
    if (NPOINT > 0)
	G_warning
	    (_("Points are more dense than specified 'DMIN'--ignored %d points (remain %d)"),
	     NPOINT, k - NPOINT);
    NPOINT = k - NPOINT - NPT - OUTRANGE;
    if (NPOINT < KMIN) {
	if (NPOINT != 0) {
	    G_warning
		(_("%d points given for interpolation (after thinning) is less than given NPMIN=%d"),
		 NPOINT, KMIN);
	    KMIN = NPOINT;
	}
	else {
	    fprintf(stderr, "ERROR: zero points in the given region!\n");
	    return -1;
	}
    }
    if (NPOINT > KMAXPOINTS && KMIN <= KMAX) {
	fprintf(stderr,
		"ERROR: segmentation parameters set to invalid values: npmin = %d, segmax = %d \n",
		KMIN, KMAX);
	fprintf(stderr,
		"for smooth connection of segments, npmin > segmax (see manual) \n");
	return -1;
    }

    if (NPOINT < KMAXPOINTS && KMAX != KMAXPOINTS)
	G_warning
	    (_("There is less than %d points for interpolation, no segmentation is necessary, to run the program faster, set segmax=%d (see manual)"),
	     KMAXPOINTS, KMAXPOINTS);

    deltx = xmax - xmin;
    delty = ymax - ymin;
    deltz = zmax - zmin;
    nsg = (double)NPOINT / (double)KMIN;
    dnorm = deltx * delty * deltz / nsg;
    nsg = 3.0;
    nsg = 1. / nsg;
    dnorm = pow(dnorm, nsg);
    /* DEBUG
       if (fd4 != NULL)
       fprintf (fd4, "deltx,delty %f %f \n", deltx, delty);
     */
    nsizc = current_region.cols;	/* ((int)(deltx/ew_res))+1;  */
    nsizr = current_region.rows;	/* ((int)(delty/ns_res))+1;   */
    NPT = k;
    x0utm = 0.;
    y0utm = 0.;
    z0utm = 0.;

  /** create a bitmap mask from given raster map **/
    if (maskmap != NULL) {
	mapsetm = G_find_raster2(maskmap, "");
	if (!mapsetm) {
	    clean();
	    G_fatal_error(_("Mask raster map [%s] not found"), maskmap);
	}
	bitmask = BM_create(nsizc, nsizr);
	cellmask = Rast_allocate_c_buf();
	cfmask = Rast_open_old(maskmap, mapsetm);
	for (i = 0; i < nsizr; i++) {
	    irev = nsizr - i - 1;
	    Rast_get_c_row(cfmask, cellmask, i);
	    for (j = 0; j < nsizc; j++) {
		if ((cellmask[j] == 0) || Rast_is_c_null_value(&cellmask[j]))
		    BM_set(bitmask, j, irev, 0);
		else
		    BM_set(bitmask, j, irev, 1);
	    }
	}
	G_message(_("Bitmap mask created"));
    }

    return 1;
}
Example #8
0
int IL_resample_output_2d(struct interp_params *params, double zmin, double zmax,	/* min,max input z-values */
			  double zminac, double zmaxac,	/* min,max interpolated values */
			  double c1min, double c1max, double c2min, double c2max, double gmin, double gmax, double ertot,	/* total interplating func. error */
			  char *input,	/* input file name */
			  double *dnorm, struct Cell_head *outhd,	/* Region with desired resolution */
			  struct Cell_head *winhd,	/* Current region */
			  char *smooth, int n_points)

/*
 * Creates output files as well as history files  and color tables for
 * them.
 */
{
    FCELL *cell1;		/* cell buffer */
    int cf1 = 0, cf2 = 0, cf3 = 0, cf4 = 0, cf5 = 0, cf6 = 0;	/* cell file descriptors */
    int nrows, ncols;		/* current region rows and columns */
    int i;			/* loop counter */
    char *mapset;
    float dat1, dat2;
    struct Colors colors, colors2;
    double value1, value2;
    struct History hist, hist1, hist2, hist3, hist4, hist5;
    struct _Color_Rule_ *rule;
    char *maps, *type;
    int cond1, cond2;

    cond2 = ((params->pcurv != NULL) ||
	     (params->tcurv != NULL) || (params->mcurv != NULL));
    cond1 = ((params->slope != NULL) || (params->aspect != NULL) || cond2);

    /* change region to output cell file region */
    fprintf(stderr,
	    "Temporarily changing the region to desired resolution...\n");
    if (G_set_window(outhd) < 0) {
	fprintf(stderr, "Cannot set region to output region!\n");
	return -1;
    }
    mapset = G_mapset();

    cell1 = G_allocate_f_raster_buf();

    if (params->elev != NULL) {
	cf1 = G_open_fp_cell_new(params->elev);
	if (cf1 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n", params->elev);
	    return -1;
	}
    }

    if (params->slope != NULL) {
	cf2 = G_open_fp_cell_new(params->slope);
	if (cf2 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->slope);
	    return -1;
	}
    }

    if (params->aspect != NULL) {
	cf3 = G_open_fp_cell_new(params->aspect);
	if (cf3 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->aspect);
	    return -1;
	}
    }

    if (params->pcurv != NULL) {
	cf4 = G_open_fp_cell_new(params->pcurv);
	if (cf4 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->pcurv);
	    return -1;
	}
    }

    if (params->tcurv != NULL) {
	cf5 = G_open_fp_cell_new(params->tcurv);
	if (cf5 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->tcurv);
	    return -1;
	}
    }

    if (params->mcurv != NULL) {
	cf6 = G_open_fp_cell_new(params->mcurv);
	if (cf6 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->mcurv);
	    return -1;
	}
    }

    nrows = outhd->rows;
    if (nrows != params->nsizr) {
	fprintf(stderr, "first change your rows number(%d) to %d!\n",
		nrows, params->nsizr);
	return -1;
    }

    ncols = outhd->cols;
    if (ncols != params->nsizc) {
	fprintf(stderr, "first change your rows number(%d) to %d!\n",
		ncols, params->nsizc);
	return -1;
    }

    if (params->elev != NULL) {
	fseek(params->Tmp_fd_z, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_z, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_z);
	    if (G_put_f_raster_row(cf1, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->slope != NULL) {
	fseek(params->Tmp_fd_dx, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_dx, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_dx);
	    /*
	     * for (ii==0;ii<params->nsizc;ii++) { fprintf(stderr,"ii=%d ",ii);
	     * fprintf(stderr,"%f ",cell1[ii]); }
	     * fprintf(stderr,"params->nsizc=%d \n",params->nsizc);
	     */
	    if (G_put_f_raster_row(cf2, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->aspect != NULL) {
	fseek(params->Tmp_fd_dy, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_dy, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_dy);
	    if (G_put_f_raster_row(cf3, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->pcurv != NULL) {
	fseek(params->Tmp_fd_xx, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_xx, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_xx);
	    if (G_put_f_raster_row(cf4, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->tcurv != NULL) {
	fseek(params->Tmp_fd_yy, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_yy, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_yy);
	    if (G_put_f_raster_row(cf5, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->mcurv != NULL) {
	fseek(params->Tmp_fd_xy, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_xy, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_xy);
	    if (G_put_f_raster_row(cf6, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (cf1)
	G_close_cell(cf1);
    if (cf2)
	G_close_cell(cf2);
    if (cf3)
	G_close_cell(cf3);
    if (cf4)
	G_close_cell(cf4);
    if (cf5)
	G_close_cell(cf5);
    if (cf6)
	G_close_cell(cf6);

    /* write colormaps and history for output cell files */
    /* colortable for elevations */
    maps = G_find_file("cell", input, "");

    if (params->elev != NULL) {
	if (maps == NULL) {
	    fprintf(stderr, "file [%s] not found\n", input);
	    return -1;
	}
	G_init_colors(&colors2);
	/*
	 * G_mark_colors_as_fp(&colors2);
	 */

	if (G_read_colors(input, maps, &colors) >= 0) {
	    if (colors.modular.rules) {
		rule = colors.modular.rules;

		while (rule->next)
		    rule = rule->next;

		for (; rule; rule = rule->prev) {
		    value1 = rule->low.value * params->zmult;
		    value2 = rule->high.value * params->zmult;
		    G_add_modular_d_raster_color_rule(&value1, rule->low.red,
						      rule->low.grn,
						      rule->low.blu, &value2,
						      rule->high.red,
						      rule->high.grn,
						      rule->high.blu,
						      &colors2);
		}
	    }

	    if (colors.fixed.rules) {
		rule = colors.fixed.rules;

		while (rule->next)
		    rule = rule->next;

		for (; rule; rule = rule->prev) {
		    value1 = rule->low.value * params->zmult;
		    value2 = rule->high.value * params->zmult;
		    G_add_d_raster_color_rule(&value1, rule->low.red,
					      rule->low.grn, rule->low.blu,
					      &value2, rule->high.red,
					      rule->high.grn, rule->high.blu,
					      &colors2);
		}
	    }

	    maps = NULL;
	    maps = G_find_file("cell", params->elev, "");
	    if (maps == NULL) {
		fprintf(stderr, "file [%s] not found\n", params->elev);
		return -1;
	    }

	    if (G_write_colors(params->elev, maps, &colors2) < 0) {
		fprintf(stderr, "Cannot write color table\n");
		return -1;
	    }
	    G_quantize_fp_map_range(params->elev, mapset,
				    zminac - 0.5, zmaxac + 0.5,
				    (CELL) (zminac - 0.5),
				    (CELL) (zmaxac + 0.5));
	}
	else
	    fprintf(stderr,
		    "No color table for input file -- will not create color table\n");
    }

    /* colortable for slopes */
    if (cond1 & (!params->deriv)) {
	G_init_colors(&colors);
	G_add_color_rule(0, 255, 255, 255, 2, 255, 255, 0, &colors);
	G_add_color_rule(2, 255, 255, 0, 5, 0, 255, 0, &colors);
	G_add_color_rule(5, 0, 255, 0, 10, 0, 255, 255, &colors);
	G_add_color_rule(10, 0, 255, 255, 15, 0, 0, 255, &colors);
	G_add_color_rule(15, 0, 0, 255, 30, 255, 0, 255, &colors);
	G_add_color_rule(30, 255, 0, 255, 50, 255, 0, 0, &colors);
	G_add_color_rule(50, 255, 0, 0, 90, 0, 0, 0, &colors);

	if (params->slope != NULL) {
	    maps = NULL;
	    maps = G_find_file("cell", params->slope, "");
	    if (maps == NULL) {
		fprintf(stderr, "file [%s] not found\n", params->slope);
		return -1;
	    }
	    G_write_colors(params->slope, maps, &colors);
	    G_quantize_fp_map_range(params->slope, mapset, 0., 90., 0, 90);

	    type = "raster";
	    G_short_history(params->slope, type, &hist1);
	    if (params->elev != NULL)
		sprintf(hist1.edhist[0], "The elevation map is %s",
			params->elev);

	    sprintf(hist1.datsrc_1, "raster map %s", input);
	    hist1.edlinecnt = 1;

	    G_write_history(params->slope, &hist1);
	}

	/* colortable for aspect */
	G_init_colors(&colors);
	G_add_color_rule(0, 255, 255, 255, 0, 255, 255, 255, &colors);
	G_add_color_rule(1, 255, 255, 0, 90, 0, 255, 0, &colors);
	G_add_color_rule(90, 0, 255, 0, 180, 0, 255, 255, &colors);
	G_add_color_rule(180, 0, 255, 255, 270, 255, 0, 0, &colors);
	G_add_color_rule(270, 255, 0, 0, 360, 255, 255, 0, &colors);

	if (params->aspect != NULL) {
	    maps = NULL;
	    maps = G_find_file("cell", params->aspect, "");
	    if (maps == NULL) {
		fprintf(stderr, "file [%s] not found\n", params->aspect);
		return -1;
	    }
	    G_write_colors(params->aspect, maps, &colors);
	    G_quantize_fp_map_range(params->aspect, mapset, 0., 360., 0, 360);

	    type = "raster";
	    G_short_history(params->aspect, type, &hist2);
	    if (params->elev != NULL)
		sprintf(hist2.edhist[0], "The elevation map is %s",
			params->elev);

	    sprintf(hist2.datsrc_1, "raster map %s", input);
	    hist2.edlinecnt = 1;

	    G_write_history(params->aspect, &hist2);
	}

	/* colortable for curvatures */
	if (cond2) {
	    G_init_colors(&colors);

	    dat1 = (FCELL) amin1(c1min, c2min);
	    dat2 = (FCELL) - 0.01;

	    G_add_f_raster_color_rule(&dat1, 50, 0, 155,
				      &dat2, 0, 0, 255, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) - 0.001;
	    G_add_f_raster_color_rule(&dat1, 0, 0, 255,
				      &dat2, 0, 127, 255, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) - 0.00001;
	    G_add_f_raster_color_rule(&dat1, 0, 127, 255,
				      &dat2, 0, 255, 255, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.00;
	    G_add_f_raster_color_rule(&dat1, 0, 255, 255,
				      &dat2, 200, 255, 200, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.00001;
	    G_add_f_raster_color_rule(&dat1, 200, 255, 200,
				      &dat2, 255, 255, 0, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.001;
	    G_add_f_raster_color_rule(&dat1, 255, 255, 0,
				      &dat2, 255, 127, 0, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.01;
	    G_add_f_raster_color_rule(&dat1, 255, 127, 0,
				      &dat2, 255, 0, 0, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) amax1(c1max, c2max);
	    G_add_f_raster_color_rule(&dat1, 255, 0, 0,
				      &dat2, 155, 0, 20, &colors);
	    maps = NULL;
	    if (params->pcurv != NULL) {
		maps = G_find_file("cell", params->pcurv, "");
		if (maps == NULL) {
		    fprintf(stderr, "file [%s] not found\n", params->pcurv);
		    return -1;
		}
		G_write_colors(params->pcurv, maps, &colors);

		fprintf(stderr, "color map written\n");

		G_quantize_fp_map_range(params->pcurv, mapset,
					dat1, dat2,
					(CELL) (dat1 * MULT),
					(CELL) (dat2 * MULT));
		type = "raster";
		G_short_history(params->pcurv, type, &hist3);
		if (params->elev != NULL)
		    sprintf(hist3.edhist[0], "The elevation map is %s",
			    params->elev);

		sprintf(hist3.datsrc_1, "raster map %s", input);
		hist3.edlinecnt = 1;

		G_write_history(params->pcurv, &hist3);
	    }

	    if (params->tcurv != NULL) {
		maps = NULL;
		maps = G_find_file("cell", params->tcurv, "");
		if (maps == NULL) {
		    fprintf(stderr, "file [%s] not found\n", params->tcurv);
		    return -1;
		}
		G_write_colors(params->tcurv, maps, &colors);
		G_quantize_fp_map_range(params->tcurv, mapset,
					dat1, dat2, (CELL) (dat1 * MULT),
					(CELL) (dat2 * MULT));

		type = "raster";
		G_short_history(params->tcurv, type, &hist4);
		if (params->elev != NULL)
		    sprintf(hist4.edhist[0], "The elevation map is %s",
			    params->elev);

		sprintf(hist4.datsrc_1, "raster map %s", input);
		hist4.edlinecnt = 1;

		G_write_history(params->tcurv, &hist4);
	    }

	    if (params->mcurv != NULL) {
		maps = NULL;
		maps = G_find_file("cell", params->mcurv, "");
		if (maps == NULL) {
		    fprintf(stderr, "file [%s] not found\n", params->mcurv);
		    return -1;
		}
		G_write_colors(params->mcurv, maps, &colors);
		G_quantize_fp_map_range(params->mcurv, mapset,
					dat1, dat2,
					(CELL) (dat1 * MULT),
					(CELL) (dat2 * MULT));

		type = "raster";
		G_short_history(params->mcurv, type, &hist5);
		if (params->elev != NULL)
		    sprintf(hist5.edhist[0], "The elevation map is %s",
			    params->elev);

		sprintf(hist5.datsrc_1, "raster map %s", input);
		hist5.edlinecnt = 1;

		G_write_history(params->mcurv, &hist5);
	    }
	}
    }

    if (params->elev != NULL) {
	maps = G_find_file("cell", params->elev, "");
	if (maps == NULL) {
	    fprintf(stderr, "file [%s] not found \n", params->elev);
	    return -1;
	}
	G_short_history(params->elev, "raster", &hist);

	if (smooth != NULL)
	    sprintf(hist.edhist[0], "tension=%f, smoothing=%s",
		    params->fi * 1000. / (*dnorm), smooth);
	else
	    sprintf(hist.edhist[0], "tension=%f",
		    params->fi * 1000. / (*dnorm));
	sprintf(hist.edhist[1], "dnorm=%f, zmult=%f", *dnorm, params->zmult);
	sprintf(hist.edhist[2], "KMAX=%d, KMIN=%d, errtotal=%f", params->kmax,
		params->kmin, sqrt(ertot / n_points));
	sprintf(hist.edhist[3], "zmin_data=%f, zmax_data=%f", zmin, zmax);
	sprintf(hist.edhist[4], "zmin_int=%f, zmax_int=%f", zminac, zmaxac);

	sprintf(hist.datsrc_1, "raster map %s", input);

	hist.edlinecnt = 5;

	G_write_history(params->elev, &hist);
    }

    /* change region to initial region */
    fprintf(stderr, "Changing the region back to initial...\n");
    if (G_set_window(winhd) < 0) {
	fprintf(stderr, "Cannot set region to back to initial region!\n");
	return -1;
    }

    return 1;
}