/Users/huttone/Devel/sedflux-new/sedflux/trunk/ew/hydrotrend/hydrotrend.c

Go to the documentation of this file.
00001 /*
00002  *  HydroTrend.c
00003  *
00004  *  Improved version of HydroTrend (River)
00005  *  Main program, controls flow, counts years...
00006  *  Converted to C, streamlined the code ...
00007  *  See the file FLOWCHART for code details.
00008  *
00009  *  Author:    M.D. Morehead (June 1998)
00010  *  Author2:   S.D. Peckham  (September 2001)
00011  *  Author3:   A.J. Kettner (August-October 2002) (February-April 2003)
00012  *
00013  * 
00014  * Variable             Def.Location    Type            Units   Usage
00015  * --------             ------------    ----            -----   -----
00016  * **argv               HydroTrend.c    char            -               command line string capture variable
00017  * argc                 HydroTrend.c    int                     -               command line word counter
00018  * err                  various                 int                     -               error flag, halts program
00019  * dumdbl               various                 double          -               temporary double
00020  * i                    various         int                     -               temporary loop counter
00021  * ii                   various                 int                     -               temporary loop counter
00022  * jj                   various                 int                     -               temporary loop counter
00023  * setstartmeanQandQs HydroParams.h int         -               temporary loop counter
00024  * logarea              HydroTrend.c    double          m^2             log10 of the basin area
00025  * lyear                HydroTrend.c    int                     yr              last year of an epoch
00026  * maxnran              HydroTrend.c    int                     -               max # of random number used/year
00027  * pst[TMLEN]   HydroTrend.c    char            -               time stamp
00028  * Qgrandtotaltot HydroTrend.c  double          m^3/s   discharge for all run
00029  * Qgrandtotalperepoch HydroTrend.c double      m^3/s   discharge per epoch
00030  * Qpeakmax             HydroTrend.c    double          m^3/s   all time max. peak for all run
00031  * Qsbarnewtot  HydroTrend.c    double          kg/s    total of all Qsbarnew's
00032  * Qsgrandtotaltot HydroTrend.c double          kg/s    total of all Qsbrandtotal's
00033  * tloc                 HydroTrend.c    struct          -               time stamp structure
00034  * tm timept    HydroTrend.c    struct          -               time stamp structure
00035  *
00036  */
00037 
00038 #include "hydrofree_mem.h"
00039 #include "hydroclimate.h"
00040 #include "hydroinout.h"
00041 #include "hydroparams.h"
00042 #include "hydrotimeser.h"
00043 #include "hydroalloc_mem.h"
00044 #include "hydroreadclimate.h"
00045 #include "hydrotrend.h"
00046 #include <stdlib.h>
00047 #include <time.h>
00048 #include <string.h>
00049 
00050 /*---------------------
00051  *  Start the program
00052  *---------------------*/
00053 int main(int argc,char **argv)
00054 {
00055 
00056 /*-------------------
00057  *  Local Variables
00058  *-------------------*/
00059 char    pst[TMLEN];
00060 time_t  tloc;
00061 struct  tm *timeptr;
00062 int     err, ii, lyear, maxnran, verbose,p,k, x;
00063 double  logarea;
00064 long totaldays;
00065 gw_rainfall_etc* gw_rain;
00066 
00067 /*------------------------
00068  *  Initialize Variables
00069  *------------------------*/
00070 err             = 0;
00071 verbose         = 0;
00072 maxnran         = 0;
00073 maxerr          = 0.0;
00074 totalmass       = 0.0;
00075 globalparflag   = 0;
00076 Qgrandtotaltot  = 0.0;
00077 Qsgrandtotaltot = 0.0;
00078 TEtot                   = 0.0;
00079 yeartot                 = 0.0;
00080 gw_rain = (gw_rainfall_etc*)malloc(sizeof(gw_rainfall_etc));
00081 
00082 /*----------------------
00083  *  Get the start time
00084  *----------------------*/
00085 time( &tloc );
00086 timeptr = localtime(&tloc);
00087 
00088 /*--------------------------------
00089  *  Set the hardwired parameters
00090  *--------------------------------*/
00091 if (verbose) printf("Setting hardwired parameters... \n");
00092 err = hydrosetparams();
00093 if (err) {
00094     fprintf( stderr, " ERROR in HydroSetParams: HydroTrend Aborted \n\n" );
00095     exit(1);
00096 }
00097 
00098 /*-----------------------------------------------------------------
00099  *  Check the command line input; get file name or directory name
00100  *-----------------------------------------------------------------*/
00101 if (verbose) printf("check command line parameters... \n");
00102 err = hydrocommandline(&argc, argv);
00103 if (err) {
00104     fprintf( stderr, " ERROR in HydroCommandLine: HydroTrend Aborted \n\n" );
00105     exit(1);
00106 }
00107 
00108 /*--------------------------------------------
00109  *  Security Check, check input files on any
00110  *  characters which are not allowed.
00111  *  Set pathnames right for web directories.
00112  *--------------------------------------------*/
00113 if (webflag == 1){
00114     if (verbose) printf("Checking input files for security reasons... \n");
00115     err = hydrosecurityinputcheck();
00116     if (err) {
00117         fprintf(stderr, "  Error in HydroSecurityInputCheck: Unable to continue due to security reasons.\n");
00118         fprintf(stderr, "    The program found %d character(s) which you are not allowed to use.\n",err);
00119         fprintf(stderr, "    Get ride of the following characters and try it again.\n");
00120         for (ii=0; ii<err; ii++)
00121             fprintf(stderr, "    %c\n",chrdump[ii]);
00122         fprintf(stderr, "    program aborted. \n");
00123         fclose(fidinput);
00124         for (ep=0; ep<nepochs; ep++ )
00125                 fclose(fidhyps[ep]);
00126         exit(1);
00127     }
00128 }
00129 
00130 /*--------------------------------
00131  *  Read the main input file.
00132  *  This reads all of the epochs,
00133  *  at the very begining
00134  *--------------------------------*/
00135 if (verbose) printf("Reading input data from: HYDRO.IN... \n");
00136 err = hydroreadinput();
00137 if (err) {
00138     fprintf( stderr, " ERROR in HydroReadInput: HydroTrend Aborted \n\n" );
00139     exit(1);
00140 }
00141 
00142 /*---------------------------------------
00143  *  Set the output path name + filename
00144  *---------------------------------------*/
00145 strcpy(startname,directory);
00146 if (argc == 3) strcat(startname,commandlinearg[2]);
00147 strcat(startname,commandlinearg[1]);
00148 
00149 /*---------------------
00150  *  Open the log file
00151  *---------------------*/
00152 if (verbose) printf("Opening the log file (to append)... \n");
00153 strcpy(ffnamelog,startname);
00154 strcat(ffnamelog,fnamelog);
00155 if ((fidlog = fopen(ffnamelog,"w+")) == NULL) {
00156     printf("  HydroTrend WARNING: Unable to open the log file %s \n", ffnamelog);
00157     printf("     non-fatal error, continuing. \n\n");
00158 }
00159 
00160 /*--------------------------------
00161  *  Print the program start time
00162  *--------------------------------*/
00163 strftime( pst, TMLEN, "%X  %x", timeptr );
00164 fprintf(fidlog," ======================================================== \n\n");
00165 fprintf(fidlog," ----- HydroTrend 3.0 Model Run ----- \n\n");
00166 fprintf(fidlog," Start: %s \n\n", pst);
00167 
00168 /*---------------------------------
00169  *  Read the hypsometric curve
00170  *  and set maxalt and totalarea.
00171  *---------------------------------*/
00172 if (verbose) printf("Reading hypsometric data from: HYDRO.HYPS... \n");
00173 err = hydroreadhypsom();
00174 if (err) {
00175     fprintf( stderr, " ERROR in HydroReadHypsom: HydroTrend Aborted \n\n" );
00176     fprintf( fidlog, " ERROR in HydroReadHypsom: HydroTrend Aborted \n\n" );
00177     exit(1);
00178 }
00179         
00180 /*---------------------------------------------
00181  *  Read climate files if they are their
00182  *  For now the climate files are only usable 
00183  *  when topmodel gw module is turned on (is that so??)
00184  *---------------------------------------------*/
00185 if (verbose) printf("Reading Topmodel Groundwater data files... \n");
00186 err = hydroreadclimate(gw_rain);
00187 if (err) {
00188     fprintf( stderr, " ERROR in HydroReadclimate: HydroTrend Aborted \n\n" );
00189     fprintf( fidlog, " ERROR in HydroReadclimate: HydroTrend Aborted \n\n" );
00190     exit(1);
00191 }
00192 
00193 /*------------------------------------------
00194  *  Set global values for those parameters
00195  *  which doesn't have any input
00196  *------------------------------------------*/
00197 if ( globalparflag > 0 ){
00198         if (verbose) printf("Set global values for not filed out input parameters... \n");
00199         err = hydrosetglobalpar();
00200         if (err) {
00201         fprintf( stderr, " ERROR in HydroSetGlobalPar: HydroTrend Aborted \n\n" );
00202             fprintf( fidlog, " ERROR in HydroSetGlobalPar: HydroTrend Aborted \n\n" );
00203         exit(1);
00204         }
00205 }
00206 
00207 /*---------------------------------------------
00208  *  Check all of the input values.
00209  *  This also checks to make sure the climate
00210  *  variables match at the epoch breaks.
00211  *---------------------------------------------*/
00212 if (verbose) printf("Checking all input parameters... \n");
00213 err = hydrocheckinput();
00214 if (err) {
00215     fprintf( stderr, " ERROR in HydroCheckInput: HydroTrend Aborted \n\n" );
00216     fprintf( fidlog, " ERROR in HydroCheckInput: HydroTrend Aborted \n\n" );
00217     exit(1);
00218 }
00219 
00220 /*-----------------------
00221  *  Open the data files
00222  *-----------------------*/
00223 if (verbose) printf("Opening output data files... \n");
00224 err = hydroopenfiles();
00225 if (err) {
00226     fprintf( stderr, " ERROR in HydroOpenFiles: HydroTrend Aborted \n\n" );
00227     fprintf( fidlog, " ERROR in HydroOpenFiles: HydroTrend Aborted \n\n" );
00228     exit(1);
00229 }
00230 if (verbose)
00231     printf(" \nStarting epoch loop... \n");
00232 
00233 /*--------------------------
00234  *  Run each epoch of data
00235  *--------------------------*/
00236 for (ep=0; ep<nepochs; ep++) {
00237         total_yr += nyears[ep];
00238         ranarray = malloc1d( 2*maxran, double );
00239         
00240 /*-----------------------------------------------------------------
00241  *  Read Qs constant parameters set by geolocation of river mouth
00242  *-----------------------------------------------------------------*/
00243 if (verbose) printf("Calling HydroSetGeoParams... \n");
00244 err = hydrosetgeoparams( gw_rain );
00245 if (err) {
00246     fprintf( stderr, " ERROR in HydroSetGeoParams: HydroTrend Aborted \n\n" );
00247     fprintf( fidlog, " ERROR in HydroSetGeoParams: HydroTrend Aborted \n\n" );
00248     exit(1);
00249 }
00250         
00251 /*----------------------------------------------------------------------------
00252  *  Run each epoch 4 times; once to calculate the mean discharge (Qbar),
00253  *  once to calculate the mean sediment discharge (Qsbarnew), and once to
00254  *  calculate the daily sediment discharge. WHATS DONE THE 4TH TIME?
00255  *----------------------------------------------------------------------------*/
00256     for ( setstartmeanQandQs = 0; setstartmeanQandQs < 5; setstartmeanQandQs++ ){
00257    yr = syear[ep];
00258 
00259 /*---------------------------------------------------
00260  *  Free memory for possible multiple outlet module
00261  *---------------------------------------------------*/
00262         if ( ( ep > 0 && setstartmeanQandQs == 0 )){
00263                 hydrofreememoutlet(nyears[ep-1]);               
00264         }
00265         if ( ( ep > 0 && setstartmeanQandQs == 0 )){
00266                 hydrofreememoutlet1(ep);
00267         }
00268 
00269 /*-------------------------------------------------------
00270  *  Allocate memory for possible multiple outlet module
00271  *-------------------------------------------------------*/
00272         if ( setstartmeanQandQs == 0 )
00273                 hydroallocmemoutlet(ep);
00274         if ( setstartmeanQandQs == 1 )
00275                 hydroallocmemoutlet1(ep);
00276 
00277 /*----------------------------------
00278  *  Initialize Variables per epoch
00279  *----------------------------------*/
00280         if( (nooutletpctflag == 0) && ( setstartmeanQandQs > 0) ){
00281                 for (p=0; p<maxnoutlet; p++){
00282                         Qdummy[ep][p] = 0.0;            
00283                         for (k=0; k<eventsnr[ep]; k++){
00284                                 Qbar[ep][p][k]   = 1.0;     /* Just a start value */
00285                                 outletpct[p][ep][k] = outletpctdummy[p][ep];
00286                         }
00287                 }
00288         }
00289         if ( setstartmeanQandQs == 0 )
00290                 for (p=0; p<nyears[ep]; p++)
00291                         for (k=0; k<daysiy; k++)
00292                                 Qpeakfloodtemp[p][k] = 0.0;
00293 
00294          /*-----------------------------------------------------------------
00295           *  Start new random number sequence.
00296           *  Get 'maxran' worth of random numbers and pluck them as needed
00297           *  nran counts through the numbers stored in ranarray
00298           *-----------------------------------------------------------------*/
00299                 if (verbose) printf("Calling HydroRandom... \n");
00300                 err = hydrorandom();
00301                 if (err) {
00302                         fprintf( stderr, " ERROR in HydroRandom: HydroTrend Aborted \n\n" );
00303                         fprintf( fidlog, " ERROR in HydroRandom: HydroTrend Aborted \n\n" );
00304                         exit(1);
00305                 }
00306                 nran=0;
00307 
00308 /*-------------------------------------------------
00309  *  Initialize Variables per loop through program
00310  *-------------------------------------------------*/
00311         Qpeakall[ep] = 0.0;
00312         eventcounter = 0;
00313                 for (p=0; p<maxnoutlet; p++)
00314                 Qpeakperoutletall[ep][p] = 0.0;
00315                 if ( Qsbarformulaflag[ep] == 1 && setstartmeanQandQs == 1 )
00316                         setstartmeanQandQs++;
00317 
00318 /*-------------------------------------------
00319  *  Set the number of outlets for 10 events
00320  *  if number of outlets is not specified, 
00321  *  or given in a range.
00322  *-------------------------------------------*/
00323                 if ( noutletflag == 1 && setstartmeanQandQs == 1){
00324                         for (x=0; x<eventsnr[ep]; x++){
00325                                 nroutlets[x] = hydrosetnumberoutlet(x);
00326                                 noutlet = nroutlets[x];
00327                                 err = hydrooutletfraction(x);
00328                                 if (err) {
00329                                         fprintf( stderr, " ERROR in HydroOutletFraction (HydroOutlet): HydroTrend Aborted \n\n" );
00330                                         fprintf( fidlog, " ERROR in HydroOutletFraction (HydroOutlet): HydroTrend Aborted \n\n" );
00331                                         exit(1);
00332                                 }                               
00333                         }
00334                         noutlet = nroutlets[eventcounter];
00335                 }
00336                 if ( noutletflag == 0 && outletmodelflag == 1 && steadyoutletpctflag == 1 && setstartmeanQandQs == 1)
00337                         for (x=0; x<eventsnr[ep]; x++){                         
00338                                 nroutlets[x] = noutlet;
00339                                 err = hydrooutletfraction(x);
00340                                 if (err) {
00341                                         fprintf( stderr, " ERROR in HydroOutletFraction (HydroOutlet): HydroTrend Aborted \n\n" );
00342                                         fprintf( fidlog, " ERROR in HydroOutletFraction (HydroOutlet): HydroTrend Aborted \n\n" );
00343                                         exit(1);
00344                                 }
00345                         }
00346 
00347 /*-----------------------------------------------------------------------
00348  *  Set the discharge fraction per outlet if there are multiple outlets
00349  *  and if the discharge fraction is not set yet in the outlet file
00350  *-----------------------------------------------------------------------*/
00351         if ( outletmodelflag == 1 && nooutletpctflag == 1 && steadyoutletpctflag == 0 && setstartmeanQandQs == 1){
00352                 x=0;            
00353                 err = hydrooutletfraction(x);
00354                 if (err) {
00355                         fprintf( stderr, " ERROR in HydroOutletFraction (HydroOutlet): HydroTrend Aborted \n\n" );
00356                         fprintf( fidlog, " ERROR in HydroOutletFraction (HydroOutlet): HydroTrend Aborted \n\n" );
00357                         exit(1);
00358                 }               
00359     }
00360 
00361    /*---------------------------------------------------------
00362     *  Calculate the maximum predicted flood size.
00363     *  Since the basin area does not change within an epoch,
00364     *  only need to do this once for each epoch.
00365     *
00366     *  Maximum Flood Size for a Basin:
00367     *  Mulder T. and Syvitski J.P.M., 1995.
00368     *  Turbidity currents generated at river mouths
00369     *  during exceptional discharge to the world oceans.
00370     *  Journal of Geology, 103: 285-298.
00371     *
00372     *  The equation wants area in km^2
00373     *
00374     *---------------------------------------------------------*/
00375         if (verbose) printf("  Epoch = %d \n", ep+1);
00376         logarea  = log10( totalarea[ep] / 1e6 );
00377         maxflood = pow(10.0, (2.084 + 0.865*logarea - 0.07*sq(logarea)));
00378 
00379 #ifdef DBG
00380     fprintf( stderr,"\n ======================================= \n" );
00381     fprintf( stderr,"\n HydroTrend:  epoch = %d \n\n", ep+1 );
00382     fprintf( stderr,"\t HydroShoulder: maxflood \t = %g \n\n", maxflood);
00383     fprintf( fidlog,"\n ======================================= \n" );
00384     fprintf( fidlog,"\n HydroTrend:  epoch = %d \n\n", ep+1 );
00385     fprintf( fidlog,"\t HydroTrend: maxflood \t = %g \n\n", maxflood);
00386 #endif
00387 
00388    /*---------------------------------------------------
00389     *  Create flood wave attenuation "shoulder" params
00390     *---------------------------------------------------*/
00391         if (verbose) printf("Calling HydroShoulder... \n");
00392         err = hydroshoulder();
00393         if (err) {
00394             fprintf( stderr, " ERROR in HydroShoulder: HydroTrend Aborted \n\n" );
00395             fprintf( fidlog, " ERROR in HydroShoulder: HydroTrend Aborted \n\n" );
00396             exit(1);
00397         }
00398 
00399    /*---------------------------------------
00400     *  Loop through each year of the epoch
00401     *---------------------------------------*/
00402         lyear = syear[ep] + nyears[ep];
00403         for (yr = syear[ep]; yr < lyear; yr++) {
00404 
00405       /*-------------------------------------------------------------
00406        *  Reset annual arrays tracking carryover from previous year
00407        *-------------------------------------------------------------*/
00408             if (ep > 0 || yr > syear[ep]) 
00409                 for (ii=0; ii<maxday-daysiy; ii++) {
00410                     Qrainwrap[ii]  = Qrain[ii+daysiy];
00411                     Qicewrap[ii]   = Qice[ii+daysiy];
00412                     Qnivalwrap[ii] = Qnival[ii+daysiy];
00413                     Qsswrap[ii]    = Qnival[ii+daysiy];
00414                 }
00415             else for (ii=0; ii < maxday-daysiy; ii++) {
00416                     Qrainwrap[ii]  = 0.0;
00417                     Qicewrap[ii]   = 0.0;
00418                     Qnivalwrap[ii] = 0.0;
00419                     Qsswrap[ii]    = 0.0;
00420                 }
00421 
00422       /*---------------------------------------
00423        *  Keep track of groundwater pool size
00424        *---------------------------------------*/
00425             gwlast = gwstore[daysiy-1];
00426 
00427       /*--------------------------------------------------
00428        *  In case the model exceeds the maximum flood,
00429        *  loop through a number of times.  This normally
00430        *  gets the maximum modeled flood to be below
00431        *  the maximum predicted flood.
00432        *--------------------------------------------------*/
00433             exceedflood = 1;
00434             floodtry = 0;
00435             while (exceedflood > 0 && floodtry < 10) {
00436 
00437          /*------------------------------
00438           *  Reset annual arrays/values
00439           *------------------------------*/
00440                 for (ii=0; ii<maxday; ii++) {
00441                 Qrain[ii]       = 0.0;
00442                 Qice[ii]        = 0.0;
00443                 Qnival[ii]      = 0.0;
00444                 Qss[ii] = 0.0;
00445                 Qsumtot[ii]     = 0.0;
00446                 for (p=0; p<maxnoutlet; p++)
00447                         Qsum[ii][p] = 0.0;
00448                 }
00449             for (ii=0; ii<daysiy; ii++) {
00450                 if (outletmodelflag == 1)
00451                         for (p=0; p<maxnoutlet; p++){
00452                                                 Csoutlet[ii][p]         = 0.0;
00453                                                 Qboutlet[ii][p]         = 0.0;
00454                                                 Qsoutlet[ii][p]         = 0.0;
00455                         }
00456                 Cs[ii] = 0.0;
00457                 Qb[ii] = 0.0;
00458                 Qs[ii] = 0.0;   
00459                 Qicetogw[ii]    = 0.0;
00460                 Qnivaltogw[ii]  = 0.0;
00461                 Pdaily[ii]              = 0.0;
00462                 Tdaily[ii]              = 0.0;
00463                 gwstore[ii]             = 0.0;
00464             }
00465             Enivalannual = 0.0;
00466             Eiceannual   = 0.0;
00467         
00468          /*---------------------------
00469           *  Set the initial GW pool
00470           *---------------------------*/
00471                 if (yr == syear[0]) {
00472                     gwstore[0] = gwinitial;
00473                     gwlast = gwinitial;
00474                 }
00475                 if (yr != syear[0])
00476                     gwstore[0] = gwlast;
00477 
00478          /*-----------------------------------------------------------------
00479           *  Start new random number sequence.
00480           *  Get 'maxran' worth of random numbers and pluck them as needed
00481           *  nran counts through the numbers stored in ranarray
00482           *-----------------------------------------------------------------*/
00483                                 rmin = -6.0;
00484                                 while (rmin < -5.0 || rmax > 5.0){
00485                                         if (verbose) printf("Calling HydroRandom... \n");
00486                                         err = hydrorandom();
00487                                         if (err) {
00488                                                 fprintf( stderr, " ERROR in HydroRandom: HydroTrend Aborted \n\n" );
00489                                                 fprintf( fidlog, " ERROR in HydroRandom: HydroTrend Aborted \n\n" );
00490                                                 exit(1);
00491                                         }
00492                                 }
00493 
00494          /*---------------------------------
00495           *  Set the climate for this year
00496           *---------------------------------*/
00497                 if (verbose) printf("Calling HydroClimate... \n");
00498                 err = hydroclimate( gw_rain );
00499                 if (err) {
00500                    fprintf( stderr, " ERROR in HydroClimate: HydroTrend Aborted \n\n" );
00501                    fprintf( fidlog, " ERROR in HydroClimate: HydroTrend Aborted \n\n" );
00502                    exit(1);
00503                 }
00504 #ifdef DBG
00505 fprintf(stderr," HydroTrend: \t Pannual = %f, \t Tannual = %f \n", Pannual, Tannual );
00506 #endif
00507 
00508          /*-------------------------------------
00509           *  Calculate weather for each day of
00510           *  the year, for each hypsometric bin
00511           *-------------------------------------*/
00512                 if (verbose) printf("Calling HydroWeather... \n");
00513                 err = hydroweather(gw_rain);
00514                 if (err) {
00515                     fprintf( stderr, " ERROR in HydroWeather: HydroTrend Aborted \n\n" );
00516                     fprintf( fidlog, " ERROR in HydroWeather: HydroTrend Aborted \n\n" );
00517                     exit(1);
00518                 }
00519 
00520          /*-------------------------------------------------
00521           *  Calculate elev grid and T, for each elevation
00522           *-------------------------------------------------*/
00523                 if (verbose) printf("Calling HydroHypsom... \n");
00524                 err = hydrohypsom();
00525                 if (err) {
00526                     fprintf( stderr, " ERROR in HydroHypsom: HydroTrend Aborted \n\n" );
00527                     fprintf( fidlog, " ERROR in HydroHypsom: HydroTrend Aborted \n\n" );
00528                     exit(1);
00529                 }
00530 
00531          /*-------------------------------------------------
00532           *  Calculate ice accumulation/melt for each day.
00533           *  This is done before HydroRain or HydroSnow to
00534           *  find the glaciated area
00535           *-------------------------------------------------*/
00536                 if (verbose) printf("Calling HydroGlacial... \n");
00537                 err = hydroglacial();
00538                 if (err) {
00539                     fprintf( stderr, " ERROR in HydroGlacial: HydroTrend Aborted \n\n" );
00540                     fprintf( fidlog, " ERROR in HydroGlacial: HydroTrend Aborted \n\n" );
00541                     exit(1);
00542                 }
00543 
00544          /*------------------------------------------
00545           *  Calculate snow fall/melt for each day.
00546           *  This is done before HydroRain to find
00547           *  the "snow" area for each day
00548           *------------------------------------------*/
00549                 if (verbose) printf("Calling HydroSnow... \n");
00550                 err = hydrosnow();
00551                 if (err) {
00552                     fprintf( stderr, " ERROR in HydroSnow: HydroTrend Aborted \n\n" );
00553                     fprintf( fidlog, " ERROR in HydroSnow: HydroTrend Aborted \n\n" );
00554                     exit(1);
00555                 }
00556 
00557          /*---------------------------------
00558           *  Calculate precip for each day
00559           *---------------------------------*/
00560                 if (verbose) printf("Calling HydroRain... \n");
00561                 err = hydrorain();
00562                 if (err) {
00563                     fprintf( stderr, " ERROR in HydroRain: HydroTrend Aborted \n\n" );
00564                     fprintf( fidlog, " ERROR in HydroRain: HydroTrend Aborted \n\n" );
00565                     exit(1);
00566                 }
00567 
00568          /*------------------------------------------------------------
00569           *  Add the component flows and find peakflow for the year.
00570           *  Store the lagged overflow and groundwater pool size for
00571           *  the following year.
00572           *------------------------------------------------------------*/
00573                 if (verbose) printf("Calling HydroSumFlow... \n");
00574                 err = hydrosumflow();
00575                 if (err) {
00576                     fprintf( stderr, " ERROR in HydroSumFlow: HydroTrend Aborted \n\n" );
00577                     fprintf( fidlog, " ERROR in HydroSumFlow: HydroTrend Aborted \n\n" );
00578                     exit(1);
00579                 }
00580 
00581          /*-----------------------------------------
00582       *  Is flood peak less than max allowed ?
00583       *-----------------------------------------*/
00584                 if (Qpeak < maxflood)
00585                     exceedflood = 0;
00586                 else {
00587                         if (setstartmeanQandQs == 4){
00588                             fprintf( stderr, "\n FLOOD WARNING: epoch %d, year %d \n", ep+1, yr );
00589                         fprintf( stderr, " \t Max.Allowed %.1f, Qpeak %.1f, retry # %d \n", maxflood, Qpeak, floodtry );
00590                         }
00591                         floodtry++;
00592                                         if (floodtry < 10)
00593                             Qgrandtotal[ep] -= Qtotal;
00594                 }
00595              }  /* end flood exceedence while loop */
00596 
00597       /*-------------------------------------------------------
00598        *  Track the max flow and if we still exceed the max
00599        *  predicted flood, send warning flag, but keep going
00600        *-------------------------------------------------------*/
00601               Qpeakall[ep] = mx( Qpeak, Qpeakall[ep] );
00602               if ( outletmodelflag == 1 )
00603                       for (p=0; p<maxnoutlet; p++)
00604                                         Qpeakperoutletall[ep][p] = mx (Qpeakperoutlet[p], Qpeakperoutletall[ep][p] );
00605               if ( exceedflood > 0 && setstartmeanQandQs == 4) {
00606                   fprintf( stderr, "   FLOOD WARNING: the maximum predicted flood size");
00607                   fprintf( stderr, " has been exceeded. \n");
00608                   fprintf( stderr, "      Epoch %d, year %d \n", ep+1, yr );
00609                   fprintf( stderr, "      Maximum predicted flood %g (m^3/s) \n", maxflood );
00610                   fprintf( stderr, "      Modeled flood peak %g (m^3/s) \n", Qpeak );
00611 
00612                   fprintf( fidlog, "   FLOOD WARNING: the maximum predicted flood size");
00613                   fprintf( fidlog, " has been exceeded. \n");
00614                   fprintf( fidlog, "      Epoch %d, year %d \n", ep+1, yr );
00615                   fprintf( fidlog, "      Maximum predicted flood %g (m^3/s) \n", maxflood );
00616                   fprintf( fidlog, "      Modeled flood peak %g (m^3/s) \n", Qpeak );
00617               }
00618         
00619 /*-------------------------------------------------------------
00620  *  Calculate the maximal events = (biggest Qpeaks per epoch)
00621  *  for channel switching at delta if option is turned on
00622  *------------------------------------------------------------- */
00623                                 if ( setstartmeanQandQs == 1 && eventnrflag == 0 ){
00624                                         if (verbose) printf("Calling HydroMaxEvents... \n");
00625                                         err = hydromaxevents();
00626                                         if (err) {
00627                                                 fprintf( stderr, " ERROR in HydroMaxEvents: HydroTrend Aborted \n\n" );
00628                                                 fprintf( fidlog, " ERROR in HydroMaxEvents: HydroTrend Aborted \n\n" );
00629                                                 exit(1);
00630                                         }
00631                                 }
00632 
00633       /*---------------------------
00634        *  Calculate sediment load 
00635        *---------------------------*/
00636                         if ( setstartmeanQandQs > 1 ){
00637               if (verbose) printf("Calling HydroSedLoad... \n");
00638               err = hydrosedload( gw_rain );
00639               if (err) {
00640                   fprintf( stderr, " ERROR in HydroSedLoad: HydroTrend Aborted \n\n" );
00641                   fprintf( fidlog, " ERROR in HydroSedLoad: HydroTrend Aborted \n\n" );
00642                   exit(1);
00643               }
00644                         }
00645 
00646            /*------------------------------------------
00647             *  Output the binary daily discharge file
00648             *------------------------------------------*/
00649               if (setstartmeanQandQs == 4){
00650                   if (verbose) printf("Calling HydroOutput... \n");
00651                                         err = hydrooutput ();
00652                   if (err) {
00653                       fprintf( stderr, " ERROR in HydroOutput: HydroTrend Aborted \n\n" );
00654                       fprintf( fidlog, " ERROR in HydroOutput: HydroTrend Aborted \n\n" );
00655                       exit(1);
00656                   }
00657                   
00658            /*------------------------------------------
00659             *  Output the text file of tabulated data
00660             *------------------------------------------*/
00661 
00662                   if (verbose) printf("Calling HydroPrintTable... \n");
00663                   if (tblstart[ep] <= yr && yr <= tblend[ep]) {
00664                       err = hydroprinttable();
00665                       if (err) {
00666                           fprintf( stderr, " WARNING in HydroPrintTable: Continuing \n\n" );
00667                           fprintf( fidlog, " WARNING in HydroPrintTable: Continuing \n\n" );
00668                       }
00669                   }                  
00670 
00671            /*------------------------------------------------
00672             *  Print out annual values to trend (trn) files
00673             *------------------------------------------------*/ 
00674                   if (verbose) printf("Calling HydroPrintAnnual... \n");
00675                   err = hydroprintannual();
00676                   if (err) {
00677                       fprintf( stderr, " WARNING in HydroPrintTrend: Continuing \n\n" );
00678                       fprintf( fidlog, " WARNING in HydroPrintTrend: Continuing \n\n" );
00679                   }                 
00680               }  /* end setstartmeanQandQs == 4 statement */
00681 
00682       /*-------------------------------------------------------
00683        *  Did random number generator create enough values ?
00684        *-------------------------------------------------------*/
00685               if (nran >= maxran){
00686                   fprintf( stderr,"\n\n HydroTrend ERROR: nran exceeded maxran.\n");
00687                   fprintf( stderr,"\t increase maxran in HydroParams.h. \n");
00688                   fprintf( stderr,"\t nran = %d, maxran = %d \n\n", nran, maxran);
00689                       exit(1);
00690               }            
00691 #ifdef DBG
00692 maxnran = mx(nran,maxnran);
00693 fprintf( stderr," HydroTrend: \t nran = %d, maxnran = %d, out of maxran = %d \n", nran, maxnran, maxran);
00694 fprintf( fidlog,"\n HydroTrend: nran = %d, maxnran = %d, out of maxran = %d \n", nran, maxnran, maxran);
00695 #endif
00696             }  /* end year loop */
00697 
00698 /*------------------------------------------
00699  *  Calculate Qbartotal[ep] (before the 
00700  *  river might split in multiple outlets)
00701  *------------------------------------------*/
00702             if( setstartmeanQandQs == 0 ){
00703                 Qbartotal[ep] = Qgrandtotal[ep] / (daysiy*nyears[ep]*dTOs);
00704                 if ( eventnrflag == 1 ){
00705                         if ( floodcounter == 0 )
00706                                 eventsnr[ep] = 1;
00707                         if ( floodcounter > 0 ){
00708                                 floodcounter = 0;
00709                                                 for (p=0; p<nyears[ep]; p++)
00710                                                         for (k=0; k<daysiy; k++)
00711                                                                 if ( Qpeakfloodtemp[p][k] > 0.0 ){
00712                                                                         Qpeakfloodtemp[p][k] = (Qpeakfloodtemp[p][k] * (( Qbartotal[ep] - baseflowtot[ep] ) / Qbartotal[ep])) + baseflowtot[ep];
00713                                                                         if ( Qpeakfloodtemp[p][k] > floodvalue[ep] )
00714                                                                                 floodcounter++;
00715                                                                 }
00716                                 eventsnr[ep]=floodcounter;
00717                         }
00718                         eventnrflag = 0;
00719                 }
00720             }
00721 
00722 /*-----------------------------------------
00723  *  Calculate Qbar[ep] per outlet, taking
00724  *  the possible events into acount
00725  *-----------------------------------------*/                   
00726             if ( outletmodelflag == 1 && (setstartmeanQandQs == 1 || setstartmeanQandQs == 2))
00727                 for (p=0; p<maxnoutlet; p++)
00728                         for (k=0; k<eventsnr[ep]; k++){
00729                                 if ( daysievent[k] > 0 ){
00730                                                 Qbar[ep][p][k] = (Qgrandtotaloutlet[ep][p][k])/((daysievent[k])*dTOs);
00731                                 }
00732                                         else Qbar[ep][p][k] = 0.0;
00733                         }
00734 
00735 // allocate memory
00736             if  ( eventnrflag == 0 && setstartmeanQandQs == 0)
00737                 hydroallocmemoutlet1(ep);
00738             
00739             /*--------------------------------------------------
00740              *  Correction for baseflow on the peakevents. In
00741              *  hydrosumflow the correction will be calculated
00742              *  on a daily bases when setstartmeanQandQs > 0
00743              *--------------------------------------------------*/           
00744                         if ((noutletflag == 1 && setstartmeanQandQs == 0) || (noutletflag == 0 && setstartmeanQandQs == 0 && steadyoutletpctflag == 0))
00745                                 for (k=0; k<eventsnr[ep]; k++){                                 
00746                                         Qpeakallevents[ep][k] = ((Qpeakallevents[ep][k] * (( Qbartotal[ep] - baseflowtot[ep] ) / Qbartotal[ep])) + baseflowtot[ep]);
00747 
00748                         /*--------------------------------------------
00749                          *  Shuffle Qfraction per outlet per event              
00750                          *--------------------------------------------*/
00751                                         nroutlets[k] = hydrosetnumberoutlet(k);
00752                                         noutlet = nroutlets[k];
00753                                         err = hydroqfractionshuffle(k);
00754                                 }                                       
00755 
00756 /*---------------------------------------------
00757  *  Start Hydrocalqsnew to calc. and Qsbarnew
00758  *---------------------------------------------*/
00759             if (setstartmeanQandQs == 3){                               
00760                 if (verbose) printf("Calling Hydrocalqsnew... \n");
00761                 err = hydrocalqsnew();
00762                 if (err) {
00763                     fprintf( stderr, " ERROR in Hydrocalqsnew: HydroTrend Aborted \n\n" );
00764                     fprintf( fidlog, " ERROR in Hydrocalqsnew: HydroTrend Aborted \n\n" );
00765                     exit(1);
00766                 }
00767                 fprintf( stderr, "\nCalculating sediment load for epoch nr. %d, \n",(ep+1));
00768             
00769                     if (outletmodelflag == 1){
00770                         for (p=0; p<maxnoutlet; p++)
00771                                 outletpcttotevents[p][ep] = 0.0;
00772                                         for (p=0; p<maxnoutlet; p++){
00773                                                 totaldays = 0;
00774                                                 for (k=0; k<eventsnr[ep]; k++){
00775                                                         outletpcttotevents[p][ep] += outletpct[p][ep][k] * daysievent[k];
00776                                                         totaldays += daysievent[k];
00777                                                 }
00778                                                 outletpcttotevents[p][ep] /= (totaldays);
00779                                         }
00780                 }
00781             } /* end if setstartmeanQandQs == 3 */
00782         }    /* end for setstartmeanQandQs<5 loop */
00783 
00784 /*------------------------------------------------
00785  *  Set the variables for the summary statistics
00786  *------------------------------------------------*/
00787                 if (outletmodelflag == 1){
00788                         totpercentageQ[ep] = 0.0;               
00789                         for (p=0; p<maxnoutlet; p++){
00790                                 totaldays = 0;
00791                                 for (k=0; k<eventsnr[ep]; k++){
00792                                         totpercentageQ[ep] += outletpct[p][ep][k];
00793                                         Qdummy[ep][p] += ( Qbar[ep][p][k] * daysievent[k] );
00794                                         outletpcttotevents[p][ep] += outletpct[p][ep][k] * daysievent[k];
00795                                         totaldays += daysievent[k];
00796                                 }
00797                                 Qdummy[ep][p] /= totaldays;
00798                                 outletpcttotevents[p][ep] /= (totaldays);
00799                                 Qgrandtotaltotoutlet[p] = (Qgrandtotaloutlet[ep][p][k]);
00800                                 Qsgrandtotaltotoutlet[p] = Qsgrandtotaloutlet[ep][p];
00801                                 Qsgrandtotaldelta[ep] += Qsgrandtotaloutlet[ep][p];
00802                                 Coutlettotal[ep][p] =Coutlettotal[ep][p]/(daysiy*nyears[ep]);
00803                         }
00804                         if ((outletmodelflag == 1 && steadyoutletpctflag == 0) ||(noutletflag == 1 && steadyoutletpctflag == 1) || (noutletflag == 0 && steadyoutletpctflag == 1)){
00805                                 ep=0;
00806                                 totpercentageQ[ep] /= eventsnr[ep];
00807                         }
00808                 }
00809                 else totpercentageQ[ep] = 1.0;
00810                 Qsgrandtotaltot += Qsgrandtotal[ep];
00811                 Qgrandtotaltot += Qgrandtotal[ep];
00812                 yeartot += daysiy*nyears[ep]*dTOs;
00813         if (nepochs == 1)
00814             Qpeakmax = Qpeakall[ep];
00815         else Qpeakmax = mx( Qpeakmax, Qpeakall[ep] );
00816         TEtot += TE[ep];
00817 
00818 /*------------------------------------------------------------------
00819  *  Print out statistic file, for values used in Qs and Q formulas
00820  *------------------------------------------------------------------*/
00821         if (verbose) printf("Calling HydroprintStat... \n");
00822         err = hydroprintstat();
00823             if (err) {
00824                  fprintf( stderr, " WARNING in HydroPrintStat: Continuing \n\n" );
00825                  fprintf( fidlog, " WARNING in HydroPrintStat: Continuing \n\n" );
00826         }
00827         freematrix1D( (void*) ranarray );
00828         freematrix1D( (void*) C );
00829     }  /* end epoch loop */
00830 
00831 /*---------------------------------
00832  *  Print some summary statistics
00833  *---------------------------------*/
00834     fprintf( stderr, "\n\nSTATISTICS PER EPOCH PER OUTLET\n" );
00835     fprintf( stderr, "Ep\tOutlet\tQbar\tQsbar\tQsmean/outlet\tQpeak\tCsmean\tTEbas.TEres.\n");
00836         for (ep = 0; ep < nepochs; ep++){
00837                 p=0;
00838                 fprintf( stderr, "%d\t%d(%.0f%%)\t%.2f\t%.2f\t\t\t%.2f\t%.2f\t%.1f   %.1f\n",
00839                         (ep+1),p,totpercentageQ[ep]*100,Qbartotal[ep],Qsbartot[ep],Qpeakall[ep],Csgrandtotal[ep]/(daysiy*nyears[ep]*dTOs),TE[ep]*100, TEsubbasin[ep]*100);
00840                 if (outletmodelflag == 1)
00841                         for (p=0; p<maxnoutlet; p++)
00842                                 fprintf( stderr, "%d\t%d(%.0f%%)\t%.2f\t%.2f\t% .2f%%\t\t%.2f\t%.2f\n",
00843                                         (ep+1),p+1,outletpcttotevents[p][ep]*100,Qdummy[ep][p],Qsgrandtotaloutlet[ep][p]/(daysiy*nyears[ep]*dTOs),(Qsgrandtotaloutlet[ep][p]/Qsgrandtotaldelta[ep])*100/*/(daysiy*nyears[ep]*dTOs)*/,Qpeakperoutletall[ep][p],Csgrandtotaloutlet[ep][p]/(daysiy*nyears[ep]*dTOs));
00844             fprintf( stderr, "nr\tnr\t(m^3/s)\t(kg/s)\t(%%)\t\t(m^3/s)\t(kg/m3) (%%)   (%%)\n\n");
00845         fprintf( stderr, "Basin area                           = %.2f  (km^2) \n",  totalarea[ep]/1e6);
00846             fprintf( stderr, "Basin relief                         = %.2f  (m) \n\n\n", maxalt[ep]);
00847         }
00848         
00849     fprintf( fidlog, "\n\nSTATISTICS PER EPOCH PER OUTLET\n" );
00850     fprintf( fidlog, "Ep\tOutlet\tQbar\tQsbar\tQsmean/outlet\tQpeak\tCsmean\tTEbas.TEres.\n");
00851         for (ep = 0; ep < nepochs; ep++){
00852                 p=0;
00853                 fprintf( fidlog, "%d\t%d(%.0f%%)\t%.2f\t%.2f\t\t\t%.2f\t%.2f\t%.1f   %.1f\n",
00854                         (ep+1),p,totpercentageQ[ep]*100,Qbartotal[ep],Qsbartot[ep],Qpeakall[ep],Csgrandtotal[ep]/(daysiy*nyears[ep]*dTOs),TE[ep]*100, TEsubbasin[ep]*100);
00855                 if (outletmodelflag == 1)
00856                         for (p=0; p<maxnoutlet; p++)
00857                                 fprintf( fidlog, "%d\t%d(%.0f%%)\t%.2f\t%.2f\t% .1f%%\t\t%.2f\t%.2f\n",
00858                                         (ep+1),p+1,outletpcttotevents[p][ep]*100,Qdummy[ep][p],Qsgrandtotaloutlet[ep][p]/(daysiy*nyears[ep]*dTOs),(Qsgrandtotaloutlet[ep][p]/Qsgrandtotaldelta[ep])*100/*/(daysiy*nyears[ep]*dTOs)*/,Qpeakperoutletall[ep][p],Csgrandtotaloutlet[ep][p]/(daysiy*nyears[ep]*dTOs));
00859             fprintf( fidlog, "nr\tnr\t(m^3/s)\t(kg/s)\t(%%)\t\t(m^3/s)\t(kg/m3) (%%)   (%%)\n\n");
00860         fprintf( fidlog, "Basin area                           = %.2f  (km^2) \n",  totalarea[ep]/1e6);
00861             fprintf( fidlog, "Basin relief                         = %.2f  (m) \n\n\n", maxalt[ep]);
00862         }
00863         
00864 /*-------------------------------
00865  *  Print the program stop time
00866  *-------------------------------*/
00867     time( &tloc );
00868     timeptr = localtime( &tloc );
00869     strftime( pst, TMLEN, "%X  %x", timeptr );
00870     fprintf(fidlog,"\n ------------------------- \n");
00871     fprintf(fidlog,"\n Stop: %19s \n", pst);
00872     fprintf(fidlog," ------------------------- \n\n");
00873 
00874 /*-------------------
00875  *  Close all files
00876  *------------------*/
00877     fclose(fidq);
00878     fclose(fidqs);
00879     fclose(fidtrend1);
00880     fclose(fidtrend2);
00881     fclose(fidtrend3);
00882     fclose(fiddistot);
00883     fclose(fidlog);
00884     if (strncmp(asciioutput,ON,2) == 0){
00885         fclose(outp);
00886         fclose(outp1);
00887         fclose(outp2);
00888         fclose(outp3);
00889         fclose(outp4);
00890         fclose(outp5);
00891         fclose(outpnival_ice);
00892     }
00893         if ( outletmodelflag == 1  )
00894                 for ( p=0; p<maxnoutlet; p++ )
00895                         fclose(fiddis[p]);        
00896 
00897 /*-------------------------------------------------
00898  *  Swap big-endian and little-endian file format
00899  *-------------------------------------------------*/
00900     if (verbose) printf("Calling HydroSwap... \n");
00901     err = hydroswap();
00902     if (err)
00903         fprintf( stderr, " WARNING in HydroSwap: Continuing \n\n" );
00904 
00905 /*-------------------------------------------
00906  *  Run CGI script for the internet version
00907  *-------------------------------------------*/
00908     if (webflag == 1){
00909         char argstring[300];
00910         sprintf(argstring,"/lilac/htdocs/deltaforce/workshop/cgi-bin/returnmail.cgi %s",commandlinearg[2]);
00911         system(argstring);
00912     }
00913   
00914 /*---------------
00915  *  Free memory
00916  *---------------*/
00917         if(raindatafile ==1){
00918                 freematrix1D( (void*) gw_rain->Tperyear );
00919         }
00920                 
00921 /*---------------------------------------------------
00922  *  Free memory for possible multiple outlet module
00923  *---------------------------------------------------*/
00924         hydrofreememoutlet(ep);
00925         
00926 /*---------------------
00927  * Print exit message
00928  *---------------------*/
00929 #ifdef DBG
00930 fprintf( stderr," \n ---------------------------------------------------- \n");
00931 fprintf( stderr, "HydroTrend 3.0 finished. \n\n");
00932 #else
00933 fprintf( stderr, "\nHydroTrend 3.0 finished. \n\n");
00934 #endif
00935 return 0;
00936 }  /* end of HydroTrend */

Generated on Fri Jan 4 18:04:14 2008 for sedflux by  doxygen 1.5.2