/*!\file Matpar.c
 * \brief: implementation of the Matpar object
 */

#ifdef HAVE_CONFIG_H
	#include <config.h>
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif

#include "../classes.h"
#include "../../shared/shared.h"

/*Matpar constructors and destructor*/
Matpar::Matpar(){/*{{{*/
	return;
}
/*}}}*/
Matpar::Matpar(int matpar_mid, IoModel* iomodel){/*{{{*/

	bool isefficientlayer;
	int  hydrology_model,smb_model;
	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
	iomodel->Constant(&smb_model,SurfaceforcingsEnum);

	this->mid = matpar_mid;
	iomodel->Constant(&this->rho_ice,MaterialsRhoIceEnum);
	iomodel->Constant(&this->rho_water,MaterialsRhoSeawaterEnum);
	iomodel->Constant(&this->rho_freshwater,MaterialsRhoFreshwaterEnum);
	iomodel->Constant(&this->mu_water,MaterialsMuWaterEnum);
	iomodel->Constant(&this->heatcapacity,MaterialsHeatcapacityEnum);
	iomodel->Constant(&this->thermalconductivity,MaterialsThermalconductivityEnum);
	iomodel->Constant(&this->temperateiceconductivity,MaterialsTemperateiceconductivityEnum);
	iomodel->Constant(&this->latentheat,MaterialsLatentheatEnum);
	iomodel->Constant(&this->beta,MaterialsBetaEnum);
	iomodel->Constant(&this->meltingpoint,MaterialsMeltingpointEnum);
	iomodel->Constant(&this->referencetemperature,ConstantsReferencetemperatureEnum);
	iomodel->Constant(&this->mixed_layer_capacity,MaterialsMixedLayerCapacityEnum);
	iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
	iomodel->Constant(&this->g,ConstantsGEnum);

	switch(smb_model){
		case SMBEnum:
			/*Nothing to add*/
			break;
		case SMBpddEnum:
			iomodel->Constant(&this->desfac,SurfaceforcingsDesfacEnum);
			iomodel->Constant(&this->s0p,SurfaceforcingsS0pEnum);
			break;
		case SMBgradientsEnum:
			/*Nothing to add*/
			break;
		case SMBhenningEnum:
			/*Nothing to add*/
			break;
		case SMBcomponentsEnum:
			/*Nothing to add*/
			break;
		case SMBmeltcomponentsEnum:
			/*Nothing to add*/
			break;
		default:
			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
	}
	if(hydrology_model==HydrologydcEnum){
		iomodel->Constant(&this->sediment_compressibility,HydrologydcSedimentCompressibilityEnum);
		iomodel->Constant(&this->sediment_porosity,HydrologydcSedimentPorosityEnum);
		iomodel->Constant(&this->sediment_thickness,HydrologydcSedimentThicknessEnum);
		iomodel->Constant(&this->water_compressibility,HydrologydcWaterCompressibilityEnum);
		iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);

		if(isefficientlayer){
				iomodel->Constant(&this->epl_compressibility,HydrologydcEplCompressibilityEnum);
				iomodel->Constant(&this->epl_porosity,HydrologydcEplPorosityEnum);
				iomodel->Constant(&this->epl_init_thickness,HydrologydcEplInitialThicknessEnum);
				iomodel->Constant(&this->epl_max_thickness,HydrologydcEplMaxThicknessEnum);
				iomodel->Constant(&this->epl_conductivity,HydrologydcEplConductivityEnum);
		}
	}
	else if(hydrology_model==HydrologyshreveEnum){
		/*Nothing to add*/
	}
	else{
		_error_("Hydrology model "<<EnumToStringx(hydrology_model)<<" not supported yet");
	}

	/*gia: */
	iomodel->Constant(&this->lithosphere_shear_modulus,MaterialsLithosphereShearModulusEnum);
	iomodel->Constant(&this->lithosphere_density,MaterialsLithosphereDensityEnum);
	iomodel->Constant(&this->mantle_shear_modulus,MaterialsMantleShearModulusEnum);
	iomodel->Constant(&this->mantle_density,MaterialsMantleDensityEnum);
}
/*}}}*/
Matpar::~Matpar(){/*{{{*/
	return;
}
/*}}}*/

/*Object virtual functions definitions:*/
void Matpar::Echo(void){/*{{{*/

	_printf_("Matpar:\n");
	_printf_("   mid: " << mid << "\n");
	_printf_("   rho_ice: " << rho_ice << "\n");
	_printf_("   rho_water: " << rho_water << "\n");
	_printf_("   rho_freshwater: " << rho_freshwater << "\n");
	_printf_("   mu_water: " << mu_water << "\n");
	_printf_("   heatcapacity: " << heatcapacity << "\n");
	_printf_("   thermalconductivity: " << thermalconductivity << "\n");
	_printf_("   temperateiceconductivity: " << temperateiceconductivity << "\n");
	_printf_("   latentheat: " << latentheat << "\n");
	_printf_("   beta: " << beta << "\n");
	_printf_("   meltingpoint: " << meltingpoint << "\n");
	_printf_("   referencetemperature: " << referencetemperature << "\n");
	_printf_("   mixed_layer_capacity: " << mixed_layer_capacity << "\n");
	_printf_("   thermal_exchange_velocity: " << thermal_exchange_velocity << "\n");
	_printf_("   g: " << g << "\n");
	_printf_("   desfac: " << desfac << "\n");
	_printf_("   s0p: " << s0p << "\n");
	return;
}
/*}}}*/
void Matpar::DeepEcho(void){/*{{{*/

	this->Echo();
}		
/*}}}*/
int    Matpar::Id(void){ return mid; }/*{{{*/
/*}}}*/
int Matpar::ObjectEnum(void){/*{{{*/

	return MatparEnum;

}
/*}}}*/
Object* Matpar::copy() {/*{{{*/

	/*Output*/
	Matpar* matpar;

	/*Initialize output*/
	matpar=new Matpar(*this);

	/*copy fields: */
	matpar->mid=this->mid;
	matpar->rho_ice=this->rho_ice;
	matpar->rho_water=this->rho_water;
	matpar->rho_freshwater=this->rho_freshwater;
	matpar->mu_water=this->mu_water;
	matpar->heatcapacity=this->heatcapacity;
	matpar->thermalconductivity=this->thermalconductivity;
	matpar->temperateiceconductivity=this->temperateiceconductivity;
	matpar->latentheat=this->latentheat;
	matpar->beta=this->beta;
	matpar->meltingpoint=this->meltingpoint;
	matpar->referencetemperature=this->referencetemperature;
	matpar->mixed_layer_capacity=this->mixed_layer_capacity;
	matpar->thermal_exchange_velocity=this->thermal_exchange_velocity;
	matpar->g=this->g;
	matpar->desfac=this->desfac;
	matpar->s0p=this->s0p;

	matpar->sediment_compressibility=this->sediment_compressibility;
	matpar->sediment_porosity=this->sediment_porosity;
	matpar->sediment_thickness=this->sediment_thickness;
	matpar->water_compressibility=this->water_compressibility;

	matpar->epl_compressibility=this->epl_compressibility;
	matpar->epl_porosity=this->epl_porosity;
	matpar->epl_init_thickness=this->epl_init_thickness;
	matpar->epl_max_thickness=this->epl_max_thickness;
	matpar->epl_conductivity=this->epl_conductivity;

	matpar->lithosphere_shear_modulus=this->lithosphere_shear_modulus;
	matpar->lithosphere_density=this->lithosphere_density;
	matpar->mantle_shear_modulus=this->mantle_shear_modulus;
	matpar->mantle_density=this->mantle_density;

	return matpar;
}
/*}}}*/

/*Update virtual functions definitions:*/
void   Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
	/*Nothing updated yet*/
}
/*}}}*/
void   Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
	/*Nothing updated yet*/
}
/*}}}*/
void  Matpar::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){/*{{{*/
	/*Nothing updated yet*/
}
/*}}}*/
void   Matpar::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/

	switch(name){
		case MaterialsRhoIceEnum:
			this->rho_ice=constant;
			break;
		case MaterialsRhoSeawaterEnum:
			this->rho_water=constant;
			break;
		case MaterialsRhoFreshwaterEnum:
			this->rho_freshwater=constant;
			break;
		case MaterialsMuWaterEnum:
			this->mu_water=constant;
			break;
		case MaterialsHeatcapacityEnum:
			this->heatcapacity=constant;
			break;
	  	case MaterialsThermalconductivityEnum:
			this->thermalconductivity=constant;
			break;
	  	case MaterialsTemperateiceconductivityEnum:
			this->temperateiceconductivity=constant;
			break;
		case  MaterialsLatentheatEnum:
			this->latentheat=constant;
			break;
		case  MaterialsBetaEnum:
			this->beta=constant;
			break;
		case  MaterialsMeltingpointEnum:
			this->meltingpoint=constant;
			break;
		case  ConstantsReferencetemperatureEnum:
			this->referencetemperature=constant;
			break;
		case  MaterialsMixedLayerCapacityEnum:
			this->mixed_layer_capacity=constant;
			break;
		case  MaterialsThermalExchangeVelocityEnum:
			this->thermalconductivity=constant;
			break;
		case  ConstantsGEnum:
			this->g=constant;
			break;
		case  SurfaceforcingsDesfacEnum:
			this->desfac=constant;
			break;
		case SurfaceforcingsS0pEnum:
			this->s0p=constant;
			break;
		default: 
			break;
	}

}
/*}}}*/
void   Matpar::InputUpdateFromConstant(int constant, int name){/*{{{*/
	/*Nothing updated yet*/
}
/*}}}*/
void   Matpar::InputUpdateFromConstant(bool constant, int name){/*{{{*/
	/*Nothing updated yet*/
}
/*}}}*/

/*Matpar management: */
void  Matpar::Configure(Elements* elementsin){/*{{{*/

	/*nothing done yet!*/

}
/*}}}*/
IssmDouble Matpar::GetMaterialParameter(int enum_in){/*{{{*/

	switch(enum_in){
		case MaterialsRhoIceEnum:                    return this->rho_ice;
		case MaterialsRhoSeawaterEnum:                  return this->rho_water;
		case MaterialsRhoFreshwaterEnum:             return this->rho_freshwater;
		case MaterialsMuWaterEnum:                   return this->mu_water;
		case MaterialsHeatcapacityEnum:              return this->heatcapacity;
		case MaterialsThermalconductivityEnum:       return this->thermalconductivity;
		case MaterialsTemperateiceconductivityEnum:  return this->temperateiceconductivity;
		case MaterialsLatentheatEnum:                return this->latentheat;
		case MaterialsBetaEnum:                      return this->beta;
		case MaterialsMeltingpointEnum:              return this->meltingpoint;
		case ConstantsReferencetemperatureEnum:      return this->referencetemperature;
		case MaterialsMixedLayerCapacityEnum:        return this->mixed_layer_capacity;
		case MaterialsThermalExchangeVelocityEnum:   return this->thermal_exchange_velocity;
		case HydrologydcSedimentPorosityEnum:        return this->sediment_porosity;
		case HydrologydcSedimentThicknessEnum:       return this->sediment_thickness;
		case HydrologydcSedimentCompressibilityEnum: return this->sediment_compressibility;
		case HydrologydcEplPorosityEnum:             return this->epl_porosity;
		case HydrologydcEplCompressibilityEnum:      return this->epl_compressibility;
		case HydrologydcEplConductivityEnum:         return this->epl_conductivity;
		case HydrologydcEplInitialThicknessEnum:     return this->epl_init_thickness;
		case HydrologydcEplMaxThicknessEnum:         return this->epl_max_thickness;
		case HydrologydcWaterCompressibilityEnum:    return this->water_compressibility;
		case ConstantsGEnum:                         return this->g;
		default: _error_("Enum "<<EnumToStringx(enum_in)<<" not supported yet");
	}

}
/*}}}*/
IssmDouble Matpar::GetBeta(){/*{{{*/
	return beta;
}
/*}}}*/
IssmDouble Matpar::GetG(){/*{{{*/
	return g;
}
/*}}}*/
IssmDouble Matpar::GetMeltingPoint(){/*{{{*/
	return meltingpoint;
}
/*}}}*/
IssmDouble Matpar::GetRhoIce(){/*{{{*/

	return rho_ice;
}
/*}}}*/
IssmDouble Matpar::GetRhoWater(){/*{{{*/
	return rho_water;
}
/*}}}*/
IssmDouble Matpar::GetRhoFreshwater(){/*{{{*/
	return rho_freshwater;
}
/*}}}*/
IssmDouble Matpar::GetDesFac(){/*{{{*/
	return desfac;
}
/*}}}*/
IssmDouble Matpar::GetS0p(){/*{{{*/
	return s0p;
}
/*}}}*/
IssmDouble Matpar::TMeltingPoint(IssmDouble pressure){/*{{{*/
	return meltingpoint-beta*pressure;
}
/*}}}*/
IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
}
/*}}}*/
IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
	if (enthalpy<PureIceEnthalpy(pressure))
		return thermalconductivity/heatcapacity;
	else
		return temperateiceconductivity/heatcapacity;
}
/*}}}*/
IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/

	int         iv;
	IssmDouble  lambda;                 // fraction of cold ice
	IssmDouble  kappa,kappa_c,kappa_t;  //enthalpy conductivities
	IssmDouble  Hc,Ht;
	IssmDouble* PIE   = xNew<IssmDouble>(numvertices);
	IssmDouble* dHpmp = xNew<IssmDouble>(numvertices);

	for(iv=0; iv<numvertices; iv++){
		PIE[iv]=PureIceEnthalpy(pressure[iv]);
		dHpmp[iv]=enthalpy[iv]-PIE[iv];
	}

	bool allequalsign=true;
	if(dHpmp[0]<0)
		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]<0));
	else
		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]>=0));

	if(allequalsign){
		kappa=GetEnthalpyDiffusionParameter(enthalpy[0], pressure[0]);
	}
	else {
		/* return harmonic mean of thermal conductivities, weighted by fraction of cold/temperate ice,
		 cf Patankar 1980, pp44 */
		kappa_c=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)-1.,0.);
		kappa_t=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)+1.,0.);
		Hc=0.; Ht=0.;
		for(iv=0; iv<numvertices;iv++){
			if(enthalpy[iv]<PIE[iv])
			 Hc+=(PIE[iv]-enthalpy[iv]);
			else
			 Ht+=(enthalpy[iv]-PIE[iv]);
		}
		_assert_((Hc+Ht)>0.);
		lambda = Hc/(Hc+Ht);
		kappa  = 1./(lambda/kappa_c + (1.-lambda)/kappa_t);
	}

	/*Clean up and return*/
	xDelete<IssmDouble>(PIE);
	xDelete<IssmDouble>(dHpmp);
	return kappa;
}
/*}}}*/
void Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/

	/*Ouput*/
	IssmDouble temperature,waterfraction;

	if(enthalpy<PureIceEnthalpy(pressure)){
		temperature=referencetemperature+enthalpy/heatcapacity;
		waterfraction=0.;
	}
	else{
		temperature=TMeltingPoint(pressure);
		waterfraction=(enthalpy-PureIceEnthalpy(pressure))/latentheat;
	}

	/*Assign output pointers:*/
	*pwaterfraction=waterfraction;
	*ptemperature=temperature;
}
/*}}}*/
void Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/

	/*Ouput*/
	IssmDouble enthalpy;

	if(temperature<TMeltingPoint(pressure)){
		enthalpy=heatcapacity*(temperature-referencetemperature);
	}
	else{
		enthalpy=PureIceEnthalpy(pressure)+latentheat*waterfraction;
	}

	/*Assign output pointers:*/
	*penthalpy=enthalpy;
}
/*}}}*/
IssmDouble Matpar::GetLithosphereShearModulus(){		 /*{{{*/
	return lithosphere_shear_modulus;			 
}		 
/*}}}*/ 
IssmDouble Matpar::GetLithosphereDensity(){		 /*{{{*/
	return lithosphere_density;			 
}		 
/*}}}*/ 
IssmDouble Matpar::GetMantleDensity(){		 /*{{{*/
	return mantle_density;			 
}		 
/*}}}*/ 
IssmDouble Matpar::GetMantleShearModulus(){		 /*{{{*/
	return mantle_shear_modulus;			 
}		 
/*}}}*/ 
void  Matpar::ResetHooks(){/*{{{*/

	//Nothing to be done
	return;
}
/*}}}*/
