WSL/SLF GitLab Repository

SnowpackInterface.cc 58.6 KB
Newer Older
Julien Esseiva's avatar
Julien Esseiva committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/***********************************************************************************/
/*  Copyright 2009-2015 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of Alpine3D.
    Alpine3D 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.

    Alpine3D 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 Alpine3D.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <alpine3d/SnowpackInterface.h>
#include <alpine3d/AlpineMain.h>
#include <alpine3d/MPIControl.h>
#include <alpine3d/OMPControl.h>

#include <errno.h>
#include <algorithm>

using namespace std;
using namespace mio;

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const std::vector<std::string> SnowpackInterface::grids_not_computed_in_worker{
"TA",
"RH",
"VW",
"DW",
"PSUM",
"PSUM_PH",
"PSUM_TECH",
"MNS",
"ISWR",
"ILWR",
"ISWR_TERRAIN",
"ILWR_TERRAIN",
"ISWR_DIFF",
"ISWR_DIR"};

Julien Esseiva's avatar
Julien Esseiva committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//sort the by increasing y and increasing x as a second key
inline bool pair_comparator(const std::pair<double, double>& l, const std::pair<double, double>& r)
{
	if (l.second == r.second)
		return l.first < r.first;

	return l.second < r.second;
}

//convert the POI to grid index representation and warn of duplicates
std::vector< std::pair<size_t,size_t> > prepare_pts(const std::vector<Coords>& vec_pts)
{
	std::vector< std::pair<size_t,size_t> > pts;
	std::vector<size_t> vec_idx;
	for (size_t ii=0; ii<vec_pts.size(); ii++) {
		const size_t ix = vec_pts[ii].getGridI();
		const size_t iy = vec_pts[ii].getGridJ();
		std::pair<size_t,size_t> tmp(ix,iy);

		const std::vector< std::pair<size_t,size_t> >::const_iterator it = std::find(pts.begin(), pts.end(), tmp);
		if (it != pts.end()) {
			if (MPIControl::instance().master()) {
				const size_t orig_idx = vec_idx[ it - pts.begin() ];
				std::cout << "[W] POI #" << ii << " " << vec_pts[ii].toString(Coords::CARTESIAN);
				std::cout << " is a duplicate of POI #" <<  orig_idx << " " << vec_pts[orig_idx].toString(Coords::CARTESIAN) << std::endl; //flush for openmp
			}
		} else {
			pts.push_back( tmp );
			vec_idx.push_back( ii ); //in order to be able to find out where a duplicate is originating from
		}
	}
	sort(pts.begin(), pts.end(), pair_comparator);
	return pts;
}

/**
 * @brief Constructs and initialise Snowpack Interface Master. He creates the Worker and
 * Distributes the Data from the other modules to the Worker. Is the acces interface A3D side
 * @param io_cfg is used to init Runoff and to create IOManager, which is used to write the standart output
 * @param nbworkers gives the new values for the wind speed
 * @param dem_in gives the demographic Data. Also tetermines size and position of the geographical modeling scope
 * @param landuse_in gives the landuse Data. Also tetermines size and position of the landuse for modeling scope
 * @param vec_pts gives the spezial points. For this points more output is done then for the others. Calcualtion is the same.
 * @param startTime is the time and date the first simulation step is done
 * @param grids_requirements list of grids that must be prepared for other modules (similar to the Output::GRIDS_PARAMETERS configuration key)
 * @param is_restart_in is used to know which files the worker needs to read to init the pixel
 */
SnowpackInterface::SnowpackInterface(const mio::Config& io_cfg, const size_t& nbworkers,
                                     const mio::DEMObject& dem_in,
                                     const mio::Grid2DObject& landuse_in,
                                     const std::vector<mio::Coords>& vec_pts,
                                     const mio::Date &startTime,
                                     const std::string& grids_requirements,
                                     const bool is_restart_in)
                : run_info(), io(io_cfg), pts(prepare_pts(vec_pts)),dem(dem_in),
                  is_restart(is_restart_in), useCanopy(false), enable_lateral_flow(false), a3d_view(false),
                  do_io_locally(true), station_name(),glacier_katabatic_flow(false), snow_production(false), snow_grooming(false),
                  Tsoil_idx(), grids_start(0), grids_days_between(0), ts_start(0.), ts_days_between(0.), prof_start(0.), prof_days_between(0.),
                  grids_write(true), ts_write(false), prof_write(false), snow_write(false), snow_poi_written(false), glacier_from_grid(false),
                  meteo_outpath(), outpath(), mask_glaciers(false), mask_dynamic(false), maskGlacier(), tz_out(0.),
                  sn_cfg(readAndTweakConfig(io_cfg, !pts.empty())), snowpackIO(sn_cfg), dimx(dem_in.getNx()), dimy(dem_in.getNy()), mpi_offset(0), mpi_nx(dimx),
                  landuse(landuse_in), mns(dem_in, IOUtils::nodata), shortwave(dem_in, IOUtils::nodata), longwave(dem_in, IOUtils::nodata), diffuse(dem_in, IOUtils::nodata),
107
                  terrain_shortwave(dem_in, IOUtils::nodata), terrain_longwave(dem_in, IOUtils::nodata),
Julien Esseiva's avatar
Julien Esseiva committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
                  psum(dem_in, IOUtils::nodata), psum_ph(dem_in, IOUtils::nodata), psum_tech(dem_in, IOUtils::nodata), grooming(dem_in, IOUtils::nodata),
                  vw(dem_in, IOUtils::nodata), dw(dem_in, IOUtils::nodata), rh(dem_in, IOUtils::nodata), ta(dem_in, IOUtils::nodata), init_glaciers_height(dem_in, IOUtils::nodata),
                  solarElevation(0.), output_grids(), workers(nbworkers), worker_startx(nbworkers), worker_deltax(nbworkers), worker_stations_coord(nbworkers),
                  timer(), nextStepTimestamp(startTime), timeStep(dt_main/86400.), dataMeteo2D(false), dataDa(false), dataSnowDrift(false), dataRadiation(false),
                  drift(NULL), eb(NULL), da(NULL), runoff(NULL), glaciers(NULL), techSnow(NULL)
{
	MPIControl& mpicontrol = MPIControl::instance();

	std::vector<SnowStation*> snow_stations;
	std::vector<std::pair<size_t,size_t> > snow_stations_coord;

	// Check if glacier height should be obtained from a grid.
	// This option overwrite landuse information.
	// To use it the following set of keys should be provided:
	//   GLACIER_FROM_GRID = TRUE
	//   GLACIER = ARC (for now no other plugin is supported)
	//   GLACIERFILE = path_to_glacier_file
	// The glacier file (grid simmilar to the DEM) should contain glacier height in meters,
	// and 0 or nodata for glacier free pixels.
	sn_cfg.getValue("GLACIER_FROM_GRID", "input", glacier_from_grid,IOUtils::nothrow);
	if(glacier_from_grid)
	{
		setInitGlacierHeight();
	}

	readInitalSnowCover(snow_stations,snow_stations_coord);

	if (mpicontrol.master()) {
136
137
138
139
140
141
142
143
144
145

    bool write_dem_details=false;
    io_cfg.getValue("WRITE_DEM_DETAILS", "output", write_dem_details,IOUtils::nothrow);
    if(write_dem_details){
      std::cout << "[i] Writing DEM details grids" << std::endl;
      io.write2DGrid(mio::Grid2DObject(dem.cellsize,dem.llcorner,dem.slope), "DEM_SLOPE");
      io.write2DGrid(mio::Grid2DObject(dem.cellsize,dem.llcorner,dem.azi), "DEM_AZI");
      io.write2DGrid(mio::Grid2DObject(dem.cellsize,dem.llcorner,dem.curvature), "DEM_CURVATURE");
    }

Julien Esseiva's avatar
Julien Esseiva committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
		std::cout << "[i] SnowpackInterface initializing a total of " << mpicontrol.size();
		if (mpicontrol.size()>1) std::cout << " processes with " << nbworkers;
		else std::cout << " process with " << nbworkers;
		if (nbworkers>1) std::cout << " workers";
		else  std::cout << " worker";
		std::cout << " each using Snowpack " << snowpack::getLibVersion() << "\n";
	}

	//create and prepare  the vector of output grids
	if (grids_write) {
		sn_cfg.getValue("GRIDS_PARAMETERS", "output", output_grids);
		std::vector<double> soil_temp_depths;
		sn_cfg.getValue("SOIL_TEMPERATURE_DEPTHS", "Output", soil_temp_depths, IOUtils::nothrow);
		const unsigned short max_Tsoil( SnGrids::lastparam - SnGrids::TSOIL1 + 1 );
		if (soil_temp_depths.size()>max_Tsoil)
			throw InvalidArgumentException("Too many soil temperatures requested", AT);
		for (size_t ii=0; ii<soil_temp_depths.size(); ii++) {
			std::stringstream ss;
			ss << (ii+1);
			const std::string ii_str(ss.str());
			Tsoil_idx.push_back( ii_str );
			output_grids.push_back( "TSOIL"+ii_str );
		}
		SnowpackInterfaceWorker::uniqueOutputGrids(output_grids);
	}
	//add the grids that are necessary for the other modules
	const std::string all_grids = sn_cfg.get("GRIDS_PARAMETERS", "output", "");
	sn_cfg.addKey("GRIDS_PARAMETERS", "output", all_grids + " " + grids_requirements + " " + getGridsRequirements()); //also consider own requirements

	//check if lateral flow is enabled
	sn_cfg.getValue("LATERAL_FLOW", "Alpine3D", enable_lateral_flow, IOUtils::nothrow);

	//check if A3D view should be used for grids
	sn_cfg.getValue("A3D_VIEW", "Output", a3d_view, IOUtils::nothrow);

	//If MPI is active, every node gets a slice of the DEM to work on
	mpicontrol.getArraySliceParamsOptim(dimx, mpi_offset, mpi_nx,dem,landuse);
	std::cout << "[i] MPI instance "<< mpicontrol.rank() <<" for solving snowpack : grid range = ["
	<< mpi_offset << " to " << mpi_offset+mpi_nx-1 << "] " << mpi_nx << " columns\n";
	//Cut DEM and landuse in MPI domain, MPI domain are computed
	//by trying to havve the same number of cell to compute per domain
	const DEMObject mpi_sub_dem(dem_in, mpi_offset, 0, mpi_nx, dimy, false);
	const Grid2DObject mpi_sub_landuse(landuse_in, mpi_offset, 0, mpi_nx, dimy);
	std::vector<std::vector<size_t> > omp_snow_stations_ind;
	//The OMP slicing for snowpack computation is not based on rectangular domain.
	//It return a table of pixel to compute and coordiantes to have the same
	//number of pixel per slice.
	OMPControl::getArraySliceParamsOptim(nbworkers,snow_stations,mpi_sub_dem, mpi_sub_landuse,omp_snow_stations_ind);
	// construct slices and workers
	#pragma omp parallel for schedule(static)
	for (size_t ii=0; ii<nbworkers; ii++) {
		// Could be optimised, but not really big gain.
		// Each worker will check again the point to be sure they belong
		// to it, so no need to double check here
		std::vector< std::pair<size_t,size_t> > sub_pts;
		const size_t n_pts = pts.size();
		for (size_t kk=0; kk<n_pts; kk++) { // could be optimised... but not really big gain
			if (pts[kk].first >= mpi_offset && pts[kk].first < mpi_offset + mpi_nx) {
				sub_pts.push_back( pts[kk] );
				sub_pts.back().first -= mpi_offset;
			}
		}
		// In this  implementation, all OMP workers see the whole MPI grid
		// This could be change but with this when passing the meteo grids
		// Only one slicing and copy is necessary per MPI, insetead of one per OMP
		const DEMObject sub_dem(mpi_sub_dem);
		const Grid2DObject sub_landuse(mpi_sub_landuse);

		// Generate workers
		std::vector<SnowStation*> thread_stations;
		std::vector<std::pair<size_t,size_t> > thread_stations_coord;
		for (std::vector<size_t>::iterator it = omp_snow_stations_ind.at(ii).begin(); it != omp_snow_stations_ind.at(ii).end(); ++it){
			thread_stations.push_back (snow_stations.at(*it));
			thread_stations_coord.push_back(snow_stations_coord.at(*it));
		}

		// The OMP slicing into rectangle is only used for post computation
		// Over the grid (i.e. lateral flow and snow preparation)
		size_t omp_offset, omp_nx;
		OMPControl::getArraySliceParams(mpi_nx, nbworkers, ii, omp_offset, omp_nx);
		const size_t offset = mpi_offset + omp_offset;

228
229
230
		workers[ii] = new SnowpackInterfaceWorker(sn_cfg, sub_dem, sub_landuse, sub_pts,
                                              thread_stations, thread_stations_coord,
                                              offset, grids_not_computed_in_worker);
Julien Esseiva's avatar
Julien Esseiva committed
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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

		worker_startx[ii] = offset;
		worker_deltax[ii] = omp_nx;
		#pragma omp critical(snowpackWorkers_status)
		{
			const std::pair<size_t,size_t> coord_start(snow_stations_coord.at(omp_snow_stations_ind.at(ii).front()));
			const std::pair<size_t,size_t> coord_end(snow_stations_coord.at(omp_snow_stations_ind.at(ii).back()));

			std::cout << "[i] SnowpackInterface worker for solving snowpack " << ii
								<< " on process " << mpicontrol.rank() << ": coord. x-y range = [" << coord_start.first + mpi_offset << "-"
								<< coord_start.second << " to " << coord_end.first + mpi_offset << "-"
								<< coord_end.second<<"] " << omp_snow_stations_ind.at(ii).size() << " cells\n";
								std::cout << "[i] SnowpackInterface worker for grid computation " << ii
								<< " on process " << mpicontrol.rank() << ": grid range = [" << offset
								<< " to " << omp_nx+offset-1 << "]  " << omp_nx << " columns\n";
		}
	}

	// init glacier map (after creating and init workers) for output
	if (mask_glaciers || glacier_katabatic_flow) {
		maskGlacier = getGrid(SnGrids::GLACIER);
		if (glacier_katabatic_flow) {
			glaciers = new Glaciers(io_cfg, dem);
			glaciers->setGlacierMap(maskGlacier);
		}
	}

	//init snow preparation
	sn_cfg.getValue("SNOW_GROOMING", "TechSnow", snow_grooming, IOUtils::nothrow);
	sn_cfg.getValue("SNOW_PRODUCTION", "TechSnow", snow_production, IOUtils::nothrow);
	if (snow_production || snow_grooming) {
		techSnow = new TechSnowA3D(io_cfg, dem);
	}
}

SnowpackInterface& SnowpackInterface::operator=(const SnowpackInterface& source) {
	if (this != &source) {
		run_info = source.run_info;
		snowpackIO = source.snowpackIO;
		dimx = source.dimx;
		dimy = source.dimy;
		landuse = source.landuse;
		mns = source.mns;
		shortwave = source.shortwave;
		longwave = source.longwave;
		diffuse = source.diffuse;
277
278
		terrain_shortwave = source.terrain_shortwave;
		terrain_longwave = source.terrain_longwave;
Julien Esseiva's avatar
Julien Esseiva committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
		psum = source.psum;
		psum_ph = source.psum_ph;
		psum_tech = source.psum_tech;
		grooming = source.grooming;
		vw = source.vw;
		dw = source.dw;
		rh = source.rh;
		ta = source.ta;
		solarElevation = source.solarElevation;
		output_grids = source.output_grids;
		workers = source.workers;
		worker_startx = source.worker_startx;
		worker_deltax = source.worker_deltax;
		timer = source.timer;
		nextStepTimestamp = source.nextStepTimestamp;
		timeStep = source.timeStep;

		drift = source.drift;
		eb = source.eb;
		da = source.da;
		runoff = source.runoff;
		dataMeteo2D = source.dataMeteo2D;
		dataDa = source.dataDa;
		dataSnowDrift = source.dataSnowDrift;
		dataRadiation = source.dataRadiation;

		//io = source.io;

		outpath = source.outpath;
		mask_glaciers = source.mask_glaciers;
		mask_dynamic = source.mask_dynamic;
		maskGlacier = source.maskGlacier;

		glacier_katabatic_flow = source.glacier_katabatic_flow;
		snow_production = source.snow_production;
		glaciers = source.glaciers;
		techSnow = source.techSnow;
		enable_lateral_flow = source.enable_lateral_flow;
		a3d_view = source.a3d_view;

		sn_cfg = source.sn_cfg;
		//dem = source.dem;
		is_restart = source.is_restart;
		useCanopy = source.useCanopy;
		do_io_locally = source.do_io_locally;
		station_name = source.station_name;

		Tsoil_idx = source.Tsoil_idx;
		grids_start = source.grids_start;
		grids_days_between = source.grids_days_between;
		ts_start = source.ts_start;
		ts_days_between = source.ts_days_between;
		prof_start = source.prof_start;
		prof_days_between = source.prof_days_between;
		grids_write = source.grids_write;
		ts_write = source.ts_write;
		prof_write = source.prof_write;
		snow_write = source.snow_write;
		snow_poi_written = source.snow_poi_written;
		meteo_outpath = source.meteo_outpath;
		tz_out = source.tz_out;
		pts = source.pts;
	}
	return *this;
}

std::string SnowpackInterface::getGridsRequirements() const
{
	if (glacier_katabatic_flow) {
		return "GLACIER TSS HS";
	}
	return "";
}

mio::Config SnowpackInterface::readAndTweakConfig(const mio::Config& io_cfg, const bool have_pts)
{
	SnowpackConfig tmp_cfg(io_cfg);
	//force some keys
	double calculation_step_length;
	tmp_cfg.getValue("CALCULATION_STEP_LENGTH", "Snowpack", calculation_step_length);
	std::stringstream ss;
	ss << calculation_step_length;
	tmp_cfg.addKey("METEO_STEP_LENGTH", "Snowpack", ss.str());
	tmp_cfg.addKey("ALPINE3D", "SnowpackAdvanced", "true");
	tmp_cfg.addKey("ALPINE3D_PTS", "SnowpackAdvanced",have_pts?"true":"false");
	tmp_cfg.addKey("PERP_TO_SLOPE", "SnowpackAdvanced", "true");

	tmp_cfg.getValue("LOCAL_IO", "General", do_io_locally, IOUtils::nothrow);
	tmp_cfg.getValue("GRID2DPATH", "Output", outpath);
	tmp_cfg.getValue("MASK_GLACIERS", "Output", mask_glaciers, IOUtils::nothrow);
	tmp_cfg.getValue("MASK_DYNAMIC", "Output", mask_dynamic, IOUtils::nothrow);
	tmp_cfg.getValue("GLACIER_KATABATIC_FLOW", "Alpine3D", glacier_katabatic_flow, IOUtils::nothrow);
	tmp_cfg.getValue("SNOW_PRODUCTION", "TechSnow", snow_production, IOUtils::nothrow);
	tmp_cfg.getValue("SNOW_GROOMING", "TechSnow", snow_grooming, IOUtils::nothrow);
	tmp_cfg.getValue("GRIDS_WRITE", "Output", grids_write);
	tmp_cfg.getValue("GRIDS_START", "Output", grids_start);
	tmp_cfg.getValue("GRIDS_DAYS_BETWEEN", "Output", grids_days_between);
	tmp_cfg.getValue("TS_WRITE", "Output", ts_write);
	tmp_cfg.getValue("TS_START", "Output", ts_start);
	tmp_cfg.getValue("TS_DAYS_BETWEEN", "Output", ts_days_between);
	tmp_cfg.getValue("PROF_WRITE", "Output", prof_write);
	tmp_cfg.getValue("PROF_START", "Output", prof_start);
	tmp_cfg.getValue("PROF_DAYS_BETWEEN", "Output", prof_days_between);

	tmp_cfg.getValue("METEOPATH", "Output", meteo_outpath);
	tmp_cfg.getValue("TIME_ZONE", "Output", tz_out, IOUtils::nothrow);
	tmp_cfg.getValue("EXPERIMENT", "Output", station_name, IOUtils::dothrow);

	tmp_cfg.getValue("SNOW_WRITE", "Output", snow_write);
	tmp_cfg.getValue("CANOPY", "Snowpack", useCanopy);

	return tmp_cfg;
}

/**
 * @brief Destructor of SnowpackInterface Master. Handels special cases with POP-C++ and
 * also free correctly runoff and workers.
 */
SnowpackInterface::~SnowpackInterface()
{
	if (glacier_katabatic_flow) delete glaciers;
	//if (runoff) delete runoff;
	while (!workers.empty()) delete workers.back(), workers.pop_back();
}


/**
 * @brief get time who was used to exchange Data with Workers and run on each Pixel
 * the Snowpack Model throught workers.
 */
double SnowpackInterface::getTiming() const
{
	return timer.getElapsed();
}


/**
 * @brief Internal in Snowpack Interface Master used method to write standard
 * results in output files.
 * Attantion: to have old format files output, set in ini file following key:
 * **A3D_VIEW	= true**
 *
 * @param date is the date for which the output is done
 */
void SnowpackInterface::writeOutput(const mio::Date& date)
{
	MPIControl& mpicontrol = MPIControl::instance();
	const bool isMaster = mpicontrol.master();

	if (do_grid_output(date)) {
		//no OpenMP pragma here, otherwise multiple threads might call an MPI allreduce_sum()
		for (size_t ii=0; ii<output_grids.size(); ii++) {
			const size_t SnGrids_idx = SnGrids::getParameterIndex( output_grids[ii] );
			mio::Grid2DObject grid( getGrid( static_cast<SnGrids::Parameters>(SnGrids_idx)) );

			if (isMaster) {
				if (mask_glaciers) grid *= maskGlacier;
				const size_t meteoGrids_idx = MeteoGrids::getParameterIndex( output_grids[ii] );
				if (meteoGrids_idx!=IOUtils::npos) { //for this, the grid plugins must be thread-safe!
					io.write2DGrid(grid, static_cast<MeteoGrids::Parameters>(meteoGrids_idx), date);
				} else {
					std::string grid_type;
					sn_cfg.getValue("GRID2D", "output",grid_type);
					if (grid_type == "ARC") {
						std::string file_name;
						if (a3d_view) {
							std::string dateStr( date.toString(Date::NUM) );
							dateStr.erase( dateStr.size()-2, string::npos); //remove the seconds
							file_name =  dateStr + "_" + output_grids[ii] + ".asc" ;
						} else {
							std::string date_str(date.toString(mio::Date::ISO));
							std::replace( date_str.begin(), date_str.end(), ':', '.');
							file_name =  date_str + "_" + output_grids[ii] + ".asc" ;
						}
						io.write2DGrid(grid, file_name);
					} else if (grid_type=="NETCDF") {
						std::string file;
						sn_cfg.getValue("GRID2DFILE", "output", file);
						io.write2DGrid(grid, output_grids[ii]+"@"+date.toString(mio::Date::ISO));
					} else {
						throw InvalidFormatException("[E] Only ARC and NetCDF allow writing out non-standard grids such as "+output_grids[ii], AT);
					}
				}
			}
		}
		// Output Runoff
		if (runoff) runoff->output(date, psum, ta, io);
	}


}

/**
 * @brief Method tells if on given date, gridded output should be done (read this out of snowpack ini)
 * @param date is the date object which is controlled, if output needs to be done
 */
bool SnowpackInterface::do_grid_output(const mio::Date &date) const
{
	return (grids_write && booleanTime(date.getJulian(), grids_days_between, grids_start, dt_main/60.));
}

/**
 * @brief commands worker to write .sno files. Is triggered by Alpine Control
 *
 * Hack --> Find better software architecture to do this then SnowpackInterface also
 * does output for other modules of A3D here..
 * @param date is the date witch the output is done
 */
void SnowpackInterface::writeOutputSNO(const mio::Date& date)
{
	MPIControl& mpicontrol = MPIControl::instance();

	vector<SnowStation*> snow_station;

	for (size_t ii=0; ii<workers.size(); ii++)
		workers[ii]->getOutputSNO(snow_station);

	if (mpicontrol.master()) {
		std::cout << "[i] Writing SNO output for process " << mpicontrol.master_rank() << "\n";
		writeSnowCover(date, snow_station); //local data

		//Now gather all elements on the master node
		for (size_t ii=0; ii<mpicontrol.size(); ii++) {
			if (ii == mpicontrol.master_rank() || do_io_locally) continue;
			std::cout << "[i] Writing SNO output for process " << ii << "\n";
			vector<SnowStation*> snow_station_tmp;

			mpicontrol.receive(snow_station_tmp, ii);
			writeSnowCover(date, snow_station_tmp);
			for (size_t jj=0; jj<snow_station_tmp.size(); jj++) delete snow_station_tmp[jj];
		}
	} else {
		if (do_io_locally) {
			std::cout << "[i] Writing SNO output for process " << mpicontrol.rank() << "\n";
			writeSnowCover(date, snow_station); //local data
		} else {
			mpicontrol.send(snow_station, mpicontrol.master_rank());
		}
	}
}

void SnowpackInterface::writeSnowCover(const mio::Date& date, const std::vector<SnowStation*>& snow_station)
{
	for (size_t jj=0; jj<snow_station.size(); jj++)
		snowpackIO.writeSnowCover(date, *(snow_station[jj]), ZwischenData());
}

/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   Methods to set references to other methodes
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
/**
 * @brief Set reference to SnowDrift module, to comunicate with it.
 * @param mydrift is the reference to the SnowDrift module
 */
void SnowpackInterface::setSnowDrift(SnowDriftA3D& mydrift)
{
	drift = &mydrift;

	if (drift) {
		for (size_t i = 0; i < workers.size(); i++) workers[i]->setUseDrift(true);

		// Provide initial snow parameters to SnowDrift
		const Grid2DObject cH( getGrid(SnGrids::HS) );
		const Grid2DObject sp( getGrid(SnGrids::SP) );
		const Grid2DObject rg( getGrid(SnGrids::RG) );
		const Grid2DObject N3( getGrid(SnGrids::N3) );
		const Grid2DObject rb( getGrid(SnGrids::RB) );
		drift->setSnowSurfaceData(cH, sp, rg, N3, rb);
	}
}

/**
 * @brief Set reference to EnergyBalance module, to comunicate with it.
 * @param myeb is the reference to the EnergyBalance module
 */
void SnowpackInterface::setEnergyBalance(EnergyBalance& myeb)
{

	eb = &myeb;
	if (eb) {
		for (size_t i = 0; i < workers.size(); i++){
			workers[i]->setUseEBalance(true);
		}
		// Provide initial albedo to EnergyBalance
		const Grid2DObject alb( getGrid(SnGrids::TOP_ALB) );
		eb->setAlbedo(alb);
	}
}

/**
 * @brief Set reference to DataAssimilation module, to comunicate with it.
 * @param init_da is the reference to the DataAssimilation module
 */
void SnowpackInterface::setDataAssimilation(DataAssimilation& init_da)
{
	da = &init_da;
}

void SnowpackInterface::setRunoff(Runoff& init_runoff)
{
	runoff = &init_runoff;
}

/**
 * @brief Interface that DataAssimilation can push the data to the SnowpackInterface
 * This is currently never used...
 * @param daData are the data from the DataAssimilation module
 * @param timestamp for controlle if data from DataAssimilation are form the correct simulation step
 */
void SnowpackInterface::assimilate(const Grid2DObject& /*daData*/, const mio::Date& timestamp)
{

	if (nextStepTimestamp != timestamp) {
		throw InvalidArgumentException("Assimilation and snowpack time steps don't match", AT);
	}

	cout << "Updating state variables...\n";
	/*for (size_t iy = 0; iy < dimy; iy++) {
		for (size_t ix = 0; ix < dimx; ix++) {
			const size_t i = dimy*iy + ix;
			if ( daData.grid2D(ix,iy) == 1.0 ) {
				//if DA-data DOES NOT have snow
				if (sn_Xdata[i].cH-sn_Xdata[i].Ground > 0.) {
					//and snowpack DOES have snow
					//clear the pixel
					store(ix,iy) = 0.;
					sn_Xdata[i].cH = sn_Xdata[i].Ground;
					sn_Xdata[i].mH = sn_Xdata[i].Ground;
					sn_Xdata[i].nElems = sn_Xdata[i].SoilNode;
					sn_Xdata[i].nNodes = sn_Xdata[i].nElems + 1;
				}
			} else {
				if ( daData.grid2D(ix,iy) == 4 ) {
					//if DA-data DOES have snow
					if (sn_Xdata[i].cH-sn_Xdata[i].Ground < 1e-15) {
						//if snowpack DOES NOT have snow -> add some snow
						store(ix,iy) += 40*M_TO_H(calculation_step_length);
					}
				}
			}
		}
	}*/

	dataDa = true;
	calcNextStep();
}

/**
 * @brief Interface that SnowDrift can push the data to the SnowpackInterface
 * @param new_mns are the data about the new Snow masses from the DataAssimilation module
 * @param timestamp for controlle if data from DataAssimilation are form the correct simulation step
 */
void SnowpackInterface::setSnowMassChange(const mio::Grid2DObject& new_mns, const mio::Date& timestamp)
{
	if (nextStepTimestamp != timestamp) {
		if (MPIControl::instance().master()) {
			std::cerr << "Providing drift snow mass at " << timestamp.toString(Date::ISO);
			std::cerr << " for Snowpack timestamp " << nextStepTimestamp.toString(Date::ISO) << "\n";
		}
		throw InvalidArgumentException("Snowdrift and snowpack steps don't match", AT);
	}

	if (!new_mns.isSameGeolocalization(dem)) {
		std::ostringstream ss;
		ss << "Trying to set snow mass changes from a (" << new_mns.getNx() << "," << new_mns.getNy() << ") grid ";
		ss << "when the dem is (" << dem.getNx() << "," << dem.getNy() << ")";
		throw IndexOutOfBoundsException(ss.str(), AT);
	}

	mns = new_mns;
	dataSnowDrift = true;
	calcNextStep();
}

/**
 * @brief get Meteo changes from AlpineControl or SnowDrift module
 * @param new_psum gives the new values for new Water High
 * @param new_psum_ph gives the new values for the precipitation phase
 * @param new_vw gives the new values for the wind speed
 * @param new_dw gives the new values for the wind direction
 * @param new_rh gives the new values for the realtiv Humidity
 * @param new_ta gives the new values for the Aire temperature
 * @param timestamp is the time of the calculation step from which this new values are comming
 */
void SnowpackInterface::setMeteo(const Grid2DObject& new_psum, const Grid2DObject& new_psum_ph, const Grid2DObject& new_vw, const Grid2DObject& new_dw, const Grid2DObject& new_rh, const Grid2DObject& new_ta, const mio::Date& timestamp)
{
	if (nextStepTimestamp != timestamp) {
		if (MPIControl::instance().master()) {
			std::cerr << "Providing meteo fields at " << timestamp.toString(Date::ISO);
			std::cerr << " for Snowpack timestamp " << nextStepTimestamp.toString(Date::ISO) << "\n";
		}
		throw InvalidArgumentException("Meteo and snowpack time steps don't match", AT);
	}

	psum = new_psum;
	psum_ph = new_psum_ph;
	vw = new_vw;
	dw = new_dw;
	rh = new_rh;
	if (mask_dynamic) maskGlacier = getGrid(SnGrids::GLACIER); //so the updated glacier map is available for all

	if (!glacier_katabatic_flow) {
		ta = new_ta;
	} else {
		if (mask_dynamic) glaciers->setGlacierMap(maskGlacier);
		const Grid2DObject TSS( getGrid(SnGrids::TSS) );
		const Grid2DObject cH( getGrid(SnGrids::HS) );
		ta = glaciers->correctTemperatures(cH, TSS, new_ta);
	}

	if (snow_production || snow_grooming) {
		const Grid2DObject cH( getGrid(SnGrids::HS) );
		techSnow->setMeteo(new_ta, new_rh, cH, timestamp);
		psum_tech = techSnow->getGrid(SnGrids::PSUM_TECH);
		grooming = techSnow->getGrid(SnGrids::GROOMING);
	}

	dataMeteo2D = true;
	calcNextStep();
}

/**
 * @brief get values from Energy Balance
 * @param shortwave_in is the 2D double Array map of ISWR [W m-2]
 * @param longwave_in is the 2D double Array map of ILWR [W m-2]
 * @param diff_in is the 2D double Array map of Diffuse radiation from the sky [W m-2]
 * @param solarElevation_in double of Solar elevation to be used for Canopy (in dec)
 * @param timestamp is the time of the calculation step from which this new values are comming
 */
708
709
void SnowpackInterface::setRadiationComponents(const mio::Array2D<double>& shortwave_in,
     const mio::Array2D<double>& longwave_in, const mio::Array2D<double>& diff_in,
710
     const mio::Array2D<double>& terrain_shortwave_in,
711
     const mio::Array2D<double>& terrain_longwave_in,
712
     const double& solarElevation_in, const mio::Date& timestamp)
Julien Esseiva's avatar
Julien Esseiva committed
713
714
715
716
717
718
719
720
721
722
723
724
{
	if (nextStepTimestamp != timestamp) {
		if (MPIControl::instance().master()) {
			std::cerr << "Providing radiation fields at " << timestamp.toString(Date::ISO);
			std::cerr << " for Snowpack timestamp " << nextStepTimestamp.toString(Date::ISO) << "\n";
		}
		throw InvalidArgumentException("Radiation and snowpack time steps don't match", AT);
	}

	shortwave.grid2D = shortwave_in;
	longwave.grid2D = longwave_in;
	diffuse.grid2D = diff_in;
725
726
	terrain_shortwave.grid2D = terrain_shortwave_in;
	terrain_longwave.grid2D = terrain_longwave_in;
727

Julien Esseiva's avatar
Julien Esseiva committed
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
	solarElevation = solarElevation_in;

	dataRadiation = true;
	calcNextStep();
}

/**
 * @brief Request specific grid by parameter type
 * @param param parameter
 * @return 2D output grid (empty if the requested parameter was not available)
 */
mio::Grid2DObject SnowpackInterface::getGrid(const SnGrids::Parameters& param) const
{
	//special case for the meteo forcing grids
	switch (param) {
		case SnGrids::TA:
			return ta;
		case SnGrids::RH:
			return rh;
		case SnGrids::VW:
			return vw;
		case SnGrids::DW:
			return dw;
		case SnGrids::PSUM:
			return psum;
		case SnGrids::PSUM_PH:
			return psum_ph;
		case SnGrids::PSUM_TECH:
			return psum_tech;
		case SnGrids::MNS:
			return mns;
		case SnGrids::ISWR:
			return shortwave;
		case SnGrids::ILWR:
			return longwave;
763
764
765
766
    case SnGrids::ISWR_TERRAIN:
      return terrain_shortwave;
    case SnGrids::ILWR_TERRAIN:
      return terrain_longwave;
767
768
769
770
    case SnGrids::ISWR_DIFF:
		  return diffuse;
		case SnGrids::ISWR_DIR:
			return shortwave-diffuse-terrain_shortwave;
Julien Esseiva's avatar
Julien Esseiva committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
		default: ; //so compilers do not complain about missing conditions
	}

	mio::Grid2DObject o_grid2D(dem, 0.); //so the allreduce_sum works
	size_t errCount = 0;
	mio::Grid2DObject tmp_grid2D_(dem,mpi_offset, 0, mpi_nx, dimy);
	mio::Grid2DObject tmp_grid2D(tmp_grid2D_,mio::IOUtils::nodata);
	#pragma omp parallel for schedule(dynamic) reduction(+: errCount)
	for (size_t ii = 0; ii < workers.size(); ii++) {
		const mio::Grid2DObject tmp( workers[ii]->getGrid(param) );
		if (!tmp.empty()) {
			for (size_t i=0; i<tmp_grid2D.getNx(); ++i){
				for (size_t j=0; j<tmp_grid2D.getNy(); ++j){
					if (tmp(i,j)!=mio::IOUtils::nodata)
					{
							tmp_grid2D(i,j)=tmp(i,j);
					}
				}
			}
		} else {
			errCount++;
		}
	}
	o_grid2D.grid2D.fill(tmp_grid2D.grid2D, mpi_offset, 0, mpi_nx, dimy);

	MPIControl::instance().allreduce_sum(o_grid2D);
	//with some MPI implementations, when transfering large amounts of data, the buffers might get full and lead to a crash

	if (errCount>0) {
		std::cerr << "[W] Requested " << SnGrids::getParameterName( param ) << " but this was not available in the workers\n";
		o_grid2D.clear(); //the requested parameter was not available
	}
	return o_grid2D;
}

/**
 * @brief Get data from other modules and run one simulation step.
 * Once the simulation step has been performed, the data are pushed to ther other modules.
 */
void SnowpackInterface::calcNextStep()
{
	//Control if all data are present
	if (!dataMeteo2D) {
		return;
	} else {
		if (drift != NULL && !dataSnowDrift) return;
		if (da != NULL && !dataDa) return;
		if (eb != NULL && !dataRadiation) return;
	}
	// control if the necessary data are available
	if (!dataRadiation) {
		throw NoDataException("Radiation data not available", AT);
	}

	dataDa = dataMeteo2D = dataSnowDrift = dataRadiation = false; //the external modules will turn them back to true when pushing their data

	// timing
	timer.restart();

	size_t errCount = 0;
	const mio::Grid2DObject tmp_psum(psum, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_psum_ph(psum_ph,  mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_psum_tech(psum_tech,  mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_rh(rh, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_ta(ta, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_vw(vw, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_dw(dw, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_mns(mns, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_shortwave(shortwave, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_diffuse(diffuse, mpi_offset, 0, mpi_nx, dimy);
	const mio::Grid2DObject tmp_longwave(longwave, mpi_offset, 0, mpi_nx, dimy);
	#pragma omp parallel for schedule(dynamic, 1) reduction(+: errCount)
	for (size_t ii = 0; ii < workers.size(); ii++) { // make slices
		// run model, process exceptions in a way that is compatible with openmp
		try {
			workers[ii]->runModel(nextStepTimestamp, tmp_psum, tmp_psum_ph, tmp_psum_tech, tmp_rh, tmp_ta, tmp_vw, tmp_dw, tmp_mns, tmp_shortwave, tmp_diffuse, tmp_longwave, solarElevation);
			if (snow_grooming) {
				const mio::Grid2DObject tmp_grooming(grooming, mpi_offset, 0, mpi_nx, dimy);
				workers[ii]->grooming( nextStepTimestamp, tmp_grooming );
			}
		} catch(const std::exception& e) {
			++errCount;
			cout << e.what() << std::endl;
		}
	}

	//Lateral flow
	if (enable_lateral_flow) {
		calcLateralFlow();
	}

	//Retrieve special points data and write files
	if (!pts.empty()) write_special_points();

	if (errCount>0) {
		//something wrong took place, quitting. At least we tried writing the special points out
		std::abort(); //force core dump
	}

	// Gather data if needed and make exchange for SnowDrift
	if (drift) {
		const Grid2DObject cH( getGrid(SnGrids::HS) );
		const Grid2DObject sp( getGrid(SnGrids::SP) );
		const Grid2DObject rg( getGrid(SnGrids::RG) );
		const Grid2DObject N3( getGrid(SnGrids::N3) );
		const Grid2DObject rb( getGrid(SnGrids::RB) );
		drift->setSnowSurfaceData(cH, sp, rg, N3, rb);
	}

	// Gather data if needed and make exchange for EnergyBalance
	if (eb) {
		const Grid2DObject alb( getGrid(SnGrids::TOP_ALB) );
		eb->setAlbedo(alb);
	}

	//make output
	writeOutput(nextStepTimestamp);

	timer.stop();
	if (MPIControl::instance().master())
		cout << "[i] Snowpack simulations done for " << nextStepTimestamp.toString(Date::ISO) << "\n";
	nextStepTimestamp = nextStepTimestamp + timeStep;
	MPIControl::instance().barrier();

}

void SnowpackInterface::write_special_points()
{
	MPIControl& mpicontrol = MPIControl::instance();

	std::vector<SnowStation*> snow_pixel;
	std::vector<CurrentMeteo*> meteo_pixel;
	std::vector<SurfaceFluxes*> surface_flux;

	// note: do not parallelize this with OpenMP
	for (size_t ii=0; ii<workers.size(); ii++)
		workers[ii]->getOutputSpecialPoints(snow_pixel, meteo_pixel, surface_flux);

	if (do_io_locally) {
		writeOutputSpecialPoints(nextStepTimestamp, snow_pixel, meteo_pixel, surface_flux);
		if (!snow_write && !snow_poi_written) {
			writeSnowCover(nextStepTimestamp, snow_pixel); //also write the .sno of the special points
			snow_poi_written = true;
		}
	} else { // data has to be sent to the master process
		if (mpicontrol.master()) {
			// Write out local data first and then gather data from all processes
			writeOutputSpecialPoints(nextStepTimestamp, snow_pixel, meteo_pixel, surface_flux);
			if (!snow_write && !snow_poi_written) {
				writeSnowCover(nextStepTimestamp, snow_pixel); //also write the .sno of the special points
			}

			for (size_t ii=0; ii<mpicontrol.size(); ii++) {
				if (ii == mpicontrol.master_rank()) continue;
				snow_pixel.clear(); meteo_pixel.clear(); surface_flux.clear();

				mpicontrol.receive(snow_pixel, ii);
				mpicontrol.receive(meteo_pixel, ii);
				mpicontrol.receive(surface_flux, ii);

				writeOutputSpecialPoints(nextStepTimestamp, snow_pixel, meteo_pixel, surface_flux);
				if (!snow_write && !snow_poi_written) {
					writeSnowCover(nextStepTimestamp, snow_pixel); //also write the .sno of the special points
				}
			}
			snow_poi_written = true;
		} else {
			mpicontrol.send(snow_pixel, mpicontrol.master_rank());
			mpicontrol.send(meteo_pixel, mpicontrol.master_rank());
			mpicontrol.send(surface_flux, mpicontrol.master_rank());
		}
	}

	#pragma omp parallel for schedule(static)
	for (size_t ii=0; ii<workers.size(); ii++) workers[ii]->clearSpecialPointsData();
}

/**
 * @brief Write the output which is asked to have more for the special points
 * @param date Output date
 * @param snow_pixel The SnowStation data for all the special points
 * @param meteoPixel The CurrentMeteo data for all the special points
 * @param surface_flux The SurfaceFlux data for all the special points
 */
void SnowpackInterface::writeOutputSpecialPoints(const mio::Date& date, const std::vector<SnowStation*>& snow_pixel, const std::vector<CurrentMeteo*>& meteo_pixel,
                                                 const std::vector<SurfaceFluxes*>& surface_flux)
{
	const bool TS = (ts_write && booleanTime(date.getJulian(), ts_days_between, ts_start, dt_main/60.));
	const bool PR = (prof_write && booleanTime(date.getJulian(), prof_days_between, prof_days_between, dt_main/60));

	const ProcessDat Hdata; // empty ProcessDat, get it from where ??
	for (size_t ii=0; ii<snow_pixel.size(); ii++) {
		write_SMET(*meteo_pixel[ii], snow_pixel[ii]->meta, *surface_flux[ii]);
		if (TS) snowpackIO.writeTimeSeries(*snow_pixel[ii], *surface_flux[ii], *meteo_pixel[ii], Hdata, 0.);
		if (PR) snowpackIO.writeProfile(date, *snow_pixel[ii]);
	}
}

/**
 * @brief Write header of SMET file for specific point
 * @param meta StationData for the SMET header initialization
 */
void SnowpackInterface::write_SMET_header(const mio::StationData& meta, const double& landuse_code) const
{
	const std::string filename( meteo_outpath + "/" + meta.stationName + "_meteo.smet" );
	if (!FileUtils::validFileAndPath(filename)) throw InvalidNameException(filename,AT);
	errno = 0;

	std::ofstream smet_out; //Output file streams
	smet_out.open(filename.c_str());
	if (smet_out.fail()) throw AccessException(filename.c_str(), AT);

	smet_out << "SMET 1.1 ASCII\n";
	smet_out << "[HEADER]\n";
	smet_out << "station_name = " << meta.stationName << "\n";
	smet_out << "station_id   = " << meta.stationID << "\n";
	smet_out << std::right;
	smet_out << std::fixed;

	smet_out << "altitude     = " << std::setw(11)  << std::setprecision(1) << meta.position.getAltitude() << "\n";
	smet_out << "latitude     = " << std::setw(11) << std::setprecision(8) << meta.position.getLat() << "\n";
	smet_out << "longitude    = " << std::setw(11) << std::setprecision(8) << meta.position.getLon() << "\n";
	smet_out << "easting      = " << std::setw(11) << std::setprecision(1) << meta.position.getEasting() << "\n";
	smet_out << "northing     = " << std::setw(11) << std::setprecision(1) << meta.position.getNorthing() << "\n";
	smet_out << "epsg         = " << std::setw(11) << std::setprecision(0) << meta.position.getEPSG() << "\n";
	smet_out << "slope        = " << std::setw(11)  << std::setprecision(1) << meta.getSlopeAngle() << "\n";
	smet_out << "azimuth      = " << std::setw(11)  << std::setprecision(1) << meta.getAzimuth() << "\n";
	smet_out << "landuse      = " << std::setw(11)  << std::setprecision(0) << SnowpackInterfaceWorker::round_landuse( landuse_code ) << "\n";
	smet_out << "nodata       = " << std::setw(11)  << std::setprecision(0) << mio::IOUtils::nodata << "\n";
	smet_out << "tz           = " << std::setw(11)  << std::setprecision(0) << tz_out << "\n";
For faster browsing, not all history is shown. View entire blame