soutifu.cc 18.4 KB
Newer Older
thomas.forbriger's avatar
thomas.forbriger committed
1
/*! \file soutifu.cc
2
 * \brief inversion for source wavelet correction filter
thomas.forbriger's avatar
thomas.forbriger committed
3
4
5
6
7
8
 * 
 * ----------------------------------------------------------------------------
 * 
 * \author Thomas Forbriger
 * \date 06/05/2011
 * 
9
 * inversion for source wavelet correction filter
thomas.forbriger's avatar
thomas.forbriger committed
10
11
 * 
 * Copyright (c) 2011 by Thomas Forbriger (BFO Schiltach) 
thomas.forbriger's avatar
thomas.forbriger committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 *
 * ----
 * SOUTIFU is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version. 
 * 
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * ----
 *
thomas.forbriger's avatar
thomas.forbriger committed
29
30
31
 * 
 * REVISIONS and CHANGES 
 *  - 06/05/2011   V1.0   Thomas Forbriger
32
 *  - 08/09/2011   V1.1   support format modifiers
33
 *  - 30/09/2011   V1.2   support additional time series pairs
34
 *  - 19/10/2015   V1.3   provide full usage information from libstfinv
35
 *  - 22/11/2016   V1.4   make proper use of output operators
thomas.forbriger's avatar
thomas.forbriger committed
36
37
38
39
 * 
 * ============================================================================
 */
#define SOUTIFU_VERSION \
40
  "SOUTIFU   V1.4   inversion for source wavelet correction filter"
thomas.forbriger's avatar
thomas.forbriger committed
41
42

#include <iostream>
43
44
#include <fstream>
#include <tfxx/error.h>
thomas.forbriger's avatar
thomas.forbriger committed
45
#include <tfxx/commandline.h>
46
#include <tfxx/seitosh.h>
47
#include <tsioxx/inputoperators.h>
48
#include <tsioxx/outputoperators.h>
49
#include <datrwxx/readany.h>
50
#include <datrwxx/writeany.h>
51
52
53
#include <stfinv/stfinvany.h>

/*----------------------------------------------------------------------*/
thomas.forbriger's avatar
thomas.forbriger committed
54
55
56
57
58

using std::cout;
using std::cerr;
using std::endl;

thomas.forbriger's avatar
thomas.forbriger committed
59
60
61
62
/*----------------------------------------------------------------------*/
// debug helper
#define PAROUT( par ) cout << #par << "=" << par << " ";

63
64
65
66
67
68
/*----------------------------------------------------------------------*/
// function to compare double
// is true if relative residual between a and b is smaller than eps
bool sameineps(const double &a, const double& b, const double& eps=1.e-8)
{
  double reldif=std::abs(a-b);
thomas.forbriger's avatar
thomas.forbriger committed
69
  return(reldif<=(std::abs(b*eps)));
70
71
}

72
73
74
75
76
/*----------------------------------------------------------------------*/

struct Options {
  bool verbose, debug, overwrite;
  bool writestf, writeconvolved;
77
  bool additionalpairs;
thomas.forbriger's avatar
thomas.forbriger committed
78
  std::string stffilename, convolvedfilename, debuglevel;
79
  std::string datafileformat, outputfileformat;
80
  std::string additionalseries, additionaloutput;
81
82
83
84
}; // struct Options

/*----------------------------------------------------------------------*/

thomas.forbriger's avatar
thomas.forbriger committed
85
86
87
88
89
90
91
int main(int iargc, char* argv[])
{

  // define usage information
  char usage_text[]=
  {
    SOUTIFU_VERSION "\n"
92
    "usage: soutifu [-v] [-o] [-wc f] [-ws f] [--type f] [--Type f]\n"
93
    "               [-add f] [-wa f]\n"
thomas.forbriger's avatar
thomas.forbriger committed
94
    "               [-DEBUG=level]\n"
95
    "               parameters data synthetics" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
96
    "   or: soutifu --help|-h" "\n"
97
    "   or: soutifu --xhelp | --iohelp | --phelp p" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
98
99
100
101
102
  };

  // define full help text
  char help_text[]=
  {
103
    "Calculate optimized source wavelet correction filter to\n"
104
    "minimize misfit between recorded data and synthetic waveforms.\n"
105
106
107
108
109
110
111
112
    "\n"
    "data         name of file containing recorded data\n"
    "synthetics   name of file containing synthetic data\n"
    "parameters   parameterstring to select STF engine\n"
    "             The string consists of an ID selecting one of the\n"
    "             available engines and a set of options an parameters\n"
    "             to be passed to this engine.\n"
    "\n"
113
    "--xhelp      print summary of usage instructions for available procedures\n"
114
    "--iohelp     print detailed usage instructions for file input/output\n"
115
    "--phelp p    print detailed usage instructions for procedure \"p\"\n"
116
    "\n"
117
    "-v           be verbose\n"
thomas.forbriger's avatar
thomas.forbriger committed
118
    "-DEBUG=level produce debug output at level \"level\"\n"
119
    "-o           overwrite existing output files\n"
120
121
122
123
    "--type f     use file format type \"f\" for file input\n"
    "--Type f     use file format type \"f\" for file output\n"
    "             if --Type is not used input and output format will\n"
    "             be the same\n"
124
    "-wc f        write convolved synthetics to file \"f\"\n"
125
    "-ws f        write source wavelet correction filter \n"
126
    "             impulse response to file \"f\"\n"
127
128
    "-add f       read additional time series to be convolved from file \"f\"\n"
    "-wa f        write additional time series after convolved to file \"f\"\n"
129
130
131
132
    "\n"
    "Upon input the consistency of recorded and synthetic data are\n"
    "checked. For coordinates only receiver positions relative to\n"
    "source coordinates are checked, not absolute locations.\n"
thomas.forbriger's avatar
thomas.forbriger committed
133
134
135
136
137
138
139
140
141
142
  };

  // define commandline options
  using namespace tfxx::cmdline;
  static Declare options[]= 
  {
    // 0: print help
    {"help",arg_no,"-"},
    // 1: verbose mode
    {"v",arg_no,"-"},
143
144
145
146
147
148
    // 2: overwrite mode
    {"o",arg_no,"-"},
    // 3: file format
    {"type",arg_yes,"sff"},
    // 4: name of convolved synthetics
    {"wc",arg_yes,"-"},
149
    // 5: name of source correction filter wavelet file
150
    {"ws",arg_yes,"-"},
151
    // 6: present full details regarding engines
152
    {"xhelp",arg_no,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
153
154
    // 7: present full details
    {"DEBUG",arg_yes,"0"},
155
156
    // 8: file format
    {"Type",arg_yes,"-"},
157
158
159
160
    // 9: additional time series to be convolved
    {"add",arg_yes,"-"},
    // 10: output file for additional convolved time series
    {"wa",arg_yes,"-"},
161
162
    // 11: provide full details regarding file i/o
    {"iohelp",arg_no,"-"},
163
164
    // 12: provide full details regarding file i/o
    {"phelp",arg_yes,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
165
166
167
168
169
170
171
    {NULL}
  };

  // no arguments? print usage...
  if (iargc<2) 
  {
    cerr << usage_text << endl;
172
    cerr << tfxx::seitosh::repository_reference << endl;
thomas.forbriger's avatar
thomas.forbriger committed
173
174
175
176
177
178
179
    exit(0);
  }

  // collect options from commandline
  Commandline cmdline(iargc, argv, options);

  // help requested? print full help text...
180
181
  if (cmdline.optset(0) || cmdline.optset(6) || cmdline.optset(11)
      || cmdline.optset(12))
thomas.forbriger's avatar
thomas.forbriger committed
182
183
  {
    cerr << usage_text << endl;
184
    cerr << endl;
thomas.forbriger's avatar
thomas.forbriger committed
185
    cerr << help_text << endl;
186
    datrw::supported_data_types(cerr);
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    if (cmdline.optset(11)) 
    { 
      cerr << endl;
      datrw::online_help(cerr); 
    }
    if (cmdline.optset(6)) 
    { 
      cerr << endl;
      stfinv::help(cerr); 
    }
    else
    {
      cerr << help_text << endl;
      stfinv::engines(cerr);
    }
    if (cmdline.optset(12)) 
    {
      cerr << endl;
      stfinv::usage(cmdline.string_arg(12), cerr); 
    }
207
    cerr << endl << tfxx::seitosh::repository_reference << endl;
thomas.forbriger's avatar
thomas.forbriger committed
208
209
210
    exit(0);
  }

211
212
213
214
215
  /*----------------------------------------------------------------------*/
  // read options and parameters
  Options opt;
  opt.verbose=cmdline.optset(1);
  opt.overwrite=cmdline.optset(2);
216
  opt.datafileformat=cmdline.string_arg(3);
217
218
219
220
  opt.writeconvolved=cmdline.optset(4);
  opt.convolvedfilename=cmdline.string_arg(4);
  opt.writestf=cmdline.optset(5);
  opt.stffilename=cmdline.string_arg(5);
thomas.forbriger's avatar
thomas.forbriger committed
221
222
  opt.debug=cmdline.optset(7);
  opt.debuglevel=cmdline.string_arg(7);
223
  opt.outputfileformat=opt.datafileformat;
thomas.forbriger's avatar
thomas.forbriger committed
224
  if (cmdline.optset(8)) { opt.outputfileformat=cmdline.string_arg(8); }
225
226
227
228
229
230
231
232
  opt.additionalpairs=cmdline.optset(9);
  opt.additionalseries=cmdline.string_arg(9);
  if (cmdline.optset(10))
  {
    TFXX_assert(opt.additionalpairs,
                "ERROR: provide input for additional series");
    opt.additionaloutput=cmdline.string_arg(10);
  }
233
234
235
236
237
238
239
240
241
242
243
244
245
246

  TFXX_assert(cmdline.extra(), "missing parameter string");
  std::string parameters=cmdline.next();
  TFXX_assert(cmdline.extra(), "missing recorded data file name");
  std::string datafilename=cmdline.next();
  TFXX_assert(cmdline.extra(), "missing synthetics data file name");
  std::string syntheticsfilename=cmdline.next();

  /*----------------------------------------------------------------------*/
  // go
  // --
 
  // read input data
  // ---------------
247
  typedef aff::Series<float> Tseries;
248
249
250
  typedef ts::sff::File<Tseries> Tfile;
  Tfile recordeddata;
  Tfile syntheticdata;
251
252
  // input for additional series
  Tfile seriesdata;
253
254
255
256

  std::ios_base::openmode iopenmode
    =datrw::ianystream::openmode(opt.datafileformat);
  if (opt.verbose) { cout << "open input file " << datafilename << endl; }
thomas.forbriger's avatar
thomas.forbriger committed
257
  {
258
259
260
    std::ifstream ifs(datafilename.c_str(), iopenmode);
    datrw::ianystream is(ifs, opt.datafileformat);
    recordeddata.read(is.idatstream(), opt.verbose);
thomas.forbriger's avatar
thomas.forbriger committed
261
262
  }

263
264
265
266
267
268
  if (opt.verbose) { cout << "open input file " << syntheticsfilename << endl; }
  {
    std::ifstream ifs(syntheticsfilename.c_str(), iopenmode);
    datrw::ianystream is(ifs, opt.datafileformat);
    syntheticdata.read(is.idatstream(), opt.verbose);
  }
269

270
271
272
273
274
275
276
277
278
279
280
  if (opt.additionalpairs)
  {
    if (opt.verbose) 
    { cout << "open input file " << opt.additionalseries << endl; }
    {
      std::ifstream ifs(opt.additionalseries.c_str(), iopenmode);
      datrw::ianystream is(ifs, opt.datafileformat);
      seriesdata.read(is.idatstream(), opt.verbose);
    }
  }

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
  // check input data consistency and prepare output files
  // -----------------------------------------------------
  if (opt.verbose) 
  { 
    cout << "check input data consistency,\n"
      << "prepare output data containers, and\n"
      << "prepare waveform data workspace" << endl; 
  }

  // number of traces per file
  TFXX_assert(recordeddata.size() == syntheticdata.size(),
              "ERROR: inconsitent number of traces");
  const unsigned int ntraces=recordeddata.size();

  // output data
  Tfile convolvedsynthetics;
  Tfile stffile;

  // waveform data workspace
  stfinv::Tvectoroftriples vectoroftriples;
  stfinv::Waveform stfwaveform;

  convolvedsynthetics.fileheader=syntheticdata.fileheader;

  // cycle through all traces
  for (unsigned int itrace=0; itrace<ntraces; ++itrace)
  {
    if (opt.verbose)
    {
      cout << "  check trace #" << itrace+1 << endl;
    }
    // create a reference to the time series with trace header for thsi
    // specific trace as read from file
    const Tfile::Ttracevector::Ttimeseries& rdtseries=recordeddata[itrace];
    const Tfile::Ttracevector::Ttimeseries& sdtseries=syntheticdata[itrace];

    // create a time series to be used in the output of convolved synthetics
    // based on the input synthetics; copy trace header
319
320
321
    Tfile::Ttracevector::Ttimeseries 
      cstseries(Tfile::Ttracevector::Ttimeseries::Tseries(sdtseries.shape()),
                sdtseries.header, sdtseries.traceindex());
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

    // place reference in a waveform triple
    stfinv::WaveformTriple tracetriple;
    tracetriple.data=rdtseries;
    tracetriple.synthetics=sdtseries;
    tracetriple.convolvedsynthetics=cstseries;
    tracetriple.header.sampling.dt=rdtseries.header.wid2().dt;
    tracetriple.header.sampling.n=rdtseries.header.wid2().nsamples;

    TFXX_assert((rdtseries.header.wid2().nsamples 
                  == sdtseries.header.wid2().nsamples),
                "ERROR: inconsistent trace size");
    TFXX_assert(sameineps(rdtseries.header.wid2().dt,
                            sdtseries.header.wid2().dt),
                "ERROR: inconsistent sampling interval");

    // read out source coordinates
    tracetriple.header.sx=recordeddata.fileheader.srce().cx;
    tracetriple.header.sy=recordeddata.fileheader.srce().cy;
    tracetriple.header.sz=recordeddata.fileheader.srce().cz;

    // read out receiver coordinates
    tracetriple.header.rx=rdtseries.header.info().cx;
    tracetriple.header.ry=rdtseries.header.info().cy;
    tracetriple.header.rz=rdtseries.header.info().cz;

    // check coordinate consistency
    double ddx=rdtseries.header.info().cx-recordeddata.fileheader.srce().cx;
    double ddy=rdtseries.header.info().cy-recordeddata.fileheader.srce().cy;
    double ddz=rdtseries.header.info().cz-recordeddata.fileheader.srce().cz;
    double sdx=sdtseries.header.info().cx-syntheticdata.fileheader.srce().cx;
    double sdy=sdtseries.header.info().cy-syntheticdata.fileheader.srce().cy;
    double sdz=sdtseries.header.info().cz-syntheticdata.fileheader.srce().cz;
thomas.forbriger's avatar
thomas.forbriger committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
    if (opt.debug)
    if (!(sameineps(ddx,sdx) && sameineps(ddy,sdy) &&
                 sameineps(ddz,sdz)))
    {
      cout << "NOTICE: ";
      PAROUT(ddx);
      PAROUT(sdx);
      PAROUT(ddy);
      PAROUT(sdy);
      PAROUT(ddz);
      PAROUT(sdz);
      PAROUT(sameineps(ddx,sdx));
      PAROUT(sameineps(ddy,sdy));
      PAROUT(sameineps(ddz,sdz));
      cout << endl;
    }
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    TFXX_assert((sameineps(ddx,sdx) && sameineps(ddy,sdy) &&
                 sameineps(ddz,sdz)),
                "ERROR: inconsistent receiver positions");

    // check time consistency
    TFXX_assert((rdtseries.header.wid2().date 
                == recordeddata.fileheader.srce().date),
                "ERROR: trigger delay not supported");
    TFXX_assert((sdtseries.header.wid2().date 
                == syntheticdata.fileheader.srce().date),
                "ERROR: trigger delay not supported");

    // add this triple to collection
    vectoroftriples.push_back(tracetriple);

    // add this trace to convolved synthetics
    convolvedsynthetics.push_back(cstseries);

    // catch values for stf waveform
    if (itrace==0)
    {
392
393
394
      Tfile::Ttracevector::Ttimeseries stftseries;
      stftseries
        =Tfile::Ttracevector::Ttimeseries::Tseries(tracetriple.data.shape()); 
395
396
397
398
399

      stfwaveform.sampling.dt=tracetriple.header.sampling.dt;
      stfwaveform.sampling.n=tracetriple.header.sampling.n;
      stfwaveform.series=stftseries;

thomas.forbriger's avatar
thomas.forbriger committed
400
401
402
403
404
405
406
407
      ::sff::WID2 wid2=stftseries.header.wid2();
      wid2.nsamples=stfwaveform.sampling.n;
      wid2.dt=stfwaveform.sampling.dt;
      wid2.date=libtime::now();
      stftseries.header.wid2(wid2);
      ::sff::SRCE srce=stffile.fileheader.srce();
      srce.date=stftseries.header.wid2().date;
      stffile.fileheader.srce(srce);
408
409
410
411
412

      stffile.push_back(stftseries);
    } // if (itrace==0)

  } // for (unsigned int itrace=0; itrace<ntraces; ++itrace)
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

  /*----------------------------------------------------------------------*/

  // prepare additional pairs
  Tfile convolvedseries;

  // waveform data workspace
  stfinv::Tvectorofpairs vectorofpairs;
  vectorofpairs.clear();

  if (opt.additionalpairs)
  {

    convolvedseries.fileheader=seriesdata.fileheader;
    if (opt.verbose)
    {
      cout << "prepare additional series to be convolved" << endl;
    }

    // cycle through all traces
    for (unsigned int itrace=0; itrace<seriesdata.size(); ++itrace)
    {
      if (opt.verbose)
      {
        cout << "  check trace #" << itrace+1 << endl;
      }
      // create a reference to the time series with trace header for thsi
      // specific trace as read from file
      const Tfile::Ttracevector::Ttimeseries& sdtseries=seriesdata[itrace];

      // create a time series to be used in the output of convolved synthetics
      // based on the input synthetics; copy trace header
445
446
447
      Tfile::Ttracevector::Ttimeseries 
        cstseries(Tfile::Ttracevector::Ttimeseries::Tseries(sdtseries.shape()),
                 sdtseries.header, sdtseries.traceindex());
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464

      // place reference in a waveform triple
      stfinv::WaveformPair tracepair;
      tracepair.synthetics=sdtseries;
      tracepair.convolvedsynthetics=cstseries;
      tracepair.sampling.dt=sdtseries.header.wid2().dt;
      tracepair.sampling.n=sdtseries.header.wid2().nsamples;

      // add this triple to collection
      vectorofpairs.push_back(tracepair);

      // add this trace to convolved synthetics
      convolvedseries.push_back(cstseries);

    } // for (unsigned int itrace=0; itrace<seriesdata.size(); ++itrace)

  } // if (opt.additionalpairs)
465
  
466
467
  /*----------------------------------------------------------------------*/

468
469
470
471
472
473
474
  // create STF engine
  // -----------------
  if (opt.verbose) 
  {
    parameters += ":verbose";
    cout << "create STF engine" << endl; 
  }
thomas.forbriger's avatar
thomas.forbriger committed
475
  if (opt.debug) { parameters += ":DEBUG="+opt.debuglevel; }
476
477
  stfinv::STFEngine engine(vectoroftriples, stfwaveform, 
                           vectorofpairs, parameters);
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498

  // run STF engine
  // --------------
  if (opt.verbose) { cout << "run engine" << endl; }
  engine.run();

  // write results
  // -------------
  
  if (opt.writestf)
  {
    if (opt.verbose) 
    {
      cout << "write STF to file " << opt.stffilename << endl;
    }
    if (!opt.overwrite)
    {
      std::ifstream file(opt.stffilename.c_str(),std::ios_base::in);
      TFXX_assert((!file.good()),"ERROR: output file exists!");
    }
    std::ios_base::openmode oopenmode
499
      =datrw::oanystream::openmode(opt.outputfileformat);
500
    std::ofstream ofs(opt.stffilename.c_str(), oopenmode);
501
    datrw::oanystream os(ofs, opt.outputfileformat, opt.debug);
502
503
504
505
    
    os << stffile.fileheader.srce();
    for (unsigned int itrace=0; itrace<stffile.size(); ++itrace)
    {
506
      os << stffile[itrace];
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
    }
  } // if (opt.writestf)

  if (opt.writeconvolved)
  {
    if (opt.verbose) 
    {
      cout << "write convolved synthetics to file " 
        << opt.convolvedfilename << endl;
    }
    if (!opt.overwrite)
    {
      std::ifstream file(opt.convolvedfilename.c_str(),std::ios_base::in);
      TFXX_assert((!file.good()),"ERROR: output file exists!");
    }
    std::ios_base::openmode oopenmode
523
      =datrw::oanystream::openmode(opt.outputfileformat);
524
    std::ofstream ofs(opt.convolvedfilename.c_str(), oopenmode);
525
    datrw::oanystream os(ofs, opt.outputfileformat, opt.debug);
526
527
528
529
    
    os << convolvedsynthetics.fileheader.srce();
    for (unsigned int itrace=0; itrace<convolvedsynthetics.size(); ++itrace)
    {
530
      os << convolvedsynthetics[itrace];
531
532
    }
  } // if (opt.writeconvolved)
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553

  if (opt.additionalpairs)
  {
    if (opt.verbose) 
    {
      cout << "write additional convolved series to file " 
        << opt.additionaloutput << endl;
    }
    if (!opt.overwrite)
    {
      std::ifstream file(opt.additionaloutput.c_str(),std::ios_base::in);
      TFXX_assert((!file.good()),"ERROR: output file exists!");
    }
    std::ios_base::openmode oopenmode
      =datrw::oanystream::openmode(opt.outputfileformat);
    std::ofstream ofs(opt.additionaloutput.c_str(), oopenmode);
    datrw::oanystream os(ofs, opt.outputfileformat, opt.debug);
    
    os << convolvedseries.fileheader.srce();
    for (unsigned int itrace=0; itrace<convolvedseries.size(); ++itrace)
    {
554
      os << convolvedseries[itrace];
555
556
557
    }
  } // if (opt.additionalpairs)

558
} // main
thomas.forbriger's avatar
thomas.forbriger committed
559
560

/* ----- END OF soutifu.cc ----- */