-
Notifications
You must be signed in to change notification settings - Fork 6
/
balrog.py
executable file
·1858 lines (1489 loc) · 73.7 KB
/
balrog.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
import shutil
import distutils.spawn
import signal
import warnings
import re
import time
import imp
import copy
import datetime
import os
import sys
import subprocess
import argparse
import logging
import traceback
import numpy as np
import astropy.io.fits as pyfits
import galsim
import galsim.des
import sextractor_engine
from model_class import *
def FindInCat(rule, name):
cat = rule.param[0]
ext = rule.param[1]
n = rule.param[2]
hdu = pyfits.open(cat)[ext]
#cut = np.in1d(hdu.columns.names,np.array([name]))
cut = np.in1d(hdu.columns.names,np.array([n]))
return cut, hdu
def WriteCatalog(sample, BalrogSetup, txt=None, fits=False, TruthCatExtra=None, extracatalog=None, setup=None):
columns = []
for key in sample.galaxy.keys():
name = '%s' %(key)
arr = sample.galaxy[key]
if key=='x':
arr = arr - BalrogSetup.xmin + 1
unit = 'pix'
elif key=='y':
arr = arr - BalrogSetup.ymin + 1
unit = 'pix'
elif key.find('flux')!=-1:
unit = 'ADU'
else:
unit = 'dimensionless'
#col = pyfits.Column(name=name, array=arr,format='E', unit=unit)
col = pyfits.Column(name=name, array=arr,format='D', unit=unit)
columns.append(col)
if TruthCatExtra is not None:
for rule,name,fmt,unit in zip(TruthCatExtra.rules,TruthCatExtra.names,TruthCatExtra.fmts, TruthCatExtra.units):
if unit is None:
if rule.type!='catalog':
unit = 'unspecified'
BalrogSetup.runlogger.info('No unit was specificed for additional truth catalog column %s' %(name))
else:
cut,hdu = FindInCat(rule, name)
unit = np.array(hdu.columns.units)[cut][0]
if unit.strip()=='':
unit = 'unspecified'
if fmt is None:
if rule.type!='catalog':
if len(extracatalog.galaxy[name])==0:
#fmt = 'E'
raise TableUnknownType(401, name)
else:
arrtype = str(type(extracatalog.galaxy[name][0]))
if arrtype.find('str')!=-1:
strlen = len(max(extracatalog.galaxy[name]))
fmt = '%iA' %(strlen)
elif arrtype.find('int')!=-1:
fmt = 'J'
else:
fmt = 'E'
else:
cut,hdu = FindInCat(rule, name)
fmt = np.array(hdu.columns.formats)[cut][0]
col = pyfits.Column(array=extracatalog.galaxy[name], name=name, format=fmt, unit=unit)
columns.append(col)
for i in range(len(sample.component)):
for key in sample.component[i].keys():
name = '%s_%i' %(key,i)
if key.find('halflightradius')!=-1:
col = pyfits.Column(name=name, array=sample.component[i][key]/np.sqrt(sample.component[i]['axisratio']), format='E', unit='arcsec')
else:
if key.find('sersicindex')!=-1:
unit = 'dimensionless'
if key.find('flux')!=-1:
unit = 'ADU'
if key.find('beta')!=-1:
unit = 'deg'
if key.find('axisratio')!=-1:
unit = 'dimensionless'
col = pyfits.Column(name=name, array=sample.component[i][key],format='E', unit=unit)
columns.append(col)
try:
tbhdu = pyfits.BinTableHDU.from_columns(pyfits.ColDefs(columns))
except:
tbhdu = pyfits.new_table(pyfits.ColDefs(columns))
tbhdu.header['XSTART'] = BalrogSetup.xmin
tbhdu.header['XEND'] = BalrogSetup.xmax
tbhdu.header['YSTART'] = BalrogSetup.ymin
tbhdu.header['YEND'] = BalrogSetup.ymax
tbhdu.header['NSIM'] = BalrogSetup.ngal
tbhdu.header['ZP'] = BalrogSetup.zeropoint
if fits:
phdu = pyfits.PrimaryHDU()
hdus = pyfits.HDUList([phdu,tbhdu])
if os.path.lexists(BalrogSetup.catalogtruth):
os.remove(BalrogSetup.catalogtruth)
hdus.writeto(BalrogSetup.catalogtruth)
if txt is not None:
data = tbhdu.data
d = []
for name in data.columns.names:
d.append( data[name] )
d = tuple(d)
np.savetxt(txt, np.dstack(d)[0], fmt='%.5f')
BalrogSetup.assocnames = data.columns.names
def CopyAssoc(BalrogSetup, outfile):
mhdus = pyfits.open(outfile, mode='update')
mhead = mhdus[BalrogSetup.catext].header
for i in range(len(BalrogSetup.assocnames)):
mhead[ 'V%i'%i ] = BalrogSetup.assocnames[i]
if BalrogSetup.assocnames[i] in ['x','y']:
unit = 'pix'
elif BalrogSetup.assocnames[i].find('halflightradius')!=-1:
unit = 'arcsec'
elif BalrogSetup.assocnames[i].find('beta')!=-1:
unit = 'deg'
elif BalrogSetup.assocnames[i].find('flux')!=-1:
unit = 'ADU'
else:
unit = 'dimensionless'
mhead[ 'VUNIT%i'%i ] = unit
mhdus.close()
def ReadImages(BalrogSetup):
if BalrogSetup.nodraw and (not BalrogSetup.subsample):
return [None]*4
matchwcs = False
image = galsim.fits.read(BalrogSetup.image, hdu=BalrogSetup.imageext)
if image.wcs==galsim.PixelScale(1):
thisdir = os.path.dirname( os.path.realpath(__file__) )
file = os.path.join(thisdir, 'fiducialwcs.fits')
image.wcs = galsim.GSFitsWCS(file)
matchwcs = True
BalrogSetup.wcshead = file
BalrogSetup.runlogger.warning('No WCS was found in the input image header. Using default pixel scale of 0.263 arcsec/pixel.')
wcs = image.wcs
subBounds = galsim.BoundsI(BalrogSetup.xmin,BalrogSetup.xmax,BalrogSetup.ymin,BalrogSetup.ymax)
image = image[subBounds]
psfmodel = galsim.des.DES_PSFEx(BalrogSetup.psf, BalrogSetup.wcshead)
weight = None
if not BalrogSetup.noweightread:
weight = galsim.fits.read(BalrogSetup.weight, hdu=BalrogSetup.weightext)
if matchwcs:
weight.wcs = image.wcs
weight = weight[subBounds]
return image, weight, psfmodel, wcs
def WriteImages(BalrogSetup, image, weight, nosim=False, setup=None):
weightout = BalrogSetup.weightout
if nosim:
imageout = BalrogSetup.nosim_imageout
else:
imageout = BalrogSetup.imageout
if (BalrogSetup.nodraw) and (not BalrogSetup.subsample):
rm_link(imageout)
os.symlink(BalrogSetup.image, imageout)
if (BalrogSetup.weight!=BalrogSetup.image) and (not BalrogSetup.noweightread):
rm_link(weightout)
os.symlink(BalrogSetup.weight, weightout)
else:
if BalrogSetup.weight==BalrogSetup.image:
if not BalrogSetup.noweightread:
galsim.fits.writeMulti(image_list=[image,weight], file_name=imageout)
else:
galsim.fits.writeMulti(image_list=[image], file_name=imageout)
else:
galsim.fits.write(image=image, file_name=imageout)
if not BalrogSeutp.noweightread:
if (BalrogSetup.nonosim) or (nosim):
if BalrogSetup.subsample:
galsim.fits.write(image=weight, file_name=weightout)
else:
rm_link(weightout)
os.symlink(BalrogSetup.weight, weightout)
if not BalrogSetup.psf_written:
WritePsf(BalrogSetup, BalrogSetup.psf, BalrogSetup.psfout, setup=setup)
if BalrogSetup.detpsf!=BalrogSetup.psf:
WritePsf(BalrogSetup, BalrogSetup.detpsf, BalrogSetup.detpsfout, setup=setup)
BalrogSetup.psf_written = True
def WritePsf(BalrogSetup, psfin, psfout, setup=None):
psfhdus = pyfits.open(psfin)
psfhdus[1].header['POLZERO1'] = psfhdus[1].header['POLZERO1'] - (BalrogSetup.xmin - 1)
psfhdus[1].header['POLZERO2'] = psfhdus[1].header['POLZERO2'] - (BalrogSetup.ymin - 1)
if os.path.lexists(psfout):
os.remove(psfout)
psfhdus.writeto(psfout)
def InsertSimulatedGalaxies(bigImage, simulatedgals, psfmodel, BalrogSetup, wcs, gspcatalog):
#psizes, athresh = simulatedgals.GetPSizes(BalrogSetup, wcs)
t0 = datetime.datetime.now()
rt = long( t0.microsecond )
'''
simulatedgals.galaxy['flux_noised'] = np.copy(simulatedgals.galaxy['x'])
simulatedgals.galaxy['flux_noiseless'] = np.copy(simulatedgals.galaxy['x'])
'''
simulatedgals.galaxy['flux_noised'] = np.zeros( len(simulatedgals.galaxy['x']) )
simulatedgals.galaxy['flux_noiseless'] = np.zeros( len(simulatedgals.galaxy['x']) )
simulatedgals.galaxy['not_drawn'] = np.array( [0]*len(simulatedgals.galaxy['x']) )
for i in range(BalrogSetup.ngal):
start = datetime.datetime.now()
#postageStampSize = int(psizes[i])
d = {}
for key in gspcatalog.galaxy.keys():
if not IsNone(gspcatalog.galaxy[key]):
if key in ['minimum_fft_size', 'maximum_fft_size', 'range_for_extrema']:
mod = gspcatalog.galaxy[key][i] % 1
if mod > 0.0:
d[key] = gspcatalog.galaxy[key][i]
else:
d[key] = int(gspcatalog.galaxy[key][i])
else:
d[key] = gspcatalog.galaxy[key][i]
with warnings.catch_warnings():
try:
warnings.simplefilter("ignore", category=galsim.GalSimDeprecationWarning)
except:
pass
gsparams = galsim.GSParams(**d)
try:
combinedObjConv = simulatedgals.GetConvolved(psfmodel, i, wcs, gsparams, BalrogSetup)
except:
simulatedgals.galaxy['not_drawn'][i] = 1
#print simulatedgals.component[0]['sersicindex'][i],simulatedgals.component[0]['halflightradius'][i],simulatedgals.component[0]['flux'][i],simulatedgals.component[0]['axisratio'][i],simulatedgals.component[0]['beta'][i], simulatedgals.galaxy['magnification'][i]; sys.stdout.flush()
continue
ix = int(simulatedgals.galaxy['x'][i])
iy = int(simulatedgals.galaxy['y'][i])
'''
smallImage = galsim.Image(postageStampSize,postageStampSize)
smallImage.setCenter(ix,iy)
smallImage.wcs = bigImage.wcs
smallImage = combinedObjConv.draw(image=smallImage)
'''
pos = galsim.PositionD(simulatedgals.galaxy['x'][i], simulatedgals.galaxy['y'][i])
local = wcs.local(image_pos=pos)
localscale = np.sqrt(local.dudx * local.dvdy)
#smallImage = combinedObjConv.draw(scale=localscale)
with warnings.catch_warnings():
try:
warnings.simplefilter("ignore", category=galsim.GalSimDeprecationWarning)
except:
pass
try:
smallImage = combinedObjConv.draw(scale=localscale, use_true_center=False)
except:
simulatedgals.galaxy['not_drawn'][i] = 1
#print simulatedgals.component[0]['sersicindex'][i],simulatedgals.component[0]['halflightradius'][i],simulatedgals.component[0]['flux'][i],simulatedgals.component[0]['axisratio'][i],simulatedgals.component[0]['beta'][i], simulatedgals.galaxy['magnification'][i]; sys.stdout.flush()
continue
smallImage.setCenter(ix,iy)
t1 = datetime.datetime.now()
dt = t1 - t0
if BalrogSetup.noiseseed is None:
micro = long( (dt.days*24*60*60 + dt.seconds)*1.0e6 + dt.microseconds ) + rt + i
else:
micro = BalrogSetup.noiseseed + i
bounds = smallImage.bounds & bigImage.bounds
simulatedgals.galaxy['flux_noiseless'][i] = smallImage.added_flux
smallImage.addNoise(galsim.CCDNoise(gain=BalrogSetup.gain,read_noise=0,rng=galsim.BaseDeviate(micro)))
flux_noised = np.sum(smallImage.array.flatten())
simulatedgals.galaxy['flux_noised'][i] = flux_noised
bounds = smallImage.bounds & bigImage.bounds
bigImage[bounds] += smallImage[bounds]
end = datetime.datetime.now()
#print (end - start).total_seconds(), simulatedgals.component[0]['sersicindex'][i], simulatedgals.component[0]['halflightradius'][i], simulatedgals.component[0]['axisratio'][i], simulatedgals.component[0]['flux'][i]; sys.stdout.flush()
return bigImage
def IsValidLine(line):
if line=='':
return False
line = line.strip()
if line=='':
return False
if line[0] =='#':
return False
return True
def ParamTxtWithoutAssoc(param_file):
txt = open(param_file).read().strip()
lines = txt.split('\n')
todelete = []
for i in range(len(lines)):
line = lines[i]
if not IsValidLine(line):
continue
if line.startswith('VECTOR_ASSOC('):
todelete.append(i)
lines = np.array(lines)
lines = np.delete(lines, todelete)
txt = '\n'.join(lines)
return txt
def WriteParamFile(BalrogSetup, catalogmeasured, nosim):
if not nosim:
param_file = BalrogSetup.sexparam
else:
param_file = BalrogSetup.nosimsexparam
pfile = DefaultName(catalogmeasured, '.fits', '.sex.params', BalrogSetup.sexdir)
txt = ParamTxtWithoutAssoc(param_file)
if not BalrogSetup.noassoc: #and not nosim:
start = 'VECTOR_ASSOC(%i)' %(len(BalrogSetup.assocnames))
txt = '%s\n%s' %(start,txt)
stream = open(pfile, 'w')
stream.write(txt)
stream.close()
return pfile
def WriteConfigFile(BalrogSetup, config_file, catalogmeasured):
cfile = DefaultName(catalogmeasured, '.fits', '.sex.config', BalrogSetup.sexdir)
txt = open(config_file).read().strip()
lines = txt.split('\n')
todelete = []
for i in range(len(lines)):
line = lines[i]
if not IsValidLine(line):
continue
if line.find('ASSOC')!=-1:
todelete.append(i)
if len(todelete)==0:
return config_file
lines = np.array(lines)
lines = np.delete(lines, todelete)
txt = '\n'.join(lines)
stream = open(cfile, 'w')
stream.write(txt)
stream.close()
return cfile
def AutoConfig(BalrogSetup, detimageout, imageout, detweightout, weightout, catalogmeasured, config_file, param_file, afile, eng, nosim):
eng.Path(BalrogSetup.sexpath)
eng.config['IMAGE'] = '%s[%i],%s[%s]' %(detimageout,BalrogSetup.outdetimageext, imageout,BalrogSetup.outimageext)
eng.config['WEIGHT_IMAGE'] = '%s[%i],%s[%i]' %(detweightout,BalrogSetup.outdetweightext, weightout,BalrogSetup.outweightext)
eng.config['CATALOG_NAME'] = catalogmeasured
eng.config['c'] = config_file
eng.config['PARAMETERS_NAME'] = param_file
eng.config['STARNNW_NAME'] = BalrogSetup.sexnnw
eng.config['FILTER_NAME'] = BalrogSetup.sexconv
eng.config['MAG_ZEROPOINT'] = BalrogSetup.zeropoint
eng.config['PSF_NAME'] = '%s,%s' %(BalrogSetup.detpsfout, BalrogSetup.psfout)
eng.config['CATALOG_TYPE'] = '%s' %(BalrogSetup.catfitstype)
if not BalrogSetup.noassoc:
ind = range(1, len(BalrogSetup.assocnames)+1)
inds = []
for i in ind:
inds.append(str(i))
if BalrogSetup.assocnames[i-1] == 'x':
x = i
if BalrogSetup.assocnames[i-1] == 'y':
y = i
eng.config['ASSOC_NAME'] = afile
eng.config['ASSOC_PARAMS'] = '%i,%i' %(x,y)
eng.config['ASSOC_DATA'] = ','.join(inds)
'''
if not nosim:
eng.config['ASSOC_DATA'] = ','.join(inds)
else:
eng.config['ASSOC_DATA'] = '%i,%i' %(x,y)
'''
eng.config['ASSOC_RADIUS'] = '2.0'
eng.config['ASSOC_TYPE'] = 'NEAREST'
eng.config['ASSOCSELEC_TYPE'] = 'MATCHED'
def RunSextractor(BalrogSetup, ExtraSexConfig, catalog, nosim=False, sim_noassoc_seg=False, setup=None):
afile = None
weightout = BalrogSetup.weightout
detweightout = BalrogSetup.detweightout
if nosim:
catalogmeasured = BalrogSetup.nosim_catalogmeasured
imageout = BalrogSetup.nosim_imageout
detimageout = BalrogSetup.nosim_detimageout
if not BalrogSetup.noassoc:
afile = BalrogSetup.assoc_nosimfile
elif not sim_noassoc_seg:
catalogmeasured = BalrogSetup.catalogmeasured
imageout = BalrogSetup.imageout
detimageout = BalrogSetup.detimageout
if not BalrogSetup.noassoc:
afile = BalrogSetup.assoc_simfile
if (BalrogSetup.image==BalrogSetup.weight) and (not BalrogSetup.noweightread):
weightout = imageout
if (BalrogSetup.detimage==BalrogSetup.detweight) and (not BalrogSetup.noweightread):
detweightout = detimageout
else:
catalogmeasured = BalrogSetup.sim_noassoc_catalogmeasured
imageout = BalrogSetup.imageout
detimageout = BalrogSetup.detimageout
if not BalrogSetup.noassoc:
afile = BalrogSetup.assoc_simfile
if (BalrogSetup.image==BalrogSetup.weight) and (not BalrogSetup.noweightread):
weightout = imageout
if (BalrogSetup.detimage==BalrogSetup.detweight) and (not BalrogSetup.noweightread):
detweightout = detimageout
if not BalrogSetup.noassoc:
WriteCatalog(catalog, BalrogSetup, txt=afile, fits=False, setup=setup)
if sim_noassoc_seg and BalrogSetup.sim_noassoc_seg_param_file:
param_file = BalrogSetup.sim_noassoc_seg_param_file
else:
param_file = WriteParamFile(BalrogSetup, catalogmeasured, nosim)
config_file = BalrogSetup.sexconfig
#if not BalrogSetup.noassoc:
config_file = WriteConfigFile(BalrogSetup, config_file, catalogmeasured)
'''
if setup.redirect is not None:
logtosend = setup.redirect
'''
if setup.kind=='system':
logtosend = BalrogSetup.sexlog
elif setup.kind=='popen':
logtosend = BalrogSetup.sexlogger
sexlogsetup = setup.Copy(redirect=logtosend)
eng = sextractor_engine.SextractorEngine(setup=sexlogsetup)
for key in ExtraSexConfig.keys():
eng.config[key] = ExtraSexConfig[key]
if BalrogSetup.nonosim:
if (BalrogSetup.nodraw) and (not BalrogSetup.subsample):
#detweightout = BalrogSetup.detweight
#weightout = BalrogSetup.weight
detimageout = BalrogSetup.detimage
imageout = BalrogSetup.image
AutoConfig(BalrogSetup, detimageout, imageout, detweightout, weightout, catalogmeasured, config_file, param_file, afile, eng, nosim)
if nosim:
msg = '# Running sextractor prior to inserting simulated galaxies\n'
else:
msg = '\n\n# Running sextractor after inserting simulated galaxies\n'
eng.run(msg=msg)
if not BalrogSetup.noassoc: #and not nosim:
CopyAssoc(BalrogSetup, catalogmeasured)
def rm_link(attr):
if os.path.lexists(attr):
os.remove(attr)
def NosimRunSextractor(BalrogSetup, bigImage, subweight, ExtraSexConfig, catalog, setup=None):
if BalrogSetup.subsample:
WriteImages(BalrogSetup, bigImage, subweight, nosim=True, setup=setup)
else:
rm_link(BalrogSetup.nosim_imageout)
rm_link(BalrogSetup.psfout)
os.symlink(BalrogSetup.psf, BalrogSetup.psfout)
os.symlink(BalrogSetup.image, BalrogSetup.nosim_imageout)
if BalrogSetup.psf!=BalrogSetup.detpsf:
rm_link(BalrogSetup.detpsfout)
os.symlink(BalrogSetup.detpsf, BalrogSetup.detpsfout)
if (BalrogSetup.weight!=BalrogSetup.image) and (not BalrogSetup.noweightread):
rm_link(BalrogSetup.weightout)
os.symlink(BalrogSetup.weight, BalrogSetup.weightout)
if (BalrogSetup.detweight!=BalrogSetup.detimage) and (not BalrogSetup.noweightread):
if BalrogSetup.detweightout!=BalrogSetup.weightout:
rm_link(BalrogSetup.detweightout)
os.symlink(BalrogSetup.detweight, BalrogSetup.detweightout)
if BalrogSetup.nosim_detimageout!=BalrogSetup.detimagein:
rm_link(BalrogSetup.nosim_detimageout)
os.symlink(BalrogSetup.detimagein, BalrogSetup.nosim_detimageout)
BalrogSetup.psf_written = True
RunSextractor(BalrogSetup, ExtraSexConfig, catalog, nosim=True, setup=setup)
def Cleanup(BalrogSetup, setup=None):
files = [BalrogSetup.imageout, BalrogSetup.psfout, BalrogSetup.weightout, BalrogSetup.nosim_imageout]
for file in files:
if os.path.lexists(file):
os.remove(file)
def UserDefinitions(cmdline_args, BalrogSetup, config, galkeys, compkeys):
rules = SimRules(BalrogSetup.ngal, galkeys, compkeys)
ExtraSexConfig = {}
results = Results(galkeys, compkeys)
cmdline_args_copy = copy.copy(cmdline_args)
TruthCatExtra = TableColumns(BalrogSetup.ngal)
if config is not None:
if 'CustomParseArgs' not in dir(config):
BalrogSetup.runlogger.warning('The function CustomParseArgs was not found in your Balrog python config file: %s. Will continue without parsing any custom command line arguments.' %BalrogSetup.pyconfig)
else:
config.CustomParseArgs(cmdline_args_copy)
copy1 = copy.copy(cmdline_args_copy)
copy2 = copy.copy(cmdline_args_copy)
if 'SimulationRules' not in dir(config):
BalrogSetup.runlogger.warning('The function SimulationRules was not found in your Balrog python config file: %s. All properties of the simulated galaxies will assume their defaults.' %BalrogSetup.pyconfig)
else:
config.SimulationRules(copy1,rules,results, TruthCatExtra)
if 'SextractorConfigs' not in dir(config):
BalrogSetup.runlogger.info('The function SextractorConfigs was not found in your Balrog python config file: %s. Add this function to manually override configurations in the sextractor config file.' %BalrogSetup.pyconfig)
else:
config.SextractorConfigs(copy2, ExtraSexConfig)
LogCmdlineOpts(cmdline_args, cmdline_args_copy, BalrogSetup.arglogger, '\n# Final parsed values for each command line option')
return rules, ExtraSexConfig, cmdline_args_copy, TruthCatExtra
class Result4GSP(object):
def __init__(self, cat):
super(Result4GSP, self).__setattr__('galkeys', cat.galaxy.keys())
for key in self.galkeys:
super(Result4GSP, self).__setattr__(key, cat.galaxy[key])
super(Result4GSP, self).__setattr__('compkeys', cat.component[0].keys())
if len(cat.component)>1:
for key in self.compkeys:
super(Result4GSP, self).__setattr__(key, [None]*len(cat.component))
for i in range(len(cat.component)):
for key in self.compkeys:
exec 'self.%s[%i] = cat.component[%i]["%s"]' %(key,i,i,key)
else:
for key in self.compkeys:
super(Result4GSP, self).__setattr__(key, cat.component[0][key])
def __getattr__(self, name):
raise SampledAttributeError(401, name, 'galaxies')
def __getitem__(self, index):
raise SampledIndexingError(402, 'galaxies')
def __setitem__(self, index, value):
raise SampledIndexingError(402, 'galaxies')
def __setattr__(self, name, value):
raise SampledAssignmentError(403, name, 'galaxies')
def GetSimulatedGalaxies(BalrogSetup, simgals, config, cmdline_opts_copy, TruthCatExtra):
used = simgals.Sample(BalrogSetup)
gkeys = ['minimum_fft_size','maximum_fft_size','alias_threshold','stepk_minimum_hlr','maxk_threshold','kvalue_accuracy','xvalue_accuracy','table_spacing','realspace_relerr','realspace_abserr','integration_relerr','integration_abserr']
gsp = SimRules(BalrogSetup.ngal, gkeys, [])
if config is not None:
if 'GalsimParams' not in dir(config):
BalrogSetup.runlogger.warning('The function GalsimParams was not found in your Balrog python config file: %s. Add this function to manually override the Galsim GSParams.' %BalrogSetup.pyconfig)
else:
s = Result4GSP(simgals)
config.GalsimParams(cmdline_opts_copy, gsp, s)
grules = [gsp.minimum_fft_size, gsp.maximum_fft_size, gsp.alias_threshold, gsp.stepk_minimum_hlr, gsp.maxk_threshold, gsp.kvalue_accuracy, gsp.xvalue_accuracy, gsp.table_spacing, gsp.realspace_relerr, gsp.realspace_abserr, gsp.integration_relerr, gsp.integration_abserr]
gsprules = DefineRules(BalrogSetup.ngal, gkeys, grules, [], [], 0)
used = gsprules.SimpleSample(BalrogSetup, used)
if len(TruthCatExtra.rules)==0:
ExtraTruthCat = None
TruthRules = None
else:
ncomp = len(simgals.component)
ExtraTruthRules = TruthCatExtra.rules
TruthRules = DefineRules(BalrogSetup.ngal, TruthCatExtra.names, ExtraTruthRules, [], [], ncomp)
for gal in simgals.galaxy.keys():
TruthRules.galaxy[gal] = simgals.galaxy[gal]
for i in range(ncomp):
for comp in simgals.component[i].keys():
TruthRules.component[i][comp] = simgals.component[i][comp]
used = TruthRules.SimpleSample(BalrogSetup, used)
simgals.galaxy['balrog_index'] = BalrogSetup.indexstart + np.arange(0, BalrogSetup.ngal)
return simgals, gsprules, TruthRules, TruthCatExtra
def CompError(name, i):
if name=='flux':
name = 'magnitude'
raise RulesAssignmentError(303, 'component %i of %s' %(i, name))
def GalError(name):
raise RulesAssignmentError(303, name)
class TableColumns(object):
def __init__(self, ngal):
super(TableColumns, self).__setattr__('ngal', ngal)
super(TableColumns, self).__setattr__('rules', [])
super(TableColumns, self).__setattr__('names', [])
super(TableColumns, self).__setattr__('fmts', [])
super(TableColumns, self).__setattr__('units', [])
self.InitializeSersic()
def InitializeSersic(self, nProfiles=1):
super(TableColumns, self).__setattr__('nProfiles', nProfiles)
def AddColumn(self, rule=None, name=None, fmt=None, unit=None):
rule = self._CheckRule(rule, name)
if rule.type != 'catalog':
if name is None:
raise ColumnNameError(703)
else:
if name is None:
name = rule.param[2]
self.rules.append(rule)
self.names.append(name)
self.fmts.append(fmt)
self.units.append(unit)
def _CheckRule(self, rule, name):
if type(rule).__name__!='Rule':
if type(rule).__name__=='CompResult':
if rule.nProfiles==1:
return self._CheckRule(rule[0], name)
else:
raise ColumnArrayError(705, name)
elif type(rule)==float or type(rule)==int or type(rule)==str:
rule = Value(rule)
else:
try:
arr = np.array(rule)
if arr.ndim==1 and arr.size==self.ngal:
rule = Array(arr)
else:
raise ColumnSizeError(701, name, len(arr), self.ngal)
except:
raise ColumnDefinitionError(702, name)
return rule
def __setattr__(self, name, value):
raise ColumnAttributeError(706, name)
## Class used with the {sersicindex, halflightradius, magnitude, axisratio, beta} components of rules.
# Since a simulated galaxy can have as many Sersic components as desired, the basic object of the class is an array called @p rules.
# Index/attribute get/set methods are overwritten to put restrictions on how users can interact with the class
# and then handle errors if they do something bad.
class CompRules(object):
## Initialize the rules, setting each rule to None, which will equate to using Balrog's defaults if the rule is not reassigned.
# @param nProfiles Integer number of Sersic profiles which make up the simulated galaxy
# @param name String name for the Sersic parameter, e.g. @p halflightradius
def __init__(self, nProfiles, name):
super(CompRules, self).__setattr__('rules', [None]*nProfiles)
super(CompRules, self).__setattr__('name', name)
super(CompRules, self).__setattr__('nProfiles', nProfiles)
## Throw an error if the user tries to define a new attribute.
# e.g. @p rules.beta.nonsense = 100
# @param name Attempted attribute name
# @param value Attempted attribute value
def __setattr__(self, name, value):
raise RulesComponentAttributeError(305)
## Throw an error if the user asks for an attribute which does not exist.
# The only attributes which exist are {rules, name, nProfiles}.
# However, unless they dig through the code, users will not know those three exist anyway.
# I would have preferred if python let me forbid access to these as well, but since
# they cannot be reassigned access to them does not hurt.
# @param name Attempted attribute name
def __getattr__(self, name):
raise RulesComponentAttributeError(305)
## Return the length of the @p rules array
def __len__(self):
return self.nProfiles
## Throw an error if the requested index is out of range; otherwise get element @p index of the rules array.
# @param index Attempted integer array position
def __getitem__(self, index):
if index >= self.nProfiles:
raise RulesIndexOutOfRange(304, self.name, self.nProfiles)
return self.rules[index]
## Throw an error if the requested index is out of range; otherwise check to make sure the rule given is valid before assigning the new rule or raising an exception.
# @param index Attempted integer array position
# @param value Attempted rule
def __setitem__(self, index, value):
if index >= self.nProfiles:
raise RulesIndexOutOfRange(304, self.name, self.nProfiles)
rule = self._CheckRule(value, index)
self.rules[index] = rule
def _CheckRule(self, rule, i):
if type(rule).__name__!='Rule':
if rule is None:
pass
elif type(rule)==float or type(rule)==int:
rule = Value(float(rule))
else:
try:
arr = np.array(rule)
if arr.ndim==1 and arr.size==self.ngal:
rule = Array(arr)
else:
CompError(self.name, i)
except:
CompError(self.name, i)
return rule
## Class which defines @p rules.
# The {sersicindex, halflightradius, magnitude, axisratio, beta} attributes are of type @p CompRules.
# No set methods are allowed to be called by the user.
class SimRules(object):
## Initialize the simulation parameters to their balrog defaults.
# @param ngal Integer number of galaxies simulated
def __init__(self, ngal, galkeys, compkeys):
super(SimRules, self).__setattr__('ngal', ngal)
super(SimRules, self).__setattr__('galkeys', galkeys)
super(SimRules, self).__setattr__('compkeys', compkeys)
for name in self._GetGalaxy():
super(SimRules, self).__setattr__(name, None)
self.InitializeSersic()
## Setup the attributes of type @p CompRules: {sersicindex, halflightradius, magnitude, axisratio, beta}.
# This function allocates the proper size array and will reset all rules to their defaults.
# @param nProfiles Integer number of Sersic profiles the simulated galaxies are composed of
def InitializeSersic(self, nProfiles=1):
super(SimRules, self).__setattr__('nProfiles', nProfiles)
for c in self._GetComponent():
super(SimRules, self).__setattr__(c, CompRules(nProfiles,c))
def _GetGalaxy(self):
#return ['x','y','g1','g2','magnification']
return self.galkeys
def _GetComponent(self):
#return ['axisratio','beta','halflightradius','magnitude','sersicindex']
return self.compkeys
## Throw an error if the user tries to index @p rules
# @param index Attempted integer array element position
def __getitem__(self, index):
raise RulesIndexingError(302)
## Throw an error if the user tries to index @p rules
# @param index Attempted integer array element position
# @param value Attempted assignment value
def __setitem__(self, index, value):
raise RulesIndexingError(302)
## Throw an error if the user asks for an attribute that does not exist.
# @param name Attempted attribute name
def __getattr__(self, name):
raise RulesAttributeError(301, name)
## Set a rule.
# Before new rules are assigned they are check and if found to be invalid an exception occurs.
# Attributes @p ngal and @p nProfiles cannot be reassigned.
# @param name Attempted attribute to reassign
# @param value Attempted assignment value
def __setattr__(self, name, value):
if name=='ngal':
raise RulesHiddenError(-1, name)
elif name=='nProfiles':
raise RulesnProfilesError(-2, name)
elif name=='galkeys':
raise RulesHiddenError(-1, name)
elif name=='compkeys':
raise RulesHiddenError(-1, name)
elif name in self._GetGalaxy():
value = self._CheckRule(name, value, 'galaxy')
super(SimRules, self).__setattr__(name, value)
elif name in self._GetComponent():
try:
size = len(value)
except:
if self.nProfiles!=1:
raise RulesAssignmentNoArrayError(306)
else:
size = 1
value = [value]
if size!=self.nProfiles:
raise RulesAssignmentNoArrayError(306)
for i in range(size):
val = self._CheckRule(name, value[i], 'component', i=i)
exec "self.%s[%i] = val" %(name, i)
else:
raise RulesAttributeError(301,name)
def _CheckRule(self, name, rule, kind, i=None):
if type(rule).__name__!='Rule':
if IsNone(rule):
pass
elif type(rule)==float or type(rule)==int:
rule = Value(float(rule))
else:
try:
arr = np.array(rule)
if arr.ndim==1 and arr.size==self.ngal:
rule = Array(arr)
else:
if kind=='galaxy':
GalError(name)
else:
CompError(name, i)
except:
if kind=='galaxy':
GalError(name)
else:
CompError(name, i)
return rule
## Class for use
# Testing more stuff
class CompResult(object):
def __init__(self, nProfiles, name):
super(CompResult, self).__setattr__('name', name)
super(CompResult, self).__setattr__('nProfiles', nProfiles)
def __len__(self):
return self.nProfiles
def __getitem__(self,index):
if index >= self.nProfiles:
raise SampledIndexOutOfRange(404, self.name, self.nProfiles)
if self.name=='magnitude':
return Same( (index,'flux') )
else:
return Same( (index,self.name) )
def __setitem__(self, index, value):
raise SampledAssignmentError(403, '%s[%i]'%(self.name,index), 'sampled')
def __setattr__(self, name, value):
raise SampledAssignmentError(403, '%s.%s'%(self.name,name), sampled)
def __getattr__(self, name):
raise SampledComponentAttributeError(405)
class Results(object):
def __init__(self, galkeys, compkeys):
super(Results, self).__setattr__('galkeys', galkeys)
super(Results, self).__setattr__('compkeys', compkeys)
self.InitializeSersic()
def InitializeSersic(self, nProfiles=1):
super(Results, self).__setattr__('nProfiles', nProfiles)
for c in self._GetComponent():
super(Results, self).__setattr__(c, CompResult(nProfiles,c))
def _GetGalaxy(self):
#return ['x','y','g1','g2','magnification']
return self.galkeys
def _GetComponent(self):
#return ['axisratio','beta','halflightradius','magnitude','sersicindex']
return self.compkeys
def __getattr__(self, name):
if name not in self._GetGalaxy():
raise SampledAttributeError(401, name, 'sampled')
else:
return Same(name)
def __getitem__(self, index):
raise SampledIndexingError(402, 'sampled')
def __setitem__(self, index, value):
raise SampledIndexingError(402, 'sampled')
def __setattr__(self, name, value):
raise SampledAssignmentError(403, name, 'sampled')
class DerivedArgs():
def __init__(self,args, known, setup=None):
self.imgdir = os.path.join(args.outdir, 'balrog_image')
self.catdir = os.path.join(args.outdir, 'balrog_cat')
#self.logdir = os.path.join(args.outdir, 'balrog_log')
self.sexdir = os.path.join(args.outdir, 'balrog_sexconfig')
self.subsample = True
if args.xmin==1 and args.ymin==1 and args.xmax==pyfits.open(args.image)[args.imageext].header['NAXIS1'] and args.ymax==pyfits.open(args.image)[args.imageext].header['NAXIS2']:
self.subsample = False
if self.subsample and args.noweightread:
raise Exception("--noweightread and subsampling isn't possible.")
length = len('.sim.fits')
#dlength = len('.sim.det.fits')
dlength = len('.fits')
self.outimageext = 0
self.outdetimageext = 0
self.outweightext = 1
self.outdetweightext = 1
self.imageout = DefaultName(args.image, '.fits', '.sim.fits', self.imgdir)
#self.detimageout = DefaultName(args.image, '.fits', '.sim.det.fits', self.imgdir)
ext = '.nosim.fits'
dext = '.nosim.det.fits'
self.nosim_imageout = '%s%s' %(self.imageout[:-length],ext)
#self.nosim_detimageout = '%s%s' %(self.detimageout[:-dlength],dext)
#self.nosim_detimageout = DefaultName(args.detimage, '.fits', '.nosim.det.fits', self.imgdir)