forked from ClimateGlobalChange/tempestremap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateTestData.cpp
656 lines (519 loc) · 15.1 KB
/
GenerateTestData.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
107
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
136
137
138
139
140
141
142
143
144
145
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
228
229
230
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
277
278
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
///////////////////////////////////////////////////////////////////////////////
///
/// \file GenerateTestData.cpp
/// \author Paul Ullrich
/// \version August 31st, 2014
///
/// <remarks>
/// Copyright 2000-2014 Paul Ullrich
///
/// This file is distributed as part of the Tempest source code package.
/// Permission is granted to use, copy, modify and distribute this
/// source code and its documentation under the terms of the GNU General
/// Public License. This software is provided "as is" without express
/// or implied warranty.
/// </remarks>
#include "CommandLine.h"
#include "GridElements.h"
#include "FiniteElementTools.h"
#include "TriangularQuadrature.h"
#include "GaussQuadrature.h"
#include "GaussLobattoQuadrature.h"
#include "Exception.h"
#include "Announce.h"
#include "DataMatrix3D.h"
#include "netcdfcpp.h"
#include <cmath>
#include <iostream>
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// A class wrapper for a test function.
/// </summary>
class TestFunction {
public:
/// <summary>
/// Virtual destructor.
/// </summary>
virtual ~TestFunction()
{ }
/// <summary>
/// Evaluate the test function.
/// </summary>
virtual double operator()(
double dLon,
double dLat
) = 0;
};
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// A relatively smooth low-order harmonic.
/// </summary>
class TestFunctionY2b2 : public TestFunction {
public:
/// <summary>
/// Evaluate the test function.
/// <summary>
virtual double operator()(
double dLon,
double dLat
) {
return (2.0 + cos(dLat) * cos(dLat) * cos(2.0 * dLon));
}
};
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// A high frequency spherical harmonic.
/// </summary>
class TestFunctionY16b32 : public TestFunction {
public:
/// <summary>
/// Evaluate the test function.
/// </summary>
virtual double operator()(
double dLon,
double dLat
) {
return (2.0 + pow(sin(2.0 * dLat), 16.0) * cos(16.0 * dLon));
//return (2.0 + pow(cos(2.0 * dLat), 16.0) * cos(16.0 * dLon));
}
};
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Stationary vortex fields.
/// </summary>
class TestFunctionVortex : public TestFunction {
public:
/// <summary>
/// Find the rotated longitude and latitude of a point on a sphere
/// with pole at (dLonC, dLatC).
/// </summary>
void RotatedSphereCoord(
double dLonC,
double dLatC,
double & dLonT,
double & dLatT
) {
double dSinC = sin(dLatC);
double dCosC = cos(dLatC);
double dCosT = cos(dLatT);
double dSinT = sin(dLatT);
double dTrm = dCosT * cos(dLonT - dLonC);
double dX = dSinC * dTrm - dCosC * dSinT;
double dY = dCosT * sin(dLonT - dLonC);
double dZ = dSinC * dSinT + dCosC * dTrm;
dLonT = atan2(dY, dX);
if (dLonT < 0.0) {
dLonT += 2.0 * M_PI;
}
dLatT = asin(dZ);
}
/// <summary>
/// Evaluate the test function.
/// </summary>
virtual double operator()(
double dLon,
double dLat
) {
const double dLon0 = 0.0;
const double dLat0 = 0.6;
const double dR0 = 3.0;
const double dD = 5.0;
const double dT = 6.0;
RotatedSphereCoord(dLon0, dLat0, dLon, dLat);
double dRho = dR0 * cos(dLat);
double dVt = 3.0 * sqrt(3.0) / 2.0
/ cosh(dRho) / cosh(dRho) * tanh(dRho);
double dOmega;
if (dRho == 0.0) {
dOmega = 0.0;
} else {
dOmega = dVt / dRho;
}
return (1.0 - tanh(dRho / dD * sin(dLon - dOmega * dT)));
}
};
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
NcError error(NcError::silent_nonfatal);
try {
// Mesh file to use
std::string strMeshFile;
// Test data to use
int iTestData;
// Output on GLL grid
bool fGLL;
// Output on an integrated GLL grid
bool fGLLIntegrate;
// Degree of polynomial
int nP;
// Include a level dimension in output
bool fHOMMEFormat;
// Output variable name
std::string strVariableName;
// Output filename
std::string strTestData;
// Flip rectilinear ordering
bool fFlipRectilinear;
// Parse the command line
BeginCommandLine()
CommandLineString(strMeshFile, "mesh", "");
CommandLineInt(iTestData, "test", 1);
CommandLineBool(fGLL, "gll");
CommandLineBool(fGLLIntegrate, "gllint");
CommandLineInt(nP, "np", 4);
CommandLineBool(fHOMMEFormat, "homme");
CommandLineString(strVariableName, "var", "Psi");
CommandLineString(strTestData, "out", "testdata.nc");
CommandLineBool(fFlipRectilinear, "fliprectilinear");
ParseCommandLine(argc, argv);
EndCommandLine(argv)
// Check arguments
if (fGLLIntegrate && fGLL) {
_EXCEPTIONT("--gll and --gllint are exclusive arguments");
}
// Announce
Announce("=========================================================");
// Triangular quadrature rule
const int TriQuadratureOrder = 8;
Announce("Using triangular quadrature of order %i", TriQuadratureOrder);
TriangularQuadratureRule triquadrule(TriQuadratureOrder);
const int TriQuadraturePoints = triquadrule.GetPoints();
const DataMatrix<double> & TriQuadratureG = triquadrule.GetG();
const DataVector<double> & TriQuadratureW = triquadrule.GetW();
// Test data
TestFunction * pTest;
if (iTestData == 1) {
pTest = new TestFunctionY2b2;
} else if (iTestData == 2) {
pTest = new TestFunctionY16b32;
} else if (iTestData == 3) {
pTest = new TestFunctionVortex;
} else {
_EXCEPTIONT("Test index out of range; expected [1,2,3]");
}
// Input mesh
AnnounceStartBlock("Loading Mesh");
Mesh mesh(strMeshFile);
// Check for rectilinear Mesh
NcFile ncMesh(strMeshFile.c_str(), NcFile::ReadOnly);
// Rectilinear grid
bool fRectilinear = false;
// Check for grid dimensions (SCRIP format grid)
std::vector<long> vecOutputDimSizes;
std::vector<std::string> vecOutputDimNames;
NcVar * varGridDims = ncMesh.get_var("grid_dims");
if (varGridDims != NULL) {
NcDim * dimGridRank = varGridDims->get_dim(0);
vecOutputDimSizes.resize(dimGridRank->size());
varGridDims->get(&(vecOutputDimSizes[0]), dimGridRank->size());
if (dimGridRank->size() == 1) {
vecOutputDimNames.push_back("num_elem");
} else if (dimGridRank->size() == 2) {
fRectilinear = true;
vecOutputDimNames.push_back("lon");
vecOutputDimNames.push_back("lat");
} else {
_EXCEPTIONT("Source grid grid_rank must be < 3");
}
}
// Check for rectilinear attribute (Exodus format grid)
NcAtt * attRectilinear = ncMesh.get_att("rectilinear");
if (attRectilinear != NULL) {
fRectilinear = true;
int nDim0Size = ncMesh.get_att("rectilinear_dim0_size")->as_int(0);
int nDim1Size = ncMesh.get_att("rectilinear_dim1_size")->as_int(0);
std::string strDim0Name =
ncMesh.get_att("rectilinear_dim0_name")->as_string(0);
std::string strDim1Name =
ncMesh.get_att("rectilinear_dim1_name")->as_string(0);
vecOutputDimSizes.push_back(nDim0Size);
vecOutputDimSizes.push_back(nDim1Size);
vecOutputDimNames.push_back(strDim0Name);
vecOutputDimNames.push_back(strDim1Name);
}
// Default case
if (vecOutputDimSizes.size() == 0) {
vecOutputDimSizes.push_back(mesh.faces.size());
vecOutputDimNames.push_back("ncol");
}
if (fRectilinear) {
Announce("Rectilinear grid detected");
} else {
Announce("Non-rectilinear grid detected");
}
if (fFlipRectilinear && !fRectilinear) {
_EXCEPTIONT("--fliprectlinear cannot be used with non-rectilinear grids");
}
if (fGLL && fRectilinear) {
_EXCEPTIONT("--gll cannot be used with rectilinear grids");
}
// Output level dimension
if (fHOMMEFormat) {
vecOutputDimSizes.push_back(1);
vecOutputDimNames.push_back("lev");
}
AnnounceEndBlock("Done");
// Generate test data
AnnounceStartBlock("Generating test data");
// Latitude and Longitude arrays (used for HOMME format output)
DataVector<double> dLat;
DataVector<double> dLon;
DataVector<double> dArea;
// Output data
DataVector<double> dVar;
// Nodal geometric area
DataVector<double> dNodeArea;
// Calculate element areas
mesh.CalculateFaceAreas();
// Sample as element averages
if ((!fGLLIntegrate) && (!fGLL)) {
// Resize the array
dVar.Initialize(mesh.faces.size());
// Loop through all Faces
for (int i = 0; i < mesh.faces.size(); i++) {
const Face & face = mesh.faces[i];
// Loop through all sub-triangles
for (int j = 0; j < face.edges.size()-2; j++) {
const Node & node0 = mesh.nodes[face[0]];
const Node & node1 = mesh.nodes[face[j+1]];
const Node & node2 = mesh.nodes[face[j+2]];
// Triangle area
Face faceTri(3);
faceTri.SetNode(0, face[0]);
faceTri.SetNode(1, face[j+1]);
faceTri.SetNode(2, face[j+2]);
double dTriangleArea = CalculateFaceArea(faceTri, mesh.nodes);
// Calculate the element average
double dTotalSample = 0.0;
// Loop through all quadrature points
for (int k = 0; k < TriQuadraturePoints; k++) {
Node node(
TriQuadratureG[k][0] * node0.x
+ TriQuadratureG[k][1] * node1.x
+ TriQuadratureG[k][2] * node2.x,
TriQuadratureG[k][0] * node0.y
+ TriQuadratureG[k][1] * node1.y
+ TriQuadratureG[k][2] * node2.y,
TriQuadratureG[k][0] * node0.z
+ TriQuadratureG[k][1] * node1.z
+ TriQuadratureG[k][2] * node2.z);
double dMagnitude = node.Magnitude();
node.x /= dMagnitude;
node.y /= dMagnitude;
node.z /= dMagnitude;
double dLon = atan2(node.y, node.x);
if (dLon < 0.0) {
dLon += 2.0 * M_PI;
}
double dLat = asin(node.z);
double dSample = (*pTest)(dLon, dLat);
dTotalSample += dSample * TriQuadratureW[k] * dTriangleArea;
}
// Flip the rectilinear coordinate
int iv = i;
if (fFlipRectilinear) {
int i0 = i % vecOutputDimSizes[0];
int i1 = i / vecOutputDimSizes[0];
iv = i0 * vecOutputDimSizes[1] + i1;
}
dVar[iv] += dTotalSample / mesh.vecFaceArea[i];
//dVar[i] += dTotalSample / mesh.vecFaceArea[i];
}
}
// Finite element data
} else {
// Generate grid metadata
DataMatrix3D<int> dataGLLNodes;
DataMatrix3D<double> dataGLLJacobian;
GenerateMetaData(mesh, nP, false, dataGLLNodes, dataGLLJacobian);
// Number of elements
int nElements = mesh.faces.size();
// Verify all elements are quadrilaterals
for (int k = 0; k < nElements; k++) {
const Face & face = mesh.faces[k];
if (face.edges.size() != 4) {
_EXCEPTIONT("Non-quadrilateral face detected; "
"incompatible with --gll");
}
}
// Number of unique nodes
int iMaxNode = 0;
for (int i = 0; i < nP; i++) {
for (int j = 0; j < nP; j++) {
for (int k = 0; k < nElements; k++) {
if (dataGLLNodes[i][j][k] > iMaxNode) {
iMaxNode = dataGLLNodes[i][j][k];
}
}
}
}
// Resize output array
if (fHOMMEFormat) {
vecOutputDimSizes[1] = iMaxNode;
dLat.Initialize(iMaxNode);
dLon.Initialize(iMaxNode);
dArea.Initialize(iMaxNode);
} else {
vecOutputDimSizes[0] = iMaxNode;
}
// Get Gauss-Lobatto quadrature nodes
DataVector<double> dG;
DataVector<double> dW;
GaussLobattoQuadrature::GetPoints(nP, 0.0, 1.0, dG, dW);
// Get Gauss quadrature nodes
const int nGaussP = 8;
DataVector<double> dGaussG;
DataVector<double> dGaussW;
GaussQuadrature::GetPoints(nGaussP, 0.0, 1.0, dGaussG, dGaussW);
// Allocate data
dVar.Initialize(iMaxNode);
dNodeArea.Initialize(iMaxNode);
// Sample data
for (int k = 0; k < nElements; k++) {
const Face & face = mesh.faces[k];
// Sample data at GLL nodes
if (fGLL) {
for (int i = 0; i < nP; i++) {
for (int j = 0; j < nP; j++) {
// Apply local map
Node node;
Node dDx1G;
Node dDx2G;
ApplyLocalMap(
face,
mesh.nodes,
dG[i],
dG[j],
node,
dDx1G,
dDx2G);
// Sample data at this point
double dNodeLon = atan2(node.y, node.x);
if (dNodeLon < 0.0) {
dNodeLon += 2.0 * M_PI;
}
double dNodeLat = asin(node.z);
double dSample = (*pTest)(dNodeLon, dNodeLat);
dVar[dataGLLNodes[j][i][k]-1] = dSample;
if (fHOMMEFormat) {
dLat[dataGLLNodes[j][i][k]-1] = dNodeLat * 180.0 / M_PI;
dLon[dataGLLNodes[j][i][k]-1] = dNodeLon * 180.0 / M_PI;
dArea[dataGLLNodes[j][i][k]-1] += dataGLLJacobian[j][i][k];
}
}
}
// High-order Gaussian integration over basis function
} else {
DataMatrix<double> dCoeff;
dCoeff.Initialize(nP, nP);
for (int p = 0; p < nGaussP; p++) {
for (int q = 0; q < nGaussP; q++) {
// Apply local map
Node node;
Node dDx1G;
Node dDx2G;
ApplyLocalMap(
face,
mesh.nodes,
dGaussG[p],
dGaussG[q],
node,
dDx1G,
dDx2G);
// Cross product gives local Jacobian
Node nodeCross = CrossProduct(dDx1G, dDx2G);
double dJacobian = sqrt(
nodeCross.x * nodeCross.x
+ nodeCross.y * nodeCross.y
+ nodeCross.z * nodeCross.z);
// Find components of quadrature point in basis
// of the first Face
SampleGLLFiniteElement(
false,
nP,
dGaussG[p],
dGaussG[q],
dCoeff);
// Sample data at this point
double dNodeLon = atan2(node.y, node.x);
if (dNodeLon < 0.0) {
dNodeLon += 2.0 * M_PI;
}
double dNodeLat = asin(node.z);
double dSample = (*pTest)(dNodeLon, dNodeLat);
// Integrate
for (int i = 0; i < nP; i++) {
for (int j = 0; j < nP; j++) {
dVar[dataGLLNodes[j][i][k]-1] +=
dSample
* dCoeff[j][i]
* dGaussW[p]
* dGaussW[q]
* dJacobian;
dNodeArea[dataGLLNodes[j][i][k]-1] +=
dCoeff[j][i]
* dGaussW[p]
* dGaussW[q]
* dJacobian;
}
}
}
}
}
}
// Divide by area
if (fGLLIntegrate) {
for (int i = 0; i < dVar.GetRows(); i++) {
dVar[i] /= dNodeArea[i];
}
}
}
AnnounceEndBlock("Done");
// Output file
AnnounceStartBlock("Writing results");
NcFile ncOut(strTestData.c_str(), NcFile::Replace);
// Add dimensions
std::vector<NcDim *> vecDimOut;
for (int d = 0; d < vecOutputDimSizes.size(); d++) {
vecDimOut.push_back(
ncOut.add_dim(
vecOutputDimNames[d].c_str(),
vecOutputDimSizes[d]));
}
// Add latitude and longitude variable
if (fHOMMEFormat) {
NcVar * varLat = ncOut.add_var("lat", ncDouble, vecDimOut[1]);
NcVar * varLon = ncOut.add_var("lon", ncDouble, vecDimOut[1]);
NcVar * varArea = ncOut.add_var("area", ncDouble, vecDimOut[1]);
varLat->put(&(dLat[0]), vecOutputDimSizes[1]);
varLon->put(&(dLon[0]), vecOutputDimSizes[1]);
varArea->put(&(dArea[0]), vecOutputDimSizes[1]);
}
/*
// Output data
if (fFlipRectilinear) {
NcVar * varOut =
ncOut.add_var(
strVariableName.c_str(),
ncDouble,
vecDimOut[1],
vecDimOut[0]);
varOut->put(&(dVar[0]), vecOutputDimSizes[1], vecOutputDimSizes[0]);
} else {
*/
NcVar * varOut =
ncOut.add_var(
strVariableName.c_str(),
ncDouble,
static_cast<int>(vecOutputDimSizes.size()),
(const NcDim**)&(vecDimOut[0]));
varOut->put(&(dVar[0]), &(vecOutputDimSizes[0]));
//}
AnnounceEndBlock("Done");
// Delete the test
delete pTest;
} catch(Exception & e) {
std::cout << e.ToString() << std::endl;
}
}
///////////////////////////////////////////////////////////////////////////////