WSL/SLF GitLab Repository

GeneratorAlgorithms.cc 23.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/***********************************************************************************/
/*  Copyright 2013 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of MeteoIO.
    MeteoIO is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MeteoIO is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <meteoio/GeneratorAlgorithms.h>
#include <meteoio/MathOptim.h>
20
21
22
#include <meteoio/meteoLaws/Atmosphere.h>
#include <meteoio/meteoLaws/Meteoconst.h>
#include <meteoio/meteoFilters/ProcHNWDistribute.h> //for the precipitation distribution
23
24
25
26
27
28
29
30
31
32
33
34

using namespace std;

namespace mio {

GeneratorAlgorithm* GeneratorAlgorithmFactory::getAlgorithm(const std::string& i_algoname, const std::vector<std::string>& vecArgs)
{
	std::string algoname(i_algoname);
	IOUtils::toUpper(algoname);

	if (algoname == "CST"){
		return new ConstGenerator(vecArgs, i_algoname);
35
36
	} else if (algoname == "SIN"){
		return new SinGenerator(vecArgs, i_algoname);
37
38
	} else if (algoname == "STD_PRESS"){
		return new StandardPressureGenerator(vecArgs, i_algoname);
39
40
	} else if (algoname == "RELHUM"){
		return new RhGenerator(vecArgs, i_algoname);
41
42
	} else if (algoname == "TS_OLWR"){
		return new TsGenerator(vecArgs, i_algoname);
43
44
45
46
	} else if (algoname == "CLEARSKY_LW"){
		return new ClearSkyLWGenerator(vecArgs, i_algoname);
	} else if (algoname == "ALLSKY_LW"){
		return new AllSkyLWGenerator(vecArgs, i_algoname);
47
48
	} else if (algoname == "POT_RADIATION"){
		return new PotRadGenerator(vecArgs, i_algoname);
49
50
	} else if (algoname == "HS_SWE"){
		return new HSSweGenerator(vecArgs, i_algoname);
51
52
53
54
55
56
57
58
59
	} else {
		throw IOException("The generator algorithm '"+algoname+"' is not implemented" , AT);
	}
}

std::string GeneratorAlgorithm::getAlgo() const {
	return algo;
}

60
61
62
63
64
65
66
void GeneratorAlgorithm::parse_args(const std::vector<std::string>& vecArgs)
{
	if(!vecArgs.empty()) { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

67
68
69
70
71
72
73
74
75
76
77
78
////////////////////////////////////////////////////////////////////////

void ConstGenerator::parse_args(const std::vector<std::string>& vecArgs)
{
	//Get the optional arguments for the algorithm: constant value to use
	if(vecArgs.size()==1) {
		IOUtils::convertString(constant, vecArgs[0]);
	} else { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

79
bool ConstGenerator::generate(const size_t& param, MeteoData& md)
80
81
82
83
84
85
86
87
{
	double &value = md(param);
	if(value == IOUtils::nodata)
		value = constant;

	return true; //all missing values could be filled
}

88
bool ConstGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
89
90
91
92
93
94
95
96
97
98
{
	if(vecMeteo.empty()) return true;

	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		generate(param, vecMeteo[ii]);
	}

	return true; //all missing values could be filled
}

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
void SinGenerator::parse_args(const std::vector<std::string>& vecArgs)
{
	//Get the optional arguments for the algorithm: constant value to use
	if(vecArgs.size()==4) {
		const string type_str=IOUtils::strToUpper(vecArgs[0]);
		if( type_str=="YEARLY" ) type='y';
		else if( type_str=="DAILY" ) type='d';
		else
			throw InvalidArgumentException("Invalid period \""+type_str+"\" specified for the "+algo+" generator", AT);

		double min, max;
		IOUtils::convertString(min, vecArgs[1]);
		IOUtils::convertString(max, vecArgs[2]);
		amplitude = 0.5*(max-min); //the user provides min, max
		offset = min+amplitude;
		IOUtils::convertString(phase, vecArgs[3]);
	} else { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

bool SinGenerator::generate(const size_t& param, MeteoData& md)
{
	double &value = md(param);
	if(value == IOUtils::nodata) {
		double t; //also, the minimum must occur at 0 if phase=0
		if(type=='y') {
			t = (static_cast<double>(md.date.getJulianDayNumber()) - phase*365.25) / 366.25 - .25;
		} else if(type=='d') {
			const double julian = md.date.getJulian();
			t = (julian - Optim::intPart(julian) - phase) + .25; //watch out: julian day starts at noon!
130
		} else {
131
			std::ostringstream ss;
132
133
			ss << "Invalid period \"" << type << "\" specified for the " << algo << " generator";
			throw InvalidArgumentException(ss.str(), AT);
134
135
		}

136
		const double w = 2.*Cst::PI;
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
		value = amplitude * sin(w*t) + offset;
	}

	return true; //all missing values could be filled
}

bool SinGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
{
	if(vecMeteo.empty()) return true;

	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		generate(param, vecMeteo[ii]);
	}

	return true; //all missing values could be filled
}

154

155
bool StandardPressureGenerator::generate(const size_t& param, MeteoData& md)
156
157
158
159
160
161
162
163
164
165
166
{
	double &value = md(param);
	if(value == IOUtils::nodata) {
		const double altitude = md.meta.position.getAltitude();
		if(altitude==IOUtils::nodata) return false;
		value = Atmosphere::stdAirPressure(altitude);
	}

	return true; //all missing values could be filled
}

167
bool StandardPressureGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
168
169
170
{
	if(vecMeteo.empty()) return true;

171
	const double altitude = vecMeteo.front().meta.position.getAltitude(); //if the stations move, this has to be in the loop
172
173
174
175
176
177
178
179
180
181
182
	if(altitude==IOUtils::nodata) return false;

	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		double &value = vecMeteo[ii](param);
		if(value == IOUtils::nodata)
			value = Atmosphere::stdAirPressure(altitude);
	}

	return true; //all missing values could be filled
}

183

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
bool RhGenerator::generate(const size_t& param, MeteoData& md)
{
	double &value = md(param);
	if(value == IOUtils::nodata) {
		const double TA = md(MeteoData::TA);
		if (TA==IOUtils::nodata) //nothing else we can do here
			return false;

		//first chance to compute RH
		if (md.param_exists("TD")) {
			const double TD = md("TD");
			if (TD!=IOUtils::nodata)
				value = Atmosphere::DewPointtoRh(TD, TA, false);
		}

		//second chance to try to compute RH
		if (value==IOUtils::nodata && md.param_exists("SH")) {
			const double SH = md("SH");
			const double altitude = md.meta.position.getAltitude();
			if (SH!=IOUtils::nodata && altitude!=IOUtils::nodata)
				value = Atmosphere::specToRelHumidity(altitude, TA, SH);
		}

		if (value==IOUtils::nodata) return false;
	}

	return true; //all missing values could be filled
}

bool RhGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
{
	if(vecMeteo.empty()) return true;

	const double altitude = vecMeteo.front().meta.position.getAltitude(); //if the stations move, this has to be in the loop

	bool all_filled = true;
	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		double &value = vecMeteo[ii](param);
		if(value == IOUtils::nodata) {
			const double TA = vecMeteo[ii](MeteoData::TA);
			if (TA==IOUtils::nodata) { //nothing else we can do here
				all_filled=false;
				continue;
			}

			//first chance to compute RH
			if (vecMeteo[ii].param_exists("TD")) {
				const double TD = vecMeteo[ii]("TD");
				if (TD!=IOUtils::nodata)
					value = Atmosphere::DewPointtoRh(TD, TA, false);
			}

			//second chance to try to compute RH
			if (value==IOUtils::nodata && vecMeteo[ii].param_exists("SH")) {
				const double SH = vecMeteo[ii]("SH");
				if (SH!=IOUtils::nodata && altitude!=IOUtils::nodata)
					value = Atmosphere::specToRelHumidity(altitude, TA, SH);
			}

			if (value==IOUtils::nodata) all_filled=false;
		}
	}

	return all_filled;
}


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
const double TsGenerator::e_snow = .983; //snow emissivity (0.969 - 0.997)
const double TsGenerator::e_soil = .9805; //grass emissivity (0.975 - 0.986)
const double TsGenerator::snow_thresh = .1; //if snow height greater than this threshold -> snow albedo

bool TsGenerator::generate(const size_t& param, MeteoData& md)
{
	double &value = md(param);
	if(value == IOUtils::nodata) {
		const double olwr = md("OLWR");
		if (olwr==IOUtils::nodata) //nothing else we can do here
			return false;

		const double hs = md(MeteoData::HS);
		const double ea = (hs==IOUtils::nodata)? .5*(e_snow+e_soil) : (hs>snow_thresh)? e_snow : e_soil;

		//value = pow( olwr / ( ea * Cst::stefan_boltzmann ), 0.25);
		value = Optim::invSqrt( Optim::invSqrt(olwr / ( ea * Cst::stefan_boltzmann )) );

		if (value==IOUtils::nodata) return false;
	}

	return true; //all missing values could be filled
}

bool TsGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
{
	if(vecMeteo.empty()) return true;

	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		generate(param, vecMeteo[ii]);
	}

	return true; //all missing values could be filled
}


287
void ClearSkyLWGenerator::parse_args(const std::vector<std::string>& vecArgs)
288
289
290
291
292
293
294
295
{
	//Get the optional arguments for the algorithm: constant value to use
	if(vecArgs.size()==1) {
		const std::string user_algo = IOUtils::strToUpper(vecArgs[0]);

		if (user_algo=="BRUTSAERT") model = BRUTSAERT;
		else if (user_algo=="DILLEY") model = DILLEY;
		else if (user_algo=="PRATA") model = PRATA;
296
297
		else if (user_algo=="CLARK") model = CLARK;
		else if (user_algo=="TANG") model = TANG;
298
		else if (user_algo=="IDSO") model = IDSO;
299
300
301
302
303
304
305
		else
			throw InvalidArgumentException("Unknown parametrization \""+user_algo+"\" supplied for the "+algo+" generator", AT);
	} else { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

306
bool ClearSkyLWGenerator::generate(const size_t& param, MeteoData& md)
307
308
{
	double &value = md(param);
309
	if (value==IOUtils::nodata) {
310
		const double TA=md(MeteoData::TA), RH=md(MeteoData::RH);
311
312
313
314
315
316
317
318
		if (TA==IOUtils::nodata || RH==IOUtils::nodata) return false;

		if (model==BRUTSAERT)
			value = Atmosphere::Brutsaert_ilwr(RH, TA);
		else if (model==DILLEY)
			value = Atmosphere::Dilley_ilwr(RH, TA);
		else if (model==PRATA)
			value = Atmosphere::Prata_ilwr(RH, TA);
319
320
321
322
		else if (model==CLARK)
			value = Atmosphere::Clark_ilwr(RH, TA);
		else if (model==TANG)
			value = Atmosphere::Tang_ilwr(RH, TA);
323
324
		else if (model==IDSO)
			value = Atmosphere::Idso_ilwr(RH, TA);
325
326
327
328
329
	}

	return true; //all missing values could be filled
}

330
bool ClearSkyLWGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
331
332
333
334
335
336
337
338
339
340
341
342
343
{
	if(vecMeteo.empty()) return true;

	bool all_filled = true;
	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		const bool status = generate(param, vecMeteo[ii]);
		if(status==false) all_filled=false;
	}

	return all_filled;
}


344
345
346
const double AllSkyLWGenerator::soil_albedo = .23; //grass
const double AllSkyLWGenerator::snow_albedo = .85; //snow
const double AllSkyLWGenerator::snow_thresh = .1; //if snow height greater than this threshold -> snow albedo
347

348
void AllSkyLWGenerator::parse_args(const std::vector<std::string>& vecArgs)
349
{
350
351
352
	//Get the optional arguments for the algorithm: constant value to use
	if(vecArgs.size()==1) {
		const std::string user_algo = IOUtils::strToUpper(vecArgs[0]);
353

354
355
356
357
358
359
		if (user_algo=="OMSTEDT") model = OMSTEDT;
		else if (user_algo=="KONZELMANN") model = KONZELMANN;
		else if (user_algo=="UNSWORTH") model = UNSWORTH;
		else if (user_algo=="CRAWFORD") model = CRAWFORD;
		else
			throw InvalidArgumentException("Unknown parametrization \""+user_algo+"\" supplied for the "+algo+" generator", AT);
360
361

		if (model==CRAWFORD) clf_model = CLF_CRAWFORD;
362
363
364
365
366
	} else { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

367
double AllSkyLWGenerator::getCloudiness(const MeteoData& md, SunObject& sun, bool &is_night)
368
369
370
371
372
{
	//we know that TA and RH are available, otherwise we would not get called
	const double TA=md(MeteoData::TA), RH=md(MeteoData::RH), HS=md(MeteoData::HS), RSWR=md(MeteoData::RSWR);
	double ISWR=md(MeteoData::ISWR);

373
374
	is_night = false;

375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
	double albedo = .5;
	if (RSWR==IOUtils::nodata || ISWR==IOUtils::nodata || RSWR<=0 || ISWR<=0) {
		if (HS!=IOUtils::nodata) //no big deal if we can not adapt the albedo
			albedo = (HS>=snow_thresh)? snow_albedo : soil_albedo;

		if (ISWR==IOUtils::nodata && (RSWR!=IOUtils::nodata && HS!=IOUtils::nodata)) {
			ISWR = RSWR / albedo;
		}
	} else {
		albedo = RSWR / ISWR;
		if (albedo>=1.) albedo=0.99;
		if (albedo<=0.) albedo=0.01;
	}

	if (ISWR<5.) {
		is_night = true;
		return IOUtils::nodata;
	}

	if (ISWR==IOUtils::nodata) return IOUtils::nodata; //no way to get ISWR

	sun.calculateRadiation(TA, RH, albedo);
	double toa, direct, diffuse;
	sun.getHorizontalRadiation(toa, direct, diffuse);
	const double iswr_clear_sky = direct+diffuse;

401
402
403
404
405
406
	//at sunrise or sunset, we might get clf<0 or clf>1 -> return nodata in order to use interpolation instead
	if (iswr_clear_sky<5. || iswr_clear_sky<ISWR) {
		is_night = true;
		return IOUtils::nodata;
	}

407
408
	if (clf_model==KASTEN) {
		const double clf = Atmosphere::Kasten_cloudiness(ISWR/iswr_clear_sky);
409
		if (clf<0. || clf>1.) return IOUtils::nodata;
410
411
412
		return clf;
	} else if (clf_model==CLF_CRAWFORD) {
		const double clf = 1. - ISWR/iswr_clear_sky;
413
		if (clf<0. || clf>1.) return IOUtils::nodata;
414
415
416
417
418
		return clf;
	} else
		return IOUtils::nodata; //this should never happen
}

419
bool AllSkyLWGenerator::generate(const size_t& param, MeteoData& md)
420
421
422
{
	double &value = md(param);
	if (value==IOUtils::nodata) {
423
424
		const double TA=md(MeteoData::TA), RH=md(MeteoData::RH);
		if (TA==IOUtils::nodata || RH==IOUtils::nodata) return false;
425
		double cloudiness = (md.param_exists("TAU_CLD"))? Atmosphere::Kasten_cloudiness( 1.-md("TAU_CLD") ) : IOUtils::nodata;
426

427
428
429
430
		const string station_hash = md.meta.stationID + ":" + md.meta.stationName;
		const double julian_gmt = md.date.getJulian(true);
		bool cloudiness_from_cache = false;

431
432
433
434
435
436
437
438
439
440
441
442
443
444
		//try to get a cloudiness value
		if (cloudiness==IOUtils::nodata) {
			const double lat = md.meta.position.getLat();
			const double lon = md.meta.position.getLon();
			const double alt = md.meta.position.getAltitude();
			SunObject sun;
			sun.setLatLon(lat, lon, alt);
			sun.setDate(julian_gmt, 0.);

			bool is_night;
			cloudiness = getCloudiness(md, sun, is_night);
			if (cloudiness==IOUtils::nodata && !is_night) return false;

			if (is_night) { //interpolate the cloudiness over the night
445
446
447
448
449
450
451
				const map< string, pair<double, double> >::const_iterator it = last_cloudiness.find(station_hash);
				if (it==last_cloudiness.end()) return false;

				cloudiness_from_cache = true;
				const double last_cloudiness_julian = it->second.first;
				const double last_cloudiness_value = it->second.second;
				if ((julian_gmt - last_cloudiness_julian) < 1.) cloudiness = last_cloudiness_value;
452
453
454
455
456
				else return false;
			}
		}

		//run the ILWR parametrization
457
458
459
460
461
462
463
464
465
466
467
		if (model==OMSTEDT)
			value = Atmosphere::Omstedt_ilwr(RH, TA, cloudiness);
		else if (model==KONZELMANN)
			value = Atmosphere::Konzelmann_ilwr(RH, TA, cloudiness);
		else if (model==UNSWORTH)
			value = Atmosphere::Unsworth_ilwr(RH, TA, IOUtils::nodata, IOUtils::nodata, cloudiness);
		else if (model==CRAWFORD) {
			int year, month, day;
			md.date.getDate(year, month, day);
			value = Atmosphere::Crawford_ilwr(RH, TA, IOUtils::nodata, IOUtils::nodata, static_cast<unsigned char>(month), cloudiness);
		}
468

469
470
471
		//save the last valid cloudiness
		if (!cloudiness_from_cache)
			last_cloudiness[station_hash] = pair<double,double>( julian_gmt, cloudiness );
472
473
474
475
	}

	return true; //all missing values could be filled
}
476

477
bool AllSkyLWGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
478
{
479
480
481
482
483
484
	if(vecMeteo.empty()) return true;

	bool all_filled = true;
	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		const bool status = generate(param, vecMeteo[ii]);
		if(status==false) all_filled=false;
485
	}
486
487

	return all_filled;
488
489
}

490

491
const double PotRadGenerator::soil_albedo = .23; //grass
492
const double PotRadGenerator::snow_albedo = .85; //snow
493
494
495
496
497
498
499
500
501
502
503
504
505
const double PotRadGenerator::snow_thresh = .1; //if snow height greater than this threshold -> snow albedo
void PotRadGenerator::parse_args(const std::vector<std::string>& vecArgs)
{
	//Get the optional arguments for the algorithm: constant value to use
	if(!vecArgs.empty()) { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

bool PotRadGenerator::generate(const size_t& param, MeteoData& md)
{
	double &value = md(param);
	if(value == IOUtils::nodata) {
506
		const double ISWR=md(MeteoData::ISWR), RSWR=md(MeteoData::RSWR), HS=md(MeteoData::HS), TAU_CLD=md(MeteoData::TAU_CLD);
507
		double TA=md(MeteoData::TA), RH=md(MeteoData::RH), ILWR=md(MeteoData::ILWR);
508
509
510
511
512
513

		const double lat = md.meta.position.getLat();
		const double lon = md.meta.position.getLon();
		const double alt = md.meta.position.getAltitude();
		if(lat==IOUtils::nodata || lon==IOUtils::nodata || alt==IOUtils::nodata) return false;

514
		double albedo = .5;
515
516
517
		if(RSWR==IOUtils::nodata || ISWR==IOUtils::nodata) {
			if(HS!=IOUtils::nodata) //no big deal if we can not adapt the albedo
				albedo = (HS>=snow_thresh)? snow_albedo : soil_albedo;
518
		} else if(ISWR>0. && RSWR>0.) { //this could happen if the user calls this generator for a copy parameter, etc
519
			albedo = RSWR / ISWR;
520
521
			if(albedo>=1.) albedo=0.99;
			if(albedo<=0.) albedo=0.01;
522
		}
523
524
525
526
527
528
529
530
531
532

		if(TA==IOUtils::nodata || RH==IOUtils::nodata) {
			//set TA & RH so the reduced precipitable water will get an average value
			TA=274.98;
			RH=0.666;
			ILWR=IOUtils::nodata; //skip solarIndex correction
		}

		sun.setLatLon(lat, lon, alt);
		sun.setDate(md.date.getJulian(true), 0.);
533
		const double solarIndex = (TAU_CLD!=IOUtils::nodata)? TAU_CLD : (ILWR!=IOUtils::nodata)? getSolarIndex(TA, RH, ILWR) : 1.;
534

535
536
537
538
539
540
		const double P=md(MeteoData::P);
		if(P==IOUtils::nodata)
			sun.calculateRadiation(TA, RH, albedo);
		else
			sun.calculateRadiation(TA, RH, P, albedo);

541
542
		double toa, direct, diffuse;
		sun.getHorizontalRadiation(toa, direct, diffuse);
543
		if(param!=MeteoData::RSWR)
544
			value = (direct+diffuse)*solarIndex; //ISWR
545
		else
546
			value = (direct+diffuse)*albedo*solarIndex; //RSWR
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
	}

	return true; //all missing values could be filled
}

bool PotRadGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
{
	if(vecMeteo.empty()) return true;

	const double lat = vecMeteo.front().meta.position.getLat();
	const double lon = vecMeteo.front().meta.position.getLon();
	const double alt = vecMeteo.front().meta.position.getAltitude();
	if(lat==IOUtils::nodata || lon==IOUtils::nodata || alt==IOUtils::nodata) return false;
	sun.setLatLon(lat, lon, alt);

	bool all_filled = true;
	for(size_t ii=0; ii<vecMeteo.size(); ii++) {
		double &value = vecMeteo[ii](param);
		if(value == IOUtils::nodata) {
566
567
			const double ISWR=vecMeteo[ii](MeteoData::ISWR), RSWR=vecMeteo[ii](MeteoData::RSWR), HS=vecMeteo[ii](MeteoData::HS);
			double TA=vecMeteo[ii](MeteoData::TA), RH=vecMeteo[ii](MeteoData::RH), ILWR=vecMeteo[ii](MeteoData::ILWR);
568

569
			double albedo = .5;
570
571
572
			if(RSWR==IOUtils::nodata || ISWR==IOUtils::nodata) {
				if(HS!=IOUtils::nodata) //no big deal if we can not adapt the albedo
					albedo = (HS>=snow_thresh)? snow_albedo : soil_albedo;
573
			} else if(ISWR>0. && RSWR>0.) { //this could happen if the user calls this generator for a copy parameter, etc
574
				albedo = RSWR / ISWR;
575
576
				if(albedo>=1.) albedo=0.99;
				if(albedo<=0.) albedo=0.01;
577
			}
578

579
580
581
582
583
584
585
586
587
			if(TA==IOUtils::nodata || RH==IOUtils::nodata) {
				//set TA & RH so the reduced precipitable water will get an average value
				TA=274.98;
				RH=0.666;
				ILWR=IOUtils::nodata; //skip solarIndex correction
			}

			sun.setDate(vecMeteo[ii].date.getJulian(true), 0.);
			const double solarIndex = (ILWR!=IOUtils::nodata)? getSolarIndex(TA, RH, ILWR) : 1.;
588

589
590
591
592
593
594
			const double P=vecMeteo[ii](MeteoData::P);
			if(P==IOUtils::nodata)
				sun.calculateRadiation(TA, RH, albedo);
			else
				sun.calculateRadiation(TA, RH, P, albedo);

595
596
			double toa, direct, diffuse;
			sun.getHorizontalRadiation(toa, direct, diffuse);
597
			if(param!=MeteoData::RSWR)
598
				value = (direct+diffuse)*solarIndex; //ISWR
599
			else
600
				value = (direct+diffuse)*albedo*solarIndex; //RSWR
601
602
603
		}
	}

604
	return all_filled;
605
606
}

607
608
double PotRadGenerator::getSolarIndex(const double& ta, const double& rh, const double& ilwr)
{// this is based on Kartsen cloudiness, Dilley clear sky emissivity and Unsworth ILWR
609
610
//this means that this solar index is the ratio of iswr for clear sky on a horizontal
//surface and the measured iswr
611
612
613
614
615
616
617
618
619
620
621
	const double epsilon_clear = Atmosphere::Dilley_emissivity(rh, ta);
	const double ilwr_clear = Atmosphere::blkBody_Radiation(1., ta);

	double cloudiness = (ilwr/ilwr_clear - epsilon_clear) / (.84 * (1.-epsilon_clear));
	if(cloudiness>1.) cloudiness=1.;
	if(cloudiness<0.) cloudiness=0.;

	const double b1 = 0.75, b2 = 3.4;
	const double karsten_Si = 1. - (b1 * pow(cloudiness, b2));
	return karsten_Si;
}
622

623
624
625
626
627
628
629
630
631
632
633
634
635
636

const bool HSSweGenerator::soft = true;
void HSSweGenerator::parse_args(const std::vector<std::string>& vecArgs)
{
	if(vecArgs.size()>0) { //incorrect arguments, throw an exception
		throw InvalidArgumentException("Wrong number of arguments supplied for the "+algo+" generator", AT);
	}
}

bool HSSweGenerator::generate(const size_t& /*param*/, MeteoData& /*md*/)
{//HACK: modify prototype so we can get the full vector + the index of the replacement
	return false; //all missing values could be filled
}

637
638
//when we can not guarantee HNW=0, we leave it at nodata. Therefore, it is highly recommended to
//run through a Cst=0 data generator afterward
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
bool HSSweGenerator::generate(const size_t& param, std::vector<MeteoData>& vecMeteo)
{
	if(param!=MeteoData::HNW)
		throw InvalidArgumentException("Trying to use "+algo+" generator on " + MeteoData::getParameterName(param) + " but it can only be applied to HNW!!", AT);

	if(vecMeteo.empty()) return true;

	//Find first point that is not IOUtils::nodata
	size_t last_good = IOUtils::npos;
	for (size_t ii=0; ii<vecMeteo.size(); ii++){
		if (vecMeteo[ii](MeteoData::HS) != IOUtils::nodata){
			last_good = ii;
			break;
		}
	}

	if (last_good == IOUtils::npos) //can not find a good point to start
		return false;

	bool all_filled = (last_good>0)? false : true;
	for(size_t ii=last_good+1; ii<vecMeteo.size(); ii++) {
		const double HS_curr = vecMeteo[ii](MeteoData::HS);
		if(HS_curr==IOUtils::nodata) continue;

		const size_t start_idx = last_good+1;
		const double HS_prev = vecMeteo[last_good](MeteoData::HS);
		const double HS_delta = HS_curr - HS_prev;

		if(HS_delta>0.) {
			const double rho = newSnowDensity(vecMeteo[ii]);
			const double precip = HS_delta * rho; //in kg/m2 or mm
670
			ProcHNWDistribute::SmartDistributeHNW(precip, start_idx, ii, param, vecMeteo);
671
		} else {
672
			all_filled = false;
673
		}
674
675
676
677
678
679
680
681

		last_good=ii;
	}

	return all_filled;
}

double HSSweGenerator::newSnowDensity(const MeteoData& md) const
682
683
{ //C. Zwart, "Significance of new-snow properties for snowcover development",
//master's thesis, 2007, Institute for Marine and Atmospheric Research, University of Utrecht, 78 pp.
684
685
686
687
688
689
690
691
692
	const double vw = max(2., md(MeteoData::VW));
	const double rh = md(MeteoData::RH);
	const double ta = md(MeteoData::TA) - Cst::t_water_triple_pt;
	const double beta01=3.28, beta1=0.03, beta02=-0.36, beta2=-0.75, beta3=0.3;

	double arg = beta01 + beta1*ta + beta2*asin(sqrt(rh)) + beta3*log10(vw);
	if(ta>=-14.)
		arg += beta02; // += beta2*ta;

693
	return min( max(30., pow(10., arg)), 250. ); //limit the density to the [30, 250] kg/m3 range
694
695
}

696
697
} //namespace