sigfit.cc 12.9 KB
Newer Older
thomas.forbriger's avatar
thomas.forbriger committed
1
2
3
4
5
/*! \file sigfit.cc
 * \brief fit signal by trial-signals
 * 
 * ----------------------------------------------------------------------------
 * 
thomas.forbriger's avatar
thomas.forbriger committed
6
 * $Id: sigfit.cc,v 1.10 2004-02-24 16:02:47 tforb Exp $
thomas.forbriger's avatar
thomas.forbriger committed
7
8
9
10
11
12
13
14
15
 * \author Thomas Forbriger
 * \date 28/01/2004
 * 
 * fit signal by trial-signals
 * 
 * Copyright (c) 2004 by Thomas Forbriger (BFO Schiltach) 
 * 
 * REVISIONS and CHANGES 
 *  - 28/01/2004   V1.0   Thomas Forbriger
thomas.forbriger's avatar
thomas.forbriger committed
16
17
 *  - 24/02/2004   V1.1   introduced search range stabilization
 *                        more output values
thomas.forbriger's avatar
thomas.forbriger committed
18
19
20
21
 * 
 * ============================================================================
 */
#define SIGFIT_VERSION \
thomas.forbriger's avatar
thomas.forbriger committed
22
  "SIGFIT   V1.1   fit signal by trial-signals"
thomas.forbriger's avatar
thomas.forbriger committed
23
#define SIGFIT_CVSID \
thomas.forbriger's avatar
thomas.forbriger committed
24
  "$Id: sigfit.cc,v 1.10 2004-02-24 16:02:47 tforb Exp $"
thomas.forbriger's avatar
thomas.forbriger committed
25
26
27
28
29
30

#include <fstream>
#include <iostream>
#include <list>
#include <vector>
#include <tfxx/commandline.h>
thomas.forbriger's avatar
thomas.forbriger committed
31
#include <tfxx/error.h>
thomas.forbriger's avatar
thomas.forbriger committed
32
#include <sffxx.h>
33
34
#include <sffostream.h>
#include <tsxx/tsxx.h>
thomas.forbriger's avatar
thomas.forbriger committed
35
36
37
#include <tsxx/innerproduct.h>
#include <aff/array.h>
#include <aff/dump.h>
38
#include <aff/seriesoperators.h>
39
#include <linearxx/lapackxx.h>
thomas.forbriger's avatar
thomas.forbriger committed
40
41

typedef std::list<std::string> Tnamelist;
42
typedef ts::TDsfftimeseries Tbundle;
thomas.forbriger's avatar
thomas.forbriger committed
43
44
typedef Tbundle::Tseries Tseries;
typedef std::vector<Tbundle> Tbundlevec;
thomas.forbriger's avatar
thomas.forbriger committed
45
typedef aff::Array<Tbundle::Tseries::Tvalue> Tmatrix;
thomas.forbriger's avatar
thomas.forbriger committed
46
47
48
49
50
51
52
53

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

// structure to store commandline options
struct Options {
  bool verbose;
thomas.forbriger's avatar
thomas.forbriger committed
54
  double Tdate;
thomas.forbriger's avatar
thomas.forbriger committed
55
  bool truncate;
thomas.forbriger's avatar
thomas.forbriger committed
56
57
  std::string residualname;
  bool writeresidual;
thomas.forbriger's avatar
thomas.forbriger committed
58
59
  double searchrange;
  bool usesearchrange;
thomas.forbriger's avatar
thomas.forbriger committed
60
61
}; // struct Options

thomas.forbriger's avatar
thomas.forbriger committed
62
63
64
65
66
67
68
69
// formatted number output
std::string formatfloat(const double &v)
{
  char seq[20];
  std::sprintf(seq, "%8.5f ", v);
  return(std::string(seq));
}

thomas.forbriger's avatar
thomas.forbriger committed
70
71
72
73
74
75
76
int main(int iargc, char* argv[])
{

  // define usage information
  char usage_text[]=
  {
    SIGFIT_VERSION "\n"
thomas.forbriger's avatar
thomas.forbriger committed
77
    "usage: sigfit [-v] [-Tdate v] [-truncate]" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
78
    "              [-searchrange[=r]]" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
79
    "              signal trial [trial ...]" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
80
81
82
83
84
85
86
87
88
89
90
    "   or: sigfit --help|-h" "\n"
  };

  // define full help text
  char help_text[]=
  {
    SIGFIT_CVSID "\n"
    "\n"
    "-v           be verbose" "\n"
    "-Sramp       add a ramp to the set of trial signals" "\n"
    "-Sconst      add a constant to the set of trial signals" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
91
92
    "-Tdate v     tolerance for comparison of date of first sample" "\n"
    "             v give the tolerance in units of the sampling interval" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
93
    "-truncate    truncate all series to the same number of samples" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
94
    "-residual f  write waveforms containing residual to file \"f\"" "\n"   
thomas.forbriger's avatar
thomas.forbriger committed
95
96
97
98
99
    "-searchrange[=r] set search range to stabilize the fit in cases" "\n"
    "             where a trial series does not (or almost not)" "\n"
    "             contribute to the signal" "\n"
    "             the search range r is given in units of" "\n"
    "             rms(signal)/rms(trial signals)" "\n"
thomas.forbriger's avatar
thomas.forbriger committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    "\n"
    "signal       signal to by explained by a linear combination" "\n"
    "             of trial signals" "\n"
    "trial        any set of trial signals"
  };

  // define commandline options
  using namespace tfxx::cmdline;
  static Declare options[]= 
  {
    // 0: print help
    {"help",arg_no,"-"},
    // 1: verbose mode
    {"v",arg_no,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
114
    // 2: date tolerance
thomas.forbriger's avatar
thomas.forbriger committed
115
    {"Tdate",arg_yes,"0."},
thomas.forbriger's avatar
thomas.forbriger committed
116
117
    // 3: truncate to a common number of samples
    {"truncate",arg_no,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
118
119
    // 4: output SFF file
    {"residual",arg_yes,"-"},
thomas.forbriger's avatar
thomas.forbriger committed
120
121
    // 5: search range
    {"searchrange",arg_opt,"100."},
thomas.forbriger's avatar
thomas.forbriger committed
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
    {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...
  if (cmdline.optset(0))
  {
    cerr << usage_text << endl;
    cerr << help_text << endl;
    exit(0);
  }

/*
  // dummy operation: print option settings
  for (int iopt=0; iopt<2; iopt++)
  {
    cout << "option: '" << options[iopt].opt_string << "'" << endl;
    if (cmdline.optset(iopt)) {  cout << "  option was set"; }
    else { cout << "option was not set"; }
    cout << endl;
    cout << "  argument (string): '" << cmdline.string_arg(iopt) << "'" << endl;
    cout << "     argument (int): '" << cmdline.int_arg(iopt) << "'" << endl;
    cout << "    argument (long): '" << cmdline.long_arg(iopt) << "'" << endl;
    cout << "   argument (float): '" << cmdline.float_arg(iopt) << "'" << endl;
    cout << "  argument (double): '" << cmdline.double_arg(iopt) << "'" << endl;
    cout << "    argument (bool): '";
    if (cmdline.bool_arg(iopt))
    { cout << "true"; } else { cout << "false"; }
    cout << "'" << endl;
  }
  while (cmdline.extra()) { cout << cmdline.next() << endl; }

  // dummy operation: print rest of command line
  while (cmdline.extra()) { cout << cmdline.next() << endl; }
*/

  // read options
  Options opt;
  opt.verbose=cmdline.optset(1);
thomas.forbriger's avatar
thomas.forbriger committed
170
  opt.Tdate=cmdline.double_arg(2);
thomas.forbriger's avatar
thomas.forbriger committed
171
  opt.truncate=cmdline.optset(3);
thomas.forbriger's avatar
thomas.forbriger committed
172
173
  opt.writeresidual=cmdline.optset(4);
  opt.residualname=cmdline.string_arg(4);
thomas.forbriger's avatar
thomas.forbriger committed
174
175
  opt.usesearchrange=cmdline.optset(5);
  opt.searchrange=cmdline.double_arg(5);
thomas.forbriger's avatar
thomas.forbriger committed
176

thomas.forbriger's avatar
thomas.forbriger committed
177
178
  /*----------------------------------------------------------------------*/

thomas.forbriger's avatar
thomas.forbriger committed
179
  // read file names
thomas.forbriger's avatar
thomas.forbriger committed
180
181
182
183
  TFXX_assert(cmdline.extra(),"ERROR: missing signal file name!");
  std::string signalname=cmdline.next();

  TFXX_assert(cmdline.extra(),"ERROR: missing trial signal file name!");
thomas.forbriger's avatar
thomas.forbriger committed
184
185
186
  Tnamelist namelist;
  while (cmdline.extra()) { namelist.push_back(cmdline.next()); }

thomas.forbriger's avatar
thomas.forbriger committed
187
188
189
190
191
192
193
194
195
196
197
198
  // read signal file
  Tbundle signal;
  {
    if (opt.verbose)
    { cout << "read signal file \"" << signalname << "\"" << endl; }
    std::ifstream is(signalname.c_str());
    sff::FileHeader fileheader(is);
    if (opt.verbose)
    { cout << "  read trace" << endl; }
    sff::InputWaveform<Tseries> inputwaveform(is);
    sff::TraceHeader traceheader=inputwaveform.header();
    signal.header=traceheader.wid2();
199
    signal=inputwaveform.series();
thomas.forbriger's avatar
thomas.forbriger committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    bool last=traceheader.last();
    std::string wid2line=signal.header.line();
    if (opt.verbose)
    { 
      cout << "  " << wid2line.substr(0,69) << endl; 
      if (!last)
      {
        cout << "there are more traces in that files" << endl 
          << "ignoring them..." << endl;
      }
    }
  }
  
  // read trial files
thomas.forbriger's avatar
thomas.forbriger committed
214
  if (opt.verbose)
thomas.forbriger's avatar
thomas.forbriger committed
215
  { cout << namelist.size() << " trial data files to read" << endl; }
thomas.forbriger's avatar
thomas.forbriger committed
216
217
218
219
  Tbundlevec bundlevec;
  for (Tnamelist::const_iterator i=namelist.begin(); i!=namelist.end(); i++)
  {
    if (opt.verbose)
thomas.forbriger's avatar
thomas.forbriger committed
220
    { cout << "read trial data file \"" << *i << "\"" << endl; }
thomas.forbriger's avatar
thomas.forbriger committed
221
222
223
224
225
226
    std::ifstream is(i->c_str());
    sff::FileHeader fileheader(is);
    bool last=false;
    while(!last)
    {
      if (opt.verbose)
thomas.forbriger's avatar
thomas.forbriger committed
227
      { cout << "  read trial signal #" << bundlevec.size()+1 << endl; }
thomas.forbriger's avatar
thomas.forbriger committed
228
229
230
231
      sff::InputWaveform<Tseries> inputwaveform(is);
      sff::TraceHeader traceheader=inputwaveform.header();
      Tbundle bundle;
      bundle.header=traceheader.wid2();
232
      bundle=inputwaveform.series();
thomas.forbriger's avatar
thomas.forbriger committed
233
234
235
236
237
238
239
      bundlevec.push_back(bundle);
      last=traceheader.last();
      std::string wid2line=bundle.header.line();
      if (opt.verbose)
      { cout << "  " << wid2line.substr(0,69) << endl; }
    }
  }
thomas.forbriger's avatar
thomas.forbriger committed
240
241
242

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

thomas.forbriger's avatar
thomas.forbriger committed
243
244
245
246
  // truncate length if requested
  if (opt.truncate)
  {
    if (opt.verbose) { cout << "truncate signals if necessary..." << endl; }
247
    long int n=signal.last();
thomas.forbriger's avatar
thomas.forbriger committed
248
249
    for (Tbundlevec::const_iterator i=bundlevec.begin(); 
         i!=bundlevec.end(); i++)
250
251
    { n=n<i->last() ? n : i->last(); }
    if (signal.last()>n)
thomas.forbriger's avatar
thomas.forbriger committed
252
    {
253
254
      signal.setlastindex(n);
      signal.header.nsamples=signal.size();
thomas.forbriger's avatar
thomas.forbriger committed
255
256
257
258
259
260
      if (opt.verbose) { cout << "truncate signal to "
        << signal.header.nsamples << " samples" << endl; }
    }
    for (Tbundlevec::iterator i=bundlevec.begin(); 
         i!=bundlevec.end(); i++)
    { 
261
      if (i->last()>n)
thomas.forbriger's avatar
thomas.forbriger committed
262
      {
263
264
        i->setlastindex(n);
        i->header.nsamples=signal.size();
thomas.forbriger's avatar
thomas.forbriger committed
265
266
267
268
269
270
271
272
273
        if (opt.verbose) { cout << "truncate trial signal" << endl
          << i->header.line() << endl; }
      }
    }
  }

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

  // check header consistency
thomas.forbriger's avatar
thomas.forbriger committed
274
275
  sff::WID2compare compare(sff::Fnsamples | sff::Fdt | sff::Fdate);
  compare.setdatetolerance(opt.Tdate);
thomas.forbriger's avatar
thomas.forbriger committed
276
277
278
279
280
281
282
283
284
285
286
287
288
  if (opt.verbose) { cout << "checking consistency..." << endl; }
  for (Tbundlevec::const_iterator i=bundlevec.begin(); i!=bundlevec.end(); i++)
  {
    if (!compare (i->header,signal.header))
    {
      cerr << "ERROR: header signature mismatch:" << endl;
      cerr << "signal:" << endl;
      cerr << signal.header.line();
      cerr << "trial signal:" << endl;
      cerr << i->header.line();
      TFXX_abort("baling out...");
    }
  }
thomas.forbriger's avatar
thomas.forbriger committed
289
290

  /*----------------------------------------------------------------------*/
thomas.forbriger's avatar
thomas.forbriger committed
291
  double signalrms=ts::rms(signal);
thomas.forbriger's avatar
thomas.forbriger committed
292
293
294
295
296
  
  // set up system of linear equations
  if (opt.verbose) { cout << "set up system of linear equations..." << endl; }
  int N=bundlevec.size();
  if (opt.verbose) { cout << "system is of size " << N << "x" << N << endl; }
thomas.forbriger's avatar
thomas.forbriger committed
297
  Tmatrix Matrix(N,N), rhs(N), coeff(N), normproduct(N), trialrms(N);
thomas.forbriger's avatar
thomas.forbriger committed
298
299
300
301
  for (int i=1; i<=N; ++i)
  {
    for (int k=i; k<=N; ++k)
    {
302
      Matrix(i,k)=ts::innerproduct(bundlevec[i-1], bundlevec[k-1]);
thomas.forbriger's avatar
thomas.forbriger committed
303
304
      Matrix(k,i)=Matrix(i,k);
    }
305
    rhs(i)=ts::innerproduct(bundlevec[i-1], signal);
thomas.forbriger's avatar
thomas.forbriger committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    trialrms(i)=ts::rms(bundlevec[i-1]);
    normproduct(i)=rhs(i)/(signalrms*trialrms(i)*signal.size());
  }

  // add stabilization
  if (opt.usesearchrange)
  {
    if (opt.verbose) 
    {
      cout << "stabilize fit:" << endl; 
      cout << "  relative search range: " << opt.searchrange << endl;
    }
    double sreachfac=signal.size()*signalrms;
    for (int i=1; i<=N; ++i)
    {
      double range=opt.searchrange*signalrms/trialrms(i);
      if (opt.verbose)
      {
        cout << "  search range for trial series " << i 
          << " is " << range << endl;
      }
      Matrix(i,i)+=pow((range/sreachfac),2);
    }
thomas.forbriger's avatar
thomas.forbriger committed
329
  }
330

331
  // solve
332
  coeff=linear::lapack::dposv(Matrix,rhs);
333
334
335

  // set up synthetics
  Tbundle synthetics;
336
337
  synthetics=Tseries(signal.shape());
  synthetics.series()=0.;
338
  for (int i=1; i<=N; ++i)
339
  { synthetics += coeff(i) * bundlevec[i-1]; }
340
341
342
343
344
  synthetics.header=signal.header;
  synthetics.header.channel="synt";

  // set up residual
  Tbundle residual;
345
346
  residual=Tseries(signal.shape());
  residual=signal-synthetics;
347
348
  residual.header=signal.header;
  residual.header.channel="diff";
thomas.forbriger's avatar
thomas.forbriger committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365

  // write waveforms
  if (opt.writeresidual)
  {
    if (opt.verbose) 
    {
      cout << "write residual waveform to " 
      << opt.residualname << endl;
    }
    std::ofstream ofs(opt.residualname.c_str());
    sff::SFFostream<Tseries> os(ofs);
    os << signal;
    os << synthetics;
    os << residual;
    for (Tbundlevec::const_iterator i=bundlevec.begin(); 
         i!=bundlevec.end(); i++)
    { os << *i; }
thomas.forbriger's avatar
thomas.forbriger committed
366
367
368
369
370
371
372
373
374
    for (int i=1; i<=N; ++i)
    {
      Tbundle psyn=bundlevec[i-1];
      psyn=bundlevec[i-1].series()*coeff(i);
      char chan[6];
      std::sprintf(chan,"s%1.1d", i);
      psyn.header.channel=std::string(chan);
      os << psyn;
    }
thomas.forbriger's avatar
thomas.forbriger committed
375
  }
376
377
  
  // calculate rms values
378
  double residualrms=ts::rms(residual);
thomas.forbriger's avatar
thomas.forbriger committed
379
  double explained=1.-(residualrms/signalrms);
thomas.forbriger's avatar
thomas.forbriger committed
380
381
382
383
384
385
386
387
388

  // calculate direction cosines
  Tmatrix normcoeff(N);
  double length=0.;
  for (int i=1; i<=N; ++i)
  { length += coeff(i)*coeff(i); }
  length=sqrt(length);
  for (int i=1; i<=N; ++i)
  { normcoeff(i) = coeff(i)/length; }
389
  
thomas.forbriger's avatar
thomas.forbriger committed
390
391
392
393
  std::string timestring(signal.header.date.timestring());
  cout << "         time: " << timestring.substr(4,21) << endl;
  cout << "      channel: " << signal.header.channel << endl;
  cout << "      station: " << signal.header.station << endl;
thomas.forbriger's avatar
thomas.forbriger committed
394
  cout << "   instrument: " << signal.header.instype << endl;
thomas.forbriger's avatar
thomas.forbriger committed
395
396
397
398
  cout << "    signalrms: " << signalrms << endl;
  cout << "  residualrms: " << residualrms << endl;
  cout << "explained rms: " << explained << endl;
  cout << " coefficients: ";
399
400
401
  for (int i=1; i<=N; ++i)
  { cout << coeff(i) << "  "; }
  cout << endl;
thomas.forbriger's avatar
thomas.forbriger committed
402
403
404
405
406
  cout << " rms coeffic.: " << length << endl;
  cout << " normalized coefficients: ";
  for (int i=1; i<=N; ++i)
  { cout << normcoeff(i) << "  "; }
  cout << endl;
thomas.forbriger's avatar
thomas.forbriger committed
407
408
409
  cout << " coefficients x rms: ";
  for (int i=1; i<=N; ++i)
  { 
thomas.forbriger's avatar
thomas.forbriger committed
410
411
412
413
414
415
416
    cout << coeff(i)*trialrms(i) << "  "; 
  }
  cout << endl;
  cout << " normalized scalar product: ";
  for (int i=1; i<=N; ++i)
  { 
    cout << normproduct(i) << "  "; 
thomas.forbriger's avatar
thomas.forbriger committed
417
418
  }
  cout << endl;
419

thomas.forbriger's avatar
thomas.forbriger committed
420
421
422
  // reportline
  cout << signal.header.station << " "
    << signal.header.channel << " "
thomas.forbriger's avatar
thomas.forbriger committed
423
    << signal.header.instype << " "
thomas.forbriger's avatar
thomas.forbriger committed
424
425
426
427
428
429
430
431
    << timestring << " ";
  cout << formatfloat(explained);
  cout << formatfloat(signalrms);
  cout << formatfloat(residualrms);
  for (int i=1; i<=N; ++i)
  { 
    cout << formatfloat(coeff(i));
  }
thomas.forbriger's avatar
thomas.forbriger committed
432
433
434
435
436
437
438
439
440
  cout << formatfloat(length);
  for (int i=1; i<=N; ++i)
  { 
    cout << formatfloat(normcoeff(i));
  }
  for (int i=1; i<=N; ++i)
  { 
    cout << formatfloat(coeff(i)*trialrms(i)); 
  }
thomas.forbriger's avatar
thomas.forbriger committed
441
442
  for (int i=1; i<=N; ++i)
  { 
thomas.forbriger's avatar
thomas.forbriger committed
443
    cout << formatfloat(normproduct(i)); 
thomas.forbriger's avatar
thomas.forbriger committed
444
  }
thomas.forbriger's avatar
thomas.forbriger committed
445
  cout << endl;
thomas.forbriger's avatar
thomas.forbriger committed
446
447
448
}

/* ----- END OF sigfit.cc ----- */