/
myScimes.py
1751 lines (1006 loc) · 38.1 KB
/
myScimes.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
import os
import sys
import numpy as np
from astropy import wcs
from astropy.io import fits
from scipy.ndimage.measurements import label
from astropy.table.table import Column
from astropy.table import Table
from astrodendro import Dendrogram, ppv_catalog
from scimes import SpectralCloudstering
from matplotlib import pyplot as plt
import matplotlib.colors as colors
import time
from myTree import dendroTree
import glob
from pdb import set_trace as stop
from spectral_cube import SpectralCube
from astrodendro import Dendrogram
from astropy import units as u
from astropy.wcs import WCS
from myPYTHON import *
doFITS=myFITS()
# this function is used to mask the data before using dendrogram
# to identify signal region
def maskWithFellWalker(CO12FITS,saveMaskFITS,clumpMark):
"""
:param CO12FITS:
:param saveMaskFITS:
:param clumpMark:
:return:
"""
runCode="fellwalkerMWISP {} {}".format(CO12FITS,clumpMark)
os.system(runCode)
clumpFITS=clumpMark+"FellwalkerClump.fits"
data,head=doFITS.readFITS(clumpFITS)
dataCO,headCO=doFITS.readFITS(CO12FITS)
maskData=np.zeros_like(data)
maskData[data>0]=1
maskedCO=maskData*dataCO
maskedCO[maskedCO<=0]=np.nan
#convert to 32 bit
maskedCO=np.float32(maskedCO)
fits.writeto(saveMaskFITS, maskedCO , header=head, overwrite=True)
#saveMaskFITS, is the noise masked fits
#maskWithFellWalker("./mosaicTest2/sub11.fits", "./mosaicTest2/sub11MaskS1.fits" ,"./mosaicTest2/sub11Sigma1")
#aaaaa
def dilmasking(hdu, fchan = 8, ed = 4, th = 2,saveName=None,rms=0.5):
data = hdu.data
hd = hdu.header
#free1 = data[0:fchan,:,:]
#rms = np.nanstd(free1[np.isfinite(free1)])
# the MWISP survey is unitform, we use a single value of RMS for 12CO data
rmsmap = data[0]*0+ rms #np.nanstd(free1, axis=0)
rmscube = np.zeros(data.shape)
s2ncube = np.zeros(data.shape)
for v in range(data.shape[0]):
s2ncube[v,:,:] = data[v,:,:]/rmsmap[:,:]
rmscube[v,:,:] = rmsmap[:,:]
mask1 = np.zeros(data.shape, dtype=np.int)
mask2 = np.zeros(data.shape, dtype=np.int)
mask1[s2ncube > ed] = 1
mask2[s2ncube > th] = 1
mask1o = np.zeros(data.shape)
mask2o = np.zeros(data.shape)
# mask1 is large than 5 sigma?
# continuously, there must be three channels both large than 5 sigma,#
mask1o[mask1*(np.roll(mask1,1,axis=0)+np.roll(mask1,-1,axis=0)) > 0] = 1
mask2o[mask2*(np.roll(mask2,1,axis=0)+np.roll(mask2,-1,axis=0)) > 0] = 1
maskt = mask1o+mask2o
# Connectivity structure
s = np.asarray([[[1,1,1],[1,1,1],[1,1,1]],\
[[1,1,1],[1,1,1],[1,1,1]],\
[[1,1,1],[1,1,1],[1,1,1]]])
# Region labelling
labarr, nfeats = label(mask2o, structure=s)
#print nfeats, " islands found"
# Eliminate the clouds without core:
# applying the mask 1 the islands with
# core only stay -> find their asgns
flabarr = labarr*mask1o
asgns = np.unique(flabarr)
asgns = asgns.astype(np.int)
asgns = asgns[asgns != 0]
# Crate the dilate mask with only
# the selected islands
dilmask = np.zeros(data.shape, dtype=np.int)
vs, ys, xs = np.where(labarr > 0)
ids = labarr[np.where(labarr > 0)]
xys = xs+ys*data.shape[0]
sids = np.in1d(ids,asgns)
sxs = xs[sids]
sys = ys[sids]
svs = vs[sids]
dilmask[(svs,sys,sxs)] = 1
data[dilmask == 0] = np.nan
dilmask = fits.PrimaryHDU(dilmask,hd)
data = fits.PrimaryHDU(data,hd)
labarr = fits.PrimaryHDU(labarr,hd)
#data is the file to save
if saveName != None:
data.writeto(saveName,overwrite=True)
return dilmask, data, labarr
# Increase the recursion limit
sys.setrecursionlimit(100000)
# Some parameters / names to set globally
bmaj = 50./3600 # Modify with the size of the beam in deg
bmin = 50./3600 # Modify with the size of the beam in deg
class mySCIMES:
dataPath="./data/"
metadata = {}
metadata['data_unit'] = u.K
metadata['spatial_scale'] = 0.5 * u.arcmin
metadata['beam_major'] = 50/60. * u.arcmin # FWHM
metadata['beam_minor'] = 50/60. * u.arcmin # FWHM
metadata['velocity_scale'] = 0.2 * u.km/u.s # FWHM
c= 299792458.
f=115271202000.0
wavelength=c/f*u.meter
metadata['wavelength'] = wavelength # 22.9 * u.arcsec # FWHM
sigma = 0.5 #K, noise level
rms=sigma
regionName=None
subRight = "right"
subLeft = "left"
subUpper = "upper"
subLower = "lower"
#clusterSavePath = saveSCIMESPath #"./saveSCIMES/"
fitsSuffix = "500Cluster_asgn.fits"
#
subRegionList=None
subRegionDict=None
minArea=0.02 # square degrees
CO12FITS=None
maskSuffix="masked.fits"
downNoise=2.0
def __init__(self ,regionName,CO12FITS=None):
self.regionName=regionName
self.subFITSPath="./{}/".format(regionName)
if not os.path.isdir(self.subFITSPath ):
os.system("mkdir "+self.subFITSPath )
self.saveSCIMESPath= self.subFITSPath #"./saveSCIMES/"
self.CO12FITS=CO12FITS
pass
def getSubFITS(self,subRegion):
return self.saveSCIMESPath+subRegion+".fits"
def cropSubRegion(self,subRegion ):
"""
#
:param subRegion:
:param subRegionD:
:return:
"""
lRange,vRange= self.subregionDict[subRegion]
print lRange,vRange
doFITS.cropFITS( CO12FITS,Lrange=lRange ,Vrange=vRange,outFITS= self.getSubFITS(subRegion) ,overWrite=True )
def doSubRegion(self,subRegion,reDo=False,doMask=False,ed = 4, th = 2):
"""
Do dendrogram and scimes for one sub region
:param subRegion:
:return:
"""
#first crop fits
#self.cropSubRegion(subRegion)
# second doDendroAnd Scimes
subRegionFITS = self.getSubFITS(subRegion)
processFITS=subRegionFITS
if doMask:
print "Masking...{} with Fellwalker".format(subRegion)
maskedRegionFITS=self.saveSCIMESPath+subRegion+self.maskSuffix
#hdu=fits.open(subRegionFITS)[0]
#dilmasking(hdu, ed = ed, th = th,saveName=maskedRegionFITS)
maskWithFellWalker(subRegionFITS, maskedRegionFITS ,"./{}/{}".format(self.regionName,subRegion))
processFITS=maskedRegionFITS
self.doDendroAndScimes( processFITS , calDendro=reDo, subRegion=subRegion,vScale=10 ) # no mask
else:
self.doDendroAndScimes( subRegionFITS , calDendro=reDo,subRegion=subRegion ) # no mask
def doDendroAndScimes(self,fitsFile,rms=0.5, minPix=500 ,reDo=False,subRegion="" ,saveAll=True,vScale=10,useVolume=True,useLuminosity=True,useVelociy=True ,calDendro=True, inputDendro=None,iinputDenroCatFile=None ):
"""
:param fitsFile:
:param rms: #not important anymore
:param minPix:
:param reDo:
:param subRegion: #only used to save
:param saveAll:
:param vScale: only useful when useVeloicty is true
:param useVolume:
:param useLuminosity:
:param useVelociy:
:return:
"""
if not calDendro and (inputDendro ==None or iinputDenroCatFile==None):
print "If you do not want to calculate dendrogram, you need to provide the inputDendro and the catalog"
return
criteriaUsed=[]
scales=[]
saveMark=''
if useLuminosity:
criteriaUsed.append('luminosity')
scales.append(None)
saveMark=saveMark+'Lu'
if useVolume:
criteriaUsed.append('volume')
#criteriaUsed.append('trueVolume')
saveMark=saveMark+'Vo'
scales.append(None)
if useVelociy:
#criteriaUsed.append('trueVelocity')
criteriaUsed.append('v_rms')
scales.append(vScale)
saveMark=saveMark+'Ve'
saveMark=saveMark+"{}_{}".format(minPix,vScale)
subRegion=subRegion+saveMark
hdu=fits.open(fitsFile)[0]
data= hdu.data
hd=hdu.header
saveDendro=self.regionName+subRegion+"Dendro.fits"
cdelt1 = abs(hd.get('CDELT1'))
cdelt2 = abs(hd.get('CDELT2'))
ppbeam = abs((bmaj*bmin)/(cdelt1*cdelt2)*2*np.pi/(8*np.log(2))) # Pixels per beam
if not calDendro and os.path.isfile( self.saveSCIMESPath+saveDendro ):
print self.regionName," has been done, skipping..."
return
print("Making dendrogram...")
#from pruning import all_true, min_vchan, min_delta, min_area
#is_independent = all_true((min_delta(3*rms), min_area(288), min_vchan(2)))
#is_independent = all_true( ( min_area(288) ) )
#d = Dendrogram.compute(data, min_value=0, is_independent=is_independent, verbose=1, min_npix=10000 )
#d = Dendrogram.compute(data, min_value=0, verbose=1, min_npix=minPix ,min_delta=1.5 , is_independent=min_area(288) )
catName=self.saveSCIMESPath+self.regionName+subRegion +"dendroCat.fit"
treeFile=self.saveSCIMESPath+subRegion+"DendroTree.txt"
if calDendro: #just for test
d = Dendrogram.compute(data, min_value=0, verbose=1, min_npix=minPix, min_delta=1.5 )
d.save_to( saveDendro )
self.metadata["wcs"]= WCS(hd)
cat = ppv_catalog(d, self.metadata)
print len(cat),"<-- total number of structures?"
#print dir(cat)
cat.write(catName,overwrite=True)
self.writeTreeStructure(d,treeFile)
# add levels.
#if saveDendro:
#cat.write(self.saveSCIMESPath+saveDenroMark+".fit" ,overwrite=True)
#return d,self.saveSCIMESPath+saveDenroMark+".fit"
else: #just for test
d =inputDendro # do not read dendro here
cat = Table.read(iinputDenroCatFile)
print len(cat),"<-- total number of structures?"
#print dir(cat)
self.writeTreeStructure(d,treeFile)
# add levels.
#newVo,newVe=self.getTrueVolumeAndVrms(treeFile,iinputDenroCatFile,subRegion=subRegion)
#cat["trueVolume"]=newVo
#cat['trueVelocity']=newVe
###Test, what if we multiply the volumen by the dispersion of velocity dispersion in km/s
#cat.sort("v_rms")
#print cat
#print cat.colnames
res = SpectralCloudstering(d, cat, hd, criteria = criteriaUsed , user_scalpars=scales, blind = True , rms = self.rms, s2nlim = 3, save_all = saveAll, user_iter=1)
res.clusters_asgn.writeto (self.saveSCIMESPath+self.regionName+subRegion+'Cluster_asgn.fits', overwrite=True)
clusterCat=cat[res.clusters]
clusterCat.write( self.saveSCIMESPath +self.regionName+subRegion +"ClusterCat.fit",overwrite=True)
def getTrueVolumeAndVrms(self,treeFile,cat,subRegion=''):
"""
:param d:
:param cat:
:return:
"""
# calculate true volumes and true Vrms, by Vrms, we mean the velocity different of two leaves,which is more reasonable
# by true volumes we mean all the sum of leaves? ,better the former
#first get Tree
trueVolume='trueVolume'
trueVms='trueVms'
vrms="v_rms"
doTree= dendroTree(treeFile,dendroCat=cat)
doTree.getAllLeaves(0)
dendroTB=Table.read(cat)
dendroTB[trueVolume]= dendroTB["flux"]
dendroTB[trueVms]= dendroTB["v_rms"]
for eachRow in dendroTB:
allL=doTree.getAllLeaves(eachRow["_idx"] )
twoChildren=doTree.getChildren( eachRow["_idx"] )
tbSubLeaves=dendroTB[allL]
if len( tbSubLeaves)>1:
trueDV= max(tbSubLeaves['v_cen'])- min(tbSubLeaves['v_cen'])
trueDV=trueDV/1000
else:
trueDV= tbSubLeaves[0][vrms]
trueDV=trueDV
#print trueDV,len(tbSubLeaves )
#tbSubChildren=dendroTB[twoChildren]
eachRow[trueVolume] = eachRow["area_exact"]* trueDV
eachRow[trueVolume] = eachRow["area_exact"]* trueDV
eachRow[trueVms] = trueDV
#allC= tbSubChildren["area_exact"]*tbSubChildren["v_rms"]
#print np.sum(allC)
return dendroTB[trueVolume], dendroTB[trueVms]
def doScimes(self,dendroFITS,hd ):
self.metadata["wcs"]= WCS(hd)
d = Dendrogram.load_from( dendroFITS )
cat = ppv_catalog(d, self.metadata)
res = SpectralCloudstering(d, cat, hd, criteria = ['volume' ], blind = True, rms = self.rms, s2nlim = 3, save_all = True, user_iter=1)
res.clusters_asgn.writeto (self.regionName+'Cluster_asgn.fits', overwrite=True)
#save the catalog
def getLVrange(self, CO12FITS ):
data,head=myFITS.readFITS(CO12FITS)
wcsCO=WCS(head )
Nz,Ny,Nx=data.shape
l0,_,v0= wcsCO.wcs_pix2world(0,0,0,0)
l1,_,v1= wcsCO.wcs_pix2world(Nx-1,Ny-1,Nz-1,0)
v0,v1=v0/1000.,v1/1000
return [l0,l1],[v0,v1]
def getDivideCubesName(self,CO12FITS, divideConfig ):
"""
velocity is in km/s
longitude is in degree
Perticularly used for WMSIPS
:param CO12FITS:
:return:
"""
# produces subscube names that their corresponding vRange, and Lrange, which would be used to crop the cube
#
startL = divideConfig["startL"]
lStep= divideConfig["lStep"]
lSize = divideConfig["lSize"]
startV = divideConfig["startV"]
vStep = divideConfig["vStep"]
vSize = divideConfig["vSize"]
data,head=myFITS.readFITS(CO12FITS)
#find the, largest l and minimum v,
#find the minimum l and maximum v,
wcsCO=WCS(head )
Nz,Ny,Nx=data.shape
l0,_,v0= wcsCO.wcs_pix2world(0,0,0,0)
l1,_,v1= wcsCO.wcs_pix2world(Nx-1,Ny-1,Nz-1,0)
v0,v1=v0/1000.,v1/1000
NL= int( abs(l1-l0)/lStep ) +1
NV= int( abs(v1-v0)/vStep ) +1
regionList=[]
regionDict={}
for i in range(NL):
for j in range(NV):
countL=i+1
countV=j+1
regionName="sub{}{}".format(countL,countV)
if i==0:
lRange=[l0,startL-lSize]
else:
lRange=[startL-lStep*i,startL-lStep*i-lSize]
if j==0:
vRange=[v0,startV+vSize ]
else:
vRange=[startV+vStep*j,startV+vStep*j+vSize ]
regionDict[ regionName ] = [ lRange,vRange ]
regionList.append(regionName)
if startV+vStep*j+vSize>v1:
break
if startL-lStep*i-lSize<l1:
break
self.subRegionList=regionList
self.subregionDict= regionDict
return regionList, regionDict
def divdeCubes(self,CO12FITS,regionList,regionDict ):
"""
### # # # # # #
:param regionList:
:param regionDict:
:return:
"""
savePath=self.saveSCIMESPath
#os.system("mkdir "+savePath )
for eachRegion in regionList:
lRange,vRange=regionDict[eachRegion]
print "producing ", eachRegion+".fits"
doFITS.cropFITS( CO12FITS,Lrange=lRange ,Vrange=vRange,outFITS=savePath+eachRegion+".fits" )
def produceRunSH(self, CO12FITS, regionList, regionDict ): #
"""
The reason to use sh file is to guareette the memeory would be released when one cube is done
:param CO12FITS:
:param regionList:
:param regionDict:
:return:
"""
print "Producing sh script file..."
f = open("runSubcube.sh", "w")
for eachRegion in regionList:
runCommand= "python myScimes.py " + eachRegion
f.write( runCommand +"\n")
f.close()
def getUpperCube(self,cubeName,cubeList):
lIndex,vIndex = cubeName[3:5]
restNameStr= cubeName[0:3]
upperCube=restNameStr+"{}{}".format(int(lIndex), int(vIndex)+1)
if upperCube in cubeName:
return upperCube
return None
def getNearCube(self,cubeName,cubeList, position="right"):
lIndex,vIndex = cubeName[3:5]
restNameStr= cubeName[0:3]
if position== self.subRight:
nextCube=restNameStr + "{}{}".format(int(lIndex)+1, int(vIndex) )
if position== self.subLeft:
nextCube=restNameStr + "{}{}".format(int(lIndex)-1, int(vIndex) )
if position== self.subUpper:
nextCube=restNameStr + "{}{}".format(int(lIndex) , int(vIndex)+1 )
if position== self.subLower:
nextCube=restNameStr + "{}{}".format(int(lIndex) , int(vIndex)-1 )
#print nextCube
if nextCube in cubeList:
return nextCube
return None
def combinSubCubes(self,CO12FITSAll,cubeList):
"""
This function is used to combine the subcubes into a common one
:param CO12FITS:
:param cubeList:
:return:
"""
# this function is essentional
#Presumably, the cubes are connected
#first, find out the lrange and vrange of those cubes, cut out the
# conbine the cluster assign, and cluster catalog
print "Combing all sub cubes?"
clusterCubePath=self.saveSCIMESPath #"/home/qzyan/WORK/myDownloads/testScimes/saveSCIMES/"
fitsSuffix = "500Cluster_asgn.fits"
# find the Lrange, and vRange, for the cubes
leftLs=[]
rightLs= []
upperV=[]
lowerV=[]
for eachSub in cubeList:
clusterCube = eachSub+fitsSuffix
lRange,vRange=self.getLVrange( clusterCubePath+clusterCube )
leftLs.append( max(lRange) )
rightLs.append( min(lRange) )
upperV.append( max(vRange) )
lowerV.append( min(vRange) )
lRange,vRange= [max( leftLs), min(rightLs )], [min(lowerV ), max( upperV) ]
#crop the CO12FITS
mosaicFITScrop= "mosaicFITScrop.fits"
if 1:
doFITS.cropFITS(CO12FITSAll,Lrange=lRange,Vrange=vRange,outFITS= mosaicFITScrop,overWrite=True)
mosaicData,mosaicHead=myFITS.readFITS(mosaicFITScrop)
mosaicCluster=np.zeros_like( mosaicData )
wcsMosaic=WCS(mosaicHead)
idCol= "_idx"
modelTB=Table.read( clusterCubePath+cubeList[0]+"500ClusterCat.fit" )
acceptCloudTB= Table( modelTB[0] )
acceptCloudTB.remove_row(0)
for eachSub in cubeList:
clusterCube = clusterCubePath+eachSub+fitsSuffix
subData,subHead= myFITS.readFITS( clusterCube )
clusterCat= clusterCubePath+eachSub+"500ClusterCat.fit"
clusterCatTB=Table.read( clusterCat )
leftRegion = self.getNearCube(eachSub, cubeList,position= self.subLeft )
rightRegion =self.getNearCube(eachSub, cubeList,position= self.subRight )
lowerRegion = self.getNearCube(eachSub, cubeList,position= self.subLower )
upperRegion = self.getNearCube(eachSub, cubeList,position=self.subUpper )
totalCloudReject= []
if leftRegion !=None:
# find those touches left
cutleft=subData[ :, :, 0 ]
cutleft=cutleft.reshape(-1)
totalCloudReject=np.concatenate( [ totalCloudReject, cutleft ] )
#cloudsTouchLeft=set(cutleft )
#print cloudsTouchLeft
if rightRegion !=None:
cutRight=subData[ :, :, -1 ]
cutRight=cutRight.reshape(-1)
totalCloudReject=np.concatenate( [ totalCloudReject, cutRight ] )
if lowerRegion !=None:
cutLower=subData[ 0, :, : ]
cutLower=cutLower.reshape(-1)
totalCloudReject=np.concatenate( [ totalCloudReject, cutLower ] )
if upperRegion !=None:
cutUpper=subData[ -1, :,: ]
cutUpper=cutUpper.reshape(-1)
totalCloudReject=np.concatenate( [ totalCloudReject, cutUpper ] )
cloudsTobeRemove= map(int, set( totalCloudReject) )
#
##
lastTwoDigital=int( eachSub[-2:] )
#get lbv0Index
wcsSub=WCS(subHead) # wcsMosaic
l0,b0,v0 = wcsSub.wcs_pix2world(0,0,0,0)
l0Index,b0Index,v0Index= wcsMosaic.wcs_world2pix( l0,b0,v0,0 )
l0Index,b0Index,v0Index= map( int, [l0Index,b0Index,v0Index ] )
lbv0MergeIndex=[ l0Index,b0Index,v0Index ]
for eachCluster in clusterCatTB:
clusterID= eachCluster[idCol ]
if clusterID in cloudsTobeRemove:
continue
#Examine area
if eachCluster["area_exact"]/3600./3600. < self.minArea: # in square degress
print "{} of {} is too small, rejected.".format(clusterID ,eachSub )
continue
if self.isDubplicated(eachCluster,acceptCloudTB):
print " {} of {} is duplicated! ignore...".format(clusterID ,eachSub )
continue
else:
acceptCloudTB.add_row(eachCluster)
newIndex=clusterID*100+lastTwoDigital
eachCluster[idCol] = newIndex
acceptCloudTB.add_row( eachCluster )
# merge this cloud into the old one
#
self.mergeSub(clusterID, newIndex,subData, mosaicCluster, lbv0MergeIndex,acceptCloudTB )
#save for test
fits.writeto("mergedCluster.fits",mosaicCluster,mosaicHead,overwrite=True )
acceptCloudTB.write("mergeCat.fit" , overwrite=True )
def touchEdge(self,subID,subFITS):
"""
check if a cloud touches the edge of cube, any edge
:param subID:
:param subFITS:
:return:
"""
data,head=myFITS.readFITS(subFITS)
Nz,Ny,Nx= data.shape
Zs,Ys,Xs=np.where(data==subID)
if max(Zs) == Nz-1 or min(Zs)==0:
return True
if max(Ys) == Ny-1 or min(Ys)==0:
return True
if max(Xs) == Nx-1 or min(Xs)==0:
return True
return False
def mergeSub(self,subID, newID, subData, mergeData,lvb0MergeIndex, acceptCloudTB, force = True ):
"""
Merge sub cluster into mergedData with newID
:param subID:
:param subData:
:param subHead:
:param mergeData:
:param mergeHead:
:return:
"""
# important function
#
#find the index of subID in subData, convertID
print "merging...{} of sub{}".format( subID, str(newID)[-2:] )
#l0,b0,v0 = lbv0 # wcsSub.wcs_pix2world(0,0,0,0)
#################
#l0Index,b0Index,v0Index= wcsMerge.wcs_world2pix( l0,b0,v0,0 )
l0Index,b0Index,v0Index= lvb0MergeIndex #map( int, [l0Index,b0Index,v0Index ] )
#### ####
subIndex=np.where( subData==subID )
vIndex=subIndex[0]+v0Index
bIndex=subIndex[1]+b0Index
lIndex=subIndex[2]+l0Index
combIndex=tuple([vIndex,bIndex,lIndex])
if np.sum( mergeData[ combIndex] )== 0:
mergeData[ combIndex] =newID
return
else:
#save to clouds
existClouds= mergeData[ combIndex ]
existClouds=existClouds.reshape(-1)
existClouds= list( set( existClouds) )
existClouds= np.array( map(int, existClouds ) )
existClouds=existClouds[existClouds>0]
#print existClouds, "??????????????????????????????"
#clashC=len( set( existClouds) )
clashC=len( existClouds )
# If there is only one cloud in clash, and one of them touches the edge, keep the one that do not touch edge
# if
print existClouds,"?????????????????"
print clashC,"??????????????????????"
if clashC ==1: #
firstID= int( existClouds[0] )
preRegionFITS= self.saveSCIMESPath+"sub"+str(firstID)[-2:]+self.fitsSuffix
preID= int( str(firstID)[0:-2 ] )
preTouchEdge= self.touchEdge(preID, preRegionFITS)
# check if the latter one touches edges
secondID = int( newID )
latterRegionFITS = self.saveSCIMESPath+"sub"+str(secondID)[-2:]+self.fitsSuffix
latterTouchEdge = self.touchEdge(subID, latterRegionFITS)