gfsfile.cc 28.1 KB
Newer Older
1
2
3
#include "radixio/gfsfile.hh"

#include "radixio/eafstream.hh"
4
#include "radixbug/bug.hh"
5
#include "radixmath/util.hh"
6
7
8
9
10
11
12
13
14

namespace radix
{

float total_seconds(int year, int month, int day, int hour)
{
    // assume 1900 as start of time
    float start = 365*86400;
    // years = hours*days*years
15
    return year*365.f*86400.f
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
            +(month-1.f)*(365.f/12.f)*86400.f
            +(day-1.f)*86400.f
            +hour*3600.f
            -start;
} // total_seconds
int ord(char c) { return (unsigned char)c; }
std::vector<std::vector<float>> pakinp(const std::string& cvar
                                       , int nx
                                       , int ny
                                       , int nx1
                                       , int ny1
                                       , int lx
                                       , int ly
                                       , float prec
                                       , int nexp
                                       , float var1)
{
    int k, jj, ii;
    float rnew;
    float rold = var1;
    float scexp = 1.0f / std::pow(2.0f, float(7-nexp)); // scaling exponent
    std::vector<std::vector<float>> rvar(nx);
    for(size_t i = 0; i < rvar.size(); ++i) rvar[i] = std::vector<float>(ny, 0.0);
    // initialize column 1 data
    for(int j = 0; j < ny; ++j)
    {
        k = j*nx;  // position at column 1
        jj = j - ny1;
        rnew = (float(ord(cvar[k])-127)*scexp)+rold;
        rold = rnew;
        if(jj >= 0 && jj <= ly)
        {
            rvar[0][jj] = rnew;
        }
    } // 1st for j < ny
    for(int j = ny1; j < (ny1+ly); ++j)
    {
        jj = j - ny1; // sub-grid array (1 to ly)
        rold = rvar[0][jj];
        for(int i = 1; i < (nx1+lx); ++i)
        {
            k = j*nx+i;
            rnew = (float(ord(cvar[k])-127)*scexp)+rold;
            rold = rnew;
            ii = i - nx1;
            if(std::abs(rnew) < prec) rnew = 0.0f;
            if(ii >= 0 && ii <= lx)
            {
                rvar[ii][jj] = rnew;
            }
        } // for i < (ny1+ly)
    } // 2nd for j < ny
    return rvar;
} // pakinp

71
std::vector<std::string> GFSFile::mVarb = { "    ", "PRSS", "TPPA", "TPPT", "TPP6", "PRT6",
72
                                            "TPP1", "CPP1", "TPP3", "CPP3", "MSLP", "SHGT",
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
                                            "U10M", "V10M", "RH2M", "DP2M", "MXHT", "VSBY",
                                            "T02M", "LHTF", "SHTF", "USTR", "RGHS", "DSWF",
                                            "UWND", "VWND", "WWND", "SPHU", "TEMP", "RELH",
                                            "HGTS", "TKEN", "TMPS", "SOLT", "SOLW", "P10M",
                                            "LCLD", "MCLD", "HCLD", "TCLD", "PBLH", "THET",
                                            "DZDT", "PRT3" };
std::vector<std::string> GFSFile::mUnits = { "    ", " hPa", "  mm", "  mm", "  mm", "mm/h",
                                             "  mm", "  mm", "  mm", "  mm", " hPa", "   m",
                                             " m/s", " m/s", "   %", "  oC", "   m", "  km",
                                             "  oC", "W/m2", "W/m2", "cm/s", "   m", "W/m2",
                                             " m/s", " m/s", "mb/h", "g/kg", "  oC", "   %",
                                             "   m", "Joul", "  oC", "  oK", "kgm2", "  oK",
                                             "   %", "   %", "   %", "   %", "   m", "  oC",
                                             " m/h", "mm/h" };
std::vector<float> GFSFile::mFact = { 1.0f, 1.0f, 1000.f, 1000.f, 1000.f, 60000.f,
88
                                      1000.f, 1000.f, 1000.f, 1000.f, 1.0f, 1.0f,
89
90
91
92
93
94
                                      1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.001f,
                                      1.0f, 1.0f, 1.0f, 100.f, 1.0f, 1.0f,
                                      1.0f, 1.0f, 3600.f, 1000.f, 1.0f, 1.0f,
                                      1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                                      1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                                      3600.f, 60000.f };
95
96
GFSFile::GFSFile(std::string file)
    : mFile(file)
97
    , mStrcmp(9, 0.0f)
98
{
99
    radix_tagged_line("GFSFile(" << file << ")" );
100
101
102
103
104
105
106
    // initialize data structure
    eafstream * rstream = new eafstream(file.c_str(), std::ifstream::in | std::ifstream::binary);
    std::string label = rstream->readString(50);
    std::string header = rstream->readString(108);
    // initialize
    mLabel.expand(label);
    mHeader.expand(header);
107
108
109
110
    mHeader.latlon = false;
    mHeader.global = false;
    mHeader.gbldat = false;
    mHeader.prime = false;
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

    // calculate length of records
    int ldat = mHeader.nx*mHeader.ny;
    int rec_len = ldat+50;
    mLrec = rec_len;
    int nndx = mHeader.lenh/ldat + 1;
    // rewind to beginning of file
    rstream->seekg(0, rstream->beg);

    // loop over remaining index records
    for(int i = 0; i < nndx; ++i)
    {
        std::string recl = rstream->readString(mLrec);
        label = recl.substr(0,50);
        header = recl.substr(50);
        mLabel.expand(label);
        mHeader.expand(header);
128
        radix_tagged_line("Found grid: " << mHeader.toString());
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
    //
    // determine if this is a lat-lon grid
    if(mHeader.size == 0.f)
    {
        mHeader.latlon = true;
    }
    if(mHeader.model_id.compare("RAMS") == 0)
    {
        mHeader.tang_lat = mHeader.pole_lat;
    }
    if(!mHeader.latlon)
    {
        //
        // initialize grid conversion variable (into gbase)
        stlmbr(mHeader.tang_lat, mHeader.ref_lon);
        //
        // use single point grid definition
        radix_line("sync_xp=" << mHeader.sync_xp
                   << " sync_yp=" << mHeader.sync_yp
                   << " sync_lat=" << mHeader.sync_lat
                   << " sync_lon=" << mHeader.sync_lon
                   << " ref_lat=" << mHeader.ref_lat
                   << " ref_lon=" << mHeader.ref_lon
                   << " size=" << mHeader.size
                   << " orient=" << mHeader.orient);
        stcm1p(mHeader.sync_xp, mHeader.sync_yp
               , mHeader.sync_lat, mHeader.sync_lon
               , mHeader.ref_lat, mHeader.ref_lon
               , mHeader.size, mHeader.orient);
    }
160
161
162
163
164
165
166
167
168
169
170
171
    int kol = 108;
    int nrec = nndx;
    int nlvl = mHeader.nz;
    mNumVarb.clear();
    mNumVarb.resize(nlvl);
    mVarbId.clear();
    mVarbId.resize(nlvl);
    mHeight.clear();
    mHeight.resize(nlvl);
    std::vector<std::vector<int>> chk_sum(mHeader.nz);
    for(int l = 0; l < nlvl; ++l)
    {
LEFEBVREJP email's avatar
LEFEBVREJP email committed
172
        mHeight[l] = (float)std::atof(header.substr(kol,6).c_str());
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
        mNumVarb[l] = std::atoi(header.substr(kol+6,2).c_str());

        kol += 8;

        mVarbId[l].resize(mNumVarb[l]);
        chk_sum[l].resize(mNumVarb[l]);
        for(int k = 0; k < mNumVarb[l]; ++k)
        {
            mVarbId[l][k] = header.substr(kol,4);
            chk_sum[l][k] = std::atoi(header.substr(kol+4,3).c_str());

            kol+=8;
            nrec++;
        }
    }
    // skip to the next time period index record to find the time interval
    // between date periods (minutes)
    nrec++;

    bool first_date_loaded = false;
    mRecordTimes.clear();
    while(rstream->good())
    {
        std::string recl = rstream->readString(mLrec);
        if(recl.empty())
        {
            break;
        }
        label = recl.substr(0,50);
        mLabel.expand(label);
203
        mRecordTimes.push_back(mLabel.totalSeconds());
204
205
206
207
208
209
210
        if(!first_date_loaded)
        {
            first_date_loaded = true;
            std::stringstream ss;
            ss << mLabel.month << "/" << mLabel.day << "/" << mLabel.year
               << " " << mLabel.hour;
            mStartTime = ss.str();
211
212
213
214
215
216
217
218
219
220
221
            mProfiles.push_back(ss.str());
        } else
        {
            // if we changed time then record profile time.
            if(mRecordTimes[mRecordTimes.size()-2] != mLabel.totalSeconds())
            {
                std::stringstream ss;
                ss << mLabel.month << "/" << mLabel.day << "/" << mLabel.year
                   << " " << mLabel.hour;
                mProfiles.push_back(ss.str());
            }
222
223
224
225
226
227
228
229
230
231
232
        }
        // peek ahead to check for eof etc...
        rstream->peek();
        if(!rstream->good())
        {
            std::stringstream ss;
            // if we are at the end of the file dump the ending time
            ss << mLabel.month << "/" << mLabel.day << "/" << mLabel.year
               << " " << mLabel.hour;
            mEndTime = ss.str();
        }
233
234
        //        radix_tagged_line("Profile time: " << mProfiles[mProfiles.size()-1]
        //                << mLabel.toString());
235
236
237
238
239
240
241
242
243
244
245
    }
    rstream->close();
    delete rstream;
}
std::pair<float, float> GFSFile::gbl2xy(float clat
                                        , float clon
                                        , float sync_lat
                                        , float ref_lat
                                        , float sync_lon
                                        , float ref_lon) const
{
246
247
248
249
    radix_tagged_line("gbl2xy("
                      << clat << ","
                      << clon << ","
                      << sync_lat << ","
250
                      << ref_lat << ","
251
252
                      << sync_lon << ","
                      << ref_lon << ")");
253
254
255
256
257
    float tlat = clat;
    std::pair<float,float> result;
    if(tlat > 90.0f) tlat = 180.0f-tlat;
    if(tlat < -90.0f) tlat = -180.0f-tlat;
    result.second = 1.0f+(tlat-sync_lat)/ref_lat;
258
    radix_tagged_line("\tcomputed y =" << result.second);
259
260

    float tlon = clon;
261
262
263
264
265
    if(!mHeader.prime)
    {
        if(tlon < 0.0f) tlon = 360.0f+tlon;
        if(tlon > 360.0) tlon = tlon-360.0f;
    }
266
267
268
    tlon = tlon-sync_lon;
    if(tlon < 0.0f) tlon = tlon+360.0f;
    result.first = 1.0f+tlon/ref_lon;
269
    radix_tagged_line("\tcomputed x =" << result.first);
270
271
    return result;
}
272

273
std::pair<float, float> GFSFile::cnllxy(float clat, float clon) const
274
275
276
{
    std::pair<float, float> result;
    float almost1 = .99999;
277
    float gamma = mStrcmp[0];
278
    float dlat = clat;
279
    float dlong = cspanf(clon - mStrcmp[1], -180, 180);
280
281
282
283
284
285
286
287
    dlong = dlong * PI_ON_180;
    float gdlong = gamma * dlong;
    float csdgam = 0.0, sndgam = 0.0;
    if(std::abs(gdlong) < 0.01)
    {
        // For gamma small or zero. avoids round-off error or division
        // by zero in the case of mercator or near-mercator projections.
        gdlong = gdlong * gdlong;
288
289
290
291
292
293
294
        sndgam = dlong * (1.f-1.f/6.f * gdlong *
                          (1.f-1.f/20.f * gdlong *
                           (1.f-1.f/42.f * gdlong)));
        csdgam = dlong * dlong * .5f *
                (1.f-1.f/12.f * gdlong *
                 (1.f-1.f/30.f * gdlong *
                  (1.f-1.f/56.f * gdlong)));
295
296
297
    } else
    {
        sndgam = std::sin(gdlong)/gamma;
298
        csdgam = (1.f-std::cos(gdlong))/gamma/gamma;
299
300
301
302
    }
    float slat = std::sin(dlat*PI_ON_180);
    if((slat >= almost1) || (slat <= -almost1))
    {
303
304
305
        result.first = 0.0f;
        result.second = 1.f/gamma;
        return result;
306
    }
307
    float mercy = .5f * std::log((1.f+slat)/(1.f-slat));
308
    float gmercy = gamma * mercy;
309
310
    float rhog1 = 0.f;
    if(std::abs(gmercy) < .001f)
311
312
313
    {
        // For gamma small or zero. avoids round-off error or division
        // by zero in the case of mercator or near-mercator projections.
314
315
316
        rhog1 = mercy * ( 1.f -.5f * gmercy *
                          (1.f-1.f/3.f * gmercy *
                           (1.f-1.f/4.f * gmercy)));
317
318
    } else
    {
319
        rhog1 = (1.f - std::exp(-gmercy)) / gamma;
320
    }
321
322
    result.first = (1.f-gamma*rhog1)*sndgam;
    result.second = rhog1 + (1.f-gamma*rhog1)*gamma*csdgam;
323
324
325

    return result;
}
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

std::pair<float, float> GFSFile::cll2xy(float clat, float clon) const
{
    radix_tagged_line("cll2xy(" << clat << "," << clon << ")");
    std::pair<float, float> xi_eta = cnllxy(clat, clon);
    radix_tagged_line("\txi=" << xi_eta.first
                      << " eta=" << xi_eta.second);

    float radius = EARTH_RADIUS_MEAN/1000.f;
    float x = mStrcmp[2] + radius/mStrcmp[6]
            * (xi_eta.first*mStrcmp[4] + xi_eta.second * mStrcmp[5]);
    float y = mStrcmp[3] + radius/mStrcmp[6]
            * (xi_eta.second*mStrcmp[4] - xi_eta.first * mStrcmp[5]);
    radix_tagged_line("\tx=" << x << " y=" << y);
    return std::make_pair(x,y);
}

std::pair<float, float> GFSFile::cg2cxy(float x, float y, float ug, float vg)
{
    float xpolg = 0.f, ypolg = 0.f, temp = 0.f, xi0 = 0.f, eta0 = 0.f;
    float radius = EARTH_RADIUS_MEAN/1000.f;
    xi0 = (x -mStrcmp[2]) * mStrcmp[6]/radius;
    eta0 = (y - mStrcmp[3]) * mStrcmp[6]/radius;
    xpolg = mStrcmp[5] - mStrcmp[0] * xi0;
    ypolg = mStrcmp[4] - mStrcmp[0] * eta0;
    temp = std::sqrt( std::pow(xpolg, 2.f) + std::pow(ypolg, 2.f));
    if(temp <= 1e03)
    {
//        std::pair<float, float> lat_lon = cxy2ll
    }
}

void GFSFile::stlmbr(float tnglat, float xlong)
{
    float radius = EARTH_RADIUS_MEAN / 1000.f;
    mStrcmp[0] = std::sin(PI_ON_180*tnglat);
    mStrcmp[1] = cspanf(xlong, -180., 180.);
    mStrcmp[2] = 0.;
    mStrcmp[3] = 0.;
    mStrcmp[4] = 1.;
    mStrcmp[5] = 0.;
    mStrcmp[6] = radius;
    std::pair<float,float> xi_eta = cnllxy(89., xlong);
    mStrcmp[7] = 2. * xi_eta.second - mStrcmp[0]
            * xi_eta.second * xi_eta.second;
    xi_eta = cnllxy(-89., xlong);
    mStrcmp[8] = 2. * xi_eta.second - mStrcmp[0]
            * xi_eta.second * xi_eta.second;
}

void GFSFile::stcm1p(float x1, float y1, float xlat1, float xlong1
                     , float xlatg, float xlongg, float gridsz, float orient)
{
    radix_tagged_line("stcm1p(" << x1 << "," << y1
                      << "," << xlat1 << "," << xlong1
                      << "," << xlatg << "," << xlongg
                      << "," << gridsz << "," << orient << ")");
    for(size_t i = 2; i < 4; ++i)
    {
        mStrcmp[i] = 0.f;
    }
    float turn = PI_ON_180 * (orient - mStrcmp[0]
            * cspanf(xlongg - mStrcmp[1], -180., 180.));
    radix_line("turn=" << turn);
    mStrcmp[4] = std::cos(turn);
    mStrcmp[5] = -std::sin(turn);
    mStrcmp[6] = 1.f;
    float cgszllResult = cgszll(xlatg, mStrcmp[1]);
    radix_line("cgszll=" << cgszllResult);
    mStrcmp[6] = gridsz * mStrcmp[6] / cgszllResult;
    radix_line("mStrcmp[7]=" << mStrcmp[6]);
    std::pair<float, float> a1 = cll2xy(xlat1, xlong1);
    radix_line("x1a=" << a1.first << " y1a=" << a1.second);
    mStrcmp[2] = mStrcmp[2] + x1 - a1.first;
    mStrcmp[3] = mStrcmp[3] + y1 - a1.second;
    radix_line("1=" << mStrcmp[0]
            << ", 2=" << mStrcmp[1]
            << ", 3=" << mStrcmp[2]
            << ", 4=" << mStrcmp[3]
            << ", 5=" << mStrcmp[4]
            << ", 6=" << mStrcmp[5]
            << ", 7=" << mStrcmp[6]
            << ", 8=" << mStrcmp[7]);
}

float GFSFile::cgszll(float xlat, float xlong) const
{
    radix_tagged_line("cgszll(" << xlat << "," << xlong);
    float slat = 0.f, ymerc = 0.f, efact = 0.f;
    if(xlat > 89.995f)
    {
        // close to north pole
        if(mStrcmp[0] > 0.9999f)
        {// and to gamma == 1
            return 2.f*mStrcmp[6];
        }
        efact = std::cos(PI_ON_180*xlat);
        if(efact <= 0.f)
        {
            return 0.f;
        } else
        {
            ymerc = -std::log(efact / (1.f + std::sin(PI_ON_180*xlat)));
        }
    } else if(xlat < -89.995f)
    {
        // close to south pole
        if(mStrcmp[0] < -0.9999f)
        {// and to gamma == -1.0
            return 2.f*mStrcmp[6];
        }
        efact = std::cos(PI_ON_180*xlat);
        if(efact <= 0.f)
        {
            return 0.f;
        } else
        {
            ymerc = std::log(efact / (1.f - std::sin(PI_ON_180*xlat)));
        }
    } else
    {
        slat = std::sin(PI_ON_180*xlat);
        ymerc = std::log((1.f+slat)/(1.f-slat))/2.f;
    }
    return mStrcmp[6] * std::cos(PI_ON_180*xlat)*std::exp(mStrcmp[0]*ymerc);
}
452
453
std::pair<int,int> GFSFile::nearestPoint(float lat, float lon) const
{
454
    std::pair<float,float> point;
455
456
457
    radix_tagged_line("nearstPoint("<<lat<<","<<lon<<")");
    radix_tagged_line("\tlatlon=" << std::boolalpha << mHeader.latlon);
    if(mHeader.latlon)
458
459
460
461
462
463
464
465
    {
        point = gbl2xy(lat, lon
                       , mHeader.sync_lat, mHeader.ref_lat
                       , mHeader.sync_lon, mHeader.ref_lon);
    } else
    {
        point = cll2xy(lat, lon);
    }
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
    std::pair<int,int> ipoint;
    ipoint.first =  (int)std::round(point.first);
    ipoint.second = (int)std::round(point.second);
    return ipoint;
}
std::string GFSFile::startTime() const
{
    return mStartTime;
}
std::string GFSFile::endTime() const
{
    return mEndTime;
}
std::string GFSFile::profileTime() const
{
    return mProfileTime;
}
483
484
485
486
const std::vector<std::string>& GFSFile::profileTimes() const
{
    return mProfiles;
}
487
488
489
490
491
492
493
494
495
496
497
std::vector<std::vector<float>> GFSFile::query(float lat
                                               , float lon
                                               , int month
                                               , int day
                                               , int year
                                               , int hour
                                               , std::vector<std::string> columns)
{
    float searchTime = total_seconds(year, month, day, hour);
    // assume class was correctly initialized
    // get the grid points for the lon, lat in the met file
498
    std::pair<int,int> point = nearestPoint(lat, lon); //gbl2xy(lat, lon
499
500
    //, mHeader.sync_lat, mHeader.ref_lat
    //, mHeader.sync_lon, mHeader.ref_lon);
501
502
503
504
505
506
507
508
509

    int x = point.first;//(int)std::round(point.first);
    int y = point.second;//(int)std::round(point.second);
    if(x < 0 || x >= mHeader.nx
            || y < 0 || y >= mHeader.ny)
    {
        std::cerr << "Selected location is outside of file boundary." << std::endl;
        return std::vector<std::vector<float>>();
    }
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
    float minDelta = 99999999.f;
    size_t minIndex = 999999999;
    for(size_t i = 0; i < mRecordTimes.size(); ++i)
    {
        float delta = mRecordTimes.at(i) - searchTime;
        if(delta > 0)
        {
            if(minDelta > delta)
            {
                minDelta = delta;
                minIndex = i;
            }
        } else
        {
            if(std::abs(minDelta) > std::abs(delta))
            {
                minDelta = delta;
                minIndex = i;
            }
        }
    }
    std::vector<size_t> matchingIndex;
    for(size_t i = minIndex; i < mRecordTimes.size(); ++i)
    {
        // if time has changed then lets break out of loop
        if(mRecordTimes.at(i) != mRecordTimes.at(minIndex))break;
        matchingIndex.push_back(i);
    }
    float sfcp = 1013.0f;
    float sfct = 0.0f;
    int lp = 0;
    std::vector<std::vector<float>> vdata(mvar);
    for(size_t i = 0; i < vdata.size(); ++i) vdata[i] = std::vector<float>(mlvl,0.0f);
    std::vector<float> utw(mlvl, 0.0f);
    std::vector<float> vtw(mlvl, 0.0f);

    std::string label, header;
    std::vector<std::vector<float>> rdata;
    // open the file for reading
549
    radix::eafstream * rstream = new radix::eafstream(mFile.c_str(), std::ifstream::in | std::ifstream::binary);
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
    for(size_t i = 0; i < matchingIndex.size(); ++i)
    {
        // get the fortran record index
        size_t irec = matchingIndex.at(i) + 1;
        // calculate the file offset
        size_t foffset = mLrec*irec;
        // seek to the position in the file
        rstream->seekg(foffset, rstream->beg);
        std::string recl = rstream->readString(mLrec);
        label = recl.substr(0,256);
        mLabel.expand(label);
        if(i == 0)
        {
            std::stringstream ss;
            ss << mLabel.month << "/" << mLabel.day << "/" << mLabel.year << " " << mLabel.hour;
            mProfileTime = ss.str();
        }
        header = recl.substr(50);
        std::string varb = mLabel.kvar;
        if(varb.compare("INDX") == 0) continue;
        rdata = pakinp(header, mHeader.nx, mHeader.ny, 0, 0, mHeader.nx, mHeader.ny, mLabel.prec, mLabel.nexp, mLabel.var1);

        int ll = mLabel.il;
        // convert level number to array index because input data
        // level index starts at 0 for the surface
575
576
577
578
579
580
581
582
583
584
585
586
587
        if(ll != lp || irec == (matchingIndex.size()-1))
        {
//            if(lp != 0)
//            {
//                if(!mHeader.latlon)
//                {
//                    std::pair<float,float> result = cg2cxy();
//                    utw[lp] = result.first;
//                    vtw[lp] = result.second;
//                }
//            }
            lp = ll;
        }
588
589
590
591
592
593
594
595
596
597
598
599
600
601

        // find the variable array element number - match the input
        // variable with its position as indicated in the index record
        int nvar = mNumVarb.at(ll);
        int kvar = 0;
        for(int kk = 0; kk < nvar; ++kk)
        {
            if( varb.compare(mVarbId[ll][kk]) == 0) kvar = kk;
        }
        vdata[kvar][ll] = rdata[x-1][y-1];
        // convert unit of temperature to oC
        if( varb.compare("TEMP") == 0
                || varb.compare("T02M") == 0
                || varb.compare("TMPS") == 0
LEFEBVREJP email's avatar
LEFEBVREJP email committed
602
                || varb.compare("DP2M") == 0) vdata[kvar][ll] = vdata[kvar][ll]-273.16f;
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

        // save the surface pressure and terrain mHeight for scaling
        // of the vertical coordinate system (mHeight = signma*scaling)
        if(varb.compare("PRSS") == 0) sfcp = vdata[kvar][ll];
        if(varb.compare("SHGT") == 0) sfct = vdata[kvar][ll];

        // load the winds for subsequent rotation to true
        if(varb.compare("UWND") == 0 || varb.compare("U10M") == 0) utw[ll] = vdata[kvar][ll];
        if(varb.compare("VWND") == 0 || varb.compare("V10M") == 0) vtw[ll] = vdata[kvar][ll];
    } // for matching records
    // close the file
    rstream->close();
    delete rstream;

    // SOUND section of Fortran
    float tpot = 0.0f;
    float temp = 0.0f;
    bool sfcwnd = false;
    float offset = 0.0f;
    float plevel = 0.0f;

    std::vector<std::vector<float>> results(mHeader.nz);
    for(int ll = 0; ll < mHeader.nz; ++ll)
    {
        int nvar = mNumVarb[ll];
        // default vertical motion units in mb/s
        for(size_t nn = 0; nn < mUnits.size(); ++nn)
            if(0 == mVarb[ll].compare("WWND")) mUnits[nn] = "mb/h";

        if(mHeader.z_flag == 1)
        {
            // pressure sigma levels
            offset = mHeader.dummy;
            plevel = offset + (sfcp-offset)*mHeight[ll];
        } else if(mHeader.z_flag == 2)
        {
            plevel = mHeight[ll];
            if(ll == 0) plevel = sfcp;
        } else if(mHeader.z_flag == 3)
        {
            float ztop = 20000.0f;
            if(mHeight[mHeader.nz-1] > ztop) ztop = 34800.0f;
            float factor = 1.0f-sfct/ztop;
            plevel = factor*mHeight[ll];
            // terrain follow Z system units in m/s
            for(size_t nn = 0; nn < mUnits.size(); ++nn)
            {
                if(0 == mVarb[ll].compare("WWND")) mUnits[nn] = " m/h";
            }
        } else if(mHeader.z_flag == 4)
        {
            //ecmwf hubrid coordinate system
            offset = static_cast<int>(mHeight[ll]);
            float psigma = mHeight[ll] - offset;
            plevel = sfcp*psigma+offset;
            if(ll == 0) plevel=sfcp;
        }
        // by default assume level = pressure unless PRES variable appears
        // (i.e. terrain data (type=3) will have local pressure variable
        int level = static_cast<int>(plevel);

        // match variables defined in file's index record with those variables
        // that have been defined in this subroutine and create a variable number
        // for simple table lookup
        std::vector<int> nt(nvar, 0);
        for(int kk = 0; kk < nvar; ++kk)
        {
            for(size_t nn = 0; nn < mUnits.size(); ++nn)
            {
                if(mVarbId[ll][kk].compare(mVarb[nn]) == 0) nt[kk] = (int)(nn);
                // check for 10 meter winds
                if((ll == 0)
                        && (mVarbId[ll][kk].compare("U10M") == 0)
                        && (mVarb[nn].compare("U10M") == 0))
                {
                    sfcwnd = true;
                } else if( (ll == 0)
                           && (mVarbId[ll][kk].compare("V10M") == 0)
                           && (mVarb[nn].compare("V10M") == 0))
                {
                    sfcwnd = true;
                }
            }
        }
        //
        // convert each variable at that level to standard units as defined
        // from the table lookup. Variales not found are not converted and
        // have no specific units label
        for(int kk = 0; kk < nvar; ++kk)
        {
            vdata[kk][ll] = vdata[kk][ll]*mFact[nt[kk]];
        }
        // initialize space for results vector
        results[ll] = std::vector<float>(columns.size(), 0.0f);
        // check for time
        auto timeIt = std::find(columns.begin(), columns.end(), "TIME");
        if(timeIt != columns.end())
        {
LEFEBVREJP email's avatar
LEFEBVREJP email committed
701
702
            int hour = (int)((mRecordTimes[minIndex] - searchTime)/3600.0f);
            results[ll][timeIt-columns.begin()] = (float)hour;
703
704
705
706
707
        }
        // check for pressure
        auto presIt = std::find(columns.begin(), columns.end(), "PRSS");
        if(presIt != columns.end())
        {
LEFEBVREJP email's avatar
LEFEBVREJP email committed
708
            results[ll][presIt-columns.begin()] = (float)level;
709
710
711
712
713
714
715
716
717
718
719
720
721
        }

        for(int kk = 0; kk < nvar; ++kk)
        {
            if(mVarbId[ll][kk].compare("PRES") == 0) plevel = vdata[kk][ll];
            if(mVarbId[ll][kk].compare("THET") == 0)
            {
                tpot = vdata[kk][ll];
                // potential temperature defined; replace with ambient
                vdata[kk][ll] = (tpot*std::pow(plevel/1000.0f,0.286f))-273.16f;
            }
            if(mVarbId[ll][kk].compare("TEMP") == 0) temp = vdata[kk][ll]+273.16f;

722
723
724
725
726
727
            std::string varb = mVarbId[ll][kk];

            //map certain varb
            if(varb.compare("T02M") == 0) varb = "TEMP";
            if(varb.compare("RH2M") == 0) varb = "RELH";
            auto it = std::find(columns.begin(), columns.end(), varb);
728
729
730
731
732
733
            if(it != columns.end())
            {
                results[ll][it-columns.begin()] = vdata[kk][ll];
            }

        }
734
735
736
737
738
739
740
741
742
743
744
745
        // check surface data (2 meters)
        if( ll == 0)
        {
            // check for surface height
            {
                auto it = std::find(columns.begin(), columns.end(), "HGTS");
                if(it != columns.end())
                {
                    results[ll][it-columns.begin()] = 2.0f;
                }
            }
        }
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
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
        bool hwind = false; // have wind?
        float wd = 0.f;
        float ws = 0.f;
        if(ll > 1)
        {
            // potential temperature not defined, then compute
            if(tpot == 0.0f) tpot = temp*std::pow(1000.0f/plevel, 0.286f);
            if(kwnd)
            {
                if(utw[ll] != 0.0f || vtw[ll] != 0.0f)
                {
                    wd = 57.29578f*std::atan2(utw[ll], vtw[ll])+360.0f;
                    wd = std::fmod(wd, 360.0f);
                    wd = std::fmod((wd+180.0f), 360.0f);
                    ws = std::sqrt(utw[ll]*utw[ll]+vtw[ll]*vtw[ll]);
                    hwind = true;
                }
            } else
            {
                wd = utw[ll];
                ws = vtw[ll];
                hwind = true;
            }
        } else
        {
            if(kwnd && sfcwnd)
            {
                if(utw[ll] != 0.0f || vtw[ll] != 0.0f)
                {
                    wd = 57.295778f*std::atan2(utw[ll],vtw[ll])+360.0f;
                    wd = std::fmod(wd, 360.0f);
                    wd = std::fmod((wd+180.0f), 360.0f);
                    ws = std::sqrt(utw[ll]*utw[ll]+vtw[ll]*vtw[ll]);
                    hwind = true;
                }
            }
        }
        if(hwind)
        {
            // check for WD
            {
                auto it = std::find(columns.begin(), columns.end(), "WD");
                if(it != columns.end())
                {
                    results[ll][it-columns.begin()] = wd;
                }
            }// check for WS
            {
                auto it = std::find(columns.begin(), columns.end(), "WS");
                if(it != columns.end())
                {
                    results[ll][it-columns.begin()] = ws;
                }
            }
        }
    } // for ll < nz

    return results;
}
} // namespace radix