Blame view

optics/material.h 16.2 KB
f1402849   dmayerich   renewed commit
1
2
3
4
5
6
7
8
9
10
  #ifndef MATERIALSTRUCT_H
  #define MATERIALSTRUCT_H
  
  #include <vector>
  #include <ostream>
  #include <iostream>
  #include <fstream>
  #include <complex>
  #include <algorithm>
  #include <sstream>
cc8715ef   dmayerich   organization
11
  #include "rts/math/complex.h"
7006df5f   David Mayerich   reformat of direc...
12
  #include "rts/math/function.h"
f1402849   dmayerich   renewed commit
13
  
3b012a80   David Mayerich   added code for co...
14
  #define PI  3.14159f
f1402849   dmayerich   renewed commit
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
  
  namespace rts{
  
      enum field_type {field_microns, field_wavenumber, field_n, field_k, field_A, field_ignore};
  
      //conversion functions
  
      //convert wavenumber to lambda
      template <class T>
      static T _wn(T inverse_cm)
      {
          return (T)10000.0/inverse_cm;
      }
  
      template <class T>
      static T _2wn(T lambda)
      {
          return (T)10000.0/lambda;
      }
  
      //convert absorbance to k
      template <class T>
      static T _A(T absorbance, T lambda)
      {
          return (absorbance * lambda) / (4 * PI);
      }
  	template <class T>
  	static T _2A(T k, T lambda)
  	{
  		return (4 * PI * k)/lambda;
  	}
  
      //define the dispersion as a single wavelength/refractive index pair
      template <class T>
      struct refIndex
      {
          //wavelength (in microns)
          T lambda;
7006df5f   David Mayerich   reformat of direc...
53
          complex<T> n;
f1402849   dmayerich   renewed commit
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
      };
  
      template <class T>
      struct entryType
      {
          //list of value types per entry
          std::vector<field_type> valueList;
  
          entryType(std::string format)
          {
              //location of the end of a parameter
              size_t e;
  
              //string storing a token
              std::string token;
  
              do
              {
                  //find the end of the first parameter
                  e = format.find_first_of(',');
  
                  //get the substring up to the comma
                  token = format.substr(0, e);
  
                  //turn the token into a val_type
                  if(token == "microns")
                      valueList.push_back(field_microns);
                  else if(token == "wavenumber")
                      valueList.push_back(field_wavenumber);
                  else if(token == "n")
                      valueList.push_back(field_n);
                  else if(token == "k")
                      valueList.push_back(field_k);
                  else if(token == "A")
                      valueList.push_back(field_A);
                  else
                      valueList.push_back(field_ignore);
  
                  //remove the first token from the format string
                  format = format.substr(e+1, format.length()-1);
              }while(e != std::string::npos);
  
  
  
          }
  
          void addValue(field_type value)
          {
              valueList.push_back(value);
          }
  
          refIndex<T> inputEntry(std::string line, T scaleA = 1.0)
          {
              T val;
              std::stringstream ss(line);
  
              //create a new refractive index
              refIndex<T> newRI;
  
  
              //read the entry from an input string
7006df5f   David Mayerich   reformat of direc...
115
              for(unsigned int i=0; i<valueList.size(); i++)
f1402849   dmayerich   renewed commit
116
              {
0174d823   dmayerich   bug fixes and exits
117
  
7006df5f   David Mayerich   reformat of direc...
118
  
0174d823   dmayerich   bug fixes and exits
119
120
121
122
123
124
                  while(ss.peek() < '0' || ss.peek() > '9')
                  {
                      //cout<<"bad char"<<endl;
                      ss.ignore();
                  }
  
f1402849   dmayerich   renewed commit
125
126
                  //retrieve the value
                  ss>>val;
0174d823   dmayerich   bug fixes and exits
127
                  //cout<<val<<endl;
f1402849   dmayerich   renewed commit
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
  
                  //store the value in the appropriate location
                  switch(valueList[i])
                  {
                      case field_microns:
                          newRI.lambda = val;
                          break;
                      case field_wavenumber:
                          newRI.lambda = _wn(val);
                          break;
                      case field_n:
                          newRI.n.real(val);
                          break;
                      case field_k:
                          newRI.n.imag(val);
                          break;
                      case field_A:
                          newRI.n.imag(_A(val * scaleA, newRI.lambda));
                          break;
3b012a80   David Mayerich   added code for co...
147
148
  		    default:
  			break;
f1402849   dmayerich   renewed commit
149
150
151
152
153
154
155
156
157
158
159
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
                  }
              }
  
              //return the refractive index associated with the entry
              return newRI;
  
          }
  
  		std::string outputEntry(refIndex<T> material)
  		{
  			//std::string result;
  			std::stringstream ss;
  
  			//for each field in the entry
  			for(int i=0; i<valueList.size(); i++)
  			{
  				if(i > 0)
  					ss<<"\t";
  				//store the value in the appropriate location
                  switch(valueList[i])
                  {
                      case field_microns:
                          ss<<material.lambda;
                          break;
                      case field_wavenumber:
                          ss<<_2wn(material.lambda);
                          break;
                      case field_n:
                          ss<<material.n.real();
                          break;
                      case field_k:
                          ss<<material.n.imag();
                          break;
                      case field_A:
                          ss<<_2A(material.n.imag(), material.lambda);
                          break;
                  }
  
  			}
  			return ss.str();
  		}
  
  
      };
  
  
      //a material is a list of refractive index values
      template <class T>
      class material
      {
0174d823   dmayerich   bug fixes and exits
199
  		std::string name;
f1402849   dmayerich   renewed commit
200
          //dispersion (refractive index as a function of wavelength)
7006df5f   David Mayerich   reformat of direc...
201
202
          //std::vector< refIndex<T> > dispersion;
  		function< T, complex<T> > dispersion;
f1402849   dmayerich   renewed commit
203
204
205
206
  
          //average refractive index (approximately 1.4)
          T n0;
  
7006df5f   David Mayerich   reformat of direc...
207
          /*void add(refIndex<T> ri)
f1402849   dmayerich   renewed commit
208
209
210
          {
              //refIndex<T> converted = convert(ri, measurement);
              dispersion.push_back(ri);
7006df5f   David Mayerich   reformat of direc...
211
          }*/
a47a23a9   dmayerich   added ENVI functions
212
  
f1402849   dmayerich   renewed commit
213
214
215
216
217
218
219
          //comparison function for sorting
          static bool compare(refIndex<T> a, refIndex<T> b)
          {
              return (a.lambda < b.lambda);
          }
  
          //comparison function for searching lambda
7006df5f   David Mayerich   reformat of direc...
220
          /*static bool findCeiling(refIndex<T> a, refIndex<T> b)
f1402849   dmayerich   renewed commit
221
222
          {
              return (a.lambda > b.lambda);
7006df5f   David Mayerich   reformat of direc...
223
          }*/
f1402849   dmayerich   renewed commit
224
225
  
  	public:
7006df5f   David Mayerich   reformat of direc...
226
227
228
229
230
  		void add(T lambda, complex<T> n)
          {
              dispersion.insert(lambda, n);
          }
  
0174d823   dmayerich   bug fixes and exits
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
  		std::string getName()
  		{
  			return name;
  		}
  		void setName(std::string n)
  		{
              name = n;
  		}
  		T getN0()
  		{
  			return n0;
  		}
  		void setN0(T n)
  		{
              n0 = n;
  		}
7006df5f   David Mayerich   reformat of direc...
247
248
249
250
251
  
  		void setM(function< T, complex<T> > m)
  		{
  			dispersion = m;
  		}
f1402849   dmayerich   renewed commit
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
          unsigned int nSamples()
          {
              return dispersion.size();
          }
  		material<T> computeN(T _n0, unsigned int n_samples = 0, T pf = 2)
  		{
  			/*	This function computes the real part of the refractive index
  				from the imaginary part.  The Hilbert transform is required. I
  				use an FFT in order to simplify this, so either the FFTW or CUFFT
  				packages are required.  CUFFT is used if this file is passed through
  				a CUDA compiler.  Otherwise, FFTW is used if available.
  			*/
  
  			n0 = _n0;
  
              int N;
              if(n_samples)
                  N = n_samples;
              else
                  N = dispersion.size();
  
  
  #ifdef FFTW_AVAILABLE
  			//allocate memory for the FFT
7006df5f   David Mayerich   reformat of direc...
276
277
278
  			complex<T>* Chi2 = (complex<T>*)fftw_malloc(sizeof(complex<T>) * N * pf);
  			complex<T>* Chi2FFT = (complex<T>*)fftw_malloc(sizeof(complex<T>) * N * pf);
  			complex<T>* Chi1 = (complex<T>*)fftw_malloc(sizeof(complex<T>) * N * pf);
f1402849   dmayerich   renewed commit
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
  
  			//create an FFT plan for the forward and inverse transforms
  			fftw_plan planForward, planInverse;
  			planForward = fftw_plan_dft_1d(N*pf, (fftw_complex*)Chi2, (fftw_complex*)Chi2FFT, FFTW_FORWARD, FFTW_ESTIMATE);
  			planInverse = fftw_plan_dft_1d(N*pf, (fftw_complex*)Chi2FFT, (fftw_complex*)Chi1, FFTW_BACKWARD, FFTW_ESTIMATE);
  
  			float k, alpha;
  			T chi_temp;
  
              //the spectrum will be re-sampled in uniform values of wavenumber
  			T nuMin = _2wn(dispersion.back().lambda);
  			T nuMax = _2wn(dispersion.front().lambda);
  			T dnu = (nuMax - nuMin)/(N-1);
  			T lambda, tlambda;
  			for(int i=0; i<N; i++)
  			{
                  //go from back-to-front (wavenumber is the inverse of wavelength)
                  lambda = _wn(nuMax - i * dnu);
  
  				//compute the frequency
  				k = 2 * PI / (lambda);
  
  				//get the absorbance
  				alpha = getN(lambda).imag() * (2 * k);
  
  				//compute chi2
  				Chi2[i] = -alpha * (n0 / k);
  			}
  
  			//use linear interpolation between the start and end points to pad the spectrum
7006df5f   David Mayerich   reformat of direc...
309
310
  			//complex<T> nMin = dispersion.back();
  			//complex<T> nMax = dispersion.front();
f1402849   dmayerich   renewed commit
311
312
313
314
315
316
317
318
319
320
321
322
323
  			T a;
  			for(int i=N; i<N*pf; i++)
  			{
                  //a = (T)(i-N)/(T)(N*pf - N);
                  //Chi2[i] = a * Chi2[0] + ((T)1 - a) * Chi2[N-1];
  
                  Chi2[i] = 0.0;//Chi2[N-1];
  			}
  
  			//perform the FFT
  			fftw_execute(planForward);
  
  			//perform the Hilbert transform in the Fourier domain
7006df5f   David Mayerich   reformat of direc...
324
  			complex<T> j(0, 1);
f1402849   dmayerich   renewed commit
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
  			for(int i=0; i<N*pf; i++)
  			{
                  //if w = 0, set the DC component to zero
                  if(i == 0)
                      Chi2FFT[i] *= (T)0.0;
                  //if w <0, multiply by i
                  else if(i < N*pf/2.0)
                      Chi2FFT[i] *= j;
                  //if i > N/2, multiply by -i
                  else
                      Chi2FFT[i] *= -j;
  			}
  
  			//execute the inverse Fourier transform (completing the Hilbert transform)
  			fftw_execute(planInverse);
  
  			//divide the Chi1 values by N
  			for(int i=0; i<N*pf; i++)
  				Chi1[i] /= (T)(N*pf);
  
  			//create a new material
  			material<T> newM;
  			newM.dispersion.clear();
  			refIndex<T> ri;
  			for(int i=0; i<N; i++)
  			{
                  ri.lambda = _wn(nuMax - i * dnu);
                  ri.n.real(Chi1[i].real() / (2 * n0) + n0);
                  ri.n.imag(getN(ri.lambda).imag());
  
                  newM.dispersion.push_back(ri);
              }
  
  
              //dispersion[i].n.real(Chi1[i].real() / (2 * n0) + n0);
  
  
  			/*//output the Absorbance value
  			ofstream outOrig("origN.txt");
  			for(int i=0; i<N; i++)
  				outOrig<<dispersion[i].lambda<<"     "<<dispersion[i].n.real()<<endl;
  
  			//output the Chi2 value
  			ofstream outChi2("chi2.txt");
  			for(int i=0; i<N; i++)
  				outChi2<<dispersion[i].lambda<<"     "<<Chi2[i].real()<<endl;
  
  			//output the Fourier transform
  			ofstream outFFT("chi2_FFT.txt");
  			for(int i=0; i<N; i++)
  			{
  			float mag = std::sqrt( std::pow(Chi2FFT[i].real(), 2.0) + std::pow(Chi2FFT[i].imag(), 2.0));
  				outFFT<<dispersion[i].lambda<<"     "<<mag<<endl;
  			}
  
  			//output the computed Chi1 value
  			ofstream outChi1("chi1.txt");
  			for(int i=0; i<N; i++)
  			{
  				outChi1<<dispersion[i].lambda<<"     "<<Chi1[i].real()<<"     "<<Chi1[i].imag()<<endl;
  			}
  
  			ofstream outN("n.txt");
  			for(int i=0; i<N; i++)
  				outN<<dispersion[i].lambda<<"     "<<Chi1[i].real() / (2 * n0) + n0<<endl;*/
  
  
  			//de-allocate memory
  			fftw_destroy_plan(planForward);
  			fftw_destroy_plan(planInverse);
  			fftw_free(Chi2);
  			fftw_free(Chi2FFT);
  			fftw_free(Chi1);
  
  			return newM;
0174d823   dmayerich   bug fixes and exits
400
401
  #else
  			std::cout<<"MATERIAL Error: Must have FFTW in order to compute Kramers-Kronig."<<std::endl;
f1402849   dmayerich   renewed commit
402
  			return material<T>();
0174d823   dmayerich   bug fixes and exits
403
  #endif
f1402849   dmayerich   renewed commit
404
405
  		}
  
7a2d0012   David Mayerich   mirst1d updates
406
          material(T lambda = 1, T n = 1, T k = 0)
f1402849   dmayerich   renewed commit
407
          {
7a2d0012   David Mayerich   mirst1d updates
408
  			dispersion.insert(lambda, complex<T>(n, k));
7006df5f   David Mayerich   reformat of direc...
409
              /*//create a default refractive index
f1402849   dmayerich   renewed commit
410
411
412
413
414
              refIndex<T> def;
              def.lambda = lambda;
              def.n.real(n);
              def.n.imag(k);
              add(def);
7006df5f   David Mayerich   reformat of direc...
415
  			*/
f1402849   dmayerich   renewed commit
416
              //set n0
7a2d0012   David Mayerich   mirst1d updates
417
              n0 = 0;
f1402849   dmayerich   renewed commit
418
419
          }
  
a47a23a9   dmayerich   added ENVI functions
420
          material(std::string filename, std::string format = "", T scaleA = 1.0)
f1402849   dmayerich   renewed commit
421
422
          {
              fromFile(filename, format);
0174d823   dmayerich   bug fixes and exits
423
              n0 = 0;
f1402849   dmayerich   renewed commit
424
425
          }
  
a47a23a9   dmayerich   added ENVI functions
426
          void fromFile(std::string filename, std::string format = "", T scaleA = 1.0)
f1402849   dmayerich   renewed commit
427
          {
7006df5f   David Mayerich   reformat of direc...
428
              name = filename;
f1402849   dmayerich   renewed commit
429
              //clear any previous values
7006df5f   David Mayerich   reformat of direc...
430
              dispersion = rts::function< T, complex<T> >();
f1402849   dmayerich   renewed commit
431
432
433
434
435
436
437
438
  
              //load the file into a string
              std::ifstream ifs(filename.c_str());
  
              std::string line;
  
              if(!ifs.is_open())
              {
0174d823   dmayerich   bug fixes and exits
439
                  std::cout<<"Material Error -- file not found: "<<filename<<std::endl;
f1402849   dmayerich   renewed commit
440
441
442
443
444
445
                  exit(1);
              }
  
              //process the file as a string
              std::string instr((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
              fromStr(instr, format, scaleA);
f1402849   dmayerich   renewed commit
446
447
          }
  
a47a23a9   dmayerich   added ENVI functions
448
          void fromStr(std::string str, std::string format = "", T scaleA = 1.0)
f1402849   dmayerich   renewed commit
449
450
451
452
453
454
455
          {
              //create a string stream to process the input data
              std::stringstream ss(str);
  
              //this string will be read line-by-line (where each line is an entry)
              std::string line;
  
a47a23a9   dmayerich   added ENVI functions
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
              //if the format is not provided, see if it is in the file, otherwise use a default
              if(format == "")
              {
                  //set a default format of "lambda,n,k"
                  format = "microns,n,k";
  
                  //see if the first line is a comment
                  char c = ss.peek();
                  if(c == '#')
                  {
                      //get the first line
                      getline(ss, line);
                      //look for a bracket, denoting the start of a format string
                      int istart = line.find('[');
                      if(istart != std::string::npos)
                      {
                          //look for a bracket terminating the format string
                          int iend = line.find(']');
                          if(iend != std::string::npos)
                          {
                              //read the string between the brackets
                              format = line.substr(istart+1, iend - istart - 1);
                          }
                      }
                  }
  
              }
  
f1402849   dmayerich   renewed commit
484
485
              entryType<T> entry(format);
  
0174d823   dmayerich   bug fixes and exits
486
              //std::cout<<"Loading material with format: "<<format<<std::endl;
a47a23a9   dmayerich   added ENVI functions
487
  
f1402849   dmayerich   renewed commit
488
489
490
491
492
493
494
495
496
              while(!ss.eof())
              {
                  //read a line from the string
                  getline(ss, line);
  
                  //if the line is not a comment, process it
                  if(line[0] != '#')
                  {
                      //load the entry and add it to the dispersion list
7006df5f   David Mayerich   reformat of direc...
497
                      add(entry.inputEntry(line, scaleA).lambda, entry.inputEntry(line, scaleA).n);
f1402849   dmayerich   renewed commit
498
499
500
501
502
503
                  }
                  //generally have to peek to trigger the eof flag
                  ss.peek();
              }
  
              //sort the vector by lambda
7006df5f   David Mayerich   reformat of direc...
504
              //sort(dispersion.begin(), dispersion.end(), &material<T>::compare);
f1402849   dmayerich   renewed commit
505
506
507
          }
  
          //convert the material to a string
a47a23a9   dmayerich   added ENVI functions
508
          std::string toStr(std::string format = "microns,n,k", bool reverse_order = false)
f1402849   dmayerich   renewed commit
509
510
511
          {
              std::stringstream ss;
  			entryType<T> entry(format);
a47a23a9   dmayerich   added ENVI functions
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
  
  			if(reverse_order)
  			{
                  for(int l=dispersion.size() - 1; l>=0; l--)
                  {
                      if(l < dispersion.size() - 1) ss<<std::endl;
                      ss<<entry.outputEntry(dispersion[l]);
                  }
  
  			}
  			else
  			{
                  for(unsigned int l=0; l<dispersion.size(); l++)
                  {
                      if(l > 0) ss<<std::endl;
                      ss<<entry.outputEntry(dispersion[l]);
                  }
f1402849   dmayerich   renewed commit
529
530
531
532
533
              }
  
              return ss.str();
          }
  
a47a23a9   dmayerich   added ENVI functions
534
          void save(std::string filename, std::string format = "microns,n,k", bool reverse_order = false)
f1402849   dmayerich   renewed commit
535
          {
a47a23a9   dmayerich   added ENVI functions
536
              std::ofstream outfile(filename.c_str());
f1402849   dmayerich   renewed commit
537
              outfile<<"#material file saved as [" + format + "]"<<std::endl;
a47a23a9   dmayerich   added ENVI functions
538
              outfile<<toStr(format, reverse_order)<<std::endl;
f1402849   dmayerich   renewed commit
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
  
          }
  
          //convert between wavelength and wavenumber
          /*void nu2lambda(T s = (T)1)
          {
              for(int i=0; i<dispersion.size(); i++)
                  dispersion[i].lambda = s/dispersion[i].lambda;
          }
  
          void lambda2nu(T s = (T)1)
          {
              for(int i=0; i<dispersion.size(); i++)
                  dispersion[i].lambda = s/dispersion[i].lambda;
          }*/
  
  
  		refIndex<T>& operator[](unsigned int i)
  		{
  			return dispersion[i];
  
  		}
  
7006df5f   David Mayerich   reformat of direc...
562
  		complex<T> getN(T l)
f1402849   dmayerich   renewed commit
563
  		{
7006df5f   David Mayerich   reformat of direc...
564
565
566
567
  			//return complex<T>(1.0, 0.0);
  			complex<T> ri = dispersion.linear(l) + n0;
  			return ri;
  		}
f1402849   dmayerich   renewed commit
568
  
7006df5f   David Mayerich   reformat of direc...
569
570
571
  		function<T, complex<T> > getF()
  		{
  			return dispersion + complex<T>(n0, 0.0);
f1402849   dmayerich   renewed commit
572
  		}
6e257ab3   dmayerich   ENVI and colormap...
573
574
  
  		//returns the scattering efficiency at wavelength l
7006df5f   David Mayerich   reformat of direc...
575
  		complex<T> eta(T l)
6e257ab3   dmayerich   ENVI and colormap...
576
577
  		{
              //get the refractive index
7006df5f   David Mayerich   reformat of direc...
578
              complex<T> ri = getN(l);
6e257ab3   dmayerich   ENVI and colormap...
579
580
581
582
583
  
              //convert the refractive index to scattering efficiency
              return ri*ri - 1.0;
  
  		}
f1402849   dmayerich   renewed commit
584
          //interpolate the given lambda value and return the index of refraction
7006df5f   David Mayerich   reformat of direc...
585
          complex<T> operator()(T l)
f1402849   dmayerich   renewed commit
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
          {
              return getN(l);
          }
  
  
      };
  }   //end namespace rts
  
  template <typename T>
  std::ostream& operator<<(std::ostream& os, rts::material<T> m)
  {
      os<<m.toStr();
  
      return os;
  }
  
  
  
  #endif