-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNIRC2_Preprocessing.py
2257 lines (1764 loc) · 71.1 KB
/
NIRC2_Preprocessing.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
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 15:57:40 2015
@author: Olivier Wertz, Carlos Gomez Gonzalez, Olivier Absil, Henry Ngo see credits.
Mar 2019: Updated print statements for Python3
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import vip_hci
from vip_hci.fits import open_fits as open_fits_vip
from vip_hci.fits import write_fits
from vip_hci.conf import time_ini, timing
from vip_hci.preproc import frame_shift
from vip_hci.preproc import cube_crop_frames
from vip_hci.var import frame_center
from astropy.coordinates import FK5
from astropy.coordinates.sky_coordinate import SkyCoord
from astropy.time import Time
from astropy.units import hourangle, degree
from scipy.optimize import minimize
from os import listdir
from os.path import isfile, join, exists, basename, dirname
from os import makedirs
import warnings
warnings.filterwarnings('ignore')
__all__ = ['open_fits',
'listing',
'create_header',
'extract_headers',
'find_header_card',
#'longestSubstringFinder',
'master',
'masterFlat',
'applyFlat',
'create_cube_from_frames',
'load_images',
'plot_surface',
'moffat',
'cone',
'gauss2d',
'gauss2d_sym',
'chisquare',
'vortex_center',
'vortex_center_routine',
'vortex_center_from_dust_signature',
'timeExtract',
'optimized_frame_size',
'cube_crop_frames_optimized',
'registration',
'cube_registration',
'precess',
'premat',
'get_parang',
'get_parallactic_angles',
'get_parallactic_angles_old']
###############################################################################
###############################################################################
###############################################################################
def open_fits(filename, header=False, verbose=False):
"""
Load a fits file as numpy array.
Parameters
----------
filename : string
Name of the fits file.
header : boolean (optional)
If True, the header is returned along with the data.
verbose : boolean (optional)
If True, additional informations are displayed in the shell.
Returns
-------
out : numpy.array, dict (optional)
The fits image as a numpy.array and (optional) the header.
Note
----
With non-standard header fits file, several "UserWarning" such as:
"The following header keyword is invalid or follows an unrecognized
non-standard convention" can be returned at the first file opening but are
ignored after.
"""
if header:
return open_fits_vip(filename, header=True, verbose=verbose, ignore_missing_end=True)
else:
return open_fits_vip(filename, header=False, verbose=verbose, ignore_missing_end=True)
# def open_fits(filename, header=False, verbose=False):
# """
# Load a fits file as numpy array.
# Parameters
# ----------
# filename : string
# Name of the fits file.
# header : boolean (optional)
# If True, the header is returned along with the data.
# verbose : boolean (optional)
# If True, additional informations are displayed in the shell.
# Returns
# -------
# out : numpy.array, dict (optional)
# The fits image as a numpy.array and (optional) the header.
# Note
# ----
# With non-standard header fits file, several "UserWarning" such as:
# "The following header keyword is invalid or follows an unrecognized
# non-standard convention" can be returned at the first file opening but are
# ignored after.
# """
# try:
# if header:
# return open_fits_vip(filename, header=True, verbose=verbose)
# else:
# return open_fits_vip(filename, header=False, verbose=verbose)
# except: # If a *missing END card* error is raised
# try:
# import pyfits
# except ImportError:
# print('Due to a possible missing END card error when opening the fits file {}, the missing pyfits package is required.'.format(filename))
# print('Download instructions can be found here: ')
# print('http://www.stsci.edu/institute/software_hardware/pyfits/Download')
# if header:
# return (None,None)
# else:
# return None
# hdulist = pyfits.open(filename,ignore_missing_end=True)
# image = hdulist[0].data
# if header:
# header = hdulist[0].header
# hdulist.close()
# if verbose:
# print('')
# print('Fits HDU:0 data and header successfully loaded. Data shape: [{},{}]'.format(image.shape[0],image.shape[1]))
# return (image,header)
# else:
# hdulist.close()
# if verbose:
# print('')
# print('Fits HDU:0 data successfully loaded. Data shape: [{},{}]'.format(image.shape[0],image.shape[1]))
# return image
# -----------------------------------------------------------------------------
def create_header(h):
"""
Create a valid fits header which can be used with write_fits().
Parameters
----------
h : dict
Header formatted as a dict.
Return
------
out : astropy header object
"""
from astropy.io.fits import Header
header_valid = Header(h)
for h_key in header_valid:
try:
header_valid[h_key] = h[h_key]
except ValueError:
continue
return header_valid
# -----------------------------------------------------------------------------
def extract_headers(file_list):
"""
Extract all the common header items from a fits file list and put it in a
new dict-type object.
Parameters
----------
file_list : str
A list of all image paths.
Returns
-------
out : dict
{'card0' : [val01, val02, ...],
'card1' : [val11, val12, ...]}
"""
_ , header = open_fits(file_list[0], header=True, verbose=False)
headers = {key : [value] for key, value in header.items()}
for f in file_list[1:]:
_ , header = open_fits(f, header=True, verbose=False)
for key,value in header.items():
try:
headers[key].append(value)
except KeyError:
pass
for key in headers.keys():
try:
headers[key].append(header.cards[key][-1])
except KeyError:
pass
return headers
# -----------------------------------------------------------------------------
def find_header_card(header, card, criterion='find', info=False):
"""
Check and return (if exists) the header card value according to the given
criterion.
Parameters
----------
header : dict
Valid header object.
card : str
The header card or part of a header card we want to extract.
criterion : str
Type of search:
find: try to find all header cards which contain /card
start: try to find all header cards which start with /card
end: try to find all header cards which end with /card
Return
------
out : dict or boolean
If there are results to returned, dict-type object. Otherwise, False.
"""
if criterion == 'xfind':
try:
res = {card : header[card]}
except KeyError:
res = {}
elif criterion == 'find':
res = {key : value for key, value in header.items() if key.find(card) > -1}
elif criterion == 'start':
res = {key : value for key, value in header.items() if key.startswith(card)}
elif criterion == 'end':
res = {key : value for key, value in header.items() if key.endswith(card)}
if bool(res) is False:
res = {card : 'not found'}
infos = {card : 'nope'}
elif info:
try:
infos = {key : header.cards[key][2] for key in res.keys()}
except AttributeError:
infos = {key : 'nope' for key in res.keys()}
if info:
return res, infos
else:
return res
# -----------------------------------------------------------------------------
#
#def longestSubstringFinder(string1, string2):
# """
# Return the longest common substring between two strings.
#
# Parameters
# ----------
# string1, 2: str
# The two strings to compare.
#
# Return
# ------
# out : str
# The longest common substring.
#
# """
# answer = ""
# len1, len2 = len(string1), len(string2)
# for i in range(len1):
# match = ""
# for j in range(len2):
# if (i + j < len1 and string1[i + j] == string2[j]):
# match += string2[j]
# else:
# if (len(match) > len(answer)): answer = match
# match = ""
# return answer
# -----------------------------------------------------------------------------
def timeExtract(date,time):
"""
Convert a list of date-time into a datetime object.
Ex:
>> date = ['2015-07-10']
>> time = ['08:06:34.123']
>> t = timeExtract(date,time)
>> print t
[datetime.datetime(2015,7,10,8,6,34)]
Parameters
----------
date : list
time : list
"""
from datetime import datetime
if not isinstance(date,list):
date = [date]
if not isinstance(time,list):
time = [time]
l = len(date)
return [datetime(int(date[j].split('-')[0]),
int(date[j].split('-')[1]),
int(date[j].split('-')[2]),
int(time[j].split(':')[0]),
int(time[j].split(':')[1]),
int(time[j].split(':')[2].split('.')[0])) for j in range(l)]
# -----------------------------------------------------------------------------
def listing(repository, selection=False, ext = 'fits'):
"""
List all fits files contained in 'repository'.
Parameters
----------
repository : str
Path to the repository which contains files to list
selection : boolean (optional)
** REMOVED **
VIP no longer supports DS9 so this no longer works.
[[ old text: If True, each image is opened with DS9 and you are asked to keep or
discard it.]]
ext : str (optional)
The file extension filter.
Returns
-------
out : list of str
A list with all (or selected) filenames.
"""
if repository.endswith('.'+ext):
if isfile(repository):
return [repository]
else:
raise IOError('File does not exist: {}'.format(repository))
elif not repository.endswith('/'):
repository += '/'
fileList = [f for f in listdir(repository) if isfile(join(repository,f)) if f.endswith('.'+ext)]
fileList.sort()
dim = len(fileList)
choice = np.ones(dim)
if selection:
# VIP no longer supports DS9. Selection is no longer allowed
raise Exception('VIP no longer supports DS9. Cannot use "selection" to choose files from DS9 displays')
# for k,f in enumerate(fileList):
# w = open_fits(repository+f)
# display_array_ds9(w)
# choice[k] = int(raw_input('File {}/{} --> {}: keep [1] or discard [0] ? '.format(k+1,dim,repository+f)))
#
# print ('')
# print ('DONE !')
return [repository+fileList[j] for j in range(dim) if choice[j] == 1]
# -----------------------------------------------------------------------------
def master(fileList, header=False, bpm=True, norm=True, display=False, save=False,
verbose=False, full_output=True, path_output=None, filename='master',
filtering=None, method='median'):
"""
Create a master image (median) from a set of single images.
Parameters
----------
fileList : list
A list of all single image paths.
header : boolean (optional)
If True, the headers of each single files are returned into a dict
file.
bpm : booelan (optional)
If True, a bad pixel map is also returned
norm : boolean (optional)
If True, the master image is normalized.
display : boolean (optional)
** REMOVED as no longer supported in VIP **
If True, the master image is opened with DS9.
save : boolean (optional)
If True, the master image is saved as a fits file in the same folder as
the single images.
filtering : float or tuple (optional)
If a tuple (a,b) is provided, then bad pixels are either "a" stddev below median or "b" stddev above median
If a float is provided, then use same upper and lower limits
Returns
-------
out : numpy.array
The master image as a numpy array with the same dimension as the single
images.
If bpm is True (default), a bad pixel map is also returned as an output object.
If header is True, a dict is also returned as an output object.
"""
# TODO: si header est True, ecrire le header dans le master image.
if verbose:
start_time = time_ini()
print ('BUILDING THE MASTER IMAGE')
print ('')
print ('Save = {}'.format(save))
# Shape and number of files
l, c = open_fits(fileList[0]).shape
n_image = len(fileList)
# Initializate variables
flats = np.zeros([l,c,n_image])
#headers = []
# Loop: open all images and concatenate them into a bigger array
for j in range(n_image):
if header:
flats[:,:,j], h = open_fits(fileList[j], header=True)
#headers.append(h)
else:
flats[:,:,j] = open_fits(fileList[j], header=False)
# Create the master image -> median
if method == 'median':
mimage = np.median(flats, axis=2)
norm_factor = np.median(mimage)
else:
mimage = np.median(flats, axis=2)
norm_factor = np.median(mimage)
# Normalization
if norm:
mimage = mimage/norm_factor
# filtering
if filtering is not None:
if isinstance(filtering,tuple):
low_filt=filtering[0]
high_filt=filtering[1]
else:
low_filt=filtering
high_filt=filtering
bad_pix_low = mimage < np.median(mimage)-low_filt*np.std(mimage)
bad_pix_high = mimage > np.median(mimage)+high_filt*np.std(mimage)
bad_pix_map = bad_pix_low + bad_pix_high
from vip_hci.preproc.badpixremoval import frame_fix_badpix_isolated
mimage=frame_fix_badpix_isolated(mimage,bpm_mask=bad_pix_map)
if verbose:
print ('filtering = {}'.format(filtering))
# Display
if display:
raise Exception("DISPLAY is no longer supported as VIP no longer supports ds9.")
#display_array_ds9(mimage)
# Save
if save:
if path_output is None:
## Save > Determine the path in which the files will be stored
index = [k for k,letter in enumerate(fileList[0]) if letter == '/']
if len(index) == 0:
path_output = ''
else:
path_output = fileList[0][:index[-2]+1]
if not exists(path_output):
makedirs(path_output)
## Save > Write the fits
write_fits(join(path_output,'{}.fits'.format(filename)), mimage, verbose=verbose)
# Headers
if header:
headers = extract_headers(fileList)
if verbose:
print ('')
print ('-------------------------------------------------------------------')
print ('Master image successfully created')
timing(start_time)
# Return output(s)
## TODO: Make this nicer
if full_output:
if header:
if bpm:
return mimage, headers, bad_pix_map
else:
return mimage, headers
else:
if bpm:
return mimage, bad_pix_map
else:
return mimage
else:
return None
# -----------------------------------------------------------------------------
def masterFlat(fileList, **kwargs):
"""
Override the former version of masterFlat by calling the function master().
Parameters
----------
fileList : list
A list of all single image paths.
kwargs : dict-type
Additional parameters are passed to master().
Return
------
out : numpy.array
The master flat as a numpy array with the same dimension as the single
images.
If bpm is True (default), a bad pixel map is also returned as an output object.
If header is True, a dict is also returned as a second output object.
"""
path_output = kwargs.pop('path_output', '')
if path_output is None: path_output = ''
filename = kwargs.pop('filename','mflat')
return master(fileList, path_output=join(path_output,'calibration',''),
filename=filename, **kwargs)
# -----------------------------------------------------------------------------
def applyFlat(fileList, path_mflat, header=False, display=False, save=False,
verbose=False, full_output=True, path_output=''):
"""
Divide all images in the fileList by the master flat.
Parameters
----------
fileList : list
A list of all image paths.
path_mflat : str
Path to the master flat.
display : boolean (optional)
** REMOVED as VIP no longer supports DS9 **
If True, the master flat is opened with DS9.
save : boolean (optional)
If True, the processed images are saved as fits files in a new
repository ([fileList_path]/processed/).
verbose : boolean (optional)
If True, additional informations are displayed in the shell.
Returns
-------
out : dict
Dictionary which contains the processed images. Each key corresponds to
the original file path.
"""
if verbose:
start_time = time_ini()
print ('PREPROCESSING IMAGES')
print ('')
print ('Save = {}'.format(save))
# Open the master flat
if isinstance(path_mflat, str):
mflat = open_fits(path_mflat, header=False)
else:
mflat = path_mflat
# Check if *fileList* is a list and raise an error if not
if isinstance(fileList, str):
if fileList.endswith('/'): # If True, fileList is a repository ...
fileList = listing(fileList)
else: # ... otherwise, it's a file path.
fileList = [fileList]
elif not isinstance(fileList, list):
raise TypeError('fileList must be a list or a str, {} given'.format(type(fileList)))
# Initializate few parameters
#processed_all = dict()
l, c = open_fits(fileList[0]).shape
processed_all_cube = np.zeros([len(fileList),l,c])
headers = dict()
if save:
if path_output is None: path_output = ''
subrep_in_path_output = join(path_output,basename(dirname(fileList[0])) + '_flatted','')
if not exists(subrep_in_path_output):
makedirs(subrep_in_path_output)
# Loop: process and handle each file
for i, filepath in enumerate(fileList):
## Loop > Open file and retrieve the header if needed
#if header:
raw, headers[fileList[i]] = open_fits(filepath, header=True)
#else:
# raw = open_fits(filepath, header=False)
## Loop > Process the image and store it
#processed = raw/mflat
#processed_all[filepath] = raw/mflat
processed_all_cube[i,:,:] = raw/mflat
## Loop > display
if display:
raise Exception("DISPLAY is no longer supported as VIP no longer supports ds9.")
#display_array_ds9(processed_all_cube[i,:,:])
## Loop > save
if save:
#filename = filepath[index_0[-1]+1:index_1[-1]]
filename = basename(filepath).split('.')[0]
### Loop > save > Create valid header
#if header:
header_valid = create_header(headers[fileList[i]])
#else:
# header_valid = None
### Loop > save > Write the fits
output = subrep_in_path_output+filename+'_flatted.fits'
write_fits(output, processed_all_cube[i,:,:], header=header_valid, verbose=False)
#if verbose:
# print ('/flatted/{} successfully saved'.format(output[-output[::-1].find('/'):]))
if verbose:
if save:
print ('')
print ('Fits files successfully created')
print ('')
print ('-------------------------------------------------------------------')
print ('Images succesfully preprocessed')
timing(start_time)
# Return the output(s)
if full_output:
if header:
return processed_all_cube, extract_headers(fileList)
else:
return processed_all_cube
else:
return None
# -----------------------------------------------------------------------------
def create_cube_from_frames(files, header=False, verbose=False, save=False):
"""
Create a cube (3d numpy.darray) from several fits images. The cube size is
N x l x c where N is the total number of frames, l x c the size of each
frame in pixels.
Parameters
----------
files : list or str
If list, it contains all the fits image filenames.
If str, it roots the the repository which contains all fits images.
header : boolean (optional)
If True, the function returns a list of all fits image headers.
verbose : boolean (optional)
If True, additional informations are displayed in the shell.
save : boolean (optional)
If True, the cube is saved as fits files in the same repository as the
single fits images.
Returns
-------
out : numpy.array
The N x l x c cube.
If header is True, is also returns a list of all headers.
"""
if isinstance(files,str): # If True, *files* is the path to a directory
# which contains all the fits image to combine.
file_list = listing(files, selection=False)
path = files
elif isinstance(files,list): # If True, *files* is already the list of all
# file names.
file_list = files
path = None
else:
print ('''*files* must be either the list of fits image filenames or the
directory which contains all the fits images''')
return None
#if header:
first, h = open_fits(file_list[0], header=True)
headers = [create_header(h)]
#else:
# first = open_fits(file_list[0])
l, c = first.shape
cube = np.zeros([len(file_list), l, c])
cube[0,:,:] = first
if verbose:
print ('Frame {} is added to the cube'.format(file_list[0]))
for k,filename in enumerate(file_list[1:]):
#if header:
temp, h_temp = open_fits(filename, header=True)
#else:
# temp = open_fits(filename, header=False)
if temp.shape != (l,c):
print ('Each frame must have the same dimension as the first one ({},{}), {} given for {}'.format(l,c,temp.shape,filename))
continue
else:
cube[k+1,:,:] = temp
headers.append(h_temp)
if verbose:
print ('Frame {} is added to the cube'.format(filename))
if save:
if path is None:
index_0 = [k for k,letter in enumerate(files[0]) if letter == '/']
if len(index_0) == 0:
path = ''
else:
path = files[0][:index_0[-1]+1]
write_fits(path+'cube.fits', cube, header=headers[0], verbose=False)
if verbose:
print ('')
print ('The cube is successfully saved')
if header:
return cube, extract_headers(file_list)
else:
return cube
# -----------------------------------------------------------------------------
def load_images(path, header=False, verbose=False):
"""
Load a set of images and return a cube build from the images.
Parameters
----------
path: str
Path to the images to load.
header : boolean (optional)
If True, the function returns a list of all fits image headers.
verbose : boolean (optional)
If True, additional informations are displayed in the shell.
Return
------
out : numpy.array
The N x l x c cube where N is the total number of frames, l x c the
size of each frame in pixels. If header is True, is also returns a
list of all headers.
"""
if path.endswith('.fits'):
image = open_fits(path, header=header, verbose=verbose)
l,c = image.shape
temp = np.zeros([1,l,c])
temp[0,:,:] = image
return temp
else:
file_list = listing(path)
return create_cube_from_frames(file_list, header=header, verbose=verbose)
# -----------------------------------------------------------------------------
def plot_surface(image, center=None, size=None, output=False, **kwargs):
"""
Create a surface plot from image.
By default, the whole image is plotted. The 'center' and 'size' attributs
allow to crop the image.
Parameters
----------
image : numpy.array
The image as a numpy.array.
center : tuple of 2 int (optional, default=None)
If None, the whole image will be plotted. Otherwise, it locates the
center of a square in the image.
size : int (optional, default=None)
If None, the whole image will be plotted. Otherwise, it corresponds to
the size of a square in the image.
kwargs:
Additional attributs are passed to the matplotlib figure() and
plot_surface() method.
Returns
-------
out : tuple of 3 numpy.array
x and y for the grid, and the intensity
"""
from mpl_toolkits.mplot3d import Axes3D
if center is None or size is None:
# If one of them is None, we just plot the whole image
#center = (image.shape[0]//2,image.shape[1]//2)
size = image.shape[0]
x = np.outer(np.arange(0,size,1), np.ones(size))
y = x.copy().T
z = image
plt.figure(figsize=kwargs.pop('figsize',(5,5)))
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0, **kwargs)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$I(x,y)$')
ax.set_title('Data')
plt.show()
if output:
return (x,y,z)
# -----------------------------------------------------------------------------
def moffat(x, y, x0, y0, i0, bkg, alpha, beta):
"""
2-D Moffat profile.
The analytical expression is given by:
I(r) = bkg + I_0 * [1 + (r/\alpha)^2]^{-\beta},
where bkg is the background value, r = (x^2 + y^2)^(1/2), \alpha is a scale
factor and \beta determines the overall shape of the profile.
Parameters
----------
x, y: numpy.array
The grid where the Moffat profile will be define.
x0, y0 : float
The position of the Moffat profile maximum intensity.
alpha : float
The scale factor.
beta : float
The parameter which determines the overall shape of the profile.
i0 : float
The maximum intensity.
bkg : float (optional)
An additive constant to take account of the background.
Returns
-------
out : numpy.array
The 2-D Moffat profile.
"""
return bkg + i0*(1 + (np.sqrt((x-x0)**2+(y-y0)**2)/alpha)**2)**(-beta)
# -----------------------------------------------------------------------------
def cone(x, y, x0, y0, i0, bkg, radius):
"""
2-D cone profile.
The analytical expression is given by:
I(r) = bkg + (1 / tan(alpha)) * (radius-r),
where r = (x^2 + y^2)^(1/2) and alpha the cone aperture.
Parameters
----------
x, y: numpy.array
The grid where the Moffat profile will be define.
x0, y0 : float
The position of the Moffat profile maximum intensity.
radius : float
The scale factor.
alpha : float
The parameter which determines the overall shape of the profile.
i0 : float
The maximum intensity.
bkg : float (optional)
An additive constant to take account of the background.
Returns
-------
out : numpy.array
The 2-D Moffat profile.
"""
alpha = np.arctan2(radius,i0)
r = np.sqrt((x-x0)**2+(y-y0)**2)
z = bkg + (1/np.tan(alpha))*(radius-r)
z[r > radius] = bkg
return z
# -----------------------------------------------------------------------------
def gauss2d(x, y, x0, y0, i0, bkg, sigma_x, sigma_y):
"""
2-D Gaussian profile.
The analytical expression is given by:
I(r) = bkg + I_0 * exp[...]
where r = (x^2 + y^2)^(1/2) ...
Parameters
----------
x, y: numpy.array
The grid where the Moffat profile will be define.
x0, y0 : float