gfsfile.cc 17.7 KB
Newer Older
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
#include "radixio/gfsfile.hh"

#include "radixio/eafstream.hh"

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
    return year*365.*86400.f
            +(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

GFSFile::GFSFile(std::string file)
    : mFile(file)
{
    // 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);

    // 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);
    }
    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)
    {
        mHeight[l] = std::atof(header.substr(kol,6).c_str());
        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);
        header = recl.substr(50);
141
        mRecordTimes.push_back(mLabel.totalSeconds());
142
143
144
145
146
147
148
        if(!first_date_loaded)
        {
            first_date_loaded = true;
            std::stringstream ss;
            ss << mLabel.month << "/" << mLabel.day << "/" << mLabel.year
               << " " << mLabel.hour;
            mStartTime = ss.str();
149
150
151
152
153
154
155
156
157
158
159
            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());
            }
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
        }
        // 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();
        }
    }
    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
{
    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;

    float tlon = clon;
    // default PRIME section
    if(tlon < 0.0f) tlon = 360.0f+tlon;
    if(tlon > 360.0) tlon = tlon-360.0f;
    tlon = tlon-sync_lon;
    if(tlon < 0.0f) tlon = tlon+360.0f;
    result.first = 1.0f+tlon/ref_lon;
    return result;
}
std::pair<int,int> GFSFile::nearestPoint(float lat, float lon) const
{
    std::pair<float,float> point = gbl2xy(lat, lon
                                          , mHeader.sync_lat, mHeader.ref_lat
                                          , mHeader.sync_lon, mHeader.ref_lon);
    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;
}
219
220
221
222
const std::vector<std::string>& GFSFile::profileTimes() const
{
    return mProfiles;
}
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
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
    std::pair<float,float> point = gbl2xy(lat, lon
                                          , mHeader.sync_lat, mHeader.ref_lat
                                          , mHeader.sync_lon, mHeader.ref_lon);
    int x =  (int)std::round(point.first);
    int y = (int)std::round(point.second);
    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
    radix::eafstream * rstream = new radix::eafstream(mFile.c_str(), std::ifstream::in);
    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
        if(ll != lp || irec == (matchingIndex.size()-1)) lp = ll;

        // 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
                || varb.compare("DP2M") == 0) vdata[kvar][ll] = vdata[kvar][ll]-273.16;

        // 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;
    int iwd10u = 0;
    int iwd10v = 0;
    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))
                {
                    iwd10u = (int)nn;
                    sfcwnd = true;
                } else if( (ll == 0)
                           && (mVarbId[ll][kk].compare("V10M") == 0)
                           && (mVarb[nn].compare("V10M") == 0))
                {
                    iwd10v = (int)nn;
                    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())
        {
            int hour = ((mRecordTimes[minIndex] - searchTime)/3600.0f);
            results[ll][timeIt-columns.begin()] = hour;
        }
        // check for pressure
        auto presIt = std::find(columns.begin(), columns.end(), "PRSS");
        if(presIt != columns.end())
        {
            results[ll][presIt-columns.begin()] = level;
        }

        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;

443
444
445
446
447
448
            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);
449
450
451
452
453
454
            if(it != columns.end())
            {
                results[ll][it-columns.begin()] = vdata[kk][ll];
            }

        }
455
456
457
458
459
460
461
462
463
464
465
466
        // 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;
                }
            }
        }
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
        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