-
Notifications
You must be signed in to change notification settings - Fork 0
/
noisempire.py
3281 lines (2759 loc) · 162 KB
/
noisempire.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
##############################################
Name="NOISEMPIRE"
Version="1.0.2" # Major.Minor.Patch sequence. When a major, minor, or patch update is made, the corresponding number is increased.
Years="2023-2024"
Developer="Ivano Baronchelli"
##############################################
# Simulates a pure noise map using real ALMA images as a reference
# Call this script as follows:
#########################################
# $ python noisempire.py config_file.txt
# or, if you want to specify the image name in the command line:
# $ python noisempire.py config_file.txt --INPUT_IMAGE input_image.fits
#########################################
#
# Given an input ALMA image (or flattened cube), it creates a simulated
# image made of pure noise.
#
# Ivano Baronchelli 2023-2024
###################################################################
# Versioning
###################################################################
# V1.0.1 --> V1.0.2 May 3 2024
# - corrected bug (arising flattening cubes problem when extracting radial - elliptical patterns)
#
#
# V1.0.0 --> V1.0.1 May 2 2024
# - removed duplicated import (re)
# - removed misleading comments
# Major version changes are related to incompatible API changes.
# Minor version changes are related to adding new functionality in a backward-compatible manner.
# Patch version changes are related to bug fixes which are also backward compatible.
print('\n\n ###################################')
print(' # '+ Name +' '+ Version+' #')
print(' # '+Developer +' '+Years+' #')
print(' ###################################\n\n')
from pdb import set_trace as stop # in this way you can just write stop() to stop the program.
import os
import sys
from astropy.io import fits
import numpy as np
from astropy.wcs import WCS
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt # to show plot and images
import math
import scipy.signal # for image convolution or to create a 2d Gaussian
from scipy.fft import fft2, ifft2, fftshift
from scipy.ndimage import binary_dilation # expand a boolean mask of a few pixels
import cv2 #("conda install opencv")
from scipy.ndimage import zoom
from skimage import measure
import re # used to identify variable types
import argparse # used to pass arguments to main()
def get_type_and_convert(value):
# Check if an input variable is an integer, float, boolean or a string
# and returns it in the correct format
#
# Check if the value is an integer
if re.match(r'^[-+]?[0-9]+$', value):
return int(value)
# Check if the value is a float
elif re.match(r'^[-+]?[0-9]*\.[0-9]+$', value):
return float(value)
# Check if the value is a boolean True
elif value.lower() == 'true':
return True
# Check if the value is a boolean False
elif value.lower() == 'false':
return False
# Check if the value is None
elif value.lower() == 'none':
return None
# Otherwise, it's likely a string
else:
return value
def get_param_value(PARAMS, VALUES, param_name, convert=True):
# inputs:
# PARAMS --> list of parameters in a string format
# VALUES --> values for each parameter in PARAMS
# param_name --> parameter for which we want to get the value (string)
# convert --> if True (default), the parameter is automatically recognized
# and converted to float, integer, boolean or string
idx1=np.where(PARAMS==param_name)
idx1=idx1[0][0]
if convert==False:
PARAMETER=VALUES[idx1]
if convert==True:
PARAMETER=get_type_and_convert(VALUES[idx1])
return PARAMETER
class Readcol(object):
##################################################################################
# Read specified columns in an ascii file and returns them in the specified format
# Example of use:
# cat=Readcol(path0+'fin_F160.cat','f,f,x,x,x,a20',i,skipline=17,skipcol=7)
# X=cat.col(0)# will be a float numpy array
# Y=cat.col(1) # will be a float numpy array
# Z=cat.col(2) # will be a string numpy array
# K=cat.col(3) # will be an integer numpy array
# # Note that the first 17 lines (skipline) and the first 7 columns (skipcol)
# # are not considered. For the columns skipped using "skipcol", the format should
# # not be specified. For the other columns, the user can specify if the format
# # should be float (f), integer (i), or a string (a). The maximum lenght of the
# # strings to be read should also be specified using the string_length keyword.
# # By default, string columns are considered 30 characters long.
# # The indexes "n" of the output columns, used in col(n), start from 0 and do not
# # consider skipped columns (skipcol or 'x').
##################################################################################
def __init__(self, filename, form,skipline=0, skipcol=0, sep='default', skip_sym='#', string_length=30 ):
self.filename=filename # string containing path+filename
self.form=form # format of the elements in the columns. Example:
# 'f,f,f,x,a,i' --> first three columns (after the
# skipped ones, specified using skipcol) will be
# returned as float, third column is jumped, fourth
# column is returned as a character, fifth as an integer.
self.skipline=skipline # number of lines to skip (optional, default=0)
self.skipcol=skipcol # number of clumns to skip (optional, default=0)
self.sep=sep # Separator. Default are spaces. Other options
# are ',' '\t' (tab). It accepts all the options
# allowed in string.split()
self.skip_sym=skip_sym # skip all lines beginning with the character specified.
# Default is lines starting with "#". Void lines are always
# skipped
if os.path.isfile(filename)==0:
print ('File '+ filename +' not found')
if os.path.isfile(filename)==True:
FILE=open(filename,'r')
ALL_COL_STR=FILE.readlines()
FILE.close()
FORMAT=np.array(form.split(',')) # Must be converted otherwise it doesn't work
ncol=len(FORMAT[FORMAT != 'x']) # Number of output columns
out_format=['' for x in range(ncol)] # Format of output columns
out_format=np.array(out_format, str) # numpy array of strings
nlines=len(ALL_COL_STR)-skipline # Number of output lines
space_string = " " * string_length
all_col=[[space_string for x in range(ncol)] for x in range(nlines)]
all_col=np.array(all_col, str) # numpy array of strings
CN=skipcol # Input Column Number (also 'x' considered here)
RCN=0 # Real (output) Column Number (no 'x')
while CN < len(FORMAT)+skipcol:
if FORMAT[CN-skipcol]!='x':
LN=skipline # Input line Number
RLN=0 # Real (output) line Number (no 'x')
while LN < len(ALL_COL_STR):
line=ALL_COL_STR[LN]
if line != '\n':
# Read line if it doesn't start with the skip symbol
if line.split()[0][0] not in self.skip_sym:
if self.sep=='default':
linesplit = line.split()
if self.sep!='default':
linesplit = line.split(self.sep)
#--------------------------------
if CN<=np.size(linesplit)-1:
all_col[RLN,RCN]=linesplit[CN]
if CN>np.size(linesplit)-1:
all_col[RLN,RCN]=' '
#--------------------------------
RLN=RLN+1
LN=LN+1
out_format[RCN]=FORMAT[CN-skipcol]
RCN=RCN+1
CN=CN+1
self.out_format=out_format
self.all_col=all_col
self.nline=RLN
def col(self,coln):
###################################################
# "coln" corresponds to the column number on the ascii
# file (start from 0) minus "skipcol", minus the number
# of "x" indicated in the input format string "form"
###################################################
if self.out_format[coln].lower()=='a':
OUTCOL=np.array(self.all_col[:self.nline,coln], str)
if self.out_format[coln].lower()=='i':
OUTCOL=np.array(self.all_col[:self.nline,coln], int)
if self.out_format[coln].lower()=='f':
OUTCOL=np.array(self.all_col[:self.nline,coln], float)
return OUTCOL
def get_granularity(image, N_sigma=1.0):
"""
Compute the granularity of a given image as the
inverse of the number of "blobs" found above a
given threshold (1 positive sigma, by default)
"""
input_image=np.copy(image)
# remove outliers (2% of higher and lower values)
outliers_low=np.where(input_image < np.percentile(input_image,[2]))
input_image[outliers_low]=np.percentile(input_image,[2])
outliers_up=np.where(input_image > np.percentile(input_image,[98]))
input_image[outliers_up]=np.percentile(input_image,[98])
inverse_image=np.max(input_image)-input_image
# Normalize to the range [0, 1]
normalized_input_image = (input_image - input_image.min()) / (input_image.max() - input_image.min())
normalized_inverse_image = (inverse_image - inverse_image.min()) / (inverse_image.max() - inverse_image.min())
# Scale to the range [0, 255]
scaled_input_image = (normalized_input_image * 255).astype(np.uint8)
scaled_inverse_image = (normalized_inverse_image * 255).astype(np.uint8)
# Apply thresholding to create a binary image
seg_thresh=127+N_sigma*np.round(np.std(scaled_input_image))
maxval=np.max(scaled_input_image)
_, binary_input_image = cv2.threshold(scaled_input_image, seg_thresh, maxval, cv2.THRESH_BINARY)
_, binary_inverse_image = cv2.threshold(scaled_inverse_image, seg_thresh, maxval, cv2.THRESH_BINARY)
# Perform connected component analysis to label connected regions
labeled_input_img = measure.label(binary_input_image, connectivity=2) # Set connectivity as needed
labeled_inverse_img = measure.label(binary_inverse_image, connectivity=2) # Set connectivity as needed
# Count the number of segments
N_seg=(np.max(labeled_input_img)+np.max(labeled_inverse_img))/2.
# Min granularity: 0, i.e., one positive pixels
# Max granularity: 1, i.e., one positive pixel every 4 pixels (corresponding to
# white pixels separated by one single black pixel)
granularity =N_seg/(np.size(input_image)/4.)
return granularity
def convolve_local_ACF(input_image, ref_image, box_size=32, SHOW_PLOT=False, norm_blocks='No', shrink_factor=1.0):
"""
Convolve an input image ("input_image") with the
Auto-Correlation Function (ACF) of a reference image
("ref_image"). The ACF is computed on a local scale,
by dividing the image in boxes whose size (in pixels)
is set by the user.
The function Returns the input image convolved as described
- If norm_blocks is set to 'No', the boxes are not normalized
after the convolution process
- If norm_blocks is set to "Global", the distribution of the
pixel values inside the boxes are normalized to the same
(percentile-based) stdv measured in the overall ref_image
- If norm_blocks is set to "Local", the distribution of the
pixel values inside the boxes are normalized to the same
(percentile-based) stdv measured in the same box of the
reference image
Setting shrink_factor, the ACF can be shrinked
(from scipy.ndimage import zoom) to reach
the desired granularity of the final image
"""
if norm_blocks == "Global":
Global_ref_stdv=(np.percentile(ref_image,[84]) - np.percentile(ref_image,[16])) /2.
# Create temporary working images
tmp_img=np.copy(input_image)
tmp_img[:,:]=0.
tmp_img_shy=np.copy(tmp_img)
tmp_img_shx=np.copy(tmp_img)
tmp_img_shxy=np.copy(tmp_img)
map_weights_y=np.copy(tmp_img)
map_weights_x=np.copy(tmp_img)
x_strip=np.copy(tmp_img[0,:]) # o ne-dimensional weights (along x)
y_strip=np.copy(tmp_img[:,0]) # one-dimensional weights (along y)
# Get image dimensions
img_height, img_width = input_image.shape[0:2]
# Number of sectors along each axis
N_SECT_axis = round(img_width/box_size)
# Actual size of the blocks in pixels
SECT_Npix_x = round(img_width / N_SECT_axis)
SECT_Npix_y = round(img_height / N_SECT_axis)
# shifts along x and y
shift_x = round(0.5*img_width / N_SECT_axis)
shift_y = round(0.5*img_height / N_SECT_axis)
# Define triangular function (0-to-1) for the
# amplitude of the weights
amp=1.0
# period
per_x=SECT_Npix_x # Triangular Period along x
per_y=SECT_Npix_y # Triangular Period along y
indices_x = np.arange(len(x_strip))
indices_y = np.arange(len(y_strip))
x_strip=1.0 - np.abs((indices_x % per_x) - per_x/2)
x_strip=x_strip-np.min(x_strip)
x_strip=amp*x_strip/np.max(x_strip)
y_strip=1.0 - np.abs((indices_y % per_y) - per_y/2)
y_strip=y_strip-np.min(y_strip)
y_strip=amp*y_strip/np.max(y_strip)
# Compute weighting maps
map_weights_x[:,:]=x_strip
# set x extremes to 1 (image borders must be kept into account)
map_weights_x[:,0:per_x//2]=amp # to keep the borders into account
map_weights_x[:,(img_width-1)-per_x//2 : img_width] = amp
map_weights_y.T[:,:]=y_strip # WARNING: must be transposed (.T), to fill it with the 1D strip!
# set y extremes to 1 (image borders must be kept into account)
map_weights_y[0:per_y//2 , :]=amp # to keep the borders into account
map_weights_y[(img_height-1)-per_y//2 : img_height , :] = amp
pix_start_y = 0
pix_stop_y = SECT_Npix_y
borrow_y=0
additive_pix_y=0
additive_pix_y_tot=0
for i in range(N_SECT_axis):
pix_start_x = 0
pix_stop_x = SECT_Npix_x
borrow_x=0
additive_pix_x=0
additive_pix_x_tot=0
for j in range(N_SECT_axis):
# Compute local ACF
LOCAL_ACF = scipy.signal.correlate2d(
ref_image[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x],
ref_image[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x],
mode="same",
boundary="wrap",
)
LOCAL_ACF = zoom(LOCAL_ACF, shrink_factor)
# Compute local ACF + shift y
if (pix_start_y+shift_y < img_height and pix_stop_y+shift_y <= img_height):
LOCAL_ACF_shy = scipy.signal.correlate2d(
ref_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x],
ref_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x],
mode="same",
boundary="wrap",
)
LOCAL_ACF_shy = zoom(LOCAL_ACF_shy, shrink_factor)
# LOCAL_ACF_shy = zoom(LOCAL_ACF_shy, shrink_factor)
# Compute local ACF + shift x
if (pix_start_x+shift_x < img_width and pix_stop_x+shift_x <= img_width):
LOCAL_ACF_shx = scipy.signal.correlate2d(
ref_image[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x],
ref_image[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x],
mode="same",
boundary="wrap",
)
LOCAL_ACF_shx = zoom(LOCAL_ACF_shx, shrink_factor)
# Compute local ACF + shift x & + shift y
if (pix_start_y+shift_y < img_height and pix_stop_y+shift_y <= img_height and pix_start_x+shift_x < img_width and pix_stop_x+shift_x <= img_width):
LOCAL_ACF_shxy = scipy.signal.correlate2d(
ref_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x],
ref_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x],
mode="same",
boundary="wrap",
)
LOCAL_ACF_shxy = zoom(LOCAL_ACF_shxy, shrink_factor)
if (SHOW_PLOT):
# Create a plot to visualize the ACF DEBUG PURPOSE ONLY!
plt.figure(figsize=(8, 8))
plt.imshow(
LOCAL_ACF,
cmap="viridis",
origin="lower",
extent=[
-LOCAL_ACF.shape[1] // 2,
LOCAL_ACF.shape[1] // 2,
-LOCAL_ACF.shape[0] // 2,
LOCAL_ACF.shape[0] // 2,
],
)
plt.colorbar(label="Local ACF")
plt.title("Local Noise Auto-Correlation Function (ACF)")
plt.xlabel("Offset (Pixels)")
plt.ylabel("Offset (Pixels)")
plt.show()
# Convolve img with local ACF (mode=same to obtain the same image size)
#----------------------------------------------------------------------
#
# SAME POSITION ############################################
tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x] = scipy.signal.convolve2d(
input_image[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x],
LOCAL_ACF,
mode="same",
boundary='wrap'
)
# TEST TEST - END
# if box_size==256:
# tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x] = scipy.signal.convolve2d(
# input_image[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x],
# LOCAL_ACF[int(256/2 - 20) : int(256/2 + 20) , int(256/2 - 20) : int(256/2 + 20)],
# mode="same",boundary='wrap'
# )
#plt.imshow(LOCAL_ACF[int(256/2 - 25) : int(256/2 + 25) , int(256/2 - 25) : int(256/2 + 25)], cmap='gray')
#plt.imshow(LOCAL_ACF, cmap='gray')
#plt.gca().invert_yaxis()
#plt.show()
## TEST TEST - END
# -- Normalization
if norm_blocks!='No':
block_img=tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x]
Local_img_stdv=(np.percentile(block_img,[84]) - np.percentile(block_img,[16])) /2.
if norm_blocks=='Local':
block_ref=ref_image[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x]
Local_ref_stdv=(np.percentile(block_ref,[84]) - np.percentile(block_ref,[16])) /2.
tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x]=(tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x]/Local_img_stdv)*Local_ref_stdv
if norm_blocks=='Global':
tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x]=(tmp_img[pix_start_y:pix_stop_y, pix_start_x:pix_stop_x]/Local_img_stdv)*Global_ref_stdv
# POSITION + shift y ############################################
if (pix_start_y+shift_y < img_height and pix_stop_y+shift_y <= img_height):
tmp_img_shy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x] = scipy.signal.convolve2d(
input_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x],
LOCAL_ACF_shy,
mode="same",
boundary='wrap'
)
# -- Normalization
if norm_blocks!='No':
block_img_shy=tmp_img_shy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x]
Local_img_stdv_shy=(np.percentile(block_img_shy,[84]) - np.percentile(block_img_shy,[16])) /2.
if norm_blocks=='Local':
block_ref_shy=ref_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x]
Local_ref_stdv_shy=(np.percentile(block_ref_shy,[84]) - np.percentile(block_ref_shy,[16])) /2.
tmp_img_shy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x]=(tmp_img_shy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x]/Local_img_stdv_shy)*Local_ref_stdv_shy
if norm_blocks=='Global':
tmp_img_shy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x]=(tmp_img_shy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x:pix_stop_x]/Local_img_stdv_shy)*Global_ref_stdv
# POSITION + shift x ############################################
if (pix_start_x+shift_x < img_width and pix_stop_x+shift_x <= img_width):
tmp_img_shx[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x] = scipy.signal.convolve2d(
input_image[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x],
LOCAL_ACF_shx,
mode="same",
boundary='wrap'
)
# -- Normalization
if norm_blocks!='No':
block_img_shx=tmp_img_shx[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x]
Local_img_stdv_shx=(np.percentile(block_img_shx,[84]) - np.percentile(block_img_shx,[16])) /2.
if norm_blocks=='Local':
block_ref_shx=ref_image[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x]
Local_ref_stdv_shx=(np.percentile(block_ref_shx,[84]) - np.percentile(block_ref_shx,[16])) /2.
tmp_img_shx[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x]=(tmp_img_shx[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x]/Local_img_stdv_shx)*Local_ref_stdv_shx
if norm_blocks=='Global':
tmp_img_shx[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x]=(tmp_img_shx[pix_start_y:pix_stop_y, pix_start_x+shift_x:pix_stop_x+shift_x]/Local_img_stdv_shx)*Global_ref_stdv
# POSITION + shift x + shift y ############################################
if (pix_start_y+shift_y < img_height and pix_stop_y+shift_y <= img_height and pix_start_x+shift_x < img_width and pix_stop_x+shift_x <= img_width):
tmp_img_shxy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x] = scipy.signal.convolve2d(
input_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x],
LOCAL_ACF_shxy,
mode="same",
boundary='wrap'
)
# -- Normalization
if norm_blocks!='No':
block_img_shxy=tmp_img_shxy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x]
Local_img_stdv_shxy=(np.percentile(block_img_shxy,[84]) - np.percentile(block_img_shxy,[16])) /2.
if norm_blocks=='Local':
block_ref_shxy=ref_image[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x]
Local_ref_stdv_shxy=(np.percentile(block_ref_shxy,[84]) - np.percentile(block_ref_shxy,[16])) /2.
tmp_img_shxy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x]=(tmp_img_shxy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x]/Local_img_stdv_shxy)*Local_ref_stdv_shxy
if norm_blocks=='Global':
tmp_img_shxy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x]=(tmp_img_shxy[pix_start_y+shift_y:pix_stop_y+shift_y, pix_start_x+shift_x:pix_stop_x+shift_x]/Local_img_stdv_shxy)*Global_ref_stdv
# When the approximate size of the boxes does not perfectly fit the image size...
# ...along x
borrow_x=(j+1)*(img_width/N_SECT_axis - round(img_width/N_SECT_axis)) - additive_pix_x_tot
additive_pix_x=round(borrow_x - int(borrow_x))
additive_pix_x_tot=additive_pix_x_tot+additive_pix_x
pix_start_x = pix_stop_x
pix_stop_x = pix_stop_x + SECT_Npix_x + additive_pix_x
# When the approximate size of the boxes does not perfectly fit the image size...
# ...along y
borrow_y=(i+1)*(img_height/N_SECT_axis - round(img_height/N_SECT_axis)) - additive_pix_y_tot
additive_pix_y=round(borrow_y - int(borrow_y))
additive_pix_y_tot=additive_pix_y_tot+additive_pix_y
pix_start_y = pix_stop_y
pix_stop_y = pix_stop_y + SECT_Npix_y + additive_pix_y
# COMPUTE MERGED IMAGE -----------------------------------------------
tmp_x=tmp_img*map_weights_x + tmp_img_shx*(amp-map_weights_x)
tmp_y=tmp_img*map_weights_y + tmp_img_shy*(amp-map_weights_y)
tmp_xy=tmp_img_shxy*(amp-map_weights_x)*(amp-map_weights_y)
output_image=tmp_x*map_weights_y + tmp_y*map_weights_x + tmp_xy*2
# FLAT FIELDING -------------------------------------------------------
# IMPORTANT NOTE: the same weights used above, for computing the merged
# image, must be used using the same order
Flat_img_ref=np.copy(map_weights_x)
Flat_img_ref[:]=1.
Flat_img=np.copy(Flat_img_ref)
Flat_img[tmp_img==0]=0.
Flat_img_shx=np.copy(Flat_img_ref)
Flat_img_shy=np.copy(Flat_img_ref)
Flat_img_shxy=np.copy(Flat_img_ref)
Flat_img_shx[tmp_img_shx==0]=0.
Flat_img_shy[tmp_img_shy==0]=0.
Flat_img_shxy[tmp_img_shxy==0]=0.
Flat_tmp_x=Flat_img*map_weights_x+Flat_img_shx*(amp-map_weights_x)
Flat_tmp_y=Flat_img*map_weights_y+Flat_img_shy*(amp-map_weights_y)
Flat_tmp_xy=Flat_img_shxy*(amp-map_weights_x)*(amp-map_weights_y)
Flat_main=Flat_tmp_x*map_weights_y+Flat_tmp_y*map_weights_x+Flat_tmp_xy*2
output_image=output_image/Flat_main
return output_image#*0.5
def create_elliptical_annular_mask(image_shape, center, b_inner, a_inner, b_outer, a_outer, angle):
"""
generates an elliptical annular mask with specified
inner and outer ellipse parameters. The mask is applied
to an image with the specified shape, and the ellipses
are rotated by a given angle around a specified center.
The function uses NumPy for array operations.
image_shape: Tuple representing the shape of the image.
center: Tuple representing the center coordinates of the ellipses.
b_inner: Semi-minor axis of the inner ellipse.
a_inner: Semi-major axis of the inner ellipse.
b_outer: Semi-minor axis of the outer ellipse.
a_outer: Semi-major axis of the outer ellipse.
angle: Rotation angle (in degrees) applied to the ellipses.
"""
print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
print('WARNING: THIS ANGLE MUST BE CHECKED')
print(' Function')
print('create_elliptical_annular_mask()')
print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
angle=angle+90
mask = np.zeros(image_shape, dtype=bool)
y, x = np.ogrid[:image_shape[0], :image_shape[1]]
# OPTION 1: Clockwise rotation
#x_rot = (x - center[0]) * np.sin(np.deg2rad(angle)) + (y - center[1]) * np.cos(np.deg2rad(angle))
#y_rot = (x - center[0]) * np.cos(np.deg2rad(angle)) + (y - center[1]) * np.sin(np.deg2rad(angle))
# OPTION 2: Counter-clockwise rotation
x_rot = (x - center[0]) * np.cos(np.deg2rad(angle)) + (y - center[1]) * np.sin(np.deg2rad(angle))
y_rot = -(x - center[0]) * np.sin(np.deg2rad(angle)) + (y - center[1]) * np.cos(np.deg2rad(angle))
distance = (x_rot / a_outer)**2 + (y_rot / b_outer)**2
inner_distance = (x_rot / a_inner)**2 + (y_rot / b_inner)**2
mask[(distance <= 1) & (inner_distance >= 1)] = True
return mask
def compute_elliptical_structure(in_image, sigma_thresh, stripes_width, stripes_length, AXES_RATIO, P_ANGLE):
#
# Given an input image, for each pixel it computes the average
# computed over a strip whose width and length are defined
# (in pixels) using the input parameters (stripes_width and
# stripes_length). Each strip orientation is concentrical
# to the image center and defined by the parameters
# "AXES_RATIO" (ratio between a and b axes) and by P_ANGLE
# (defining the position angle of the ellipses used).
# Only pixels with intensity higher than sigma_thresh times
# the RMS of the image are taken into account.
#
# AXES_RATIO = a/b
Elliptically_averaged_image=np.copy(in_image)
Elliptically_averaged_image[:]=0.
# Calculate the center of the image
img_center_x = in_image.shape[1] / 2
img_center_y = in_image.shape[0] / 2
###########################################
img_idx_set=np.copy(in_image)
img_idx_set[:]=0
###########################################
# Compute size (width, height) of the image
width=in_image.shape[0]
height=in_image.shape[1]
max_size=np.max([width,height])
# Create a meshgrid to represent the x and y coordinates of each pixel
xx, yy = np.meshgrid(np.linspace(-1, 1, width), np.linspace(-1, 1, height))
# Calculate the arctan(y/x)
pixel_angles = np.arctan2(yy, xx)
# Angle going from 0 to 2pi
pixel_angles = pixel_angles-np.min(pixel_angles)
pixel_angles = pixel_angles/np.max(pixel_angles)
pixel_angles = pixel_angles*2.0*np.pi
# Actual X and Y coordinates [pixels]
x_coord, y_coord = np.meshgrid(np.linspace(0,width-1 , width), np.linspace(0, height-1, height))
###########################################
# Number of pixels to consider inside a corona:
N_PIX_COR_W=stripes_width
N_PIX_COR_L=stripes_length//2
####################
# isotropic RMS
box_size=np.round(np.sqrt(np.round(stripes_width)*np.round(stripes_length)))
N_elem_box=np.round(stripes_width)*np.round(stripes_length)
SIGMA_BOX=stdv_of_array_blocks_means(in_image,box_size)
####################
# Iterate over increasing distances (values of 'b')
#for b in range(1, max(in_image.shape[1], in_image.shape[0]) // 2, N_PIX_COR): # Limit the range to the smaller size
for b in range(1, max(in_image.shape[1], in_image.shape[0]), int(np.round(N_PIX_COR_W))): # Limit the range to the smaller size
#a = b / (FWHM_PIX_y / FWHM_PIX_x) # Corresponding semi-major axis for the elliptical annulus
a = b * AXES_RATIO # Corresponding semi-major axis for the elliptical annulus
# Create an elliptical annular mask with the current 'a' and 'b' values
elliptical_annular_mask = create_elliptical_annular_mask(in_image.shape, (img_center_x, img_center_y), b - N_PIX_COR_W, a - N_PIX_COR_W, b + N_PIX_COR_W, a + N_PIX_COR_W, P_ANGLE)
if np.size(in_image[elliptical_annular_mask])>0:
######################################
img_idx_set[elliptical_annular_mask]=1
idx_set=np.where(img_idx_set==1)
IDX_cols,IDX_rows=idx_set
# iterate through all the pixels in this elliptical corona
for ii in range(np.size(in_image[elliptical_annular_mask])):
#this_x=x_coord[elliptical_annular_mask][ii]
#this_y=y_coord[elliptical_annular_mask][ii]
# Find closest pixels inside the corona
idx_average=np.where(np.sqrt(((y_coord[idx_set]-y_coord[elliptical_annular_mask][ii])**2) + ((x_coord[idx_set]-x_coord[elliptical_annular_mask][ii])**2)) < N_PIX_COR_L )
strip_average=np.mean(in_image[elliptical_annular_mask][idx_average])
if np.abs(strip_average) > sigma_thresh*SIGMA_BOX:
# Update the pixels in the copy of the input image with the average value
#Elliptically_averaged_image[IDX_cols[ii],IDX_rows[ii]]= average_value
Elliptically_averaged_image[IDX_cols[ii],IDX_rows[ii]]= strip_average # np.mean(in_image[elliptical_annular_mask][idx_average])
img_idx_set[elliptical_annular_mask]=0 # Reset list of pixels considered for the average
######################################
return Elliptically_averaged_image
def stdv_of_array_blocks_means(array_2d, box_size):
"""
Calculate the standard deviation of the mean values within blocks of specified size in a 2D array.
Parameters:
- array_2d (numpy.ndarray): Input 2D array containing data.
- box_size (int): Size of the square blocks used for calculating means.
Returns:
- float: Standard deviation of the mean values within the specified blocks.
"""
# Get the shape of the input array
rows, cols = array_2d.shape
# Calculate the number of complete boxes in each dimension
num_boxes_rows = int(rows // round(box_size))
num_boxes_cols = int(cols // round(box_size))
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# Initialize an array to store the average values of each block
Block_means = np.zeros((num_boxes_rows,num_boxes_cols))
# Iterate over blocks
for y in range(num_boxes_rows):
for x in range(num_boxes_cols):
Block_means[y,x]=np.mean(array_2d[y*round(box_size):(y+1)*round(box_size) , x*round(box_size): (x+1)*round(box_size)])
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# Trim the array to a multiple of box_size
trimmed_array = array_2d[:num_boxes_rows*round(box_size),:num_boxes_cols*round(box_size)]
# Calculate the standard deviation of the block means
#std_deviation_of_block_means = np.std(Block_means)
std_deviation_of_block_means = (np.percentile(Block_means,[84]) - np.percentile(Block_means,[16])) /2.
std_deviation_of_block_means=std_deviation_of_block_means[0]
#print("std_deviation_of_block_means:")
#print(std_deviation_of_block_means)
#print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
#AA,BB,CC,DD=get_histogram(Block_means,perc_min=2.5,perc_max=97.5,SHOW_PLOT=True,get_perc=-99)
## TEST Save resampled image to a file
#TEST_name='Boxes_'+original_image_name
#fits.writeto(directory+'/'+TEST_name, Block_means , overwrite=True)
return std_deviation_of_block_means
def radial_patterns(input_image, sigma_thresh, delta_theta, delta_rad, SHOW_PLOT=False):
# Given a 2D numpy array (an image), it computes the average
# of the pixel aligned with the image center along each direction
# The average is computed inside circular corona sections whose
# size is defined by the following parameters:
# > delta_theta [radians], representing the HALF length of the circular
# corona section (i.e., the bended strip)
# inside which the average value is computed
# > delta_rad [pixels], representing The half width of the circular
# corona section (i.e., the bended strip)
# inside which the average value is computed
# Important Notes: this functions can be used in successive runs to
# obtain radial patterns and angular patterns. this can
# be achieved by opportunely setting delta_theta and
# delta_rad so that they enclose thin stripes oriented
# circularly (delta_theta>>, delta_rad<<) or radially
# (delta_theta<<, delta_rad>>) with respect to the image
# center.
####################################################################
# Create an output image with the same shape as the input
output_image = np.copy(input_image)
output_image[:,:] = 0.
# Create an array with position angles as values
pixel_angles = np.copy(input_image)
pixel_angles[:,:] = 0.
# Compute size (width, height) of the image
width=input_image.shape[0]
height=input_image.shape[1]
max_size=np.max([width,height])
# Create a meshgrid to represent the x and y coordinates of each pixel
xx, yy = np.meshgrid(np.linspace(-1, 1, width), np.linspace(-1, 1, height))
# Calculate the arctan(y/x)
pixel_angles = np.arctan2(yy, xx)
# Angle going from 0 to 2pi
pixel_angles = pixel_angles-np.min(pixel_angles)
pixel_angles = pixel_angles/np.max(pixel_angles)
pixel_angles = pixel_angles*2.0*np.pi
# Calculate distance of the pixels from the image center
new_x=(xx/np.max(xx))*float(width//2) # -128 to 128. min distance=0.5 pixels
new_y=(yy/np.max(yy))*float(height//2) # -128 to 128. min distance=0.5 pixels
pixel_distances = np.sqrt(new_x**2 + new_y**2)
# Actual X and Y coordinates [pixels]
x_coord, y_coord = np.meshgrid(np.linspace(0,width-1 , width), np.linspace(0, height-1, height))
#x_coord=new_x-np.min(new_x)
#y_coord=new_y-np.min(new_y)
if SHOW_PLOT==True:
plt.imshow(pixel_distances, cmap='gray')
plt.title('pixel distances')
# invert the y-axis (to make it consistent with visualization in ds9)
plt.gca().invert_yaxis()
plt.show()
if SHOW_PLOT==True:
plt.imshow(pixel_angles, cmap='gray')
plt.title('pixel angle')
# invert the y-axis (to make it consistent with visualization in ds9)
plt.gca().invert_yaxis()
plt.show()
approx_stripes_half_size=max_size*delta_theta/(np.pi/2.)
#box_size=np.round(np.sqrt(((delta_rad)*2.)*((approx_stripes_half_size)*2.)))
box_size=np.round(np.sqrt(((np.round(delta_rad))*2.)*((np.round(approx_stripes_half_size))*2.)))
N_elem_box=box_size*box_size
SIGMA_BOX=stdv_of_array_blocks_means(input_image,box_size)
# Iterate through all pixels in the image
# For each pixel, compute position angle
for ii in range(input_image.shape[0]):
for jj in range(input_image.shape[1]):
angle_i = pixel_angles[ii,jj]
distance_i = pixel_distances[ii,jj]
delta_theta_corr=delta_theta*max_size/np.max([distance_i,1])
# Remember:
# & = bitwise logical operator "and"
# | = bitwise logical operator "or"
# Normal case (0°<theta<360°)
if (angle_i>=delta_theta_corr) and (angle_i<=2.0*np.pi-delta_theta_corr):
STRIP=input_image[(pixel_angles > angle_i-delta_theta_corr)
& (pixel_angles < angle_i+delta_theta_corr)
& (pixel_distances > distance_i-delta_rad )
& (pixel_distances < distance_i+delta_rad )]
# CLOSE TO THE EDGE (theta>~0°)
if (angle_i<delta_theta_corr):
STRIP =input_image[( (pixel_angles < angle_i+delta_theta_corr)
| (pixel_angles > 2.0*np.pi - delta_theta_corr + angle_i) )
& (pixel_distances > distance_i-delta_rad )
& (pixel_distances < distance_i+delta_rad ) ]
# CLOSE TO THE EDGE (theta<~360°)
if (angle_i>2.0*np.pi-delta_theta_corr):
STRIP=input_image[( (pixel_angles > angle_i-delta_theta_corr)
| (pixel_angles < delta_theta_corr - (2.0*np.pi - angle_i) ) )
& (pixel_distances > distance_i-delta_rad )
& (pixel_distances < distance_i+delta_rad ) ]
strip_average=np.mean(STRIP)
#strip_percts=np.percentile(STRIP,[30,70])
#strip_average=np.mean(STRIP[(STRIP>strip_percts[0]) & (STRIP<strip_percts[1])])
#strip_average=(strip_percts[0]+strip_percts[1])/2.
if np.abs(strip_average) > sigma_thresh*SIGMA_BOX:
output_image[ii,jj] = strip_average
# if output_image[ii,jj] != output_image[ii,jj]:
# print('WARNING: Nan found in radial_background()')
# stop()
#
return output_image
# read image header and data
def read_fits_image(image_name):
"""
Reads a FITS image and returns the data and header
as separate variables.
-----------
PARAMETERS:
image_name : str
The file path of the FITS image.
-----------
RETURNS:
data : numpy.ndarray
The data array of the FITS image.
header : astropy.io.fits.header.Header
The header of the FITS image.
--------
CALL THIS FUNCTION AS FOLLOWS:
data, header = read_fits_image('/path/to/fits/image.fits')
"""
with fits.open(image_name) as hdulist:
data = hdulist[0].data
header = hdulist[0].header
return data, header
def get_keyword_value(header, keyword):
"""
Get the value of a keyword in a fits header, handling HISTORY entries as well.
Parameters:
header (astropy.io.fits.Header): The header object to search for the keyword.
keyword (str): The name of the keyword to search for.
Returns:
The value of the keyword (str, float, int, etc.) or None if the keyword is not found.
"""
# Try to get the keyword value from the header normally
value = header.get(keyword)
if value is None:
# If the keyword isn't found in the header, look for it in the HISTORY entries
for card in header.cards:
if card.keyword.startswith('HISTORY'):
print (card)
imax=np.size(card)
for ii in range(imax):
print(card[ii])
if keyword in card[ii]:
try:
value = float(card[ii].split(keyword + "='")[1].split("'")[0])
except ValueError:
value = card[ii].split(keyword + "='")[1].split("'")[0]
if value is None:
# If the keyword isn't found among the HISTORY entries with the previous search,
# search using regular expression (it's a non general, specific solution)
if keyword in ["FWHM_maj", "FWHM_min"]:
match = re.search(rf"{keyword} used in restoration: (\d+\.\d+) by (\d+\.\d+)", card.comment)
if match:
if keyword == "FWHM_maj":
value = float(match.group(1))
elif keyword == "FWHM_min":
value = float(match.group(2))
elif keyword == "POS_ANGLE":
match = re.search(rf">2 \(arcsec\) at pa (-?\d+\.\d+) \(deg\)", card.comment)
if match:
value = float(match.group(1))
return value
def get_filter_name(FWHM_PIX):
# Automatically define the most appropriate filter name
# given the FWHM of the image
#Filter selection
G_filters_poss=np.array([1.5,2.0,2.5,3.0,4.0,5.0])
#------------------------------------------
# GOOD FOR A CENTRAL CALIBRATOR (header FWHM)
ID_FIL=np.where(abs(FWHM_PIX-G_filters_poss) == min(abs(FWHM_PIX-G_filters_poss)))
#------------------------------------------
# GOOD FOR REAL FWHM = 2 x header FWHM
# ID_FIL=np.where(abs(2.*FWHM_PIX-G_filters_poss) == min(abs(2.*FWHM_PIX-G_filters_poss)))
#------------------------------------------
if ID_FIL[0] == 0 : filter='1.5_3x3'
if ID_FIL[0] == 1 : filter='2.0_5x5'
if ID_FIL[0] == 2 : filter='2.5_5x5'
if ID_FIL[0] == 3 : filter='3.0_7x7'
if ID_FIL[0] == 4 : filter='4.0_7x7'
if ID_FIL[0] == 5 : filter='5.0_9x9'
filt_name="gauss_"+filter+".conv"
return filt_name
def run_sex1(imagename_input,imagename_output,SEx_folder,filter_name,PIXEL_SCALE,FWHM_PIX_x,FWHM_PIX_y,BACK_SIZE,BACK_FILTERSIZE, img_type="BACKGROUND", DETECT_THRESH=1.5, ANALYSIS_THRESH=1.5, DETECT_MINAREA_BEAM=2.0):
#-------------------------------------------------------
# This function outputs an image (imagename_output) of
# the large scale background of the input image
#-------------------------------------------------------
# Internal parameters #########################
BEAM_AREA=(1./(4.*np.log(2.))) * (np.pi*(FWHM_PIX_x)*(FWHM_PIX_y))
FWHM_PIX=(FWHM_PIX_x+FWHM_PIX_y)/2.
FWHM_asec=FWHM_PIX/PIXEL_SCALE
# SExtractor parameters #######################
# DETECT_THRESH=1.5 # different from IDL test (was 1.2)
# ANALYSIS_THRESH=1.5 # different from IDL test (was 1.2)
# DETECT_MINAREA=2.0*np.pi*(FWHM_PIX_x/2.355)*(FWHM_PIX_y/2.355) #(=BEAM_AREA[pixels])
DETECT_MINAREA=DETECT_MINAREA_BEAM*np.pi*(FWHM_PIX_x/2.355)*(FWHM_PIX_y/2.355) #(=BEAM_AREA[pixels])
MAG_ZEROPOINT=8.9+2.5*np.log10(BEAM_AREA)
# n_fwhm=4.
# BACK_SIZE=n_fwhm*FWHM_PIX ####### PARAMETER CONTROLLED FROM OUTSIDE
# BACK_FILTERSIZE=2 ####### PARAMETER CONTROLLED FROM OUTSIDE
###############################################
# set "img_type" to select the type of sextractor "check image" desired
# (BACKGROUND, BACKGROUND_RMS, -BACKGROUND, FILTERED, OBJECTS, -OBJECTS,
# SEGMENTATION, or APERTURES
# create temporary folder to store temporary files
tmp_folder='tmp_folder'
os.system('mkdir '+tmp_folder)
# RUN SEXTRACTOR TO GET BACKGROUND
os.system('source-extractor '+imagename_input+' -c '+SEx_folder+'config_A.txt -CATALOG_NAME '+tmp_folder+'/tmp_cat.fits -PARAMETERS_NAME '+SEx_folder+'default.param -FILTER_NAME '+SEx_folder+filter_name+' -STARNNW_NAME '+SEx_folder+'default.nnw -DETECT_THRESH '+str(DETECT_THRESH)+' -ANALYSIS_THRESH '+str(ANALYSIS_THRESH)+' -DETECT_MINAREA '+str(round(DETECT_MINAREA))+' -SATUR_LEVEL 50000.0'+' -MAG_ZEROPOINT '+str(MAG_ZEROPOINT)+' -GAIN 0.0 -PIXEL_SCALE '+str(PIXEL_SCALE)+' -SEEING_FWHM '+str(FWHM_asec)+' -BACK_SIZE '+str(BACK_SIZE)+' -BACK_FILTERSIZE '+str(BACK_FILTERSIZE) +' -BACKPHOTO_TYPE LOCAL -WEIGHT_TYPE BACKGROUND -CHECKIMAGE_TYPE '+img_type+' -CHECKIMAGE_NAME '+imagename_output)
# remove temporary folder and temporary files
os.system('rm -r tmp_folder')
def resample(x, y, N):
x_res = np.array([])
y_res = np.array([])
for i in range(len(x) - 1):
x_start = x[i]
y_start = y[i]
x_end = x[i + 1]
y_end = y[i + 1]
x_res = np.append(x_res, x_start)
y_res = np.append(y_res, y_start)
for j in range(1, N):
x_interpolated = x_start + (x_end - x_start) * j / N
y_interpolated = y_start + (y_end - y_start) * j / N
x_res = np.append(x_res, x_interpolated)
y_res = np.append(y_res, y_interpolated)
x_res = np.append(x_res, x[-1])
y_res = np.append(y_res, y[-1])
return x_res, y_res
def get_histogram(input_array,perc_min=2.5,perc_max=97.5,SHOW_PLOT=False,get_perc=-99):
# §§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§