示例#1
0
/* -------------------------------------------------------------
   ChannelCut
   computes necessary parameters for cell storage adjustment from
   channel/road dimensions
   ------------------------------------------------------------- */
void ChannelCut(int y, int x, CHANNEL * ChannelData, ROADSTRUCT * Network)
{
  float bank_height = 0.0;
  float cut_area = 0.0;

  if (channel_grid_has_channel(ChannelData->stream_map, x, y)) {
    bank_height = channel_grid_cell_bankht(ChannelData->stream_map, x, y);
    cut_area = channel_grid_cell_width(ChannelData->stream_map, x, y) * 
      channel_grid_cell_length(ChannelData->stream_map, x, y);
  }
  else if (channel_grid_has_channel(ChannelData->road_map, x, y)) {
    bank_height = channel_grid_cell_bankht(ChannelData->road_map, x, y);
    cut_area = channel_grid_cell_width(ChannelData->road_map, x, y) * 
      channel_grid_cell_length(ChannelData->road_map, x, y);
  }
  Network->Area = cut_area;
  Network->BankHeight = bank_height;
}
示例#2
0
/*****************************************************************************
   ChannelCulvertSedFlow ()   
   computes sediment outflow (kg) of channel/road network to a grid cell, if it
   contains a sink (sink check is in channel_grid_sed_outflow)

*****************************************************************************/
double ChannelCulvertSedFlow(int y, int x, CHANNEL * ChannelData, int i)
{
  if (channel_grid_has_channel(ChannelData->road_map, x, y)){
    return channel_grid_sed_outflow(ChannelData->road_map, x, y, i);
  }
  else {
    return 0;
  }
}
示例#3
0
/*****************************************************************************
  RouteCulvertSediment()

*****************************************************************************/
void RouteCulvertSediment(CHANNEL * ChannelData, MAPSIZE * Map,
			  TOPOPIX ** TopoMap, SEDPIX ** SedMap, 
			  AGGREGATED * Total, float *SedDiams)
{
  int x, y;
  float CulvertSedFlow;   /* culvert flow of sediment, kg */
  int i;

  Total->CulvertReturnSedFlow = 0.0;

  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
 
	for(i=0; i<NSEDSIZES; i++) {
	    
	  CulvertSedFlow = ChannelCulvertSedFlow(y, x, ChannelData, i);
	  CulvertSedFlow /= Map->DX * Map->DY;

	  if (channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	    /* Percent delivery to streams is conservative and based on particle size */
	    if (SedDiams[i] <= 0.063){
	      ChannelData->stream_map[x][y]->channel->sediment.overlandinflow[i] += CulvertSedFlow;
	      Total->CulvertSedToChannel += CulvertSedFlow;
	      CulvertSedFlow = 0.;
	    }
	    if ((SedDiams[i] > 0.063) && (SedDiams[i] <= 0.5)){
	      ChannelData->stream_map[x][y]->channel->sediment.overlandinflow[i] += 0.3*CulvertSedFlow;
	      Total->CulvertSedToChannel += 0.3*CulvertSedFlow;
	      Total->CulvertReturnSedFlow += 0.7*CulvertSedFlow;
	      CulvertSedFlow = 0.;
	    }
	    if ((SedDiams[i] > 0.5) && (SedDiams[i] <= 2.)){
	      ChannelData->stream_map[x][y]->channel->sediment.overlandinflow[i] += 0.1*CulvertSedFlow;
	      Total->CulvertSedToChannel += 0.1*CulvertSedFlow;
	      Total->CulvertReturnSedFlow += 0.9*CulvertSedFlow;
	      CulvertSedFlow = 0.;
	    }
	    Total->CulvertReturnSedFlow += CulvertSedFlow;
	  }
	  else {
	    Total->CulvertReturnSedFlow += CulvertSedFlow;
	  }
	}
      }
    }
  }
}
示例#4
0
/*****************************************************************************
MassEnergyBalance()
*****************************************************************************/
void MassEnergyBalance(int y, int x, float SineSolarAltitude, float DX, 
					   float DY, int Dt, int HeatFluxOption, 
					   int CanopyRadAttOption, int MaxVegLayers, 
					   PIXMET *LocalMet, ROADSTRUCT *LocalNetwork, CHANNEL *ChannelData, 
					   PRECIPPIX *LocalPrecip, VEGTABLE *VType, 
					   VEGCHEMPIX *LocalVeg, SOILTABLE *SType,
					   SOILPIX *LocalSoil, SNOWPIX *LocalSnow,
					   EVAPPIX *LocalEvap, PIXRAD *TotalRad,  CHEMTABLE *ChemTable,
					   SOILCHEMTABLE *SCType, VEGCHEMTABLE *VCType, DATE CurDate, BASINWIDE * Basinwide, GWPIX *LocalGW,
					   GEOTABLE *GType, float Slope, MAPSIZE *Map, VEGCHEMPIX **VegChemMap,OPTIONSTRUCT *Options,
						int NSoilLayers, SOILPIX ** SoilMap, GWPIX ** Groundwater, 
						 int NpsCats, NPSPIX **NpsMap, NONPOINTSOURCE **NpsTable,
						AGGREGATED *Total, int NChems, int HasGroundwater, TOPOPIX ** TopoMap, float **PopulationMap)

		

{
	PIXRAD LocalRad;		/* Radiation balance components (W/m^2) */
	float SurfaceWater_m;		/* Pixel average depth of water before infiltration is calculated (m) */
	float Infiltration;		/* Infiltration into the top soil layer (m) */
	float LowerRa;		/* Aerodynamic resistance for lower layer (s/m) */
	float LowerWind;		/* Wind for lower layer (m/s) */
	float MaxInfiltration;	/* Maximum infiltration into the top soil layer (m) */
	float MaxRoadbedInfiltration;	/* Maximum infiltration through the road bed soil layer (m) */
	float MeltEnergy;		/* Energy used to melt snow and  change of cold content of snow pack */
	float MoistureFlux;		/* Amount of water transported from the pixel  to the atmosphere (m/timestep) */
	float NetRadiation;		/* Net radiation for a layer (W/m2) */
	float Reference;		/* Reference height for sensible heat calculation (m) */
	float RoadbedInfiltration;	/* Infiltration through the road bed (m) */
	float Roughness;		/* Roughness length (m) */
	float Rp;			/* radiation flux in visible part of the spectrum (W/m^2) */
	float UpperRa;		/* Aerodynamic resistance for upper layer (s/m) */
	float UpperWind;		/* Wind for upper layer (m/s) */
	float SnowLongIn;		/* Incoming longwave radiation at snow surface (W/m2) */
	float SnowNetShort;		/* Net amount of short wave radiation at the snow surface (W/m2) */
	float SnowRa;			/* Aerodynamic resistance for snow */
	float SnowWind;		/* Wind 2 m above snow */
	float Tsurf;			/* Surface temperature used in LongwaveBalance() (C) */
	int NVegLActual;		/* Number of vegetation layers above snow */
	int HasSnow;
	float SurfaceSoilWaterFlux;	/* Track the movement from soil to surfce or vice versa for use in Chemistry routing, MWW -sc */
	float Thrufall = 0.0;		/* Temporarily stores the amount of rainfall for use in atmospheric deposition of Chems, MWW -sc */ 
	int CurMonth = CurDate.Month;  /* current month*/
	

	ApplyNonPointSources(x,y,NSoilLayers, SoilMap, Groundwater, ChemTable,  NpsCats, NpsMap, NpsTable, Total, 
		NChems, HasGroundwater, Map, TopoMap, PopulationMap, VType, VegChemMap);
	
	NVegLActual = VType->NVegLayers;
	if (LocalSnow->HasSnow == TRUE && VType->UnderStory == TRUE)--NVegLActual;

	/* initialize the total amount of evapotranspiration, and MeltEnergy */
	LocalEvap->ETot = 0.0;
	LocalEvap->ET_potential = 0.0;
	MeltEnergy = 0.0;
	MoistureFlux = 0.0;

	/* calculate the radiation balance for the ground/snow surface and the
	vegetation layers above that surface */
	RadiationBalance(HeatFluxOption, CanopyRadAttOption, SineSolarAltitude, 
		LocalMet->Sin, LocalMet->SinBeam, LocalMet->SinDiffuse, 
		LocalMet->Lin, LocalMet->Tair, LocalVeg->Tcanopy, 
		LocalSoil->TSurf, SType->Albedo, VType, LocalSnow, 
		&LocalRad);

	/* calculate the actual aerodynamic resistances and wind speeds */
	UpperWind = VType->U[0] * LocalMet->Wind;
	UpperRa = VType->Ra[0] / LocalMet->Wind;
	if((isnan(UpperRa))) assert(FALSE); //JASONS EDIT: 061025 moved from 3 lines above, because otherwise, was checking isNAN before being set!
	if (VType->OverStory == TRUE) {
		LowerWind = VType->U[1] * LocalMet->Wind;
		LowerRa = VType->Ra[1] / LocalMet->Wind;
	}
	else {
		LowerWind = UpperWind;
		LowerRa = UpperRa;
	}

/* calculate the amount of interception storage, and the amount of 
	throughfall.  Of course this only needs to be done if there is
	vegetation present. */
#ifndef NO_SNOW
	if (VType->OverStory == TRUE &&
		(LocalPrecip->IntSnow[0] || LocalPrecip->SnowFall > 0.0)) {
			SnowInterception(y, x, Dt, VType->Fract[0], VType->LAI[0],
				VType->MaxInt[0], VType->MaxSnowInt, VType->MDRatio,
				VType->SnowIntEff, UpperRa, LocalMet->AirDens,
				LocalMet->Eact, LocalMet->Lv, &LocalRad, LocalMet->Press,
				LocalMet->Tair, LocalMet->Vpd, UpperWind,
				&(LocalPrecip->RainFall), &(LocalPrecip->SnowFall),
				&(LocalPrecip->IntRain[0]), &(LocalPrecip->IntSnow[0]),
				&(LocalPrecip->TempIntStorage),
				&(LocalSnow->CanopyVaporMassFlux), &(LocalVeg->Tcanopy),
				&MeltEnergy);
			MoistureFlux -= LocalSnow->CanopyVaporMassFlux;

			// Because we now have a new estimate of the canopy temperature we can recalculate the longwave balance 
			if (LocalSnow->HasSnow == TRUE)Tsurf = LocalSnow->TSurf;
			else if (HeatFluxOption == TRUE)Tsurf = LocalSoil->TSurf;
			else Tsurf = LocalMet->Tair;
			LongwaveBalance(VType->OverStory, VType->Fract[0], LocalMet->Lin, LocalVeg->Tcanopy, Tsurf, &LocalRad);
	}//if no snow, then calculate rain interception
	else if (VType->NVegLayers > 0) {
		LocalVeg->Tcanopy = LocalMet->Tair;
		LocalSnow->CanopyVaporMassFlux = 0.0;
		LocalPrecip->TempIntStorage = 0.0;
		InterceptionStorage(VType->NVegLayers, NVegLActual, VType->MaxInt,VType->Fract, LocalPrecip->IntRain,&(LocalPrecip->RainFall));
	}
	Thrufall = LocalPrecip->RainFall;

	/* if snow is present, simulate the snow pack dynamics */
	if (LocalSnow->HasSnow || LocalPrecip->SnowFall > 0.0) {
		if (VType->OverStory == TRUE) {
			SnowLongIn = LocalRad.LongIn[1];
			SnowNetShort = LocalRad.NetShort[1];
		}
		else {
			SnowLongIn = LocalRad.LongIn[0];
			SnowNetShort = LocalRad.NetShort[0];
		}
		SnowWind = VType->USnow * LocalMet->Wind;
		SnowRa = VType->RaSnow / LocalMet->Wind;
		LocalSnow->Outflow =
			SnowMelt(y, x, Dt, 2. + Z0_SNOW, 0.f, Z0_SNOW, SnowRa, LocalMet->AirDens,
			LocalMet->Eact, LocalMet->Lv, SnowNetShort, SnowLongIn,
			LocalMet->Press, LocalPrecip->RainFall, LocalPrecip->SnowFall,
			LocalMet->Tair, LocalMet->Vpd, SnowWind,
			&(LocalSnow->PackWater), &(LocalSnow->SurfWater),
			&(LocalSnow->Swq), &(LocalSnow->VaporMassFlux),
			&(LocalSnow->TPack), &(LocalSnow->TSurf), &MeltEnergy, 
			&(LocalSnow->ShearStress), &(LocalSnow->IceA), &(LocalSnow->IceVelocity), Slope );

		/* Rainfall was added to SurfWater of the snow pack and has to be set to zero */

		LocalPrecip->RainFall = 0.0;
		MoistureFlux -= LocalSnow->VaporMassFlux;

		/* Because we now have a new estimate of the snow surface temperature we can recalculate the longwave balance */
		Tsurf = LocalSnow->TSurf;
		LongwaveBalance(VType->OverStory, VType->Fract[0], LocalMet->Lin,
			LocalVeg->Tcanopy, Tsurf, &LocalRad);
	}
	else {
		LocalSnow->Outflow = 0.0;
		LocalSnow->VaporMassFlux = 0.0;
	}

	/* Determine whether a snow pack is still present, or whether everything
	has melted */

	if (LocalSnow->Swq > 0.0)LocalSnow->HasSnow = TRUE;
	else LocalSnow->HasSnow = FALSE;

	/*do the glacier add */
	if (LocalSnow->Swq < 1.0 && VType->Index == GLACIER) {
		printf("resetting glacier swe of %f to 5.0 meters\n", LocalSnow->Swq);
		LocalSnow->Glacier += (5.0 - LocalSnow->Swq);
		LocalSnow->Swq = 5.0;
		LocalSnow->TPack = 0.0;
		LocalSnow->TSurf = 0.0;
	}
#endif  //end if there is snow

#ifndef NO_ET
	/* calculate the amount of evapotranspiration from each vegetation layer 
	above the ground/soil surface.  Also calculate the total amount of 
	evapotranspiration from the vegetation */
//	NetRadiation=0; //JASONS EDIT: BUGBUG: the following line uses this as a param, but it is not yet defined.
	
	/* Calculate the potentail ET, this is not used for any other calcs but is a desired 
	output in some situations, VARID added as 100.  MWW 052405 */
/*	LocalEvap->ET_potential = ((LocalMet->Slope/(LocalMet->Slope + LocalMet->Gamma) * NetRadiation) + 
		(LocalMet->Gamma/(LocalMet->Slope + LocalMet->Gamma) *
		(6.43*(1+0.536*LocalMet->Wind)*LocalMet->Vpd/1000)/LocalMet->Lv))/
		(WATER_DENSITY * LocalMet->Lv);
	LocalEvap->ET_potential *=Dt;   // convert to meters per timestep
*/
	//calculate  evapotranspiration if overstory present
	if (VType->OverStory == TRUE) {
		Rp = VISFRACT * LocalRad.NetShort[0];
		NetRadiation = LocalRad.NetShort[0] + LocalRad.LongIn[0] - 2 * VType->Fract[0] * LocalRad.LongOut[0];
		EvapoTranspiration(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
			MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]), LocalEvap, LocalNetwork->Adjust, UpperRa, Total);
		MoistureFlux += LocalEvap->EAct[0] + LocalEvap->EInt[0];
		if (LocalSnow->HasSnow != TRUE) {//calc understory evapotranspiration if there is no snow
			Rp = VISFRACT * LocalRad.NetShort[1];
			NetRadiation = LocalRad.NetShort[1] + LocalRad.LongIn[1] - VType->Fract[1] * LocalRad.LongOut[1];
			EvapoTranspiration(1, Dt, LocalMet, NetRadiation, Rp, VType, SType,
				MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[1]), LocalEvap, LocalNetwork->Adjust, LowerRa, Total);
			MoistureFlux += LocalEvap->EAct[1] + LocalEvap->EInt[1];
		}
		else  {//calc understory evapotranspiration if there is snow
			LocalEvap->EAct[1] = 0.;
			LocalEvap->EInt[1] = 0.;
		}
	}//end overstory == true	

	// calc evapotranspiration if there is understory but not overstory and no snow  
	else if (LocalSnow->HasSnow != TRUE && VType->UnderStory == TRUE) {
		Rp = VISFRACT * LocalRad.NetShort[0];
		NetRadiation = LocalRad.NetShort[0] + LocalRad.LongIn[0] - VType->Fract[0] * LocalRad.LongOut[0];
		EvapoTranspiration(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
			LocalEvap, LocalNetwork->Adjust, LowerRa, Total);
		MoistureFlux += LocalEvap->EAct[0] + LocalEvap->EInt[0];
	}

	// calc evapotranspiration if there is snow and understory 
	else if (VType->UnderStory == TRUE) {
		LocalEvap->EAct[0] = 0.;
		LocalEvap->EInt[0] = 0.;
	}

	// Calculate soil evaporation from the upper soil layer if no snow is present and there is no understory 
	if (LocalSnow->HasSnow != TRUE && VType->UnderStory != TRUE) {
		if (VType->OverStory == TRUE){
			printf("this should never happen.");
			ASSERTTEST(NetRadiation = LocalRad.NetShort[1] + LocalRad.LongIn[1] - LocalRad.LongOut[1]);
		}
		else
			ASSERTTEST(NetRadiation =LocalRad.NetShort[0] + LocalRad.LongIn[0] - LocalRad.LongOut[0]);
		NEGTEST(LocalEvap->EvapSoil =
			SoilEvaporation(Dt, LocalMet->Tair, LocalMet->Slope, LocalMet->Gamma,
			LocalMet->Lv, LocalMet->AirDens, LocalMet->Vpd,
			NetRadiation, LowerRa, MoistureFlux, SType->Porosity[0],
			SType->Ks[0], SType->Press[0], SType->PoreDist[0],
			VType->RootDepth_m[0], &(LocalSoil->Moist_m_m[0]),
			LocalNetwork->Adjust[0], &(LocalEvap->ET_potential)));
	}
	else
		LocalEvap->EvapSoil = 0.0;
	ASSERTTEST(MoistureFlux += LocalEvap->EvapSoil);
	if(LocalEvap->ETot <0){
		printf("negative total evap: %g\n",LocalEvap->ETot);
		LocalEvap->ETot=0;
	}
	
#endif

	/* add the water that was not intercepted to the upper soil layer */
#ifndef NO_SOIL

	LocalSoil->SurfaceWater_m = 0.0;
	NEGTEST(SurfaceWater_m = LocalPrecip->RainFall + LocalSoil->Runoff_m + LocalSnow->Outflow);
	NEGTEST(MaxInfiltration = (1 - VType->ImpervFrac) * LocalNetwork->PercArea[0] * SType->MaxInfiltrationRate * Dt); 
	Infiltration = min(MaxInfiltration,(1 - VType->ImpervFrac) * LocalNetwork->PercArea[0] *SurfaceWater_m); 
	if (Infiltration > MaxInfiltration)assert(FALSE);
	Total->Soil.Infiltration_m+=Infiltration;
	NEGTEST(MaxRoadbedInfiltration = (1 - LocalNetwork->PercArea[0]) * LocalNetwork->MaxInfiltrationRate * Dt); 
	NEGTEST(RoadbedInfiltration = (1 - LocalNetwork->PercArea[0]) *SurfaceWater_m); 
		//temporary measure JSB 4-4-09 There is no roadbed - why is roadbedinterception >0?
	RoadbedInfiltration=0;

	if (RoadbedInfiltration > MaxRoadbedInfiltration) RoadbedInfiltration = MaxRoadbedInfiltration;
	ASSERTTEST(LocalSoil->Runoff_m = SurfaceWater_m - Infiltration - RoadbedInfiltration);

	if(LocalSoil->Runoff_m<0){
		if(LocalSoil->Runoff_m < -0.0001){ //add this check, in case very small float multiplication rounding error may occur
			printf("Warning: Negative runoff: %.5f m at X: %d Y: %d \n",LocalSoil->Runoff_m,y,x);
			assert(FALSE);
		}
		LocalSoil->Runoff_m=0;
	}
		
	//	if(LocalSoil->Runoff_m>1)assert(FALSE);

	NEGTEST(LocalSoil->SurfaceWater_m = LocalSoil->Runoff_m);
	/* Calculate unsaturated soil water movement, and adjust soil water 
	table depth */
	UnsaturatedFlow(Dt,  Infiltration, RoadbedInfiltration,SType->NLayers, LocalSoil->Depth,  VType->RootDepth_m,
		SType->Ks, SType->PoreDist, SType->Porosity, SType->FCap, LocalSoil->Perc, LocalNetwork->PercArea, 
		LocalNetwork->Adjust, LocalNetwork->CutBankZone,LocalNetwork->BankHeight, &(LocalSoil->TableDepth_m),
		&(LocalSoil->Runoff_m), LocalSoil->Moist_m_m,  LocalSoil->ChannelReturn,y,x);
	
	NEGTEST(LocalSoil->Runoff_m);
	//if(LocalSoil->Runoff_m>1)printf("Warning: surface runoff is %.3f m at X: %d Y: %d \n",LocalSoil->Runoff_m,y,x);

	/* positive SurfaceSoilWaterFlux, means water has moved from the surface into the soil */
	ASSERTTEST(SurfaceSoilWaterFlux = (LocalSoil->SurfaceWater_m - LocalSoil->Runoff_m));

	if(ChemTable->NChems > 0) {
		/* MWW Add new chems from veg to surface and soil, also Track the source of surface waters and route disolved chems appropriately  */
	
			SoilChemistry(y, x, Dt, DX, DY,LocalSoil, SType, LocalVeg, VType, GType,  ChemTable, Thrufall,
				SurfaceSoilWaterFlux, SCType, VCType, LocalMet, CurMonth,Basinwide, CurDate,Options);
	} 

	if (HeatFluxOption == TRUE) {
		if (LocalSnow->HasSnow == TRUE) {
			Reference = 2. + Z0_SNOW;
			Roughness = Z0_SNOW;
		}
		else {
			Reference = 2. + Z0_GROUND;
			Roughness = Z0_GROUND;
		}
		SensibleHeatFlux(y, x, Dt, LowerRa, Reference, 0.0f, Roughness,
			LocalMet, LocalRad.PixelNetShort, LocalRad.PixelLongIn,
			MoistureFlux, SType->NLayers, VType->RootDepth_m,
			SType, MeltEnergy, LocalSoil);
		Tsurf = LocalSoil->TSurf;
		LongwaveBalance(VType->OverStory, VType->Fract[0], LocalMet->Lin,
			LocalVeg->Tcanopy, Tsurf, &LocalRad);
	}
	else NoSensibleHeatFlux(Dt, LocalMet, MoistureFlux, LocalSoil);
#endif

	/* ----------------------------------------------------------*/
	/* Assign local met data to the Stream Channel variables for */
	/* stream temperature calculations.  Added 08/12/2004 MWW    */

	if (channel_grid_has_channel(ChannelData->stream_map, x, y)) {
		/* assign Pixel met data to channel segment for the current time step */
		if (LocalSnow->HasSnow)HasSnow = 1;
		else HasSnow = 0;
		channel_grid_metdata(ChannelData->stream_map, x, y, 
			LocalMet->Tair, LocalRad.PixelNetShort,
			LocalRad.PixelLongIn, LowerWind, 
			LocalMet->Rh, LocalMet->Press, HasSnow);
	}

	/* -END-STREAM-TEMP-SECTION-----------------------------------*/

	/* add the components of the radiation balance for the current pixel to 
	the total */
	AggregateRadiation(MaxVegLayers, VType->NVegLayers, &LocalRad, TotalRad);
}
示例#5
0
/* -------------------------------------------------------------
   RouteChannel
   ------------------------------------------------------------- */
void
RouteChannel(CHANNEL * ChannelData, TIMESTRUCT * Time, MAPSIZE * Map,
	    TOPOPIX ** TopoMap, SOILPIX ** SoilMap, AGGREGATED * Total, 
	     OPTIONSTRUCT *Options, ROADSTRUCT ** Network, 
	     SOILTABLE * SType, PRECIPPIX ** PrecipMap, SEDPIX **SedMap,
	     float Tair, float Rh, float *SedDiams)
{
  int x, y;
  int flag;
  char buffer[32];
  float CulvertFlow;


  /* give any surface water to roads w/o sinks */
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	SoilMap[y][x].IExcessSed = SoilMap[y][x].IExcess;
	if (channel_grid_has_channel(ChannelData->road_map, x, y) && !channel_grid_has_sink(ChannelData->road_map, x, y)) {	/* road w/o sink */


	  SoilMap[y][x].RoadInt += SoilMap[y][x].IExcess;
	  channel_grid_inc_inflow(ChannelData->road_map, x, y,
				  SoilMap[y][x].IExcess * Map->DX * Map->DY);
	  SoilMap[y][x].IExcess = 0.0f;
	  
	}
      }
    }
  }
  
  if(Options->RoadRouting){
    RouteRoad(Map, Time, TopoMap, SoilMap, Network, SType, ChannelData, 
	      PrecipMap, SedMap, Tair, Rh, SedDiams);  
  }

  /* route the road network and save results */
  SPrintDate(&(Time->Current), buffer);
  flag = IsEqualTime(&(Time->Current), &(Time->Start));
  if (ChannelData->roads != NULL) {
    channel_route_network(ChannelData->roads, Time->Dt);
    channel_save_outflow_text(buffer, ChannelData->roads,
			      ChannelData->roadout, ChannelData->roadflowout,
			      flag);
  }
  
  /* add culvert outflow to surface water */
  Total->CulvertReturnFlow = 0.0;
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {

	CulvertFlow = ChannelCulvertFlow(y, x, ChannelData);
	CulvertFlow /= Map->DX * Map->DY;
	/* CulvertFlow = (CulvertFlow > 0.0) ? CulvertFlow : 0.0; */
	
	if (channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	  channel_grid_inc_inflow(ChannelData->stream_map, x, y,
				  (SoilMap[y][x].IExcess + 
				   CulvertFlow) * Map->DX * Map->DY);
	  SoilMap[y][x].ChannelInt += SoilMap[y][x].IExcess;
	  
	  Total->CulvertToChannel += CulvertFlow;
	  Total->RunoffToChannel += SoilMap[y][x].IExcess;
	  
	  SoilMap[y][x].IExcess = 0.0f;

	}
	else {
	  SoilMap[y][x].IExcess += CulvertFlow;
	  Total->CulvertReturnFlow += CulvertFlow;
	  
	}
      }
    }
  }
  /* route stream channels */
  if (ChannelData->streams != NULL) {
    channel_route_network(ChannelData->streams, Time->Dt);
    channel_save_outflow_text(buffer, ChannelData->streams,
			      ChannelData->streamout,
			      ChannelData->streamflowout, flag);
	/* save parameters for John's RBM model */
	if (Options->StreamTemp)
	  channel_save_outflow_text_cplmt(Time, buffer,ChannelData->streams,ChannelData, flag);
  }
  
}
示例#6
0
/*****************************************************************************
  RouteSubSurface()

  Sources: 
  Wigmosta, M. S., L. W. Vail, and D. P. Lettenmaier, A distributed 
      hydrology-vegetation model for complex terrain, Water Resour. Res.,
      30(6), 1665-1679, 1994.

  Quinn, P., K. Beven, P. Chevallier, and O. Planchon, The prediction of 
      hillslope flow paths for distributed hydrological modelling using 
      digital terrain models, Hydrological Processes, 5, 59-79, 1991.

  This routine follows Wigmosta et al. [1994] in calculating the subsurface
  flow.  The local gradient is based on the local hydraulic head, consisting 
  of the height of the pixel surface minus the depth of the water table 
  below the water surface.  This has the disadvantage that the local gradients
  have to be recalculated for each pixel for each timestep.  In Wigmosta et
  al. [1994] the local gradient is taken to be equal to the slope of the land
  surface, which is a reasonable assunption for mountainous areas.  For the 
  flat boreal forest landscape it is probably better to use the slope
  of the water surface.

  Set the gradient with pixels that are outside tha basin to zero.  This 
  ensures that there is no flux of water across the basin boundary.  In the 
  current implementation water can only leave the basin as surface flow.  
  This may not be entirely realistic, and should be analyzed further.  
  One consequence of this could be that the soil in the basin is more 
  saturated than it would be if subsurface flow out of the basin would
  be allowed.

  The surrounding grid cells are numbered in the following way

                |-----| DX

          0-----1-----2  ---
	  |\    |    /|   |
          | \   |   / |   |
          |  \  |  /  |   | DY
          |   \ | /   |   |
          |    \|/    |   |
          7-----*-----3  ---
          |    /|\    |
          |   / | \   |
          |  /  |  \  |
          | /   |   \ |
          |/    |    \|
          6-----5-----4

  For the current implementation it is assumed that the resolution is the 
  same in both the X and the Y direction.  If this is not the case an error
  message is generated and the program exits.  The reason is that the 
  formulation for the flow width in the diagonal direction changes if the
  grid is not square.  The method for defining the flow widths in the case
  of square grids is taken from Quinn et al [1991]

  Update Jan 2004 COD
  When Gradient = WATERTABLE, the watertable was used to route the
  surface water. This was because of the common use of TopoMap.Dir and 
  TopoMap.TotalDir. These are now for surface routing (always) and subsurface 
  routing (when Gradient = TOPOGRAPHY). Subsurface routing directions 
  and FlowGrad (SubDir, SubTotalDir, SubFlowGrad) for Gradient = WATERTABLE 
  are now determined locally here (in RouteSubsurface.c.)

  WORK IN PROGRESS
*****************************************************************************/
void RouteSubSurface(int Dt, MAPSIZE *Map, TOPOPIX **TopoMap,
		     VEGTABLE *VType, VEGPIX **VegMap,
		     ROADSTRUCT **Network, SOILTABLE *SType,
		     SOILPIX **SoilMap, CHANNEL *ChannelData,
		     TIMESTRUCT *Time, OPTIONSTRUCT *Options, 
		     char *DumpPath, SEDPIX **SedMap, FINEPIX ***FineMap,
		     SEDTABLE *SedType, int MaxStreamID, SNOWPIX **SnowMap)
{
  const char *Routine = "RouteSubSurface";
  int x;			/* counter */
  int y;			/* counter */
  int i,j, ii, jj, yy, xx;	/* counters for FineMap initialization */
  float BankHeight;
  float *Adjust;
  float fract_used;
  float depth;
  float OutFlow;
  float water_out_road;
  float Transmissivity;
  float AvailableWater;
  int k;
  float **SubFlowGrad;	        /* Magnitude of subsurface flow gradient
				   slope * width */
  unsigned char ***SubDir;         /* Fraction of flux moving in each direction*/ 
  unsigned int **SubTotalDir;	/* Sum of Dir array */

  /* variables for mass wasting trigger. */
  int count, totalcount;
  float mgrid, sat;
  char buffer[32];
  char satoutfile[100];          /* Character arrays to hold file name. */ 
  FILE *fs;                     /* File pointer. */

  /*****************************************************************************
   Allocate memory 
  ****************************************************************************/
  
  if (!(SubFlowGrad = (float **)calloc(Map->NY, sizeof(float *))))
    ReportError((char *) Routine, 1);
  for(i=0; i<Map->NY; i++) {
    if (!(SubFlowGrad[i] = (float *)calloc(Map->NX, sizeof(float))))
      ReportError((char *) Routine, 1);
  }
  
  if (!((SubDir) = (unsigned char ***) calloc(Map->NY, sizeof(unsigned char **))))
    ReportError((char *) Routine, 1);
  for(i=0; i<Map->NY; i++) {
    if (!((SubDir)[i] = (unsigned char **) calloc(Map->NX, sizeof(unsigned char*))))
	ReportError((char *) Routine, 1);
    for(j=0; j<Map->NX; j++) {
      if (!(SubDir[i][j] = (unsigned char *)calloc(NDIRS, sizeof(unsigned char ))))
    ReportError((char *) Routine, 1);
    }
  }

  if (!(SubTotalDir = (unsigned int **)calloc(Map->NY, sizeof(unsigned int *))))
    ReportError((char *) Routine, 1);
  for(i=0; i<Map->NY; i++) {
    if (!(SubTotalDir[i] = (unsigned int *)calloc(Map->NX, sizeof(unsigned int))))
      ReportError((char *) Routine, 1);
  }
  
  /* reset the saturated subsurface flow to zero */
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	SoilMap[y][x].SatFlow = 0;
	/* ChannelInt and RoadInt are initialized in Aggregate.c Why are there here? */
	/* 	SoilMap[y][x].ChannelInt = 0; */
	SoilMap[y][x].RoadInt = 0;
      }
    }
  }

  if (Options->FlowGradient == WATERTABLE)
    HeadSlopeAspect(Map, TopoMap, SoilMap, SubFlowGrad, SubDir, SubTotalDir);

  /* next sweep through all the grid cells, calculate the amount of
     flow in each direction, and divide the flow over the surrounding
     pixels */

  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	
	if (Options->FlowGradient == TOPOGRAPHY){
	  SubTotalDir[y][x] = TopoMap[y][x].TotalDir;
	  SubFlowGrad[y][x] = TopoMap[y][x].FlowGrad;
	  for (k = 0; k < NDIRS; k++) 
	    SubDir[y][x][k] = TopoMap[y][x].Dir[k];
	}

	BankHeight = (Network[y][x].BankHeight > SoilMap[y][x].Depth) ?
	  SoilMap[y][x].Depth : Network[y][x].BankHeight;
	Adjust = Network[y][x].Adjust;
	fract_used = 0.0f;
	water_out_road = 0.0;

	if (!channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	  for (k = 0; k < NDIRS; k++) {
	    fract_used += (float) SubDir[y][x][k];
/* 	    fract_used += (float) TopoMap[y][x].Dir[k]; */
	  }
/* 	  fract_used /= 255.0f; */
/* 	  fract_used /= (float) TopoMap[y][x].TotalDir; */
	  if (SubTotalDir[y][x] > 0)
	    fract_used /= (float) SubTotalDir[y][x];
	  else
	    fract_used = 0.;

	  /* only bother calculating subsurface flow if water table is above bedrock */
	  if (SoilMap[y][x].TableDepth < SoilMap[y][x].Depth) {
	    depth =
	      ((SoilMap[y][x].TableDepth > BankHeight) ?
	       SoilMap[y][x].TableDepth : BankHeight);

	    Transmissivity =
	      CalcTransmissivity(SoilMap[y][x].Depth, depth,
				 SType[SoilMap[y][x].Soil - 1].KsLat,
				 SType[SoilMap[y][x].Soil - 1].KsLatExp,
				 SType[SoilMap[y][x].Soil - 1].DepthThresh);

	    OutFlow =
	      (Transmissivity * fract_used * SubFlowGrad[y][x] * Dt) /
	      (Map->DX * Map->DY);
/* 	      (Transmissivity * fract_used * TopoMap[y][x].FlowGrad * Dt) / */
/* 	      (Map->DX * Map->DY); */

	    /* check whether enough water is available for redistribution */

	    AvailableWater =
	      CalcAvailableWater(VType[VegMap[y][x].Veg - 1].NSoilLayers,
				 SoilMap[y][x].Depth,
				 VType[VegMap[y][x].Veg - 1].RootDepth,
				 SType[SoilMap[y][x].Soil - 1].Porosity,
				 SType[SoilMap[y][x].Soil - 1].FCap,
				 SoilMap[y][x].TableDepth, Adjust);

	    OutFlow = (OutFlow > AvailableWater) ? AvailableWater : OutFlow;
	  }
	  else {
	    depth = SoilMap[y][x].Depth;
	    OutFlow = 0.0f;
	  }

	  /* compute road interception if water table is above road cut */

	  if (SoilMap[y][x].TableDepth < BankHeight &&
	      channel_grid_has_channel(ChannelData->road_map, x, y)) {
/* 	    fract_used = ((float) Network[y][x].fraction / 255.0f); */
/* 	    fract_used = ((float) Network[y][x].fraction / (float)TopoMap[y][x].TotalDir); */
	    if (SubTotalDir[y][x] > 0)
	      fract_used = ((float) Network[y][x].fraction /
			    (float)SubTotalDir[y][x]);
	    else
	      fract_used = 0.;

	    Transmissivity =
	      CalcTransmissivity(BankHeight, SoilMap[y][x].TableDepth,
				 SType[SoilMap[y][x].Soil - 1].KsLat,
				 SType[SoilMap[y][x].Soil - 1].KsLatExp,
				 SType[SoilMap[y][x].Soil - 1].DepthThresh);
	    water_out_road = (Transmissivity * fract_used *
			      SubFlowGrad[y][x] * Dt) / (Map->DX *
							      Map->DY);
/*                               (Transmissivity * fract_used * */
/* 			      TopoMap[y][x].FlowGrad * Dt) / (Map->DX * */
/* 							      Map->DY); */

	    AvailableWater =
	      CalcAvailableWater(VType[VegMap[y][x].Veg - 1].NSoilLayers,
				 BankHeight,
				 VType[VegMap[y][x].Veg - 1].RootDepth,
				 SType[SoilMap[y][x].Soil - 1].Porosity,
				 SType[SoilMap[y][x].Soil - 1].FCap,
				 SoilMap[y][x].TableDepth, Adjust);
	    water_out_road = (water_out_road > AvailableWater) ? AvailableWater
	      : water_out_road;

	    /* increase lateral inflow to road channel */
	    SoilMap[y][x].RoadInt = water_out_road;
	    channel_grid_inc_inflow(ChannelData->road_map, x, y,
				    water_out_road * Map->DX * Map->DY);

	  }

	  /* Subsurface Component - Decrease water change by outwater */

	  SoilMap[y][x].SatFlow -= OutFlow + water_out_road;

	  /* Assign the water to appropriate surrounding pixels */

/* 	  OutFlow /= 255.0f; */
/* 	  OutFlow /= (float) TopoMap[y][x].TotalDir; */
	  if (SubTotalDir[y][x] > 0)
	    OutFlow /= (float) SubTotalDir[y][x];
	  else
	    OutFlow = 0.;

	  for (k = 0; k < NDIRS; k++) {
	    int nx = xdirection[k] + x;
	    int ny = ydirection[k] + y;
	    if (valid_cell(Map, nx, ny)) {
	      SoilMap[ny][nx].SatFlow += OutFlow * SubDir[y][x][k];
/* 	      SoilMap[ny][nx].SatFlow += OutFlow * TopoMap[y][x].Dir[k]; */
	    }
	  }

	}
	else {			/* cell has a stream channel */

	  if (SoilMap[y][x].TableDepth < BankHeight &&
	      channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	    /* float gradient =  */
	    /*   (4.0 * SoilMap[y][x].Depth > 2.0 * MIN_GRAD * Map->DX) ?  */
	    /*   4.0 * SoilMap[y][x].Depth : 2.0 * MIN_GRAD * Map->DX; */

	    float gradient = 4.0 * (BankHeight - SoilMap[y][x].TableDepth);
	    if (gradient < 0.0)
	      gradient = 0.0;

	    Transmissivity =
	      CalcTransmissivity(BankHeight, SoilMap[y][x].TableDepth,
				 SType[SoilMap[y][x].Soil - 1].KsLat,
				 SType[SoilMap[y][x].Soil - 1].KsLatExp,
				 SType[SoilMap[y][x].Soil - 1].DepthThresh);

	    OutFlow = (Transmissivity * gradient * Dt) / (Map->DX * Map->DY);

	    /* check whether enough water is available for redistribution */

	    AvailableWater =
	      CalcAvailableWater(VType[VegMap[y][x].Veg - 1].NSoilLayers,
				 BankHeight,
				 VType[VegMap[y][x].Veg - 1].RootDepth,
				 SType[SoilMap[y][x].Soil - 1].Porosity,
				 SType[SoilMap[y][x].Soil - 1].FCap,
				 SoilMap[y][x].TableDepth, Adjust);

	    OutFlow = (OutFlow > AvailableWater) ? AvailableWater : OutFlow;

	    /* remove water going to channel from the grid cell */
	    SoilMap[y][x].SatFlow -= OutFlow;

	    /* contribute to channel segment lateral inflow */
	    channel_grid_inc_inflow(ChannelData->stream_map, x, y,
				    OutFlow * Map->DX * Map->DY);

	    SoilMap[y][x].ChannelInt += OutFlow;
	  }
	}
      }
    }
  }

 for(i=0; i<Map->NY; i++) { 
    free(SubTotalDir[i]);
    free(SubFlowGrad[i]);
    for(j=0; j<Map->NX; j++){
      free(SubDir[i][j]);
    }
    free(SubDir[i]);
  }
  free(SubDir);
  free(SubTotalDir);
  free(SubFlowGrad);

  /**********************************************************************/
  /* Dump saturation extent file to screen for Mass Wasting dates.
     Saturation extent is based on the number of pixels with a water table 
     that is at least MTHRESH of soil depth. */ 
  
  count =0;
  totalcount = 0;
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	mgrid = (SoilMap[y][x].Depth - SoilMap[y][x].TableDepth)/SoilMap[y][x].Depth;
	if(mgrid > MTHRESH) count += 1;
	totalcount +=1;
      }
    }
  }
 
  sat = 100.*((float)count/(float)totalcount);
  
  sprintf(satoutfile, "%ssaturation_extent.txt", DumpPath);
  
  if((fs=fopen(satoutfile,"a")) == NULL){
    printf("Cannot open saturation extent output file.\n");
    exit(0);
  }
  
  SPrintDate(&(Time->Current), buffer);
  fprintf(fs, "%-20s %.4f \n", buffer, sat); 
  fclose(fs);    
  
  /* Initialize the mass wasting variables for all time steps
     to maintain the mass balance */
  if(Options->Sediment){
    for (y = 0; y < Map->NY; y++) {
      for (x = 0; x < Map->NX; x++) {
	if (INBASIN(TopoMap[y][x].Mask)) {
	  for(ii=0; ii< Map->DY/Map->DMASS; ii++) { /* Fine resolution counters. */
	    for(jj=0; jj< Map->DX/Map->DMASS; jj++) {
	      yy = (int) y*Map->DY/Map->DMASS + ii;
	      xx = (int) x*Map->DX/Map->DMASS + jj;
	      (*FineMap[yy][xx]).Probability = 0.;
	      (*FineMap[yy][xx]).MassWasting = 0.;
	      (*FineMap[yy][xx]).MassDeposition = 0.;
	      (*FineMap[yy][xx]).SedimentToChannel = 0.;
	    }
	  }
	}
      }
    }
    
    /* Call the mass wasting algorithm */
    if(Options->MassWaste){
      if(Time->NMWMTotalSteps > 0){
	if(Time->Current.Julian == Time->MWMnext.Julian){   
	  MainMWM(SedMap, FineMap, VType, SedType, ChannelData, DumpPath, SoilMap,
		  Time, Map, TopoMap, SType, VegMap, MaxStreamID, SnowMap);
	  
	  /* catch the next date */
	  for (i = 0; i < Time->NMWMTotalSteps; i++){
	    if(Time->MWMnext.Julian < Time->MWM[i].Julian){
	      Time->MWMnext = Time->MWM[i];
	      break;
	    }
	  }
	}
      }
      else{ /* Time->NMWMTotalSteps == 0 run the old way*/
	if((float)count/((float)totalcount) > SATPERCENT) {
	  MainMWM(SedMap, FineMap, VType, SedType, ChannelData, DumpPath, SoilMap,
		  Time, Map, TopoMap, SType, VegMap, MaxStreamID, SnowMap);
	}
      }
    }
  }
  
  /**********************************************************************/
  /* End added code. */
  
}
示例#7
0
/*****************************************************************************
  Function name: InitNetwork()

  Purpose      : Initialize road/channel work.  Memory is allocated, and the
                 necessary adjustments for the soil profile are calculated

  Comments     : 
*****************************************************************************/
void InitNetwork(int NY, int NX, float DX, float DY, TOPOPIX **TopoMap, 
		 SOILPIX **SoilMap, VEGPIX **VegMap, VEGTABLE *VType, 
		 ROADSTRUCT ***Network, CHANNEL *ChannelData, 
		 LAYER Veg, OPTIONSTRUCT *Options)
{
  const char *Routine = "InitNetwork";
  int i;			/* counter */
  int x;			/* column counter */
  int y;			/* row counter */
  int sx, sy;
  int minx, miny;
  int doimpervious;
  int numroads;          /* Counter of number of pixels
			    with a road and channel */
  int numroadschan;      /* Counter of number of pixels
			    with a road */
  FILE *inputfile;
  /* Allocate memory for network structure */

  if (!(*Network = (ROADSTRUCT **) calloc(NY, sizeof(ROADSTRUCT *))))
    ReportError((char *) Routine, 1);

  for (y = 0; y < NY; y++) {
    if (!((*Network)[y] = (ROADSTRUCT *) calloc(NX, sizeof(ROADSTRUCT))))
      ReportError((char *) Routine, 1);
  }

  for (y = 0; y < NY; y++) {
    for (x = 0; x < NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
		  if (!((*Network)[y][x].Adjust = 
			  (float *) calloc((VType[VegMap[y][x].Veg - 1].NSoilLayers + 1), sizeof(float))))
			  ReportError((char *) Routine, 1);
		  
		  if (!((*Network)[y][x].PercArea =
			  (float *) calloc((VType[VegMap[y][x].Veg - 1].NSoilLayers + 1), sizeof(float))))
			  ReportError((char *) Routine, 1);
      }
    }
  }

  numroadschan = 0;
  numroads = 0;

  /* If a road/channel Network is imposed on the area, read the Network
     information, and calculate the storage adjustment factors */
  if (Options->HasNetwork) {
    for (y = 0; y < NY; y++) {
      for (x = 0; x < NX; x++) {
	if (INBASIN(TopoMap[y][x].Mask)) {
	  ChannelCut(y, x, ChannelData, &((*Network)[y][x]));
	  AdjustStorage(VType[VegMap[y][x].Veg - 1].NSoilLayers,
			SoilMap[y][x].Depth,
			VType[VegMap[y][x].Veg - 1].RootDepth,
			(*Network)[y][x].Area, DX, DY, 
			(*Network)[y][x].BankHeight,
			(*Network)[y][x].PercArea,
			(*Network)[y][x].Adjust,
			&((*Network)[y][x].CutBankZone));
	  (*Network)[y][x].IExcess = 0.;
	  if (channel_grid_has_channel(ChannelData->road_map, x, y)) {
	    numroads++;
	    if (channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	      numroadschan++;
	    }
	    (*Network)[y][x].fraction =
	      ChannelFraction(&(TopoMap[y][x]), ChannelData->road_map[x][y]);
	    (*Network)[y][x].MaxInfiltrationRate = 
	      MaxRoadInfiltration(ChannelData->road_map, x, y);
	    (*Network)[y][x].RoadClass = 
	      channel_grid_class(ChannelData->road_map, x, y);
	    (*Network)[y][x].FlowSlope = 
	      channel_grid_flowslope(ChannelData->road_map, x, y);
	    (*Network)[y][x].FlowLength = 
	      channel_grid_flowlength(ChannelData->road_map, x, y,(*Network)[y][x].FlowSlope);
	    (*Network)[y][x].RoadArea = channel_grid_cell_width(ChannelData->road_map, x, y) * channel_grid_cell_length(ChannelData->road_map, x, y);
	  }
	  else {
	    (*Network)[y][x].MaxInfiltrationRate = DHSVM_HUGE;
	    (*Network)[y][x].FlowSlope = 0.;
	    (*Network)[y][x].FlowLength = 0.;
	    (*Network)[y][x].RoadArea = 0.;
	    (*Network)[y][x].RoadClass = NULL;
	    (*Network)[y][x].IExcess = 0.;
	  }
	}
      }
    }
  }
  /* if no road/channel Network is imposed, set the adjustment factors to the
     values they have in the absence of an imposed network */
  else {
    for (y = 0; y < NY; y++) {
      for (x = 0; x < NX; x++) {
	if (INBASIN(TopoMap[y][x].Mask)) {
	  for (i = 0; i <= VType[VegMap[y][x].Veg - 1].NSoilLayers; i++) {
	    (*Network)[y][x].Adjust[i] = 1.0;
	    (*Network)[y][x].PercArea[i] = 1.0;
	    (*Network)[y][x].CutBankZone = NO_CUT;
	    (*Network)[y][x].MaxInfiltrationRate = 0.;
	  }
	  (*Network)[y][x].FlowSlope = 0.;
	  (*Network)[y][x].FlowLength = 0.;
	  (*Network)[y][x].RoadArea = 0.;
	  (*Network)[y][x].RoadClass = NULL;
	  (*Network)[y][x].IExcess = 0.;
	}
      }
    }
  }

  if (numroads > 0){
    printf("There are %d pixels with a road and %d with a road and a channel.\n",
	    numroads, numroadschan);
  }
 
  /* this all pertains to the impervious surface */

  doimpervious = 0;
  for (i = 0; i < Veg.NTypes; i++)
    if (VType[i].ImpervFrac > 0.0)
      doimpervious = 1;

  if (doimpervious) {
    if (!(inputfile = fopen(Options->ImperviousFilePath, "rt"))) {
      fprintf(stderr, 
	      "User has specified a percentage impervious area \n");
      fprintf(stderr, 
	      "To incorporate impervious area, DHSVM needs a file\n");
      fprintf(stderr, 
	      "identified by the key: \"IMPERVIOUS SURFACE ROUTING FILE\",\n");
      fprintf(stderr, 
	      "in the \"VEGETATION\" section.  This file is used to \n");
      fprintf(stderr, 
	      "determine the fate of surface runoff, i.e. where does it go \n");
      fprintf(stderr, 
	      "This file was not found: see InitNetwork.c \n");
      fprintf(stderr, 
	      "The code find_nearest_channel.c will make the file\n");
      ReportError(Options->ImperviousFilePath, 3);
    }
    for (y = 0; y < NY; y++) {
      for (x = 0; x < NX; x++) {
	if (INBASIN(TopoMap[y][x].Mask)) {
	  if (fscanf(inputfile, "%d %d %d %d \n", &sy, &sx, &miny, &minx) !=
	      EOF) {
	    TopoMap[y][x].drains_x = minx;
	    TopoMap[y][x].drains_y = miny;
	  }
	  else {
	    ReportError(Options->ImperviousFilePath, 63);
	  }
	  if (sx != x || sy != y) {
	    ReportError(Options->ImperviousFilePath, 64);
	  }
         if (!channel_grid_has_channel(ChannelData->stream_map, minx, miny)) {
	    printf("Routing file is wrong. The desitination cell is no channel cell!\n"); 
	    exit(0);
	  }
	}
      }
    }
  }
}
示例#8
0
void MainMWM(SEDPIX **SedMap, FINEPIX ***FineMap, VEGTABLE *VType,
	     SEDTABLE *SedType, CHANNEL *ChannelData, char *DumpPath, 
	     SOILPIX **SoilMap, TIMESTRUCT *Time, MAPSIZE *Map,
	     TOPOPIX **TopoMap, SOILTABLE *SType, VEGPIX **VegMap,
	     int MaxStreamID, SNOWPIX **SnowMap) 
{
  int x,y,xx,yy,i,j,ii,jj,k,iter;  /* Counters. */
  int coursei, coursej;
  int nextx, nexty;
  int prevx, prevy;
  int numfailedpixels;
  int numlikelyfailedpixels;
  int numfailures;
  float avgnumfailures;
  float avgpixperfailure;
  float failure_threshold = 0.0;
  char buffer[32];
  char sumoutfile[100];  /* Character array to hold file name. */ 
  int **failure;
  float factor_safety;
  float LocalSlope;
  FILE *fs;                  /* File pointer. */
  int numpixels;
  int cells, count, checksink;
  int massitertemp;               /* if massiter is 0, sets the counter to 1 here */
  float TotalVolume;
  node *head, *tail;
  float SlopeAspect, SedimentToChannel;
  float *SegmentSediment;         /* The cumulative sediment content over all stochastic
				     iterations for each channel segment. */
  float **SegmentSedimentm;         /* The cumulative sediment mass over all stochastic
				     iterations for each channel segment. */
  float *InitialSegmentSediment; /* Placeholder of segment sediment load at 
				    beginning of time step. */
float **InitialSegmentSedimentm; /* Placeholder of segment sediment mass at 
				    beginning of time step. */
  float **SedThickness;          /* Cumulative sediment depth over all stochastic
				    iterations for each pixel.  */
  float **InitialSediment;       /* Place holder of pixel sediment load at beginning of
				    time step. */
  float SedToDownslope;		/* Sediment wasted from a pixel, awaiting redistribution */
  float SedFromUpslope;		/* Wasted sediment being redistributed */
  float FineMapTableDepth;       /* Fine grid water table depth (m) */
  float TableDepth;              /* Coarse grid water table depth (m) */
  float FineMapSatThickness;    /* Fine grid saturated thickness (m) */
  float **Redistribute, **TopoIndex, **TopoIndexAve;
  int firsti, firstj;
  head = NULL;
  tail = NULL;

  /*****************************************************************************
   Allocate memory for Soil Moisture Redistribution
  ****************************************************************************/
  if (!(Redistribute = (float **)calloc(Map->NY, sizeof(float *))))
    ReportError("MainMWM", 1);
  for(i=0; i<Map->NY; i++) {
    if (!(Redistribute[i] = (float *)calloc(Map->NX, sizeof(float))))
      ReportError("MainMWM", 1);
  }
  
  if (!(TopoIndex = (float **)calloc(Map->NY, sizeof(float *))))
    ReportError("MainMWM", 1);
  for(i=0; i<Map->NY; i++) {
    if (!(TopoIndex[i] = (float *)calloc(Map->NX, sizeof(float))))
      ReportError("MainMWM", 1);
  }
  
  if (!(TopoIndexAve = (float **)calloc(Map->NY, sizeof(float *))))
    ReportError("MainMWM", 1);
  for(i=0; i<Map->NY; i++) {
    if (!(TopoIndexAve[i] = (float *)calloc(Map->NX, sizeof(float))))
      ReportError("MainMWM", 1);
  }
  
  /* Redistribute soil moisture from coarse grid to fine grid. The is done similarly
     to Burton, A. and J.C. Bathurst, 1998, Physically based modelling of shallow 
     landslide sediment yield as a catchment scale, Environmental Geology, 
     35 (2-3), 89-99.*/
  
  for (i = 0; i < Map->NY; i++) {
    for (j = 0; j < Map->NX; j++) {
      
      /* Check to make sure region is in the basin. */
      if (INBASIN(TopoMap[i][j].Mask)) {
	
        /* Step over each fine resolution cell within the model grid cell. */
	for(ii=0; ii< Map->DY/Map->DMASS; ii++) { /* Fine resolution counters. */
	  for(jj=0; jj< Map->DX/Map->DMASS; jj++) {
	    y = (int) i*Map->DY/Map->DMASS + ii;
	    x = (int) j*Map->DX/Map->DMASS + jj;
	    
	    TopoIndex[i][j] += (*FineMap[y][x]).TopoIndex;
	    
	  }
	}
	/* TopoIndexAve is the TopoIndex for the coarse grid calculated as the average of the 
	   TopoIndex of the fine grids in the coarse grid. */
	TopoIndexAve[i][j] = TopoIndex[i][j]/Map->NumFineIn;
      }
    }
  }
  
  FineMapSatThickness = 0.;
  
  for (i = 0; i < Map->NY; i++) {
    for (j  = 0; j < Map->NX; j++) {
      if (INBASIN(TopoMap[i][j].Mask)) {
	
	TableDepth = SoilMap[i][j].TableDepth;
	
	/* Do not want to distribute ponded water  */
	if (TableDepth < 0.)
	  TableDepth = 0.;
	
	for(ii=0; ii< Map->DY/Map->DMASS; ii++) {
	  for(jj=0; jj< Map->DX/Map->DMASS; jj++) {
	    y = (int) i*Map->DY/Map->DMASS + ii;
	    x = (int) j*Map->DX/Map->DMASS + jj;
	    
	    if (SoilMap[i][j].Depth > SoilMap[i][j].TableDepth){

	      FineMapTableDepth = TableDepth + 
		((TopoIndexAve[i][j]-(*FineMap[y][x]).TopoIndex)/ 
		 SType[SoilMap[i][j].Soil - 1].KsLatExp);
	      
	      if (FineMapTableDepth < 0.) {
		(*FineMap[y][x]).SatThickness = (*FineMap[y][x]).sediment; 
	      }
	      else if (FineMapTableDepth > (*FineMap[y][x]).sediment)
		(*FineMap[y][x]).SatThickness = 0.; 
	      
	      else 
		(*FineMap[y][x]).SatThickness = (*FineMap[y][x]).sediment -
		  FineMapTableDepth;
	    }	    
	    else (*FineMap[y][x]).SatThickness = 0.; 
	    
	    FineMapSatThickness += (*FineMap[y][x]).SatThickness;
	    
	    if ((ii== Map->DY/Map->DMASS - 1) & (jj== Map->DX/Map->DMASS - 1)){
	      
	      /* Calculating the difference between the volume of water distributed
		 (only saturated) and available volume of water (m3)*/
	      Redistribute[i][j] = (Map->DY * Map->DX *
				    (SoilMap[i][j].Depth - TableDepth)) - 
		(FineMapSatThickness*Map->DMASS*Map->DMASS); 
	      FineMapSatThickness = 0.;
	    }
	  }
	}
      }
    }
  }
  
  /* Redistribute volume difference. Start with cells with too much water. */ 
  for (i = 0; i < Map->NY; i++) {
    for (j  = 0; j < Map->NX; j++) {
      if (INBASIN(TopoMap[i][j].Mask)) {
	
	if (Redistribute[i][j]< -25.){
	  
	  for (k = 0; k < Map->NumFineIn; k++) { 
	    y = TopoMap[i][j].OrderedTopoIndex[k].y;
	    x = TopoMap[i][j].OrderedTopoIndex[k].x;
	    yy = TopoMap[i][j].OrderedTopoIndex[(Map->NumFineIn)-k-1].y;
	    xx = TopoMap[i][j].OrderedTopoIndex[(Map->NumFineIn)-k-1].x;
	    
	    /* Convert sat thickness to a volume */
	    (*FineMap[y][x]).SatThickness *= (Map->DMASS)*(Map->DMASS);
	    /* Add to volume based on amount to be redistributed */
	    (*FineMap[y][x]).SatThickness += Redistribute[i][j] * 
	      ((*FineMap[yy][xx]).TopoIndex/TopoIndex[i][j]); 
	    /* Convert back to thickness (m)*/
	    (*FineMap[y][x]).SatThickness /= (Map->DMASS)*(Map->DMASS);
	    
	  }
	}
      }
    }
  }
  
  /* Redistribute volume difference for cells with too little water.*/ 
  for (i = 0; i < Map->NY; i++) {
    for (j  = 0; j < Map->NX; j++) {
      
      if (INBASIN(TopoMap[i][j].Mask)) {
	
	for(ii=0; ii< Map->DY/Map->DMASS; ii++) {
	  for(jj=0; jj< Map->DX/Map->DMASS; jj++) {
	    y = (int) i*Map->DY/Map->DMASS + ii;
	    x = (int) j*Map->DX/Map->DMASS + jj;
	    
	    if (Redistribute[i][j] > 25.){
	      
	      /* Convert sat thickness to a volume */
	      (*FineMap[y][x]).SatThickness *= (Map->DMASS)*(Map->DMASS);
	      /* Add to volume based on amount to be redistributed */
	      (*FineMap[y][x]).SatThickness += Redistribute[i][j] * 
		((*FineMap[y][x]).TopoIndex/TopoIndex[i][j]);
	      /* Convert back to thickness (m)*/
	      (*FineMap[y][x]).SatThickness /= (Map->DMASS)*(Map->DMASS);
	      
	    }
	    
	    if ((Redistribute[i][j] > 25.)||(Redistribute[i][j]< -25.)){
	      
	      if ((*FineMap[y][x]).SatThickness > (*FineMap[y][x]).sediment)
		(*FineMap[y][x]).SatThickness = (*FineMap[y][x]).sediment; 
	      
	      else if ((*FineMap[y][x]).SatThickness < 0.)
		(*FineMap[y][x]).SatThickness = 0.;
	    }
	  }
	}
      }
    }
  }	      
  
  for(i=0; i<Map->NY; i++) { 
    free(Redistribute[i]);
    free(TopoIndex[i]);
    free(TopoIndexAve[i]);
  }
  free(Redistribute);
  free(TopoIndex);
  free(TopoIndexAve);
  
  /*****************************************************************************
    Allocate memory for ensemble calculations
  *****************************************************************************/
  if (!(failure = (int **)calloc(Map->NYfine, sizeof(int *))))
    ReportError("MainMWM", 1);
  for(i=0; i<Map->NYfine; i++) {
    if (!(failure[i] = (int *)calloc(Map->NXfine, sizeof(int))))
      ReportError("MainMWM", 1);
  }
  
  if (!(SedThickness = (float **)calloc(Map->NYfine, sizeof(float *))))
    ReportError("MainMWM", 1);
  for(i=0; i<Map->NYfine; i++) {
    if (!(SedThickness[i] = (float *)calloc(Map->NXfine, sizeof(float))))
      ReportError("MainMWM", 1);
  }
  
  if (!(InitialSediment = (float **)calloc(Map->NYfine, sizeof(float *))))
    ReportError("MainMWM", 1);
  for(i=0; i<Map->NYfine; i++) {
    if (!(InitialSediment[i] = (float *)calloc(Map->NXfine, sizeof(float))))
      ReportError("MainMWM", 1);
  }
  
  if (!(SegmentSediment = (float *)calloc(MaxStreamID, sizeof(float ))))
    ReportError("MainMWM", 1);

  if (!(SegmentSedimentm = (float **)calloc(MaxStreamID, sizeof(float *))))
    ReportError("MainMWM", 1);
  for(i=1; i<MaxStreamID+1; i++) {
    if (!(SegmentSedimentm[i] = (float *)calloc(NSEDSIZES, sizeof(float))))
      ReportError("MainMWM", 1);
  }
  
  if (!(InitialSegmentSediment = (float *)calloc(MaxStreamID, sizeof(float ))))
    ReportError("MainMWM", 1);

  if (!(InitialSegmentSedimentm = (float **)calloc(MaxStreamID, sizeof(float *))))
    ReportError("MainMWM", 1);  
 for(i=1; i<MaxStreamID+1; i++) {
    if (!(InitialSegmentSedimentm[i] = (float *)calloc(NSEDSIZES, sizeof(float))))
      ReportError("MainMWM", 1);
  }

  /* Initialize arrays. */
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	for(ii=0; ii< Map->DY/Map->DMASS; ii++) { /* Fine resolution counters. */
	  for(jj=0; jj< Map->DX/Map->DMASS; jj++) {
	    yy = (int) y*Map->DY/Map->DMASS + ii;
	    xx = (int) x*Map->DX/Map->DMASS + jj;
	    InitialSediment[yy][xx] = (*FineMap[yy][xx]).sediment;
	    (*FineMap[yy][xx]).Probability = 0.;
	    (*FineMap[yy][xx]).MassWasting = 0.;
	    (*FineMap[yy][xx]).MassDeposition = 0.;
	    (*FineMap[yy][xx]).SedimentToChannel = 0.;
	  }
	}
      }
    }
  }
  initialize_sediment_mass(ChannelData->streams, InitialSegmentSedimentm);
  update_sediment_array(ChannelData->streams, InitialSegmentSediment, InitialSegmentSedimentm);
  
  /************************************************************************/
  /* Begin iteration for multiple ensembles. */
  /************************************************************************/

  /* sloppy fix for when MASSITER=0 -- this only needs to be checked once */
  if(MASSITER==0) massitertemp=1;
  else massitertemp=MASSITER;
  
  numfailures = 0;
  for(iter=0; iter < massitertemp; iter++) {
    
    printf("iter=%d\n",iter);
    
    /************************************************************************/
    /* Begin factor of safety code. */
    /************************************************************************/
    for(i=0; i<Map->NY; i++) {
      for(j=0; j<Map->NX; j++) {
	if (INBASIN(TopoMap[i][j].Mask)) {		
	  
	  for(ii=0; ii<Map->DY/Map->DMASS; ii++) {
	    for(jj=0; jj<Map->DX/Map->DMASS; jj++) {
	      y = i*Map->DY/Map->DMASS + ii; 
	      x = j*Map->DX/Map->DMASS + jj;
	      coursei = i;
	      coursej = j;

	      firsti=y;
	      firstj=x;
	      /* Don't allow failures that will propagate outside the basin. */
	      /* Fine mask is optional, so they still may occur. */
	      if(INBASIN((*FineMap[y][x]).Mask)) {
		checksink = 0;
		numpixels = 0;
		SedToDownslope = 0.0;
		SedFromUpslope = 0.0;
		SedimentToChannel = 0.0;
		/* First check for original failure. */
		if((*FineMap[y][x]).SatThickness/SoilMap[i][j].Depth > MTHRESH && failure[y][x] == 0
		   && (*FineMap[y][x]).sediment > 0.0) {

		  LocalSlope = ElevationSlope(Map, TopoMap, FineMap, y, x, &nexty, &nextx, y, x, &SlopeAspect);
	
		  if(LocalSlope >= 10.) { 
		    factor_safety = CalcSafetyFactor(LocalSlope, SoilMap[i][j].Soil, 
						     (*FineMap[y][x]).sediment, 
						     VegMap[i][j].Veg, SedType, VType, 
						     (*FineMap[y][x]).SatThickness, SType, 
						     SnowMap[i][j].Swq, SnowMap[i][j].Depth,
						     iter);
		    
		    /* check if fine pixel fails */
		    if (factor_safety < FS_CRITERIA && factor_safety > 0) {
                      numfailures++;
		      numpixels = 1;
		      failure[y][x] = 1;	      
		      
		      /* Update sediment depth. All sediment leaves failed fine pixel */
		      SedToDownslope = (*FineMap[y][x]).sediment;
		      (*FineMap[y][x]).sediment = 0.0;
		   		      
		      // Pass sediment down to next pixel
		      SedFromUpslope = SedToDownslope;

		      /* Follow failures down slope; skipped if no original failure. */
		      while(failure[y][x] == 1 && checksink == 0 
			    && !channel_grid_has_channel(ChannelData->stream_map, coursej, coursei)
			    && INBASIN(TopoMap[coursei][coursej].Mask)) {
			
			/* Update counters. */
			prevy = y;
			prevx = x;
			y = nexty;
			x = nextx;
			coursei = floor(y*Map->DMASS/Map->DY);
			coursej = floor(x*Map->DMASS/Map->DX);
			
			if (!INBASIN(TopoMap[coursei][coursej].Mask)) {
			  
			  printf("WARNING: attempt to propagate failure to grid cell outside basin: y %d x %d\n",y,x);
			  printf("Depositing wasted sediment in grid cell y %d x %d\n",prevy,prevx);
			  (*FineMap[prevy][prevx]).sediment += SedFromUpslope;
			  SedFromUpslope = SedToDownslope = 0.0;
			  
			  // Since we're returning SedFromUpslope to the upslope pixel,
			  // the upslope pixel can't be considered as part of the failure
			  failure[prevy][prevx] = 0;
			  
			}
			else {
			  
			  // Add sediment from upslope to current sediment
			  (*FineMap[y][x]).sediment += SedFromUpslope;
			 			  
			  LocalSlope = ElevationSlope(Map, TopoMap, FineMap, y, x, &nexty, 
					            &nextx, prevy, prevx, &SlopeAspect);
			  /*  Check that not a sink */
			  if(LocalSlope >= 0.) {
			    
			    factor_safety = CalcSafetyFactor(LocalSlope, SoilMap[coursei][coursej].Soil, 
							     (*FineMap[y][x]).sediment, 
							     VegMap[coursei][coursej].Veg, SedType, VType,
							     (*FineMap[y][x]).SatThickness, SType,
							     SnowMap[coursei][coursej].Swq, 
							     SnowMap[coursei][coursej].Depth, iter);
			    
			    /* check if fine pixel fails */
			    if (factor_safety < FS_CRITERIA && factor_safety > 0) {
			      numpixels += 1;
			      failure[y][x] = 1;
			      
			      /* Update sediment depth. All sediment leaves failed fine pixel */
			      SedToDownslope = (*FineMap[y][x]).sediment;
			      (*FineMap[y][x]).sediment = 0.0;
			      
			      // Pass sediment down to next pixel
			      SedFromUpslope = SedToDownslope;
			      
			    }
			    else {
			      /* Update sediment depth. */
			      // Remove the sediment we added for the slope calculation
			      // and instead prepare to distribute this sediment along runout zone
			      (*FineMap[y][x]).sediment -= SedFromUpslope;
			      
			    }
			  } /* end  if(LocalSlope >= 0) { */
			  else {
			    /* Update sediment depth. */
			    // Remove the sediment we added for the slope calculation
			    // and instead prepare to distribute this sediment along runout zone
			    //   (*FineMap[y][x]).sediment -= SedFromUpslope;
			    /* If it reaches here, a sink exists. A sink can 
			       not fail or run out, so move to the next pixel. */
			    checksink++;
			    
			  }
			  
			}
			
		      }  /* End of while loop. */
		      
		      if (checksink > 0) continue;
		      
		      /* Failure has stopped, now calculate runout distance and 
			 redistribute sediment. */
		      
		      // y and x are now the coords of the first pixel of the runout
		      // (downslope neighbor of final pixel of the failure);
		      // this is the pixel that caused the last loop to exit,
		      // whether due to being a sink, not failing,
		      // being in a coarse pixel containing a stream,
		      // or being outside the basin
		      
		      // If current cell is outside the basin,
		      // stop processing this runout and go to next failure candidate
		      if (!INBASIN(TopoMap[coursei][coursej].Mask)) {
			continue;
		      }
		      
		      // TotalVolume = depth (not volume) being redistributed
		      TotalVolume = SedFromUpslope;
		      
		      cells = 1;
		      
		      /* queue begins with initial unfailed pixel. */
		      enqueue(&head, &tail, y, x); 
		      
		      while(LocalSlope > 4. && !channel_grid_has_channel(ChannelData->stream_map, coursej, coursei)
			    && INBASIN(TopoMap[coursei][coursej].Mask)) {
			/* Redistribution stops if last pixel was a channel
			   or was outside the basin. */
			/* Update counters. */
			prevy = y;
			prevx = x;
			y = nexty;
			x = nextx;
			coursei = floor(y*Map->DMASS/Map->DY);
			coursej = floor(x*Map->DMASS/Map->DX);
			
			if (INBASIN(TopoMap[coursei][coursej].Mask)) {
			  
			  LocalSlope = ElevationSlope(Map, TopoMap, FineMap, y, x, &nexty,
						      &nextx, prevy, prevx,
						      &SlopeAspect);
			  enqueue(&head, &tail, y, x);
			  cells++;
			}
			else {
			  printf("WARNING: attempt to propagate runout to grid cell outside the basin: y %d x %d\n",y,x);
			  printf("Final grid cell of runout will be: y %d x %d\n",prevy,prevx);
			}
		      }
		      prevy = y;
		      prevx = x;
		      
		      for(count=0; count < cells; count++) {
			dequeue(&head, &tail, &y, &x);
			coursei = floor(y*Map->DMASS/Map->DY);
			coursej = floor(x*Map->DMASS/Map->DX);
			
			
			// If this node has a channel, then this MUST be the end of the queue
			if(channel_grid_has_channel(ChannelData->stream_map, coursej, coursei)) {
			  /* TotalVolume at this point is a depth in m over one fine
			     map grid cell - convert to m3 */
			  SedimentToChannel = TotalVolume*(Map->DMASS*Map->DMASS)/(float) cells;
			}
			else {
			  /* Redistribute sediment equally among all hillslope cells. */
			  (*FineMap[y][x]).sediment += TotalVolume/cells;
			}
		      }
		      
		      if(SedimentToChannel > 0.0) {
			if(SlopeAspect < 0.) {
			  printf("Invalid aspect (%3.1f) in cell y= %d x= %d\n",
				  SlopeAspect,y,x);
			  exit(0);
			}
			else {
			  
			  // Add Current value of SedimentToChannel to running total for this FineMap cell
			  // (allowing for more than one debris flow to end at the same channel)
			  (*FineMap[y][x]).SedimentToChannel += SedimentToChannel;
			  
			  // Now route SedimentToChannel through stream network
			  RouteDebrisFlow(&SedimentToChannel, coursei, coursej, SlopeAspect, ChannelData, Map); 

			}
		      }
		     
		    } /* End of this failure/runout event */
		    
		  }		      
		}
	      
	      }   /* End of fine mask check. */
	    }  /* End of jj loop. */
	  }
	}
	
	
      }       
    }    /* End of course resolution loop. */
    
    /* Record failures and Reset failure map for new iteration. */
    for(i=0; i<Map->NY; i++) {
      for(j=0; j<Map->NX; j++) {
	if (INBASIN(TopoMap[i][j].Mask)) {		
	  
	  for(ii=0; ii<Map->DY/Map->DMASS; ii++) {
	    for(jj=0; jj<Map->DX/Map->DMASS; jj++) {
	      y = i*Map->DY/Map->DMASS + ii; 
	      x = j*Map->DX/Map->DMASS + jj;
	      
	      (*FineMap[y][x]).Probability += (float) failure[y][x];
	  
	      /* Record cumulative sediment volume. */
	      SedThickness[y][x] += (*FineMap[y][x]).sediment;
	  
	      /* Reset sediment thickness for each iteration; otherwise there is 
	         a decreasing probability of failure for subsequent iterations. */
	      /* If not in stochastic mode, then allow a history of past failures
	         and do not reset sediment depth */
	      if(massitertemp>1) {
	        (*FineMap[y][x]).sediment = InitialSediment[y][x];
	        failure[y][x] = 0;
	      }
	    }
	  }
	}
      }
    }
/*  printf("Sediment Mass is "); */
/*  count_sediment_mass(ChannelData->streams, InitialSegmentSediment); */
    

    /* Record cumulative stream sediment volumes. */
    initialize_sediment_array(ChannelData->streams, SegmentSediment,
			      SegmentSedimentm);

    /* Reset channel sediment volume for each iteration. */
    update_sediment_array(ChannelData->streams, InitialSegmentSediment, InitialSegmentSedimentm);
    
    update_sediment_mass(ChannelData->streams, SegmentSedimentm, 
			 massitertemp);

  }    /* End iteration loop */

  // Normalize mass wasting vars by number of iterations
  numfailedpixels = 0;
  numlikelyfailedpixels = 0;
  for(i=0; i<Map->NY; i++) {
    for(j=0; j<Map->NX; j++) {
      if (INBASIN(TopoMap[i][j].Mask)) {		
	  
	for(ii=0; ii<Map->DY/Map->DMASS; ii++) {
	  for(jj=0; jj<Map->DX/Map->DMASS; jj++) {
	    y = i*Map->DY/Map->DMASS + ii; 
	    x = j*Map->DX/Map->DMASS + jj;
	      
	    (*FineMap[y][x]).Probability /= (float)massitertemp;
	    (*FineMap[y][x]).sediment = SedThickness[y][x]/(float)massitertemp;
	    (*FineMap[y][x]).SedimentToChannel /= (float)massitertemp;

	    if ((*FineMap[y][x]).sediment > InitialSediment[y][x]) {
	      (*FineMap[y][x]).MassDeposition = ((*FineMap[y][x]).sediment - InitialSediment[y][x])*(Map->DMASS*Map->DMASS);
	      (*FineMap[y][x]).MassWasting = 0.0;
	    }
	    else if ((*FineMap[y][x]).sediment < InitialSediment[y][x]) {
	      (*FineMap[y][x]).MassDeposition = 0.0;
	      (*FineMap[y][x]).MassWasting = (InitialSediment[y][x] - (*FineMap[y][x]).sediment)*(Map->DMASS*Map->DMASS);
	    }
	    if((*FineMap[y][x]).Probability > 0)
	      numfailedpixels +=1;
	  
	    if((*FineMap[y][x]).Probability > failure_threshold)
	      numlikelyfailedpixels +=1;
	  
	    (*FineMap[y][x]).DeltaDepth = (*FineMap[y][x]).sediment - 
	      SoilMap[i][j].Depth;

	  }
	}
      }
    }
  }

  // Compute average number of failures
  avgnumfailures = numfailures/(float)massitertemp;

  // Compute average number of pixels per failure
  if (numfailures > 0) {
    avgpixperfailure = (float)numfailedpixels/(float)numfailures;
  }
  else {
    avgpixperfailure = 0.0;
  }

  // Average sediment delivery to each stream segment
  for(i=1; i<MaxStreamID+1; i++) {
    SegmentSediment[i] /= (float)massitertemp;
    if(SegmentSediment[i] < 0.0) SegmentSediment[i]=0.0;
  }
  update_sediment_array(ChannelData->streams, SegmentSediment, SegmentSedimentm);
  /* Take new sediment inflow and distribute it by representative diameters*/
  /* and convert to mass */
  sed_vol_to_distrib_mass(ChannelData->streams, SegmentSediment);


  /*************************************************************************/
  /* Create failure summary file, in the specified output directory:       */
  /* failure_summary.txt - for each date that the mwm algorithm is run:    */
  /*                       ave. no. of failures (strip of pixels           */
  /*                            originating from a failed pixel)           */
  /*                       ave. no. of pixles per failure                  */
  /*                       total number of failed pixels with probability  */
  /*                            of failure > failure_threshold             */ 
  /*************************************************************************/

  sprintf(sumoutfile, "%sfailure_summary.txt", DumpPath);

  if((fs=fopen(sumoutfile,"a")) == NULL)
    {
      printf("Cannot open factor of safety summary output file.\n");
      exit(0);
    }

  SPrintDate(&(Time->Current), buffer);
  fprintf(fs, "%-20s %.4f %.4f %7d\n", buffer, avgnumfailures, avgpixperfailure, numlikelyfailedpixels); 
  printf("%.4f failures; %.4f pixels per failure; %d pixels have failure likelihood > %.2f\n",
    avgnumfailures, avgpixperfailure, numlikelyfailedpixels, failure_threshold);
  fclose(fs);

  for(i=0; i<Map->NYfine; i++) { 
    free(failure[i]);
    free(SedThickness[i]);
    free(InitialSediment[i]);
  }
  for(i=1; i<MaxStreamID+1; i++) {
    free(SegmentSedimentm[i]);
  }
  free(failure);
  free(SedThickness);
  free(InitialSediment);
  free(SegmentSediment);
  free(SegmentSedimentm);
  free(InitialSegmentSediment);
  free(InitialSegmentSedimentm);
}
示例#9
0
/*****************************************************************************
  Function name: MassEnergyBalance()

  Purpose      : Calculate mass and energy balance

  Required     :

  Returns      : void

  Modifies     :

  Comments     :

  Reference    :
    Epema, G.F. and H.T. Riezbos, 1983, Fall Velocity of waterdrops at different
heights as a factor influencing erosivity of simulated rain. Rainfall simulation,
Runoff and Soil Erosion. Catena suppl. 4, Braunschweig. Jan de Ploey (Ed), 1-17.

  Laws, J.o., and D.A. Parsons, 1943, the relation of raindrop size to intensity.
Trans. Am. Geophys. Union, 24: 452-460.

  Wicks, J.M. and J.C. Bathurst, 1996, SHESED: a physically based, distributed
erosion and sediment yield component for the SHE hydrological modeling system,
Journal of Hydrology, 175, 213-238.

*****************************************************************************/
void MassEnergyBalance(OPTIONSTRUCT *Options, int y, int x, float SineSolarAltitude,
		       float DX, float DY, int Dt, int HeatFluxOption,
		       int CanopyRadAttOption, int RoadRouteOption,
		       int InfiltOption, int MaxVegLayers, PIXMET *LocalMet,
		       ROADSTRUCT *LocalNetwork, PRECIPPIX *LocalPrecip,
		       VEGTABLE *VType, VEGPIX *LocalVeg, SOILTABLE *SType,
		       SOILPIX *LocalSoil, SNOWPIX *LocalSnow,
		       EVAPPIX *LocalEvap, PIXRAD *TotalRad,
		       CHANNEL *ChannelData, float **skyview)
{
  PIXRAD LocalRad;			/* Radiation balance components (W/m^2) */
  float SurfaceWater;		/* Pixel average depth of water before infiltration is calculated (m) */

  float RoadWater;          /* Average depth of water on the road surface
							   (normalized by grid cell area)
							   before infiltration is calculated (m) */
  float ChannelWater;       /* Precip that hits the channel */
  float Infiltration;		/* Infiltration into the top soil layer (m) */
  float Infiltrability;     /* Dynamic infiltration capacity (m/s)*/
  float B;                  /* Capillary drive and soil saturation deficit used
							   in dynamic infiltration calculation*/
  float LowerRa;		    /* Aerodynamic resistance for lower layer (s/m) */

  float LowerWind;			/* Wind for lower layer (m/s) */
  float MaxInfiltration;	/* Maximum infiltration into the top soil layer (m) */

  float MaxRoadbedInfiltration;	/* Maximum infiltration through the road bed soil layer (m) */

  float MeltEnergy;			/* Energy used to melt snow and  change of cold content of snow pack */

  float MoistureFlux;		/* Amount of water transported from the pixel
							   to the atmosphere (m/timestep) */
  float NetRadiation;		/* Total Net long- and shortwave radiation for each veg layer (W/m2) */
  float PercArea;           /* Surface area of percolation corrected for
							   channel and road area, divided by the grid cell area (0-1)  */

  float Reference;			/* Reference height for sensible heat calculation (m) */

  float RoadbedInfiltration;/* Infiltration through the road bed (m) */
  float Roughness;			/* Roughness length (m) */
  float Rp;					/* radiation flux in visible part of the spectrum (W/m^2) */

  float UpperRa;		    /* Aerodynamic resistance for upper layer (s/m) */

  float UpperWind;			/* Wind for upper layer (m/s) */
  float SnowLongIn;			/* Incoming longwave radiation at snow surface (W/m2) */



  float SnowNetShort;		/* Net amount of short wave radiation at the snow surface (W/m2) */
  float SnowRa;				/* Aerodynamic resistance for snow */
  float SnowWind;		    /* Wind 2 m above snow */
  float Tsurf;				/* Surface temperature used in LongwaveBalance() (C) */
  float RainfallIntensity;  /* Rainfall intensity (mm/h) */
  float MS_Rainfall;        /* Momentum squared for rain throughfall((kg* m/s)^2 /(m^2 * s)) */
  int MS_Index;             /* Index for determining alpha and beta cooresponding to RainfallIntensity*/
  int   NVegLActual;		/* Number of vegetation layers above snow */
  float alpha[4]={2.69e-8,3.75e-8,6.12e-8,11.75e-8}; /* empirical coefficient
				for rainfall momentum after Wicks and Bathurst (1996) */
  float beta[4]={1.6896,1.5545,1.4242,1.2821};       /* empirical coefficient
				for rainfall momentum after Wicks and Bathurst (1996) */
  int i;
  float CanopyHeight[18] = {0.5,1,1.5,2,3,4,5,6,7,8,9,10,11,12,
			    13,14,15,16};        /* Canopy height at which drip fall
			          velocity is prescribed after Epema and Riezebos (1983) (m)*/
  float FallVelocity[18] = {2.96,4.12,5.12,5.82,6.84,7.54,8.05,8.36,
			    8.54,8.66,8.75,8.82,8.87,8.91,8.96,9.02,9.07,9.13};
                                     /* Drip fall velocity corresponding to
                                     CanopyHeight after Epema and Riezebos (1983) (m/s)*/
  float LD_FallVelocity;             /* Leaf drip fall velocity corresponding to the
                                     canopy height in vegetation map (m/s) */

  /* Calculate the number of vegetation layers above the snow */

  NVegLActual = VType->NVegLayers;
  if (LocalSnow->HasSnow == TRUE && VType->UnderStory == TRUE)
    --NVegLActual;

  /* initialize the total amount of evapotranspiration, and MeltEnergy */

  LocalEvap->ETot = 0.0;
  MeltEnergy = 0.0;
  MoistureFlux = 0.0;

  /* calculate the radiation balance for the ground/snow surface and the
     vegetation layers above that surface */
  /* related files: settings.h data.h Calendar.h  DHSVMerror.h massenergy.h constants.h
  */
//  RadiationBalance(Options, HeatFluxOption, CanopyRadAttOption, SineSolarAltitude,
//	       LocalMet->VICSin, LocalMet->Sin, LocalMet->SinBeam, LocalMet->SinDiffuse,
//		   LocalMet->Lin, LocalMet->Tair, LocalVeg->Tcanopy,
//		   LocalSoil->TSurf, SType->Albedo, VType, LocalSnow, &LocalRad);
	CRadiationBalance * crb = new CRadiationBalance;
	crb->init(Options, HeatFluxOption, CanopyRadAttOption, SineSolarAltitude,
	       LocalMet->VICSin, LocalMet->Sin, LocalMet->SinBeam, LocalMet->SinDiffuse,
		   LocalMet->Lin, LocalMet->Tair, LocalVeg->Tcanopy,
		   LocalSoil->TSurf, SType->Albedo, VType, LocalSnow, &LocalRad);
    crb->execute();
    delete crb;

  /* calculate the actual aerodynamic resistances and wind speeds */
  UpperWind = VType->U[0] * LocalMet->Wind;
  UpperRa = VType->Ra[0] / LocalMet->Wind;
  if (VType->OverStory == TRUE) {
    LowerWind = VType->U[1] * LocalMet->Wind;
    LowerRa = VType->Ra[1] / LocalMet->Wind;
  }
  else {
    LowerWind = UpperWind;
    LowerRa = UpperRa;
  }

  /* Leaf drip impact*/
  /* Find corresponding fall velocity for overstory and understory heights
     by weighting scheme */
  /* related files: independent module
  */
//  if (VType->OverStory){
//    /* staring at 1 assumes the overstory height > 0.5 m */
//    for (i = 1; i <= 17; i++ ) {
//      if (VType->Height[0] < CanopyHeight[i]) {
//        LD_FallVelocity = ((VType->Height[0] - CanopyHeight[i-1])
//			   *FallVelocity[i] +
//			   (CanopyHeight[i] - VType->Height[0])*FallVelocity[i-1]) /
//	  (CanopyHeight[i] - CanopyHeight[i-1]);
//      }
//    }
//    if (VType->UnderStory) {
//      /* ending at 16 assumes the understory height < 16 m */
//      for (i = 0; i <= 16; i++) {
//	if (VType->Height[1] < CanopyHeight[i]) {
//	  LD_FallVelocity = ((VType->Height[1] - CanopyHeight[i])*FallVelocity[i] +
//			     (CanopyHeight[i+1] - VType->Height[1])*FallVelocity[i-1]) /
//	    (CanopyHeight[i+1] - CanopyHeight[i]);
//	}
//      }
//    }
//  }
//  else if (VType->UnderStory) {
//    /* ending at 16 assumes the understory height < 16 m */
//    for (i = 0; i <= 16; i++) {
//      if (VType->Height[0] < CanopyHeight[i]) {
//	LD_FallVelocity = ((VType->Height[0] - CanopyHeight[i])*FallVelocity[i] +
//			   (CanopyHeight[i+1] - VType->Height[0])*FallVelocity[i-1]) /
//	  (CanopyHeight[i+1] - CanopyHeight[i]);
//      }
//    }
//  }
//  else LD_FallVelocity = 0;

    CLeafDripImpact * cLeafDripImpact = new CLeafDripImpact();
    cLeafDripImpact->init(VType, CanopyHeight, FallVelocity);
    cLeafDripImpact->execute();
    cLeafDripImpact->query(&LD_FallVelocity);
    delete cLeafDripImpact;


  /* RainFall impact */
  /* 3600 is conversion factor (number of seconds per hour) */
  /* related files: independant
  */
//  if (LocalPrecip->RainFall > 0.) {
//    RainfallIntensity = LocalPrecip->RainFall * (1./MMTOM) * (3600./Dt);
//
//    /* Momentum is later weighted with the overstory/understory fraction */
//    if (RainfallIntensity < 10.)
//      MS_Index = 0;
//    else if (RainfallIntensity >= 10. && RainfallIntensity < 100.)
//      MS_Index = floor((RainfallIntensity + 49)/50);
//    else
//      MS_Index = 3;
//
//    /* Eq. 1, Wicks and Bathurst (1996) */
//    MS_Rainfall = alpha[MS_Index] * pow(RainfallIntensity, beta[MS_Index]);
//
//    /* Calculating mediam raindrop diameter after Laws and Parsons (1943) */
//    LocalPrecip->Dm =  0.00124 * pow((double)RainfallIntensity, 0.182);
//  }
//  else {
//    MS_Rainfall = 0;
//    LocalPrecip->Dm = LEAF_DRIP_DIA;
//  }

    CRainfallImpact * cRainfallImpact = new CRainfallImpact();
    cRainfallImpact->init(LocalPrecip->RainFall, Dt);
    cRainfallImpact->execute();
    cRainfallImpact->query(&MS_Rainfall, &(LocalPrecip->Dm));
    delete cRainfallImpact;

  /* calculate the amount of interception storage, and the amount of
     throughfall.  Of course this only needs to be done if there is
     vegetation present. */
  /* related files:
  SnowInterception.c brent.h constants.h settings.h massenergy.h data.h
  Calendar.h snow.h functions.h DHSVMChannel.h getinit.h channel.h channel_grid.h

  RadiationBalance.c settings.h data.h Calendar.h  DHSVMerror.h massenergy.h constants.h

  InterceptionStorage.c settings.h data.h Calendar.h DHSVMerror.h massenergy.h constants.h

  SnowMelt.c brent.h constants.h settings.h massenergy.h data.h Calendar.h
  functions.h DHSVMChannel.h getinit.h channel.h channel_grid.h snow.h
  */

#ifndef NO_SNOW

  if (VType->OverStory == TRUE &&
      (LocalPrecip->IntSnow[0] || LocalPrecip->SnowFall > 0.0)) {
//    SnowInterception(y, x, Dt, VType->Fract[0], VType->LAI[0],
//		     VType->MaxInt[0], VType->MaxSnowInt, VType->MDRatio,
//		     VType->SnowIntEff, UpperRa, LocalMet->AirDens,
//		     LocalMet->Eact, LocalMet->Lv, &LocalRad, LocalMet->Press,
//		     LocalMet->Tair, LocalMet->Vpd, UpperWind,
//		     &(LocalPrecip->RainFall), &(LocalPrecip->SnowFall),
//		     &(LocalPrecip->IntRain[0]), &(LocalPrecip->IntSnow[0]),
//		     &(LocalPrecip->TempIntStorage),
//		     &(LocalSnow->CanopyVaporMassFlux), &(LocalVeg->Tcanopy),
//		     &MeltEnergy, &(LocalPrecip->MomentSq), VType->Height,
//		     VType->UnderStory, MS_Rainfall, LD_FallVelocity);

    CSnowInterception * cSnowInterception = new CSnowInterception();
    cSnowInterception->init(y, x, Dt, VType->Fract[0], VType->LAI[0],
		     VType->MaxInt[0], VType->MaxSnowInt, VType->MDRatio,
		     VType->SnowIntEff, UpperRa, LocalMet->AirDens,
		     LocalMet->Eact, LocalMet->Lv, &LocalRad, LocalMet->Press,
		     LocalMet->Tair, LocalMet->Vpd, UpperWind,
		     &(LocalPrecip->RainFall), &(LocalPrecip->SnowFall),
		     &(LocalPrecip->IntRain[0]), &(LocalPrecip->IntSnow[0]),
		     &(LocalPrecip->TempIntStorage),
		     &(LocalSnow->CanopyVaporMassFlux), &(LocalVeg->Tcanopy),
		     &MeltEnergy, &(LocalPrecip->MomentSq), VType->Height,
		     VType->UnderStory, MS_Rainfall, LD_FallVelocity);
    delete cSnowInterception;

    MoistureFlux -= LocalSnow->CanopyVaporMassFlux;

    /* Because we now have a new estimate of the canopy temperature we can
       recalculate the longwave balance */
    if (LocalSnow->HasSnow == TRUE)
      Tsurf = LocalSnow->TSurf;
    else if (HeatFluxOption == TRUE)
      Tsurf = LocalSoil->TSurf;
    else
      Tsurf = LocalMet->Tair;
    LongwaveBalance(Options, VType->OverStory, VType->Fract[0], LocalMet->Lin,
	               LocalVeg->Tcanopy, Tsurf, &LocalRad);
  }
  else if (VType->NVegLayers > 0) {
    LocalVeg->Tcanopy = LocalMet->Tair;
    LocalSnow->CanopyVaporMassFlux = 0.0;
    LocalPrecip->TempIntStorage = 0.0;
//    InterceptionStorage(VType->NVegLayers, NVegLActual, VType->MaxInt,
//			VType->Fract, LocalPrecip->IntRain,
//			&(LocalPrecip->RainFall), &(LocalPrecip->MomentSq),
//			VType->Height, VType->UnderStory, Dt, MS_Rainfall,
//			LD_FallVelocity);
    CInterceptionStorage * cInterceptionStorage = new CInterceptionStorage();
    cInterceptionStorage->init(VType->NVegLayers, NVegLActual, VType->MaxInt,
			VType->Fract, LocalPrecip->IntRain,
			&(LocalPrecip->RainFall), &(LocalPrecip->MomentSq),
			VType->Height, VType->UnderStory, Dt, MS_Rainfall,
			LD_FallVelocity);
    cInterceptionStorage->execute();
    delete cInterceptionStorage;

  }
  else {
    /* If no vegetation, kinetic energy is all due to direct precipitation. */
    if(LocalPrecip->RainFall > 0.0)
    LocalPrecip->MomentSq = MS_Rainfall;
  }

  /* If snow on the ground, assume no overland flow erosion. */
  if(LocalSnow->HasSnow)
    LocalPrecip->MomentSq = 0.0;

  /* if snow is present, simulate the snow pack dynamics */

  if (LocalSnow->HasSnow || LocalPrecip->SnowFall > 0.0) {

    if (VType->OverStory == TRUE) {
      SnowLongIn = LocalRad.LongIn[1];
      SnowNetShort = LocalRad.NetShort[1];
    }
    else {
      SnowLongIn = LocalRad.LongIn[0];
      SnowNetShort = LocalRad.NetShort[0];
    }

    SnowWind = VType->USnow * LocalMet->Wind;
    SnowRa = VType->RaSnow / LocalMet->Wind;

//    LocalSnow->Outflow =
//      SnowMelt(y, x, Dt, 2. + Z0_SNOW, 0.f, Z0_SNOW, SnowRa, LocalMet->AirDens,
//	       LocalMet->Eact, LocalMet->Lv, SnowNetShort, SnowLongIn,
//	       LocalMet->Press, LocalPrecip->RainFall, LocalPrecip->SnowFall,
//	       LocalMet->Tair, LocalMet->Vpd, SnowWind,
//	       &(LocalSnow->PackWater), &(LocalSnow->SurfWater),
//	       &(LocalSnow->Swq), &(LocalSnow->VaporMassFlux),
//	       &(LocalSnow->TPack), &(LocalSnow->TSurf), &MeltEnergy);

     CSnowMelt * cSnowMelt = new CSnowMelt();
     cSnowMelt->init(y, x, Dt, 2. + Z0_SNOW, 0.f, Z0_SNOW, SnowRa, LocalMet->AirDens,
	       LocalMet->Eact, LocalMet->Lv, SnowNetShort, SnowLongIn,
	       LocalMet->Press, LocalPrecip->RainFall, LocalPrecip->SnowFall,
	       LocalMet->Tair, LocalMet->Vpd, SnowWind,
	       &(LocalSnow->PackWater), &(LocalSnow->SurfWater),
	       &(LocalSnow->Swq), &(LocalSnow->VaporMassFlux),
	       &(LocalSnow->TPack), &(LocalSnow->TSurf), &MeltEnergy, &(LocalSnow->Outflow));
	 cSnowMelt->execute();
	 delete cSnowMelt;

    /* Rainfall was added to SurfWater of the snow pack and has to be set to zero */

    LocalPrecip->RainFall = 0.0;
    MoistureFlux -= LocalSnow->VaporMassFlux;

    /* Because we now have a new estimate of the snow surface temperature we
       can recalculate the longwave balance */

    Tsurf = LocalSnow->TSurf;
    LongwaveBalance(Options, VType->OverStory, VType->Fract[0], LocalMet->Lin,
		    LocalVeg->Tcanopy, Tsurf, &LocalRad);
  }
  else {
    LocalSnow->Outflow = 0.0;
    LocalSnow->VaporMassFlux = 0.0;
  }

  /* Determine whether a snow pack is still present, or whether everything
     has melted */

  if (LocalSnow->Swq > 0.0)
    LocalSnow->HasSnow = TRUE;
  else
    LocalSnow->HasSnow = FALSE;

  /*do the glacier add */
  if (LocalSnow->Swq < 1.0 && VType->Index == GLACIER) {
    printf("resetting glacier swe of %f to 5.0 meters\n", LocalSnow->Swq);
    LocalSnow->Glacier += (5.0 - LocalSnow->Swq);
    LocalSnow->Swq = 5.0;
    LocalSnow->TPack = 0.0;
    LocalSnow->TSurf = 0.0;
  }
#endif

#ifndef NO_ET
  /* calculate the amount of evapotranspiration from each vegetation layer
     above the ground/soil surface.  Also calculate the total amount of
     evapotranspiration from the vegetation */

  /* related files: EvapoTranspiration.c settings.h data.h Calendar.h DHSVMerror.h massenergy.h constants.h
                    SoilEvaporation.c settings.h DHSVMerror.h massenergy.h data.h Calendar.h constants.h
  */
  if (VType->OverStory == TRUE) {
    Rp = VISFRACT * LocalRad.NetShort[0];
    NetRadiation =
      LocalRad.NetShort[0] +
      LocalRad.LongIn[0] - 2 * VType->Fract[0] * LocalRad.LongOut[0];
//    EvapoTranspiration(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
//		       MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
//		       LocalEvap, LocalNetwork->Adjust, UpperRa);
    CEvapoTranspiration* cEvapoTranspiration = new CEvapoTranspiration();
    cEvapoTranspiration->init(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
		       MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
		       LocalEvap, LocalNetwork->Adjust, UpperRa);
    cEvapoTranspiration->execute();
    delete cEvapoTranspiration;

    MoistureFlux += LocalEvap->EAct[0] + LocalEvap->EInt[0];

    if (LocalSnow->HasSnow != TRUE && VType->UnderStory == TRUE) {
      Rp = VISFRACT * LocalRad.NetShort[1];
      NetRadiation =
	LocalRad.NetShort[1] +
	LocalRad.LongIn[1] - VType->Fract[1] * LocalRad.LongOut[1];
      EvapoTranspiration(1, Dt, LocalMet, NetRadiation, Rp, VType, SType,
			 MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[1]),
			 LocalEvap, LocalNetwork->Adjust, LowerRa);
      MoistureFlux += LocalEvap->EAct[1] + LocalEvap->EInt[1];
    }
    else if (VType->UnderStory == TRUE) {
      LocalEvap->EAct[1] = 0.;
      LocalEvap->EInt[1] = 0.;
    }
  }				/* end if(VType->OverStory == TRUE) */
  else if (LocalSnow->HasSnow != TRUE && VType->UnderStory == TRUE) {
    Rp = VISFRACT * LocalRad.NetShort[0];
    NetRadiation =
      LocalRad.NetShort[0] +
      LocalRad.LongIn[0] - VType->Fract[0] * LocalRad.LongOut[0];
    EvapoTranspiration(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
		       MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
		       LocalEvap, LocalNetwork->Adjust, LowerRa);
    MoistureFlux += LocalEvap->EAct[0] + LocalEvap->EInt[0];
  }
  else if (VType->UnderStory == TRUE) {
    LocalEvap->EAct[0] = 0.;
    LocalEvap->EInt[0] = 0.;
  }

  /* Calculate soil evaporation from the upper soil layer if no snow is
     present and there is no understory */

  if (LocalSnow->HasSnow != TRUE && VType->UnderStory != TRUE) {

    if (VType->OverStory == TRUE)
      NetRadiation =
	LocalRad.NetShort[1] + LocalRad.LongIn[1] - LocalRad.LongOut[1];
    else
      NetRadiation =
	LocalRad.NetShort[0] + LocalRad.LongIn[0] - LocalRad.LongOut[0];

//    LocalEvap->EvapSoil =
//      SoilEvaporation(Dt, LocalMet->Tair, LocalMet->Slope, LocalMet->Gamma,
//		      LocalMet->Lv, LocalMet->AirDens, LocalMet->Vpd,
//		      NetRadiation, LowerRa, MoistureFlux, SType->Porosity[0],
//		      SType->Ks[0], SType->Press[0], SType->PoreDist[0],
//		      VType->RootDepth[0], &(LocalSoil->Moist[0]),
//		      LocalNetwork->Adjust[0]);
{
    CSoilEvaporation * cSoilEvaporation = new CSoilEvaporation();
    cSoilEvaporation->init(Dt, LocalMet->Tair, LocalMet->Slope, LocalMet->Gamma,
		      LocalMet->Lv, LocalMet->AirDens, LocalMet->Vpd,
		      NetRadiation, LowerRa, MoistureFlux, SType->Porosity[0],
		      SType->Ks[0], SType->Press[0], SType->PoreDist[0],
		      VType->RootDepth[0], &(LocalSoil->Moist[0]),
		      LocalNetwork->Adjust[0], &(LocalEvap->EvapSoil));
    cSoilEvaporation->execute();
    delete cSoilEvaporation;
}


  }
  else
    LocalEvap->EvapSoil = 0.0;

  MoistureFlux += LocalEvap->EvapSoil;
  LocalEvap->ETot += LocalEvap->EvapSoil;

#endif

  /* add the water that was not intercepted to the upper soil layer */

#ifndef NO_SOIL

  /* This has been modified so that PercArea for infiltration is calculated
     locally to account for the fact that some cells have roads and streams.
     I am not sure if the old PercArea (which does not account for the fact
     that some cells have roads and streams) needs to remain the same.
     Currently, the old PercArea is passed to UnsaturatedFlow */

  MaxRoadbedInfiltration = 0.;
  MaxInfiltration = 0.;
  ChannelWater = 0.;
  RoadWater = 0.;
  SurfaceWater = 0.;
  PercArea = 1.;
  RoadbedInfiltration = 0.;

  /* ChannelWater is precipitation falling on the channel */
  /* (if there is no road, LocalNetwork->RoadArea = 0) */
  if (channel_grid_has_channel(ChannelData->stream_map, x, y)){
    PercArea = 1. - (LocalNetwork->Area + LocalNetwork->RoadArea)/(DX*DY);
    ChannelWater = LocalNetwork->Area/(DX*DY) * LocalPrecip->RainFall;
  }
  /* If there is a road and no channel, the PercArea is
     based on the road only */
  else if (channel_grid_has_channel(ChannelData->road_map, x, y)){
    PercArea = 1. - (LocalNetwork->RoadArea)/(DX*DY);
    MaxRoadbedInfiltration = (1. - PercArea) *
      LocalNetwork->MaxInfiltrationRate * Dt;
  }

  /* SurfaceWater is rain falling on the hillslope +
     snowmelt on the hillslope (there is no snowmelt on the channel) +
     existing IExcess */
  /* related files: independant
  */
//  SurfaceWater = (PercArea * LocalPrecip->RainFall) +
//    ((1. - (LocalNetwork->RoadArea)/(DX*DY)) * LocalSnow->Outflow) +
//    LocalSoil->IExcess;
    CSurfaceWater * cSurfaceWater = new CSurfaceWater();
    //float m_PercArea, float m_Rainfall, float m_RoadArea, float m_DX, float m_DY, float m_Outflow, float m_IExcess
    cSurfaceWater->init(PercArea,LocalPrecip->RainFall,LocalNetwork->RoadArea, DX, DY, LocalSnow->Outflow, LocalSoil->IExcess );
    cSurfaceWater->execute();
    cSurfaceWater->query(&SurfaceWater);
    delete cSurfaceWater;

  /* RoadWater is rain falling on the road surface +
     snowmelt on the road surface + existing Road IExcess
     (Existing road IExcess = 0). WORK IN PROGRESS*/
  /* related files: independant
  */
//  RoadWater = (LocalNetwork->RoadArea/(DX*DY) *
//	       (LocalPrecip->RainFall + LocalSnow->Outflow)) +
//    LocalNetwork->IExcess;
    CRoadWater * cRoadWater = new CRoadWater();
    cRoadWater->init(LocalNetwork->RoadArea, DX, DY, LocalPrecip->RainFall, LocalSnow->Outflow, LocalNetwork->IExcess);
    cRoadWater->execute();
    cRoadWater->query(&RoadWater);
    delete cRoadWater;

  /* Infiltration module
  *  related files or modules: SurfaceWater, RoadWater,UnsaturatedFlow.c
								constants.h settings.h functions.h
								data.h Calendar.h DHSVMChannel.h getinit.h channel.h
								channel_grid.h soilmoisture.h
  */
  if(InfiltOption == STATIC)
    MaxInfiltration = (1. - VType->ImpervFrac) * PercArea * SType->MaxInfiltrationRate * Dt;

  else { /* InfiltOption == DYNAMIC
	    Dynamic Infiltration Capacity after Parlange and Smith 1978,
	    as used in KINEROS and THALES */
    Infiltration = 0.0;

    if (SurfaceWater > 0.) {
      /* Infiltration is a function of the amount of water infiltrated since
	 the storm started */
      if (LocalPrecip->PrecipStart){
	LocalSoil->MoistInit = LocalSoil->Moist[0];
	LocalSoil->InfiltAcc = 0.0;
      }

      /* Check that the B parameter > 0 */
      if ((LocalSoil->InfiltAcc > 0.) && (SType->Porosity[0] > LocalSoil->MoistInit)) {

	B = (SType->Porosity[0] - LocalSoil->MoistInit) *
	  (SType->G_Infilt + SurfaceWater);
	Infiltrability = SType->Ks[0] * exp((LocalSoil->InfiltAcc)/B) /
	  (exp((LocalSoil->InfiltAcc)/B) - 1.);
      }

      else
	Infiltrability = SurfaceWater/Dt ;

      MaxInfiltration = Infiltrability * PercArea *
	(1. - VType->ImpervFrac) *  Dt;

      LocalPrecip->PrecipStart = FALSE;
    }/* end  if (SurfaceWater > 0.) */
    else
      LocalPrecip->PrecipStart = TRUE;

  } /* end Dynamic MaxInfiltration calculation */

  Infiltration = (1. - VType->ImpervFrac) * SurfaceWater;

  if (Infiltration > MaxInfiltration)
    Infiltration = MaxInfiltration;

  RoadbedInfiltration = RoadWater;

  if (RoadbedInfiltration > MaxRoadbedInfiltration)
    RoadbedInfiltration = MaxRoadbedInfiltration;

  if (RoadRouteOption == FALSE)
    LocalSoil->IExcess = SurfaceWater - Infiltration +
      RoadWater - RoadbedInfiltration;
  else {
    LocalSoil->IExcess = SurfaceWater - Infiltration;
    LocalNetwork->IExcess = RoadWater - RoadbedInfiltration;
    if (LocalNetwork->IExcess < 0.){
      LocalNetwork->IExcess = 0.;
      printf("MEB: NetIExcess(%f), reset to 0\n", LocalNetwork->IExcess);
    }
  }

  if (LocalSoil->IExcess < 0.){
    printf("MEB: SoilIExcess(%f), reset to 0\n", LocalSoil->IExcess);
    LocalSoil->IExcess = 0.;
  }

  /*Add water that hits the channel network to the channel network */
  /* related files: channel_grid.c channel_grid.h channel.h settings.h
					data.h Calendar.h tableio.h errorhandler.h DHSVMChannel.h
					getinit.h
  */
  if (ChannelWater > 0.){
    channel_grid_inc_inflow(ChannelData->stream_map, x, y, ChannelWater * DX * DY);
    LocalSoil->ChannelInt += ChannelWater;
   }

  /* Calculate unsaturated soil water movement, and adjust soil water
     table depth */
  /* related files: UnsaturatedFlow.c constants.h settings.h functions.h
					data.h Calendar.h DHSVMChannel.h getinit.h channel.h
					channel_grid.h soilmoisture.h
  */
//		  LocalSoil->Depth, LocalNetwork->Area, VType->RootDepth,
//		  SType->Ks, SType->PoreDist, SType->Porosity, SType->FCap,
//		  LocalSoil->Perc, LocalNetwork->PercArea,
//		  LocalNetwork->Adjust, LocalNetwork->CutBankZone,
//		  LocalNetwork->BankHeight, &(LocalSoil->TableDepth),
//		  &(LocalSoil->IExcess), LocalSoil->Moist, RoadRouteOption,
//		  InfiltOption, &(LocalNetwork->IExcess));

    CUnsaturatedFlow * cUnsaturatedFlow = new CUnsaturatedFlow();
    cUnsaturatedFlow->init(Dt, DX, DY, Infiltration, RoadbedInfiltration,
		  LocalSoil->SatFlow, SType->NLayers,
		  LocalSoil->Depth, LocalNetwork->Area, VType->RootDepth,
		  SType->Ks, SType->PoreDist, SType->Porosity, SType->FCap,
		  LocalSoil->Perc, LocalNetwork->PercArea,
		  LocalNetwork->Adjust, LocalNetwork->CutBankZone,
		  LocalNetwork->BankHeight, &(LocalSoil->TableDepth),
		  &(LocalSoil->IExcess), LocalSoil->Moist, RoadRouteOption,
		  InfiltOption, &(LocalNetwork->IExcess));
    cUnsaturatedFlow->execute();
    delete cUnsaturatedFlow;

  /* Infiltration is updated in UnsaturatedFlow and accumulated
     below */
  if ((InfiltOption == DYNAMIC) && (SurfaceWater > 0.))
    LocalSoil->InfiltAcc += Infiltration;

  if (HeatFluxOption == TRUE) {
    if (LocalSnow->HasSnow == TRUE) {
      Reference = 2. + Z0_SNOW;
      Roughness = Z0_SNOW;
    }
    else {
      Reference = 2. + Z0_GROUND;
      Roughness = Z0_GROUND;
    }

	/* Calculate sensible heat flux
	related file: SensibleHeatFlux.c settings.h data.h Calendar.h
				  DHSVMerror.h massenergy.h constants.h brent.h functions.h
				  DHSVMChannel.h getinit.h channel.h channel_grid.h
	*/
//    SensibleHeatFlux(y, x, Dt, LowerRa, Reference, 0.0f, Roughness,
//		     LocalMet, LocalRad.PixelNetShort, LocalRad.PixelLongIn,
//		     MoistureFlux, SType->NLayers, VType->RootDepth,
//		     SType, MeltEnergy, LocalSoil);

    CSensibleHeatFlux *cSensibleHeatFlux = new CSensibleHeatFlux();
    cSensibleHeatFlux->init(y, x, Dt, LowerRa, Reference, 0.0f, Roughness,
		     LocalMet, LocalRad.PixelNetShort, LocalRad.PixelLongIn,
		     MoistureFlux, SType->NLayers, VType->RootDepth,
		     SType, MeltEnergy, LocalSoil);
	cSensibleHeatFlux->execute();
    delete cSensibleHeatFlux;
    Tsurf = LocalSoil->TSurf;

	/* Calculate long wave balance
	related files: RadiationBalance.c settings.h data.h Calendar.h
				   DHSVMerror.h massenergy.h constants.h
	*/
    LongwaveBalance(Options, VType->OverStory, VType->Fract[0], LocalMet->Lin,
		    LocalVeg->Tcanopy, Tsurf, &LocalRad);
  }
  else

    /* Calculate No sensible heat flux
	related files: SensibleHeatFlux.c settings.h data.h Calendar.h
					DHSVMerror.h massenergy.h constants.h brent.h functions.h
					DHSVMChannel.h getinit.h channel.h channel_grid.h
	*/
//    NoSensibleHeatFlux(Dt, LocalMet, MoistureFlux, LocalSoil);


{
    CNoSensibleHeatFlux *cNoSensibleHeatFlux = new CNoSensibleHeatFlux();
    cNoSensibleHeatFlux->init(Dt, LocalMet, MoistureFlux, LocalSoil);
    cNoSensibleHeatFlux->execute();
    delete cNoSensibleHeatFlux;
}

#endif

  /* add the components of the radiation balance for the current pixel to
     the total */
  /* related files: AggregateRadiation.c settings.h data.h Calendar.h massenergy.h
  */
//  AggregateRadiation(MaxVegLayers, VType->NVegLayers, &LocalRad, TotalRad);

  CAggregateRadiation *cAggregateRadiation = new CAggregateRadiation();
  cAggregateRadiation->init(MaxVegLayers, VType->NVegLayers, &LocalRad, TotalRad);
  cAggregateRadiation->execute();
  delete cAggregateRadiation;

  /* For RBM model, save the energy fluxes for outputs */
  /* related files: channel_grid.c channel_grid.h channel.h settings.h
					data.h Calendar.h tableio.h errorhandler.h DHSVMChannel.h
					getinit.h
  */
  if (Options->StreamTemp) {
    if (channel_grid_has_channel(ChannelData->stream_map, x, y))
      channel_grid_inc_other(ChannelData->stream_map, x, y, &LocalRad, LocalMet, skyview[y][x]);
  }
}