soutifu.cc 13.1 KB
Newer Older
thomas.forbriger's avatar
thomas.forbriger committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*! \file soutifu.cc
 * \brief inversion for source time function
 * 
 * ----------------------------------------------------------------------------
 * 
 * $Id$
 * \author Thomas Forbriger
 * \date 06/05/2011
 * 
 * inversion for source time function
 * 
 * Copyright (c) 2011 by Thomas Forbriger (BFO Schiltach) 
 * 
 * REVISIONS and CHANGES 
 *  - 06/05/2011   V1.0   Thomas Forbriger
16
 *  - 08/09/2011   V1.1   support format modifiers
thomas.forbriger's avatar
thomas.forbriger committed
17 18 19 20
 * 
 * ============================================================================
 */
#define SOUTIFU_VERSION \
21
  "SOUTIFU   V1.1   inversion for source time function"
thomas.forbriger's avatar
thomas.forbriger committed
22 23 24 25
#define SOUTIFU_CVSID \
  "$Id$"

#include <iostream>
26 27
#include <fstream>
#include <tfxx/error.h>
thomas.forbriger's avatar
thomas.forbriger committed
28
#include <tfxx/commandline.h>
29 30
#include <tsxx/sffheaders.h>
#include <datrwxx/readany.h>
31
#include <datrwxx/writeany.h>
32 33 34
#include <stfinv/stfinvany.h>

/*----------------------------------------------------------------------*/
thomas.forbriger's avatar
thomas.forbriger committed
35 36 37 38 39

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

thomas.forbriger's avatar
thomas.forbriger committed
40 41 42 43
/*----------------------------------------------------------------------*/
// debug helper
#define PAROUT( par ) cout << #par << "=" << par << " ";

44 45 46 47 48 49
/*----------------------------------------------------------------------*/
// 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
50
  return(reldif<=(std::abs(b*eps)));
51 52
}

53 54 55 56 57
/*----------------------------------------------------------------------*/

struct Options {
  bool verbose, debug, overwrite;
  bool writestf, writeconvolved;
thomas.forbriger's avatar
thomas.forbriger committed
58
  std::string stffilename, convolvedfilename, debuglevel;
59
  std::string datafileformat, outputfileformat;
60 61 62 63
}; // struct Options

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

thomas.forbriger's avatar
thomas.forbriger committed
64 65 66 67 68 69 70
int main(int iargc, char* argv[])
{

  // define usage information
  char usage_text[]=
  {
    SOUTIFU_VERSION "\n"
71
    "usage: soutifu [-v] [-o] [-wc f] [-ws f] [--type f] [--Type f]\n"
thomas.forbriger's avatar
thomas.forbriger committed
72
    "               [-DEBUG=level]\n"
73
    "               parameters data synthetics" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
74
    "   or: soutifu --help|-h" "\n"
75
    "   or: soutifu --xhelp" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
76 77 78 79 80
  };

  // define full help text
  char help_text[]=
  {
81 82 83 84 85 86 87 88 89 90 91 92 93
    SOUTIFU_CVSID "\n"
    "\n"
    "Calculate optimized source time function to minimize misfit\n"
    "between recorded data and synthetic waveforms.\n"
    "\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"
    "-v           be verbose\n"
thomas.forbriger's avatar
thomas.forbriger committed
94
    "-DEBUG=level produce debug output at level \"level\"\n"
95
    "-o           overwrite existing output files\n"
96 97 98 99
    "--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"
100 101
    "-wc f        write convolved synthetics to file \"f\"\n"
    "-ws f        write source time function to file \"f\"\n"
102 103 104 105
    "\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
106 107 108 109 110 111 112 113 114 115
  };

  // define commandline options
  using namespace tfxx::cmdline;
  static Declare options[]= 
  {
    // 0: print help
    {"help",arg_no,"-"},
    // 1: verbose mode
    {"v",arg_no,"-"},
116 117 118 119 120 121 122 123 124 125
    // 2: overwrite mode
    {"o",arg_no,"-"},
    // 3: file format
    {"type",arg_yes,"sff"},
    // 4: name of convolved synthetics
    {"wc",arg_yes,"-"},
    // 5: name of source time function
    {"ws",arg_yes,"-"},
    // 6: present full details
    {"xhelp",arg_no,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
126 127
    // 7: present full details
    {"DEBUG",arg_yes,"0"},
128 129
    // 8: file format
    {"Type",arg_yes,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143
    {NULL}
  };

  // no arguments? print usage...
  if (iargc<2) 
  {
    cerr << usage_text << endl;
    exit(0);
  }

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

  // help requested? print full help text...
144
  if (cmdline.optset(0) || cmdline.optset(6))
thomas.forbriger's avatar
thomas.forbriger committed
145 146 147
  {
    cerr << usage_text << endl;
    cerr << help_text << endl;
148 149 150 151 152 153
    datrw::supported_input_data_types(cerr);
    if (cmdline.optset(6)) { datrw::online_help(cerr); }
    cerr << endl;
    stfinv::STFEngine::help(cerr);
    cerr << endl;
    if (cmdline.optset(6)) { stfinv::help(cerr); }
thomas.forbriger's avatar
thomas.forbriger committed
154 155 156
    exit(0);
  }

157 158 159 160 161
  /*----------------------------------------------------------------------*/
  // read options and parameters
  Options opt;
  opt.verbose=cmdline.optset(1);
  opt.overwrite=cmdline.optset(2);
162
  opt.datafileformat=cmdline.string_arg(3);
163 164 165 166
  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
167 168
  opt.debug=cmdline.optset(7);
  opt.debuglevel=cmdline.string_arg(7);
169 170
  opt.outputfileformat=opt.datafileformat;
  if (cmdline.optset(8)) { opt.outputfileformat=cmdline.optset(8); }
171 172 173 174 175 176 177 178 179 180 181 182 183 184

  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
  // ---------------
185
  typedef aff::Series<float> Tseries;
186 187 188 189 190 191 192
  typedef ts::sff::File<Tseries> Tfile;
  Tfile recordeddata;
  Tfile syntheticdata;

  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
193
  {
194 195 196
    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
197 198
  }

199 200 201 202 203 204
  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);
  }
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

  // 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
    Tfile::Ttracevector::Ttimeseries cstseries(rdtseries.shape());
    cstseries.Mtraceindex=sdtseries.Mtraceindex;
    cstseries.header=sdtseries.header;

    // 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
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    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;
    }
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
    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)
    {
      Tfile::Ttracevector::Ttimeseries stftseries(tracetriple.data.shape()); 

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

thomas.forbriger's avatar
thomas.forbriger committed
323 324 325 326 327 328 329 330
      ::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);
331 332 333 334 335 336 337 338 339 340 341 342 343

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

  } // for (unsigned int itrace=0; itrace<ntraces; ++itrace)
  
  // create STF engine
  // -----------------
  if (opt.verbose) 
  {
    parameters += ":verbose";
    cout << "create STF engine" << endl; 
  }
thomas.forbriger's avatar
thomas.forbriger committed
344
  if (opt.debug) { parameters += ":DEBUG="+opt.debuglevel; }
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  stfinv::STFEngine engine(vectoroftriples, stfwaveform, parameters);

  // 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
367
      =datrw::oanystream::openmode(opt.outputfileformat);
368
    std::ofstream ofs(opt.stffilename.c_str(), oopenmode);
369
    datrw::oanystream os(ofs, opt.outputfileformat, opt.debug);
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    
    os << stffile.fileheader.srce();
    for (unsigned int itrace=0; itrace<stffile.size(); ++itrace)
    {
      os << stffile[itrace].header.wid2();
      os << stffile[itrace].header.info();
      os << stffile[itrace].series();
    }
  } // 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
393
      =datrw::oanystream::openmode(opt.outputfileformat);
394
    std::ofstream ofs(opt.convolvedfilename.c_str(), oopenmode);
395
    datrw::oanystream os(ofs, opt.outputfileformat, opt.debug);
396 397 398 399 400 401 402 403 404 405
    
    os << convolvedsynthetics.fileheader.srce();
    for (unsigned int itrace=0; itrace<convolvedsynthetics.size(); ++itrace)
    {
      os << convolvedsynthetics[itrace].header.wid2();
      os << convolvedsynthetics[itrace].header.info();
      os << convolvedsynthetics[itrace].series();
    }
  } // if (opt.writeconvolved)
} // main
thomas.forbriger's avatar
thomas.forbriger committed
406 407

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