-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtfgi.py
2140 lines (1875 loc) · 75.7 KB
/
tfgi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
53
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
115
116
117
118
119
120
121
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
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
199
200
201
202
203
204
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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
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
445
446
447
448
449
450
451
452
453
454
455
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Various functions related to tgi
#
# Version history:
#
# 15-Apr-2019 M. Peel Started
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
import astropy.io.fits as fits
from astropy.modeling import models, fitting
import pandas as pd
import scipy.fftpack
from scipy import signal, optimize
import astropy.units as u
from astropy.coordinates import SkyCoord, EarthLocation, AltAz, Galactic, ICRS, FK5
from astropy.time import Time
from astropy.coordinates import Angle
# import astropy_speedups
from scipy.optimize import curve_fit
import os
import astroplan
from tfgi_functions import *
from tfgi_functions_plot import *
from tfgi_functions_read import *
from astroutils import *
import datetime
import time
import skyfield
import skyfield.api as sfa
# from skyfield.api import load, Topos
import ephem
import multiprocessing as mp
from astropy.coordinates.erfa_astrom import erfa_astrom, ErfaAstromInterpolator
import astropy.units as u
import sys
def calc_beam_area(beam):
return (np.pi * (beam*np.pi/180.0)**2)/(4.0*np.log(2.0))
def calc_Tsys(std,B,t):
return std*np.sqrt(B*t)
class tfgi:
def __init__(self,datadir="/net/nas/proyectos/quijote2/tod/",outdir='',pixelfileloc="/net/nas/proyectos/quijote2/etc/qt2_pixel_masterfile.",pixelposfileloc="/net/nas/proyectos/quijote2/etc/tgi_fgi_horn_positions_table.txt",polcalfileloc="/net/nas/proyectos/quijote2/etc/qt2_polcal.",nside=512):
self.numpixels = 31
self.datadir = datadir
self.outdir = outdir
self.telescope = EarthLocation(lat=28.300224*u.deg, lon=-16.510113*u.deg, height=2390*u.m)
# skyfield
planets = sfa.load('de421.bsp')
earth = planets['earth']
self.sfobservatory = earth + sfa.Topos('28.300224 N', '-16.510113 W',elevation_m=2390.0)
# ephem
# self.observer = ephem.Observer()
# observer.lon = lon
# observer.lat = lat
# observer.elevation = alt
# observer.date = utc
# print observer.radec_of(azimuth, elevation)
self.jd_ref = 2456244.5 # Taken as the first day of the Commissioning (13/Nov/2012, 0.00h)
self.nside = nside
self.npix = hp.nside2npix(self.nside)
self.pixeljds, self.pixelarrays = read_pixel_masterfiles(pixelfileloc)
self.polcaljds, self.polcalarrays = read_pixel_masterfiles(polcalfileloc,usefloat=True)
self.pixelpositions = read_pixel_positions(pixelposfileloc)
self.apobserver = astroplan.Observer(latitude=28.300224*u.deg, longitude=-16.510113*u.deg, elevation=2390*u.m)
# NB: Galactic doesn't work with hour angles
self.coordsys = 1 # 0 = Galactic, 1 = ICRS.
# Constants
self.k = 1.380e-23 # Boltzman constant m2 kg s-2 K-1
self.c = 2.9979e8
# Pointing model
self.Pmodel = {'P_f': -270.58, 'P_x': -1.71, 'P_y': -11.18, 'P_c': 1877.60, 'P_n': -1894.07, 'P_a': 10680.67, 'P_b': -593.53}
# Roughly
self.nu_tgi = 30e9
self.B_tgi = 8e9
self.nu_fgi = 40e9
self.B_fgi = 8e9
# Stable version control
self.ver = 0.2
def find_observations(self,searchtext):
results = []
for file in os.listdir(self.datadir):
if searchtext in file:
obsname = "-".join(file.split("-")[:-1])
if obsname not in results:
results.append(obsname)
return results
def calc_JytoK(self,beam,freq):
return 1e-26*((self.c/freq)**2)/(2.0*self.k*calc_beam_area(beam))
def calc_farfield(self,diameter,frequency=0.0,wavelength=0.0):
if wavelength != 0.0:
return 2.0 * diameter**2 / wavelength
else:
return 2.0 * diameter**2 * frequency / self.c
def get_pixel_info(self, jd, das):
pixel_jd = [x for x in self.pixeljds if x <= jd][-1]
# print(pixel_jd)
pixel_id = self.pixeljds.index(pixel_jd)
# print(pixel_id)
for line in self.pixelarrays[pixel_id]:
# print(line)
if line[5] == das:
if line[1] >= 40:
tgi = 0
fgi = 1
else:
tgi = 1
fgi = 0
pixelposition = self.pixelpositions[line[0]-1]
# print(pixelposition)
# See if we can get polcal info
polcal = self.get_polcal_info(jd,das)
return {'fp':line[0],'pixel':line[1],'fem':line[2],'bem':line[3],'das':line[5],'tgi':tgi,'fgi':fgi,'x_pos':pixelposition[1],'y_pos':pixelposition[2],'polcal':polcal}
# return line
return []
def get_polcal_info(self, jd, das):
try:
pixel_jd = [x for x in self.polcaljds if x <= jd][-1]
except:
return []
pixel_id = self.polcaljds.index(pixel_jd)
returnvals = []
for line in self.polcalarrays[pixel_id]:
if line[0] == das:
returnvals.append([line[1],line[2],line[3]])#,line[4],line[5],line[6],line[7]])
return returnvals
def read_tod(self, prefix, numfiles=50,quiet=True):
# Moved into tgi_functions_read.py
return read_tod_files(self.datadir, prefix, self.numpixels, numfiles=numfiles,quiet=quiet)
def convert_azel_radec(inputarr):
az,el,timearr=inputarr
with erfa_astrom.set(ErfaAstromInterpolator(300 * u.s)):
newpos = position.AltAz(az=az*u.deg,alt=el*u.deg,location=self.telescope,obstime=timearr).transform_to(ICRS)
return newpos
# Note: this is currently slow and over-precise, see
# https://github.com/astropy/astropy/pull/6068
def calc_positions(self, az, el, jd):
timearr = Time(jd[0]+self.jd_ref, format='jd')
# print(jd[0][0])
# print(jd[0][1]-jd[0][0])
# exit()
# Apply the pointing model
print('Applying pointing model')
az,el = self.pointing_model(az[0],el[0])
# This was using skyfield - but it's slow.
# print('Converting to sky position (1)')
# start = time.time()
# timing = sfa.load.timescale()
# times = timing.tt_jd(jd[0]+self.jd_ref)
# ra,dec,distance = self.sfobservatory.at(times).from_altaz(alt_degrees=el[0], az_degrees=az[0]).radec(epoch=times)
# end = time.time()
# print(end-start)
# print(ra)
# print(dec)
# print('Converting to sky position(1)')
# start = time.time()
# factor=10
# position = AltAz(az=az[0][::factor]*u.deg,alt=el[0][::factor]*u.deg,location=self.telescope,obstime=timearr[::factor])
# skypos_part = position.transform_to(ICRS)
# # interpolate
# dt = (timearr - timearr[0]).sec
# dtp = dt[::factor]
# def interpolate(q):
# return np.interp(dt, dtp, q.value) * q.unit
# skypos_compare = SkyCoord(ra=interpolate(skypos_part.ra),
# dec=interpolate(skypos_part.dec),frame=ICRS)
# print(skypos_compare)
# end = time.time()
# print(end-start)
# print("Number of processors: ", mp.cpu_count())
# start = time.time()
# pool = mp.Pool(mp.cpu_count())
# numsets=100
# setsize = len(az[0])//numsets
# print(setsize)
# inputarr = [az[0][:],el[0][:],timearr[:]]
# skypos = [pool.apply(self.convert_azel_radec,args=(az[0][i*setsize:(i+1)*setsize-1],el[0][i*setsize:(i+1)*setsize-1],timearr[i*setsize:(i+1)*setsize-1])) for i in range(0,numsets)]
# pool.close()
# end = time.time()
# print(end-start)
# exit()
# print('Converting to sky position(3)')
# # Could also do it this way - from the pointing code.
# c = SkyCoord(alt = el[0]*u.deg, az = az[0]*u.deg, unit = 'deg', frame= 'altaz', obstime = time, location = self.telescope)
# skypos=c.icrs
# start = time.time()
position = AltAz(az=az[0]*u.deg,alt=el[0]*u.deg,location=self.telescope,obstime=timearr)
if self.coordsys == 0:
skypos = position.transform_to(Galactic)
pa = []
else:
skypos = position.transform_to(ICRS)
# end = time.time()
# print(end-start)
# print(skypos)
# print(np.max(skypos.ra-skypos_compare.ra))
# print(np.max(skypos.dec-skypos_compare.dec))
# exit()
# pa = []
print('Calculating position angles')
pa = self.apobserver.parallactic_angle(timearr,skypos)
print('Done with positions')
return skypos,pa
def calc_healpix_pixels(self, skypos):
if self.coordsys == 0:
healpix_pixel = hp.ang2pix(self.nside, (np.pi/2)-Angle(skypos.b).radian, Angle(skypos.l).radian)
pos = (np.median(Angle(skypos.l).degree),np.median((Angle(skypos.b).degree)))
else:
print(skypos)
healpix_pixel = hp.ang2pix(self.nside, (np.pi/2)-Angle(skypos.dec).radian, Angle(skypos.ra).radian)
pos = (np.median(Angle(skypos.ra).degree),np.median((Angle(skypos.dec).degree)))
return healpix_pixel, pos
def write_healpix_map(self, data, prefix, outputname,headerinfo=[]):
extra_header = []
extra_header.append(("instrum",("tfgi")))
extra_header.append(("tgfi_v",(str(self.ver))))
extra_header.append(("obsname",(prefix)))
now = datetime.datetime.now()
extra_header.append(("writedat",(now.isoformat())))
# for args in extra_header:
# print(args[0].upper())
# print(args[1:])
hp.write_map(outputname,data,overwrite=True,extra_header=extra_header)
return
def plot_fft(self, data, outputname, samplerate=1000, numsmoothbins=50):
fft_w = np.fft.rfft(data)
fft_f = np.fft.rfftfreq(len(data), 1/samplerate)
fft_spectrum = np.abs(fft_w)
# Do a smoothed version
bins = np.linspace(np.log(min(fft_f[1:-1])),np.log(max(fft_f[1:-1])),numsmoothbins,endpoint=False)
values = np.zeros(numsmoothbins)
values2 = np.zeros(numsmoothbins)
matches = np.digitize(np.log(fft_f),bins)
binmask = np.ones(numsmoothbins)
for i in range(0,numsmoothbins):
values[i] = np.nanmean(np.log(fft_spectrum[matches == i]))
values2[i] = np.nanmean(fft_spectrum[matches == i])
if np.isnan(values[i]) or np.isnan(values2[i]):
binmask[i] = 0
binmask[0] = 0
binmask[-1] = 0
binmask[-2] = 0
# Fit to get the knee frequency
# Using modified code from http://pchanial.github.io/python-for-data-scientists/body.html (by Jm. Colley)
# params = np.array([np.sqrt(np.median(fft_spectrum))/5, 0.01, 1.0])
params = np.array([(values[binmask==1])[-2], 0.01, 1.0])
#print(params)
# print np.exp(values[0,5:])
# print np.exp(bins[5:])
#print(values[binmask==1])
#print(values2[binmask==1])
# param_est, cov_x, infodict, mesg_result, ret_value = optimize.leastsq(compute_residuals, params, args=(values2[binmask==1], bins[binmask==1]),full_output=True)
param_est, cov_x, infodict, mesg_result, ret_value = optimize.leastsq(compute_residuals, params, args=(np.exp(values[binmask==1]), np.exp(bins[binmask==1])),full_output=True)
#print(param_est)
#print(cov_x)
#print(mesg_result)
#print(ret_value)
# exit()
# Plot the spectrum
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power')
plt.xscale('log')
plt.yscale('log')
ymax = np.max(fft_spectrum[1:])*1.5
ymin = np.min(fft_spectrum[1:])
plt.ylim(ymin=ymin,ymax=ymax)
plt.plot(fft_f, fft_spectrum,label='Data')
plt.plot(np.exp(bins[1:]), np.exp(values[1:]), 'r', label='Mean (in log)')
plt.plot(np.exp(bins[1:]), values2[1:], 'm', label='Mean (in linear)')
try:
sigma_param_est = np.sqrt(np.diagonal(cov_x))
mesg_fit = (
r'$\sigma={:5.3g}\pm{:3.2g}$'.format(
param_est[0], sigma_param_est[0]) + ','
r'$f_{{\rm knee}}={:5.3f}\pm{:3.2f}$'.format(
param_est[1], sigma_param_est[1]) + ','
r' $\alpha={:5.3f}\pm{:3.2f}$'.format(
param_est[2], sigma_param_est[2]))
plt.plot(fft_f, fit_kneefreq(fft_f, param_est),label="Fit: " + mesg_fit)
except:
mesg_fit = (
r'$\sigma={:5.3g}$'.format(
param_est[0]) + ','
r'$f_{{\rm knee}}={:5.3f}$'.format(
param_est[1]) + ','
r' $\alpha={:5.3f}$'.format(
param_est[2]))
plt.plot(fft_f, fit_kneefreq(fft_f, param_est),label="Fit" + mesg_fit)
plt.legend(prop={'size':8})
plt.savefig(outputname)
plt.close()
plt.clf()
return param_est, sigma_param_est
def subtractbaseline(self, data, option=0, navg=1500):
# Crude baseline removal
npoints = len(data)
# print(npoints)
for i in range(0,npoints//navg):
start = i*navg
end = ((i+1)*navg)
# print('start:' + str(start) + ', end: ' + str(end))
if option == 0:
data[start:end] = data[start:end] - np.median(data[start:end])
else:
xline = range(0,len(data[start:end]))
if len(xline) != 0:
A,B=curve_fit(linfit,xline,data[start:end])[0]
# print(A,B)
data[start:end] = data[start:end] - (A*xline+B)
if option == 0:
data[(npoints//navg)*navg-1:] = data[(npoints//navg)*navg-1:] - np.median(data[(npoints//navg)*navg-1:])
else:
xline = range(0,len(data[(npoints//navg)*navg-1:]))
if len(xline) != 0:
A,B=curve_fit(linfit,xline,data[(npoints//navg)*navg-1:])[0]
# print(A,B)
data[(npoints//navg)*navg-1:] = data[(npoints//navg)*navg-1:] - (A*xline+B)
return data
def converttopol(self, data, ordering=[0,1,2,3],pa=[],polangle=0,polcorr=[1.0,1.0,1.0,1.0]):
newdata = np.zeros(np.shape(data))
# This didn't work, so isn't currently used.
# data[ordering[0]] = data[ordering[0]] * polcorr[0]
# data[ordering[1]] = data[ordering[1]] * polcorr[1]
# data[ordering[2]] = data[ordering[2]] * polcorr[2]
# data[ordering[3]] = data[ordering[3]] * polcorr[3]
newdata[0] = (data[ordering[0],:] + data[ordering[1],:])# / 2.0
newdata[1] = (data[ordering[0],:] - data[ordering[1],:])# / 2.0
newdata[2] = (data[ordering[2],:] - data[ordering[3],:])# / 2.0
newdata[3] = (data[ordering[2],:] + data[ordering[3],:])# / 2.0
if len(pa) > 0:
ang = 2.0*pa # Already in radians
Q = newdata[1,:]*np.cos(ang) + newdata[2,:]*np.sin(ang)
U = -newdata[1,:]*np.sin(ang) + newdata[2,:]*np.cos(ang)
newdata[1] = Q.copy()
newdata[2] = U.copy()
# print(polangle)
if polangle != 0:
Q = newdata[1,:]*np.cos(2.0*polangle*np.pi/180.0) + newdata[2,:]*np.sin(2.0*polangle*np.pi/180.0)
U = -newdata[1,:]*np.sin(2.0*polangle*np.pi/180.0) + newdata[2,:]*np.cos(2.0*polangle*np.pi/180.0)
newdata[1] = Q.copy()
newdata[2] = U.copy()
return newdata
def analyse_tod(self, prefix, pixelrange=range(0,31), detrange=range(0,4), phaserange=range(0,4), plotlimit=0.0, quiet=False, dofft=False, plottods=True, plotmap=True, dopol=False, plotcombination=True, numfiles=50):
polext = ""
if dopol:
polext = "_pol"
plotext = "/plots"
print(self.outdir+'/'+prefix+polext)
ensure_dir(self.outdir+'/'+prefix+polext)
ensure_dir(self.outdir+'/'+prefix+polext+plotext)
if 'DIP' in prefix:
# We have a sky dip. Run the routine to analyse that rather than this routine.
self.analyse_skydip(prefix,pixelrange=pixelrange,detrange=detrange,phaserange=phaserange,quiet=quiet,plottods=plottods,dopol=dopol)
return
if 'LOCALMAP' in prefix:
self.analyse_localmap(prefix,pixelrange=pixelrange,detrange=detrange,phaserange=phaserange,quiet=quiet,plottods=plottods,dopol=dopol)
return
# Read in the data
az, el, jd, data = self.read_tod(prefix,numfiles=numfiles,quiet=quiet)
# Calculate the Galactic Healpix pixels and the central position from az/el
skypos,pa = self.calc_positions(az, el, jd)
healpix_pixel, centralpos = self.calc_healpix_pixels(skypos)
plot_tfgi_tod(skypos.ra,self.outdir+'/'+prefix+polext+plotext+'/plot_ra.png')
plot_tfgi_tod(skypos.dec,self.outdir+'/'+prefix+polext+plotext+'/plot_dec.png')
plot_tfgi_tod(pa,self.outdir+'/'+prefix+polext+plotext+'/plot_pa.png')
# exit()
aperflux_outputfile = open(self.outdir+'/'+prefix+polext+'/aperflux.txt', "w")
gauflux_outputfile = open(self.outdir+'/'+prefix+polext+'/gauflux.txt', "w")
# Make maps for each pixel, detector, phase
for pix in pixelrange:
try:
# Get the pixel info
pixinfo = self.get_pixel_info(jd[0][0]+self.jd_ref,pix+1)
print(pixinfo)
if pixinfo == []:
# We don't have a good pixel, skip it
continue
if pixinfo['pixel'] <= 0:
# Pixel isn't a pixel
continue
for det in detrange:
for j in phaserange:
print(j)
if plottods:
# Plot some tods
plot_tfgi_tod(data[det][pix][j][10:-1500], self.outdir+'/'+prefix+polext+plotext+'/plot_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'_pre.png')
plot_tfgi_tod(data[det][pix][j][10:5000],self.outdir+'/'+prefix+polext+plotext+'/plot_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'_pre_zoom.png')
# Do an FFT. Warning, this can slow things down quite a bit.
if dofft:
param_est, sigma_param_est = self.plot_fft(data[det][pix][j][0:10000],self.outdir+'/'+prefix+polext+plotext+'/plot_fft_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'_fit.png',samplerate=1000)
print(str(param_est[0]) + " " + str(sigma_param_est[0]) + " " + str(param_est[1]) + " " + str(sigma_param_est[1]) + " " + str(param_est[2]) + " " + str(sigma_param_est[2]))
data[det][pix][j] = self.subtractbaseline(data[det][pix][j])
if plottods:
plot_tfgi_tod(data[det][pix][j][10:-1500], self.outdir+'/'+prefix+polext+plotext+'/plot_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
plot_tfgi_tod(data[det][pix][j][10:5000], self.outdir+'/'+prefix+polext+plotext+'/plot_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'_zoom.png')
# Do we want to change from phase to I1,Q,U,I2?
if dopol:
if pixinfo['tgi'] == 1:
# if det == 0:
ordering = [0,1,2,3]
# elif det == 1:
# ordering = [1,2,3,0]
# elif det == 2:
# ordering = [2,3,0,1]
# elif det == 3:
# ordering = [3,0,1,2]
else:
# if det == 0:
ordering = [0,2,1,3]
# elif det == 1:
# ordering = [2,1,3,0]
# elif det == 2:
# ordering = [1,3,0,2]
# elif det == 3:
# ordering = [3,0,2,1]
# If we have polcal data, use it
print(pixinfo['polcal'])
# print(pixinfo['polcal'][det])
if pixinfo['polcal'] != []:
# polcorr = [pixinfo['polcal'][det][3],pixinfo['polcal'][det][4],pixinfo['polcal'][det][5],pixinfo['polcal'][det][6]]
data[det][pix] = self.converttopol(data[det][pix],ordering=ordering,pa=pa,polangle=pixinfo['polcal'][det][1])#,polcorr=polcorr)
else:
data[det][pix] = self.converttopol(data[det][pix],ordering=ordering,pa=pa)
for j in phaserange:
print('Pixel ' + str(pix+1) + ', detector ' + str(det+1) + ', phase ' + str(j+1))
if plottods:
plot_tfgi_tod(data[det][pix][j][10:-1500], self.outdir+'/'+prefix+polext+plotext+'/plot_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'_cal.png')
plot_tfgi_tod(data[det][pix][j][10:5000], self.outdir+'/'+prefix+polext+plotext+'/plot_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'_cal_zoom.png')
skymap = np.zeros(self.npix, dtype=np.float)
hitmap = np.zeros(self.npix, dtype=np.float)
for i in range(0,len(healpix_pixel)):
skymap[healpix_pixel[i]] = skymap[healpix_pixel[i]] + data[det][pix][j][i]
hitmap[healpix_pixel[i]] = hitmap[healpix_pixel[i]] + 1
for i in range(0,len(skymap)):
if hitmap[i] >= 1:
skymap[i] = skymap[i]/hitmap[i]
else:
skymap[i] = hp.pixelfunc.UNSEEN
# Get the maximum value in the map
maxval = np.max(skymap)
# Get a sample of data from the start of the measurement
std = np.std(data[det][pix][j][0:4000])
print(maxval)
print(std)
if pixinfo['tgi']:
conv = self.calc_JytoK(0.2,self.nu_tgi)
flux = 344.0
else:
conv = self.calc_JytoK(0.2,self.nu_fgi)
flux = 318.0
estimate = std*(flux/maxval)/np.sqrt(4000.0)
print('In Jy/sec:' + str(estimate))
print('In K/sec:' + str(estimate*conv))
print('System temperature:' + str(calc_Tsys(estimate*conv,8e9,1/4000)))
self.write_healpix_map(skymap,prefix,self.outdir+'/'+prefix+polext+'/skymap_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.fits')
self.write_healpix_map(hitmap,prefix,self.outdir+'/'+prefix+polext+'/hitmap_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.fits')
pixel = np.where(skymap == maxval)
pos = hp.pix2ang(self.nside,pixel)
lon = pos[1] * 180.0/np.pi
lat = (np.pi/2.0 - pos[0]) * 180.0/np.pi
# print(lon,lat)
if pixinfo['tgi'] == 1:
freq = 30.0
else:
freq = 40.0
res_arcmin = 4.0*np.pi / self.npix
aperflux = haperflux(skymap, freq, res_arcmin, lon[0][0], lat[0][0], 100.0, 100.0, 140.0, units='JyPix',column=0,nested=False, noise_model=0)
print(aperflux)
aperflux_outputfile.write(str(pix+1)+' '+str(det+1)+' '+str(j+1)+' '+str(freq)+' '+str(aperflux[0])+' '+str(aperflux[1])+' '+str(aperflux[2]) + '\n')
# Also do a Gaussian fit
pixels_tofit = query_ellipse(self.nside, lon[0][0], lat[0][0], 5.0, 1.0, 0.0)
pixels_tofit = pixels_tofit[skymap[pixels_tofit] != hp.pixelfunc.UNSEEN]
pixels_positions = hp.pix2ang(self.nside,pixels_tofit)
# print(pixels_positions)
# print(len(pixels_positions))
fit_w = fitting.LevMarLSQFitter()
gaussianfit = models.Gaussian2D(maxval, np.pi/2.0-lat[0][0]*np.pi/180.0, lon[0][0]*np.pi/180.0, 1.0*np.pi/180.0, 1.0*np.pi/180.0)
# print(gaussianfit)
# print('hello')
xi = pixels_positions[0]
yi = pixels_positions[1]
plt.plot(xi,skymap[pixels_tofit])
plt.savefig('test_x.png')
plt.clf()
plt.plot(yi,skymap[pixels_tofit])
plt.savefig('test_y.png')
plt.clf()
# print(len(xi))
# print(len(yi))
# print(len(skymap[pixels_tofit]))
gauss = fit_w(gaussianfit, xi, yi, skymap[pixels_tofit])
print(gauss)
# print(gauss.amplitude)
model_data = gauss(xi, yi)
# print(model_data)
# plt.plot(xi,model_data)
# plt.savefig('test_x_model.png')
# plt.clf()
# plt.plot(yi,model_data)
# plt.savefig('test_y_model.png')
# plt.clf()
skymap_residual = skymap.copy()
skymap_residual[pixels_tofit] = skymap_residual[pixels_tofit] - model_data
gauflux_outputfile.write(str(pix+1)+' '+str(det+1)+' '+str(j+1)+' '+str(freq)+' '+str(gauss.amplitude.value)+' '+str(gauss.x_stddev.value*180.0/np.pi)+' '+str(gauss.y_stddev.value*180.0/np.pi)+' '+str(gauss.theta.value*180.0/np.pi) + '\n')
if plotmap:
hp.mollview(skymap)
plt.savefig(self.outdir+'/'+prefix+polext+plotext+'/skymap_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
plt.close()
plt.clf()
if plotmap:
hp.mollview(hitmap)
plt.savefig(self.outdir+'/'+prefix+polext+plotext+'/hitmap_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
hp.gnomview(skymap,rot=centralpos,reso=5)
plt.savefig(self.outdir+'/'+prefix+polext+plotext+'/skymap_zoom_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
hp.gnomview(skymap_residual,rot=centralpos,reso=5)
plt.savefig(self.outdir+'/'+prefix+polext+plotext+'/skymap_zoom_sub_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
plt.close()
plt.clf()
if plotmap and plotlimit != 0.0:
hp.mollview(skymap,min=-plotlimit,max=plotlimit)
plt.savefig(self.outdir+'/'+prefix+polext+plotext+'/skymap_cut_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
plt.close()
plt.clf()
hp.gnomview(skymap,rot=centralpos,reso=5,min=-plotlimit,max=plotlimit)
plt.savefig(self.outdir+'/'+prefix+polext+plotext+'/skymap_zoom_cut_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1)+'.png')
plt.close()
plt.clf()
except:
continue
aperflux_outputfile.close()
gauflux_outputfile.close()
array = np.loadtxt(self.outdir+'/'+prefix+polext+'/aperflux.txt')
x = range(0,len(array[:,4]))
plt.errorbar(x,array[:,4],yerr=array[:,5],fmt='r+')
plt.savefig(self.outdir+'/'+prefix+polext+'/aperflux.pdf')
# Do some combined plots if requested
if plotcombination:
for i in range(1,5):
if i == 2 or i == 3:
plotlimit2 = plotlimit
else:
plotlimit2 = 0.0
for k in range(1,5):
filelist = []
hitlist = []
for pix in range(1,self.numpixels):
filelist.append(self.outdir+'/'+prefix+polext+'/skymap_'+str(pix)+'_'+str(k)+'_'+str(i)+'.fits')
hitlist.append(self.outdir+'/'+prefix+polext+'/hitmap_'+str(pix)+'_'+str(k)+'_'+str(i)+'.fits')
print(filelist)
self.combine_sky_maps(filelist,hitlist,prefix,self.outdir+'/'+prefix+polext+'/combined_'+str(i)+'_'+str(k),centralpos=centralpos,plotlimit=plotlimit2)
for i in range(1,5):
self.calc_P_angle_skymaps(self.outdir+'/'+prefix+polext+'/combined_1_'+str(i)+'_skymap.fits',self.outdir+'/'+prefix+polext+'/combined_2_'+str(i)+'_skymap.fits',self.outdir+'/'+prefix+polext+'/combined_3_'+str(i)+'_skymap.fits',prefix,self.outdir+'/'+prefix+polext+'/combined_pol_'+str(i),centralpos=centralpos)
# # Plot a boxcar average
# numboxcar = 101
# boxcar = signal.boxcar(numboxcar)
# boxcar = boxcar/np.sum(boxcar)
# print(np.shape(data))
# for i in range(0,31):
# print(data[i])
# print (len(data[i]))
# fig = plt.figure(figsize=(20,10))
# for j in range(0,4):
# toplot = signal.convolve(data[i][j],boxcar)
# print(len(toplot))
# plt.plot(toplot[numboxcar:ndata-numboxcar]-np.median(toplot[numboxcar:ndata-numboxcar]))
# plt.savefig('plot_boxcar_'+str(i+1)+'_tod.png')
# plt.clf()
return
def stack_maps_tod(self, prefix,schedules,pixelrange=range(0,31),detrange=range(0,4),phaserange=range(0,4),plotlimit=0.0,quiet=False,dofft=False,dopol=False,numfiles=50):
polext = ""
if dopol:
polext = "_pol"
print(self.outdir+'/'+prefix+polext)
ensure_dir(self.outdir+'/'+prefix+polext)
skymap = np.zeros((len(pixelrange),self.npix), dtype=np.float)
hitmap = np.zeros((len(pixelrange),self.npix), dtype=np.float)
centralpos = (0,0)
for schedule in schedules:
# Read in the data
az, el, jd, data = self.read_tod(schedule,numfiles=numfiles,quiet=quiet)
# Calculate the Galactic Healpix pixels and the central position from az/el
healpix_pixel, centralpos = self.calc_positions(az, el, jd)
# Make maps for each pixel, detector, phase
pixnum=-1
for pix in pixelrange:
pixnum = pixnum+1
for det in detrange:
# Do we want to change from phase to I1,Q,U,I2?
if dopol:
# Different for TGI and FGI...
if pix > 10:
option = 1
else:
option = 0
# data[det][pix] = self.converttopol(data[det][pix],option=option)
for j in phaserange:
data[det][pix][j] = self.subtractbaseline(data[det][pix][j])
for i in range(0,len(healpix_pixel)):
skymap[pixnum][healpix_pixel[i]] = skymap[pixnum][healpix_pixel[i]] + data[det][pix][j][i]
hitmap[pixnum][healpix_pixel[i]] = hitmap[pixnum][healpix_pixel[i]] + 1
# We're done making the maps, now normalise them and write it out
pixnum=-1
for pix in pixelrange:
pixnum = pixnum+1
for i in range(0,len(skymap[pixnum])):
if hitmap[pixnum][i] >= 1:
skymap[pixnum][i] = skymap[pixnum][i]/hitmap[pixnum][i]
else:
skymap[pixnum][i] = hp.pixelfunc.UNSEEN
self.write_healpix_map(skymap[pixnum],prefix,self.outdir+'/'+prefix+polext+'/skymap_'+str(pix+1)+'.fits')
self.write_healpix_map(hitmap[pixnum],prefix,self.outdir+'/'+prefix+polext+'/hitmap_'+str(pix+1)+'.fits')
hp.mollview(skymap[pixnum])
plt.savefig(self.outdir+'/'+prefix+polext+'/skymap_'+str(pix+1)+'.png')
plt.close()
plt.clf()
hp.mollview()
plt.savefig(self.outdir+'/'+prefix+polext+'/hitmap_'+str(pix+1)+'.png')
hp.gnomview(skymap[pixnum],rot=centralpos,reso=5)
plt.savefig(self.outdir+'/'+prefix+polext+'/skymap_zoom_'+str(pix+1)+'.png')
plt.close()
plt.clf()
if plotlimit != 0.0:
hp.mollview(skymap[pixnum],min=-plotlimit,max=plotlimit)
plt.savefig(self.outdir+'/'+prefix+polext+'/skymap_cut_'+str(pix+1)+'.png')
plt.close()
plt.clf()
hp.gnomview(skymap[pixnum],rot=centralpos,reso=5,min=-plotlimit,max=plotlimit)
plt.savefig(self.outdir+'/'+prefix+polext+'/skymap_zoom_cut_'+str(pix+1)+'.png')
plt.close()
plt.clf()
return
def combine_sky_maps(self,skymaps,hitmaps,prefix,outputname,centralpos=(0,0),plotlimit=0.0):
skymap = np.zeros(self.npix, dtype=np.float)
hitmap = np.zeros(self.npix, dtype=np.float)
nummaps = len(skymaps)
for i in range(0,nummaps):
try:
inputmap = hp.read_map(skymaps[i])
inputhitmap = hp.read_map(hitmaps[i])
except:
continue
for j in range(0,self.npix):
if inputhitmap[j] > 0:
skymap[j] = skymap[j] + inputmap[j]*inputhitmap[j]
hitmap[j] = hitmap[j] + inputhitmap[j]
# We now have a combined map, time to normalise it
for i in range(0,self.npix):
if hitmap[i] >= 1:
skymap[i] = skymap[i]/hitmap[i]
else:
skymap[i] = hp.pixelfunc.UNSEEN
self.write_healpix_map(skymap,prefix,outputname+'_skymap.fits')
self.write_healpix_map(hitmap,prefix,outputname+'_hitmap.fits')
hp.mollview(skymap)
plt.savefig(outputname+'_skymap.png')
plt.close()
plt.clf()
hp.mollview(hitmap)
plt.savefig(outputname+'_hitmap.png')
if plotlimit != 0.0:
hp.gnomview(skymap,rot=centralpos,reso=5,min=-plotlimit,max=plotlimit)
else:
hp.gnomview(skymap,rot=centralpos,reso=5)
plt.savefig(outputname+'_zoom.png')
plt.close()
plt.clf()
return
def calc_P_angle_skymaps(self,I_filename,Q_filename,U_filename,prefix,outputname,centralpos=(0,0),plotlimit=0.0):
print(I_filename)
I = hp.read_map(I_filename)
Q = hp.read_map(Q_filename)
U = hp.read_map(U_filename)
P = np.sqrt(Q**2+U**2)
ang = (0.5*np.arctan2(U,Q)* 180 / np.pi)
frac = P/I
P[I == hp.pixelfunc.UNSEEN] = hp.pixelfunc.UNSEEN
ang[I == hp.pixelfunc.UNSEEN] = hp.pixelfunc.UNSEEN
ang[P < 0.1*np.max(P)] = hp.pixelfunc.UNSEEN
frac[I == hp.pixelfunc.UNSEEN] = hp.pixelfunc.UNSEEN
frac[P < 0.1*np.max(P)] = hp.pixelfunc.UNSEEN
self.write_healpix_map(P,prefix,outputname+'_P.fits')
self.write_healpix_map(ang,prefix,outputname+'_ang.fits')
self.write_healpix_map(frac,prefix,outputname+'_pfrac.fits')
hp.mollview(P)
plt.savefig(outputname+'_P.png')
plt.close()
plt.clf()
hp.mollview(ang)
plt.savefig(outputname+'_ang.png')
plt.close()
plt.clf()
hp.mollview(frac,min=0,max=10)
plt.savefig(outputname+'_Pfrac.png')
plt.close()
plt.clf()
if plotlimit != 0.0:
hp.gnomview(P,rot=centralpos,reso=5,min=-plotlimit,max=plotlimit)
else:
hp.gnomview(P,rot=centralpos,reso=5)
plt.savefig(outputname+'_P_zoom.png')
plt.close()
plt.clf()
hp.gnomview(ang,rot=centralpos,reso=5,cmap=plt.get_cmap('hsv'))
plt.savefig(outputname+'_ang_zoom.png')
plt.close()
plt.clf()
hp.gnomview(frac,rot=centralpos,reso=5,min=0)#,max=0.1)
plt.savefig(outputname+'_Pfrac_zoom.png')
plt.close()
plt.clf()
return
def examine_source(self,skymaps,hitmaps,outputname,sourcepos=(0,0),plotlimit=0.0):
skymap = np.zeros(self.npix, dtype=np.float)
hitmap = np.zeros(self.npix, dtype=np.float)
nummaps = len(skymaps)
for i in range(0,nummaps):
try:
inputmap = hp.read_map(skymaps[i])
inputhitmap = hp.read_map(hitmaps[i])
except:
continue
if sourcepos == (0,0):
# We have a map but no position, let's find the peak position
skymax = np.max(inputmap)
pixelpos = np.where(inputmap==skymax)[0][0]
print(pixelpos)
sourcepos = hp.pixelfunc.pix2ang(self.nside,pixelpos,lonlat=True)
print(sourcepos)
sourcecoord = SkyCoord(sourcepos[0]*u.deg, sourcepos[1]*u.deg, frame=Galactic)
x_val = []
y_val = []
for i in range(0,self.npix):
if inputmap[i] != hp.UNSEEN:
if inputmap[i] != 0.0:
pixelpos = hp.pixelfunc.pix2ang(self.nside,i,lonlat=True)
pixelcoord = SkyCoord(pixelpos[0]*u.deg, pixelpos[1]*u.deg, frame=Galactic)
sep=pixelcoord.separation(sourcecoord)
# print(sep.degree,inputmap[i])
if sep.degree < 2.0:
x_val.append(sep.degree)
y_val.append(inputmap[i])
x_val = np.array(x_val)
y_val = np.array(y_val)
plt.plot(x_val,y_val,'b.')
params = [10.0,1.0,0.0]
param_est, cov_x, infodict, mesg_result, ret_value = optimize.leastsq(compute_residuals_gaussian, params, args=(x_val, y_val),full_output=True)
sigma_param_est = np.sqrt(np.diagonal(cov_x))
mesg_fit = (
r'$A={:5.3f}\pm{:3.2f}$'.format(
param_est[0], sigma_param_est[0]) + ','
r'$B={:5.3f}\pm{:3.2f}$'.format(
param_est[1], sigma_param_est[1]) + ','
r'$C={:5.3f}\pm{:3.2f}$'.format(
param_est[2], sigma_param_est[2]))
toplot = np.arange(0,2.0,0.01)
plt.plot(toplot,fit_gaussian(toplot,param_est),label=mesg_fit)
plt.xlabel('Distance')
plt.ylabel('Power')
plt.yscale('log')
plt.ylim((1e-4,skymax))
plt.legend(prop={'size':8})
plt.savefig('test.pdf')
plt.close()
plt.clf()
return
def analyse_skydip(self, prefix, pixelrange=range(0,31), detrange=range(0,4), phaserange=range(0,4), plotlimit=0.0, quiet=False, plottods=False, dopol=False, numfiles=50, minel=35.0, maxel=85.0, numelbins=100, plotindividual=False):
polext = ""
if dopol:
polext = "_pol"
plotext = "/plots"
print(self.outdir+'/'+prefix+polext)
ensure_dir(self.outdir+'/'+prefix+polext)
ensure_dir(self.outdir+'/'+prefix+polext+plotext)
atm_tgi = 5.0
atm_fgi = 10.0
meas_outputfile = open(self.outdir+'/'+prefix+polext+'/measurements.txt', "w")
avg_outputfile = open(self.outdir+'/'+prefix+polext+'/measurements_avg.txt', "w")
std_outputfile = open(self.outdir+'/'+prefix+polext+'/measurements_std.txt', "w")
meas_outputfile.write('#Assuming atmosphere of ' + str(atm_tgi) + 'K for TGI and ' + str(atm_fgi) + 'K for FGI\n')
std_outputfile.write('#Assuming atmosphere of ' + str(atm_tgi) + 'K for TGI and ' + str(atm_fgi) + 'K for FGI\n')
# Read in the data
az, el, jd, data = self.read_tod(prefix,numfiles=numfiles,quiet=quiet)
# Create a mask of the different elevation dips
tempmask = el[0].copy()
tempmask[tempmask < minel] = 0.
tempmask[tempmask > maxel] = 0.
# plot_tfgi_tod(tempmask,self.outdir+'/'+prefix+polext+'/mask.pdf')
skydip_mask = tempmask.copy()
# Find out whether we're going up or down in elevation
for i in range(1,len(skydip_mask)):
if tempmask[i] != 0.:
if tempmask[i-1] < tempmask[i]:
skydip_mask[i] = -1
else:
skydip_mask[i] = 1
# To catch noisy bits in transitions, require that sets of testlen all have to have the same value
testlen = 10
for i in range(0,len((skydip_mask/testlen)-testlen)):
if np.sum(np.abs(skydip_mask[i*testlen:i*testlen+testlen])) != testlen:
skydip_mask[i*testlen:i*testlen+testlen] = 0
# Count how many different sections we have, and update the mask so we can extract them.
num_skydips = 1
notzero = 0
for i in range(0,len(skydip_mask)):
if skydip_mask[i] != 0:
skydip_mask[i] = skydip_mask[i] * num_skydips
notzero = 1
else:
if notzero == 1:
num_skydips = num_skydips+1
notzero = 0
# print(num_skydips)
plot_tfgi_tod(skydip_mask,self.outdir+'/'+prefix+polext+plotext+'/mask_bit.pdf',formatstr='b')
# Make maps for each pixel, detector, phase
for pix in pixelrange:
# Get the pixel info
pixinfo = self.get_pixel_info(jd[0][0]+self.jd_ref,pix+1)
print(pixinfo)
if pixinfo == []:
# We don't have a good pixel, skip it
continue
if pixinfo['pixel'] <= 0:
# Pixel isn't a pixel
continue
for det in detrange:
# Do we want to change from phase to I1,Q,U,I2?
if dopol:
if pixinfo['tgi'] == 1:
ordering = [0,1,2,3]
else:
ordering = [0,2,1,3]
data[det][pix] = self.converttopol(data[det][pix],ordering=ordering)
for j in phaserange:
if plottods:
# Do a plot of az vs. tod
plot_tfgi_tod(data[det][pix][j],self.outdir+'/'+prefix+polext+plotext+'/tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1))
plot_tfgi_val_tod(az[det],data[det][pix][j],self.outdir+'/'+prefix+polext+plotext+'/az_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1))
plot_tfgi_val_tod(el[det],data[det][pix][j],self.outdir+'/'+prefix+polext+plotext+'/el_tod_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1))
plot_tfgi_val_tod(az[det],el[det],self.outdir+'/'+prefix+polext+plotext+'/az_el_'+str(pix+1)+'_'+str(det+1)+'_'+str(j+1))
# Plot the individual skydips
elbins = np.zeros((5,num_skydips,numelbins))
avg_systemp = 0.0
for i in range(1,num_skydips):
elstep = (maxel-minel)/float(numelbins)
stepmask = np.zeros(len(skydip_mask))
stepmask[skydip_mask == i] = 1
stepmask[skydip_mask == -i] = 1
for k in range(0,numelbins):
elstepmin = minel+k*elstep
elstepmax = minel+(k+1)*elstep
elbins[0][i][k] = (elstepmin+elstepmax)/2.0
elmask = np.zeros(len(skydip_mask))
elmask[el[det] > elstepmin] = elmask[el[det] > elstepmin] + 0.5
elmask[el[det] < elstepmax] = elmask[el[det] < elstepmax] + 0.5
elmask[elmask < 1] = 0
elbins[1][i][k] = np.mean(data[det][pix][j][stepmask*elmask==1])
# elbins[2][i][k] = np.sum(data[det][pix][j][stepmask*elmask==1])
# Before doing the std, subtract out a fit
params = [1,1]#,0]
param_est, cov_x, infodict, mesg_result, ret_value = optimize.leastsq(compute_residuals_skydip, params, args=(elbins[0][i], elbins[1][i]),full_output=True)
if pixinfo['tgi'] == 1:
systemp = (param_est[0]/(param_est[1]*np.sin(60.0*np.pi/180.0)))*atm_tgi
else:
systemp = (param_est[0]/(param_est[1]*np.sin(60.0*np.pi/180.0)))*atm_fgi
avg_systemp = avg_systemp + systemp
meas_outputfile.write(str(pix) + " " + str(det) + " " + str(j) + ' ' + str(i) + " " + str(systemp) + ' ' + str(param_est[0]) + " " + str(param_est[1])+'\n')
for k in range(0,numelbins):
elstepmin = minel+k*elstep
elstepmax = minel+(k+1)*elstep
elmask = np.zeros(len(skydip_mask))
elmask[el[det] > elstepmin] = elmask[el[det] > elstepmin] + 0.5
elmask[el[det] < elstepmax] = elmask[el[det] < elstepmax] + 0.5
elmask[elmask < 1] = 0
tempdata = data[det][pix][j][stepmask*elmask==1] - fit_skydip(el[det][stepmask*elmask==1],param_est)
elbins[2][i][k] = np.mean(tempdata)