source: Sophya/trunk/SophyaLib/SkyT/extractRS.cc@ 704

Last change on this file since 704 was 704, checked in by ansari, 26 years ago

SHV: adding extractRS.cc and the corresponding datacard RSextract.

File size: 13.8 KB
RevLine 
[704]1#include "machdefs.h"
2#include <stdlib.h>
3#include <stdio.h>
4#include <fstream.h>
5#include <iostream.h>
6#include <math.h>
7
8#include <string>
9#include <vector>
10
11#include "tmatrix.h"
12#include "tvector.h"
13#include "vector3d.h"
14
15#include "timing.h"
16#include "sambainit.h"
17#include "pexceptions.h"
18#include "datacards.h"
19#include "fitsioserver.h"
20
21#include "radspecvector.h"
22#include "blackbody.h"
23#include "nupower.h"
24
25#include "squarefilt.h"
26#include "trianglefilt.h"
27#include "specrespvector.h"
28#include "gaussfilt.h"
29
30// -----------------------------------------------------------------
31// ------------- Function declaration ------------------------------
32int CheckCards(DataCards & dc, string & msg);
33char * BuildFITSFileName(string const & fname);
34SpectralResponse * getSpectralResponse(DataCards & dc);
35template <class T>
36void addComponent(SpectralResponse& sr, PixelMap<T>& finalMap,
37 PixelMap<T>& mapToAdd, RadSpectra& rs, double K=1.);
38template <class T>
39void MeanSig(NDataBlock<T> const & dbl, double& gmoy, double& gsig);
40float ComputeFrequency(DataCards &,string&);
41
42// -----------------------------------------------------------------
43
44// ----- Global (static) variables ------------
45static bool rdmap = false; // true -> Read map first
46static char mapPath[256]; // Path for input maps
47static int nskycomp = 0; // Number of sky components
48static int debuglev = 0; // Debug Level
49static int printlev = 0; // Print Level
50static POutPersist * so = NULL; // Debug PPFOut file
51
52// -------------------------------------------------------------------------
53// main program
54// -------------------------------------------------------------------------
55int main(int narg, char * arg[])
56{
57 if ((narg < 4) || ((narg > 1) && (strcmp(arg[1], "-h") == 0) )) {
58 cout << " Usage: extractRS parameterFile outputfitsnameformaps outputfitsnameforsource [outppfname]" << endl;
59 exit(0);
60 }
61
62 InitTim();
63
64 string msg;
65 int rc = 0;
66 RadSpectra * es = NULL;
67 SpectralResponse * sr = NULL;
68 double moy, sig;
69
70 DataCards dc;
71 so = NULL;
72
73 try {
74 string dcard = arg[1];
75 cout << " Decoding parameters from file " << dcard << endl;
76 dc.ReadFile(dcard);
77
78 rc = CheckCards(dc, msg);
79 if (rc) {
80 cerr << " Error condition -> Rc= " << rc << endl;
81 cerr << " Msg= " << msg << endl;
82 return(rc);
83 }
84 }
85 catch (PException exc) {
86 msg = exc.Msg();
87 cerr << " !!!! extractRS/ Readcard - Catched exception - Msg= " << exc.Msg() << endl;
88 return(90);
89 }
90
91
92 cout << " extractRS/Info : NComp = " << nskycomp << endl;
93 cout << " ... MapPath = " << (string)mapPath << " DebugLev= " << debuglev
94 << " PrintLev= " << printlev << endl;
95
96
97 // We create an output persist file for writing debug objects
98 if (debuglev > 0) so = new POutPersist("extrRSdbg.ppf");
99
100
101 TMatrix<float> outgs;
102 bool okout = false;
103
104 try {
105
106 FitsIoServer fios; // Our FITS IO Server
107 char * flnm, buff[90];
108 string key;
109 string key2;
110
111 double K = 1.;
112
113 // Loop over sky frequencies components
114 int maxOfSkyComp = nskycomp;
115 int nbOfPix;
116 int sk;
117 Vector freq(maxOfSkyComp);
118 TMatrix<float> spectrum;
119 TMatrix<float> fdenu; //par freq et par pixel
120 int nb_source;
121 TMatrix<float> rareSource; //par freq et par numero de source
122
123 for(sk = 0; sk<maxOfSkyComp; sk++)
124 {
125
126 TMatrix<float> ings;
127 // Opening the file containing the map
128
129 if (printlev > 2) cout << " Processing map's frequency component No " << sk+1 << endl;
130 sprintf(buff, "%d", sk+1);
131 key = (string)"RADSPECMAP" + buff;
132
133 flnm = BuildFITSFileName(dc.SParam(key,0));
134 if (printlev > 2) cout << " Reading Input FITS map " << (string)flnm << endl;
135
136 fios.load(ings, flnm) ;
137 if (printlev > 2)
138 {
139 MeanSig(ings.DataBlock(), moy, sig );
140 cout << " MeanSig for input map - Mean= " << moy << " Sigma= " << sig << endl;
141 }
142
143 // Computing the frequency according to the name of the file
144 freq(sk) = ComputeFrequency(dc,key);
145 if (printlev > 2) cout << "filling spectrum for freq = " << freq(sk) << endl;
146 // Opening the file containing the point source
147 sprintf(buff, "%d", sk+1);
148 key2 = (string)"SOURCEPTMAP" + buff;
149 flnm = BuildFITSFileName(dc.SParam(key2,0));
150 const char* nameOfFile = flnm ;
151 if (printlev > 2) cout << " Reading Input FITS map " << nameOfFile << endl;
152 ifstream from(nameOfFile);
153 char ch;
154 string dum;
155 from >> nb_source >> dum;
156 if(sk==0) rareSource.ReSize(maxOfSkyComp,nb_source);
157 for (int ii=0; ii< nb_source; ii++)
158 {
159 double value = 0;
160 from >> value;
161 rareSource(sk,ii) = value*1.e-26; //for Jansky->W
162 }
163 from.close();
164
165 nbOfPix = ings.NRows()*ings.NCols();
166 spectrum.ReSize(ings.NRows(),ings.NCols());
167 if(sk==0) fdenu.ReSize(maxOfSkyComp,nbOfPix);
168 int xy=0;
169 for(int x=0;x<ings.NRows(); x++)
170 {
171 for(int y=0;x<ings.NCols(); x++)
172 {
173 spectrum(x,y) = ings(x,y)*1.e-26; //for Jansky->W
174 fdenu(sk,xy) = spectrum(x,y);
175 xy += 1;
176 }
177 }
178 if (printlev > 2)
179 {
180 MeanSig(spectrum.DataBlock(), moy, sig );
181 cout << " MeanSig for spectrum map - Mean= " << moy << " Sigma= " << sig << endl;
182 }
183
184
185 K = dc.DParam(key, 1, 1.);
186 if (debuglev > 4) { // Writing the input map to the outppf
187 FIO_TMatrix<float> fiog;
188 fiog.Write(*so, key);
189 }
190
191 if(printlev>2)
192 {
193 sprintf(buff, "End of Proc. Comp. %d ", sk+1);
194 cout << " --------------------------------------- \n" << endl;
195 PrtTim(buff);
196 }
197 } // End of sky component loop
198
199 // ---------------------------------------------------------------------
200 // Integration in the detector band of the maps
201 // ---------------------------------------------------------------------
202 SpectralResponse* sr = NULL;
203 sr = getSpectralResponse(dc);
204
205 if (printlev > 2) cout << "SpectralResponse!" << *sr << endl;
206 TVector<float> outCoeff(nbOfPix);
207
208 for(int pix=1;pix<nbOfPix;pix++)
209 {
210 Vector smallFDeNu(maxOfSkyComp);
211 for(sk = 0; sk<maxOfSkyComp; sk++)
212 {
213 smallFDeNu(sk) = fdenu(sk,pix);
214 }
215
216 RadSpectraVec radSV(freq,smallFDeNu);
217 if (printlev > 10) cout << "RadiationSpectra" << radSV << endl;
218
219 TVector<float> smallFDeNuT(maxOfSkyComp);
220 for(sk = 0; sk<maxOfSkyComp; sk++)
221 {
222 smallFDeNuT(sk) = smallFDeNu(sk);
223 }
224 outCoeff(pix) = radSV.filteredIntegratedFlux(*sr);
225 }
226
227 FitsIoServer fiosrs;
228 fiosrs.save(outCoeff,arg[2]);
229 cout << "Output Map (TMatrix<float>) written to FITS file "
230 << arg[2]<< endl;
231 cout << endl;
232
233 // ---------------------------------------------------------------------
234 // Integration in the detector band of the sources
235 // ---------------------------------------------------------------------
236 TVector<float> sourceCoeff(nb_source);
237 for(int nsource=0;nsource<nb_source;nsource++)
238 {
239 Vector SourceFDeNu(maxOfSkyComp);
240 for(sk = 0; sk<maxOfSkyComp; sk++)
241 {
242 SourceFDeNu(sk) = rareSource(sk,nsource);
243 }
244 RadSpectraVec radSV_Source(freq,SourceFDeNu);
245 sourceCoeff(nsource) = radSV_Source.filteredIntegratedFlux(*sr);
246 }
247 FitsIoServer fiosrs_source;
248 fiosrs_source.save(sourceCoeff,arg[3]);
249 cout << "Output Map (TMatrix<float>) written to FITS file "
250 << arg[3]<< endl;
251 cout << endl;
252
253 // ---------------------------------------------------------------------
254 // Check of write/read on FITS file
255 // ---------------------------------------------------------------------
256 if (printlev > 2)
257 {
258 cout << " Check of write/read on FITS file for skymap!" << endl;
259 TVector<float> outout;
260 FitsIoServer fiotest;
261 fiotest.load(outout, arg[2]);
262 cout << "Coeff(2)" << outout(2) << " ? " << outCoeff(2) << endl;
263 cout << endl;
264 }
265 if (printlev > 2)
266 {
267 cout << " Check of write/read on FITS file for sources!" << endl;
268 FitsIoServer fiotest;
269 TVector<float> outout2;
270 fiotest.load(outout2, arg[3]);
271 cout << "sourceCoeff(2)" << outout2(2) << " ? " << sourceCoeff(2) << endl;
272 }
273
274
275 } // End of try block
276
277
278 catch (PException exc) {
279 msg = exc.Msg();
280 cerr << " !!!! extractRS - Catched PException - Msg= " << exc.Msg() << endl;
281 rc = 50;
282 }
283 catch (PThrowable exc) {
284 msg = exc.Msg();
285 cerr << " !!!! extractRS - Catched PThrowable - Msg= " << exc.Msg() << endl;
286 rc = 50;
287 }
288 catch (...) {
289 cerr << " Une exception de type inconnue !!! " << endl;
290 exit(99);
291 }
292
293 // Saving the output map in FITS format
294 if (okout) {
295 FitsIoServer fios;
296 fios.save(outgs, arg[2]);
297 cout << "Output Map (TMatrix<float>) written to FITS file "
298 << (string)(arg[2]) << endl;
299 if(printlev>2) PrtTim("End of WriteFITS ");
300 // Saving the output map in PPF format
301 if (narg > 3) {
302 POutPersist s(arg[3]);
303 FIO_TMatrix<float> fiog ;
304 fiog.Write(s);
305 cout << "Output Map (TMatrix<float>) written to POutPersist file "
306 << (string)(arg[3]) << endl;
307 if(printlev>2) PrtTim("End of WritePPF ");
308 }
309 }
310 if (so) delete so; // Closing the debug ppf file
311 return(rc);
312}
313
314
315
316/* Nouvelle-Fonction */
317int CheckCards(DataCards & dc, string & msg)
318 // Function to check datacards
319{
320 rdmap = false;
321 mapPath[0] = '\0';
322 nskycomp = 0;
323 debuglev = 0;
324 printlev = 0;
325
326 int rc = 0;
327 string key, key2;
328
329 // Checking datacards
330 if (dc.NbParam("EXT_RS") < 1) {
331 rc = 71;
332 msg = "Invalid parameters - Check @EXT_RS card ";
333 return(rc);
334 }
335 int kc;
336 char buff[256];
337 bool pb = false;
338 string key3;
339 int ncomp = 0;
340 ncomp = dc.IParam("EXT_RS", 0);
341
342 for(kc=0; kc<ncomp; kc++)
343 {
344 key = "RS_EXT_PATH";
345 if (dc.NbParam(key) < 3) strncpy(mapPath, dc.SParam(key, 0).c_str(), 255);
346 mapPath[255] = '\0';
347 sprintf(buff, "RADSPECMAP%d", kc+1);
348 key = buff;
349
350 if (dc.NbParam(key) < 1) {
351 msg = "Missing or invalid card : " + key;
352 pb = true; break;
353 }
354 }
355
356 // Checking detection filter specification
357
358 key = "GAUSSFILTER";
359 key2 = "FILTERFITSFILE";
360 if ( (dc.NbParam(key) < 5) && (dc.NbParam(key2) < 3)) {
361 msg = "Missing card or parameters : Check @GAUSSFILTER or @FILTERFITSFILE";
362 rc = 73; return(rc);
363 }
364
365 if (pb) {
366 rc = 75;
367 return(75);
368 }
369
370
371 // Initialiazing parameters
372 rc = 0;
373 msg = "OK";
374 nskycomp = ncomp;
375
376 // Checking for PATH definition card
377 key = "RS_EXT_PATH";
378 if (dc.NbParam(key) < 3) strncpy(mapPath, dc.SParam(key, 0).c_str(), 255);
379 mapPath[255] = '\0';
380 key = "DEBUGLEVEL";
381 debuglev = dc.IParam(key, 0, 0);
382 key = "PRINTLEVEL";
383 printlev = dc.IParam(key, 0, 0);
384 return(rc);
385}
386
387static char buff_flnm[1024]; // Mal protege !
388/* Nouvelle-Fonction */
389char* BuildFITSFileName(string const & fname)
390{
391if (mapPath[0] != '\0') sprintf(buff_flnm, "%s/%s", mapPath, fname.c_str());
392else sprintf(buff_flnm, "%s", fname.c_str());
393return(buff_flnm);
394}
395
396
397/* Nouvelle-Fonction */
398template <class T>
399void MeanSig(NDataBlock<T> const & dbl, double& gmoy, double& gsig)
400
401{
402 gmoy=0.;
403 gsig = 0.;
404 double valok;
405 for(int k=0; k<(int)dbl.Size(); k++) {
406 valok = dbl(k);
407 gmoy += valok; gsig += valok*valok;
408 }
409 gmoy /= (double)dbl.Size();
410 gsig = gsig/(double)dbl.Size() - gmoy*gmoy;
411 if (gsig >= 0.) gsig = sqrt(gsig);
412}
413/* Nouvelle-Fonction */
414template <class T>
415void addComponent(SpectralResponse& sr, PixelMap<T>& finalMap,
416 PixelMap<T>& mapToAdd, RadSpectra& rs, double K)
417{
418 // finalMap = finalMap + coeff* mapToAdd
419 // coeff = convolution of sr and rs
420 // compute the coefficient corresponding to mapToAdd
421 if (finalMap.NbPixels() != mapToAdd.NbPixels())
422 throw SzMismatchError("addComponent()/Error: Unequal number of Input/Output map pixels");
423 double coeff = rs.filteredIntegratedFlux(sr) * K;
424 if (printlev > 1)
425 cout << " addComponent - Coeff= " << coeff << " (K= " << K << ")" << endl;
426 for(int i=0; i<finalMap.NbPixels(); i++)
427 {
428 finalMap(i) += coeff * mapToAdd(i);
429 }
430}
431
432
433/* Nouvelle-Fonction */
434SpectralResponse * getSpectralResponse(DataCards & dc)
435{
436 SpectralResponse * filt = NULL;
437
438 string key = "FILTERFITSFILE";
439 string key2 = "GAUSSFILTER";
440 string ppfname = "filter";
441
442 if (dc.HasKey(key) ) { // Reading FITS filter file
443 FitsIoServer fios;
444 char ifnm[256];
445 strncpy(ifnm, dc.SParam(key, 1).c_str(), 255);
446 ifnm[255] = '\0';
447 Matrix mtx(2,10);
448 fios.load(mtx, ifnm);
449 double numin = dc.DParam(key, 2, 1.);
450 double numax = dc.DParam(key, 3, 9999.);
451 Vector nu(mtx.NCols());
452 Vector fnu(mtx.NCols());
453 for(int k=0; k<mtx.NCols(); k++) {
454 nu(k) = mtx(0, k);
455 fnu(k) = mtx(1, k);
456 }
457 filt = new SpecRespVec(nu, fnu, numin, numax);
458 ppfname = key;
459 }
460 else if (dc.HasKey(key2) ) { // creating GaussianFilter
461 double nu0 = dc.DParam(key2, 0, 10.);
462 double s = dc.DParam(key2, 1, 1.);
463 double a = dc.DParam(key2, 2, 1.);
464 double numin = dc.DParam(key2, 3, 0.1);
465 double numax = dc.DParam(key2, 4, 9999);
466 filt = new GaussianFilter(nu0, s, a, numin, numax);
467 ppfname = key2;
468 }
469 if (filt == NULL) throw ParmError("datacard error ! No detection filter");
470 cout << " Filter decoded - Created " << endl;
471 cout << *filt << endl;
472
473// for debug
474 // if (debuglev > 1) SpectralResponse2Nt(*filt, *so, ppfname);
475 return(filt);
476}
477
478
479float ComputeFrequency(DataCards & dc,string& key)
480{
481 ofstream filename("temp_filename");
482 filename << dc.SParam(key,0) << '\n';
483 filename.close();
484
485 ifstream fromtempfile("temp_filename");
486 char chtemp;
487 string temp_str;
488 int count = 0;
489 do {
490 fromtempfile.get(chtemp);
491 if(count> 12 && count < 20)
492 {
493 temp_str+= chtemp;
494 }
495 count+=1;
496 } while(chtemp!='\n');
497 fromtempfile.close();
498
499 ofstream filename2("temp_filename");
500 filename2 << temp_str << '\n';
501 filename2.close();
502
503 int frequency;
504 ifstream fromtempfile2("temp_filename");
505 fromtempfile2 >> frequency;
506 fromtempfile2.close();
507 return ((float)frequency/1000.);
508}
Note: See TracBrowser for help on using the repository browser.