-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulationfunctions.py
More file actions
2216 lines (1349 loc) · 71.3 KB
/
Copy pathsimulationfunctions.py
File metadata and controls
2216 lines (1349 loc) · 71.3 KB
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
from astropy.io import fits
import matplotlib.pyplot as plt
import numpy as np
from astropy.nddata.utils import Cutout2D
from astropy.wcs import WCS
from astropy import table
import pandas as pd
import math
from math import pi
from PIL import Image
from numpy import asarray
import yaml
from congrid import congrid
import generate_PSF
import numpy as np
import scipy.interpolate
import scipy.ndimage
import glob
import matplotlib.animation as animation
import imageio
import imageio.v3 as iio
import os
from scipy import interpolate
from matplotlib.colors import LogNorm
from scipy import signal
import scipy.constants as sc
import pdb
import copy
import skimage.io
from skimage.util import random_noise
from datetime import datetime
# ===========================================================================
# :: PyISH: Python Integral Field Spectrograph Simulation ::
# ===========================================================================
# Below is every function in this simulation!
# [ Image Processing ] -----------------------------------------------
# Image processing reads in the excel files you filled out specifiying your paths to the spatial maps, spectrum, specs, etc.
# It will seperate the spectrum into flux contributions from the continuum vs flux from each emission
# It will then use each flux contribution to scale either the emission spatial maps, or the continuum spatial maps
# It will also convolve each map with the respective PSF
# Overall, image processing creates the input 3D cubes, that are scaled to Rayleighs and convolved with the PSF
# -----------------------------------------------------------------------------
def imageprocessing(widthof1slice, bandwidth, detectorbandpass, bandpassstart, detectorFOV):
#Reading excel file
sim_inputs = pd.read_excel('inputdataIFUSim.xlsx')
path_to_spectrum = sim_inputs.loc[0, 'path_to_spectrum']
#Pulls continuum info, already scaled to rayleighs
albedowavelength, albedoflux = np.loadtxt(path_to_spectrum, skiprows=1, usecols=(0, 1), delimiter=',', unpack = True)
#reading in inputs from excel file
lines = sim_inputs['Ion'].tolist()
emissionline_wl = sim_inputs['Wavelength (nm)'].tolist()
widthemissionlines = sim_inputs['delta_lambda (nm)'].tolist()
# mask with all true values
mask = np.full_like(albedowavelength, True, dtype=bool)
#Fun little loop that masks the emission lines, them fits a line to the remaining data
#this remaining fit represents the flux contribution from the continuum
for peak, width in zip(emissionline_wl, widthemissionlines):
mask &= ~(((peak-(width/2)) <= albedowavelength) & (albedowavelength < (peak+(width/2))))
#Essentially if you have a spectrum like this
# Y-Axis
# ^
# | *
# | * *
# | * * *
# | * * * *
# | * * * *
# | * * * *
# | * * * * * *
# |* *
# +-------------------------------------------> X-Axis
#
#Essentially if you have a spectrum like this
emissionsubtracted_spectrum_wl = albedowavelength[mask]
emissionsubtracted_spectrum_flux = albedoflux[mask]
#The mask will do this:
# Y-Axis
# ^
# |
# |
# |
# |
# |
# | *
# | * * * * * *
# |* *
# +-------------------------------------------> X-Axis
#
#gets a function of the data
#if I change fill value to extrapolate, I get a warning (I think it just becomes 0)
function_spectrum = interpolate.interp1d(albedowavelength, albedoflux, fill_value= np.nan, bounds_error=False)
function_continuum = interpolate.interp1d(emissionsubtracted_spectrum_wl,emissionsubtracted_spectrum_flux, fill_value= 'extrapolate', bounds_error=False)
#Then the intepolation fills in. This is what your "function_continuum" would look like in your example:
# Y-Axis
# ^
# |
# |
# |
# |
# |
# | * - - -
# | * - * * * * - - - *
# |* *
# +-------------------------------------------> X-Axis
#and your "function_spectrum is just a fit of your original spectrum "
#This loop will open the continuum spatial map, then go through each wavelength in youur bandpass and flux-calibrate the continuum map to the flux at that wavelength step
#In addition, when the loop reaches a specified emission line, it will flux-calibrate the emission to the flux contribution from just that emission line (total flux - continuum flux = emission flux contribution)
#Calibrates to the center of each bin (wavelength), assuming 1 bin per bandwidth
#NOTE: If you don't have a high resolution map of your source for the continuum (like a surface reflectance map), for your "continuum map" user input, input an array of 0's matching the shape of your emission line maps
#PyISH will still work
contdata_listR = []
continuummap = sim_inputs.loc[0, 'path to continuum map']
with fits.open(continuummap) as hdul:
contdata = hdul[0].data
#sets values in image between 0-1
contdata = np.abs(contdata/np.max(contdata))
#k is what goes through bandpass
k = bandpassstart + bandwidth
index = 0
emission_wavelength_dict = [[] for _ in range(0,len(lines))]
emission_flux_dict = [[] for _ in range(0,len(lines))]
while k <= bandpassstart + detectorbandpass:
#print(k)
#figuring out where the center of the wavelength bin is.
#Example: IF there is 1 data point between 100nm and 101nm, lambda correspondence would be 100.5nm
lambdacorrespondence = k - (bandwidth/2)
spectrumflux = function_spectrum(lambdacorrespondence)
if spectrumflux < 0 or math.isnan(spectrumflux):
spectrumflux = np.float64(0)
#Figures out flux contribution from the continuum at the specified wavelength
continuumflux = function_continuum(lambdacorrespondence)
if continuumflux < 0 or math.isnan(continuumflux):
continuumflux = np.float64(0)
#flux calibrates the continuum spatial map to the flux at that wavelength
scaledcontdata = contdata * continuumflux
#saves all of these bad boys in a list
contdata_listR.append(scaledcontdata)
#loop inside of a loop (fancy) that checks if we have reached a emission line
#if k is the wavelength of a listed emission line, then we flux calibrate the emission line map as well!
ion_counter = 0
for ion, peak, width in zip(lines, emissionline_wl, widthemissionlines):
#determines the range for an emission line
lower = (peak-(width/2))
upper = (peak+(width/2))
if lower <= k < upper:
#list of the wavelengths that are associated with emission lines
emission_wavelength_dict[ion_counter].append(k)
#if in the range, flux calibrate the associated map
em_flux = spectrumflux - continuumflux
if em_flux < 0:
em_flux = 0
#list of the fluxes associated with emission lines
emission_flux_dict[ion_counter].append(em_flux)
break
ion_counter+=1
k += bandwidth
index += 1
#Just to recap on the most recent loop
#the loop goes across the x-axis (wavelength) in steps consistent with the resolution
# Y-Axis (Amplitude)
# ^
# | *
# | * *
# | * * *
# | * * * *
# | * * * *
# | * * * *
# | * * * *
# |* * * * * * * * * * * * *
# +----------|----------------|-----------------------------> X-Axis (wavelength)
# 0 | |
# ^ ^
# [ when k gets here ] [ when k gets here ]
# flux calibrate emission flux calibrate the continuum spatial map only!
# total - continuum = emission
# flux calibrate continuum
# with continuum function
#All of this in between the hashtags is how I made one of the figures in my paper
########################################################################################
#y1 = function_spectrum(albedowavelength)
#y2 = function_continuum(albedowavelength)
#plt.plot(albedowavelength, y1, color = "Blue", label = "UV Spectrum of Europa")
#plt.plot(albedowavelength, y2, color = "Red", label = "Continuum of Europa", linestyle='dashed')
#plt.fill_between(albedowavelength, y2, color = "Purple", label = "Continuum of Europa", linestyle='dashdot')
#plt.grid()
#plt.xlabel("Wavelength [nm]")
#plt.ylabel("Flux [R]")
#plt.legend()
#plt.yscale('log')
#plt.savefig('spectrumeuropa.png', dpi = 600)
#plt.show()
#commented out in case you wanna pause here
#pdb.set_trace()
#########################################################################################
model_files = sim_inputs['path to model spectral map'].tolist()
inputs = pd.read_excel('InputInformationIFU.xlsx')
pixelscale = inputs.loc[0, 'Pixel_Scale'] #mas/pixel
eac_files = inputs['path to eac yamls'].tolist()
eac = inputs.loc[0, 'EAC']
data_list = [[] for _ in range(0,len(model_files))]
print("step size: ", bandwidth, " nm" )
psf_option = input("Option 1: Generate a new PSF at every wavelength step, or Option 2: Use one wavelength - specified PSF for the entire bandpass? Type `1` for Option 1, `2` for Option 2. ")
if psf_option == '2':
psf_option_wl = float(input("You have selected Option 2. What wavelength would you like the PSF? Please specify in nm: "))
psf_option2 = generate_PSF.create_psf(psf_option_wl, eac_files[int(eac) - 1], pixelscale, FOV = np.array([detectorFOV, detectorFOV]), EAC = str(int(eac)), display = False)
counter = 0
#This next loop is applying the appropriate PSF to every flux - calibrated map we just did
for model, ion_list, wavelengthlist, fluxlist in zip(model_files, lines, emission_wavelength_dict, emission_flux_dict):
with fits.open(model) as hdul_1:
modeldata = hdul_1[0].data
#my images were flipping and rotating for some reason so I have these commented out just in case it happens to you
#modeldata = np.rot90(modeldata, k=2)
modeldata = modeldata / (np.max(modeldata))
#modeldata = np.flipud(modeldata)
#pdb.set_trace()
for j in range(0, len(wavelengthlist)):
if psf_option == '1':
psf = generate_PSF.create_psf(wavelengthlist[j], eac_files[int(eac) - 1], pixelscale, FOV = np.array([detectorFOV, detectorFOV]), EAC = str(int(eac)), display = False)
if psf_option == '2':
psf = psf_option2
#convolving PSF
modelwpsf = signal.convolve2d(modeldata , psf, mode = 'same')
#if you don't want to convolve with the psf at all, comment out line 350 (where I define modelwpsf, and switch "modelwpsf" with 'modeldata' in the line below. (you can see that in my commented version))
#convolving takes a lot of time, so this helps check things
#scaledmodeldata = fluxlist[j] * modeldata
scaledmodeldata = fluxlist[j] * modelwpsf
#uncomment this if you want to see what your images look like post - convolving. beware, this will go through your entire bandpass in tiny steps
#plt.imshow(scaledmodeldata)
#plt.show()
data_list[counter].append(scaledmodeldata)
time = datetime.now()
e = time.strftime("%H:%M:%S")
print("just got through image processing ion: " , ion_list," current time:",e)
counter += 1
time1 = datetime.now()
f = time.strftime("%H:%M:%S")
print("just got through image processing completely, current time:", f)
return data_list, albedowavelength, albedoflux, contdata_listR, emission_wavelength_dict, widthemissionlines, emissionline_wl, lines
# [Telescope Calibration] -----------------------------------------------
# This will take your input 3D cube that you made in the image processing function, and convert the Rayleighs to a photon count
# Rayleighs -> photons depends on instrument specs like efficiencies, exposure time, etc
# which is why these are all user inputs!
#
# -----------------------------------------------------------------------------
def telescopecalibration(data_list, emission_wavelength_dict, contdata_listR, bandpassstart, detectorbandpass, bandwidth, widthemissionlines, emissionline_wl, detectorpixelscale, splitdetector, cutoutsonxaxis, cutoutsonyaxis ):
#extracting efficiencies
sim_inputs = pd.read_excel('inputdataIFUSim.xlsx')
arcsecdata = sim_inputs.loc[0, 'arcsecspectra']
pixelsasdetector = int(arcsecdata / detectorpixelscale)
heightof1slice = splitdetector[cutoutsonyaxis-1][cutoutsonxaxis-1].shape[0]
path_to_grating = sim_inputs.loc[0, 'path to grating yaml']
#these are pulling all the efficiencies from the yaml files
#I could have made this much more efficient but I am ~lazy~
with open(path_to_grating, 'r') as file:
grating_efficiency = yaml.safe_load(file)
grating = np.array([grating_efficiency['wavelength'], grating_efficiency['grating_efficiency']])
#2d numpy array out of yaml file
x_g,y_g = grating
path_to_QE = sim_inputs.loc[0, 'path to QE yaml']
with open(path_to_QE, 'r') as file:
QE = yaml.safe_load(file)
MCP_QE = np.array([QE['wavelength'], QE['QE']])
x_QE,y_QE = MCP_QE
path_to_coating = sim_inputs.loc[0, 'path to coating yaml']
with open(path_to_coating, 'r') as file:
coating_efficiency = yaml.safe_load(file)
coating = np.array([coating_efficiency['wavelength'], coating_efficiency['reflectivity']])
x_c,y_c = coating
inputs = pd.read_excel('InputInformationIFU.xlsx')
reflections = inputs.loc[0, 'reflections']
Inscribed_diameter = inputs.loc[0, 'Inscribed_diameter'] #m
AGeo = pi * ((Inscribed_diameter/2)**2)
#All of this commented out is how I made the efficiency plots for the .yaml files
'''
plt.plot(x_g,y_g, color = "Blue", label = "Grating Efficiency")
plt.plot(x_QE,y_QE, color = "Green", label = "Quantum Efficiency",linestyle='dashed')
plt.plot(x_c,y_c, color = "Purple", label = "Coating Reflectivity", linestyle='dashdot')
plt.xlim(90,400)
plt.ylim(0,1)
plt.xlabel('Wavelength [nm]')
plt.legend()
plt.ylabel('Efficiency')
#plt.grid()
#plt.show()
plt.savefig('efficiencies.png', dpi = 600)
#plt.show()
pdb.set_trace()
'''
#Exposure Time
ExpTime = inputs.loc[0, 'ExpTime']
#pixel scale (converted to radians)
pixelscale_r = inputs.loc[0, 'Pixel_Scale'] * 0.001 * (pi/(180*3600))
domega = pixelscale_r * pixelscale_r
#continuum scaling to photon count
contdata_listphoton = []
scaledHRIdata = [[] for _ in range(0,len(data_list))]
indexingcontinuum = 0
k = bandpassstart + bandwidth
ep = []
test = []
while k <= (bandpassstart + detectorbandpass):
#sets scaling to middle of the bin
lambdacorrespondence = k - (bandwidth/2)
difference_g_cont = np.absolute(x_g - k)
indicies_g_cont = difference_g_cont.argmin()
grating_efficiency_continuum = float(y_g[indicies_g_cont])
difference_QE_cont = np.absolute(x_QE - k)
indicies_QE_cont = difference_QE_cont.argmin()
detector_loss_continuum = float(y_QE[indicies_QE_cont])
difference_c_cont = np.absolute(x_c - k)
indicies_c_cont = difference_c_cont.argmin()
coating_efficiency_cont = float(y_c[indicies_c_cont])
epsilon_cont = grating_efficiency_continuum*detector_loss_continuum*(coating_efficiency_cont**reflections)
ep.append(epsilon_cont)
AEff_lamb = AGeo * epsilon_cont
#this below is the equation for Rayleighs -> photons. It depends on effective area (which is geometric area * efficiencies), exposure time, pixel scale squared, and some constants
contdata_photoncount = contdata_listR[indexingcontinuum] * AEff_lamb * ExpTime * domega *((1e10)/(4*pi))
#the couple of lines below are reshaping your maps!
#the input spatial maps are not neccesarily representative of how the soruce would be captured by an HWO IFS
#more specifically, the pixel pitch needs adjustment. If your IFS has a field of view of 5 arcseconds, and a pixel pitch of 0.1 arcseconds/pixel,
#these next couple lines makes sure that each image is 50 x 50 pixels
#first reshapes to the correct amount of pixels tall
contdata_photoncount = resample(contdata_photoncount, (pixelsasdetector, contdata_photoncount.shape[1]), method = 'linear')
#then adds extra 0 space to match detector height
#if your image was too little pixels, extra pixels will be filled in as 0's (as if no data was captured)
#if your image was too many pixels, iteratively chops off top and bottom of image, one pixel at a time to reach desired size
contdata_photoncount = rebin(contdata_photoncount, heightof1slice)
#Next two lines do the exact same thing on the x-axis
contdata_photoncount = resample(contdata_photoncount, (contdata_photoncount.shape[0], pixelsasdetector), method = 'linear')
contdata_photoncount = rebinx(contdata_photoncount, heightof1slice)
contdata_listphoton.append(contdata_photoncount)
#the loop above went from rayleighs -> photons, and made sure the sizes were coreect for the continuum spatial map images
#the loop below does the exact same thing for the emission lines
#again I could make this more efficient but as I always say...if it aint broke dont fix it
emissioncounter = 0
for peak, width, wavelengthlist in zip(emissionline_wl, widthemissionlines, emission_wavelength_dict):
lower = (peak-(width/2))
upper = (peak+(width/2))
if lower <= k < upper:
values = np.absolute(wavelengthlist - k)
indexofinterest = np.argmin(values)
#scales to photon count
image_photoncount = data_list[emissioncounter][indexofinterest] * AEff_lamb * ExpTime * domega *((1e10)/(4*pi))
#first reshapes to pixels as detector high
image_photoncount = resample(image_photoncount, (pixelsasdetector, image_photoncount.shape[1]), method = 'linear')
#then adds extra 0 space to match detector height
image_photoncount = rebin(image_photoncount, heightof1slice)
#first reshapes to pixels as detector wide
image_photoncount = resample(image_photoncount, (image_photoncount.shape[0], pixelsasdetector), method = 'linear')
#then matches detector width
#height of one slice is in pixels, this sets fov in input transform
#make sure this is actually true
image_photoncount = rebinx(image_photoncount, heightof1slice)
scaledHRIdata[emissioncounter].append(image_photoncount)
break
emissioncounter += 1
k += bandwidth
indexingcontinuum = indexingcontinuum + 1
time1 = datetime.now()
e = time1.strftime("%H:%M:%S")
print("just got through telescope calibration completely, current time:", e)
return scaledHRIdata, contdata_listphoton
# [Image resampling methods] -----------------------------------------------
#The functions below are called within the modules of PyISH, not independently
# -----------------------------------------------------------------------------
__all__ = ['resample', 'reshape_image_to_4d_superpixel']
def resample(orig, dimensions, method='linear', center=False, minusone=False):
"""
Returns a new `numpy.ndarray` that has been resampled up or down.
Arbitrary resampling of source array to new dimension sizes.
Currently only supports mai ntaining the same number of dimensions.
To use 1-D arrays, first promote them to shape (x,1).
Uses the same parameters and creates the same coordinate lookup points
as IDL's ``congrid`` routine (which apparently originally came from a
VAX/VMS routine of the same name.)
Parameters
----------
orig : `numpy.ndarray`
Original input array.
dimensions : `tuple`
Dimensions that new `numpy.ndarray` should have.
method : {``"nearest"``, ``"linear"``, ``"spline"``}, optional
Method to use for resampling interpolation.
* nearest and linear - Uses "n x 1D" interpolations calculated by
`scipy.interpolate.interp1d`.
* spline - Uses `scipy.ndimage.map_coordinates`
center : `bool`, optional
If `False` (default) the interpolation points are at the front edge of the bin.
If `True`, interpolation points are at the centers of the bins
minusone : `bool`, optional
For ``orig.shape = (i,j)`` & new dimensions ``= (x,y)``, if set to `False`
(default) ``orig`` is resampled by factors of ``(i/x) * (j/y)``,
otherwise ``orig`` is resampled by ``(i-1)/(x-1) * (j-1)/(y-1)``.
This prevents extrapolation one element beyond bounds of input array.
Returns
-------
out : `numpy.ndarray`
A new `numpy.ndarray` which has been resampled to the desired dimensions.
References
----------
https://gcc02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fscipy-cookbook.readthedocs.io%2Fitems%2FRebinning.html&data=05%7C02%7Cgrace.m.sweetak%40nasa.gov%7C95cf4e9028f8472607d808ddb807fbfe%7C7005d45845be48ae8140d43da96dd17b%7C0%7C0%7C638869066600300365%7CUnknown%7CTWFpbGZsb3d8eyJFbXB0eU1hcGkiOnRydWUsIlYiOiIwLjAuMDAwMCIsIlAiOiJXaW4zMiIsIkFOIjoiTWFpbCIsIldUIjoyfQ%3D%3D%7C0%7C%7C%7C&sdata=LZeINPbSOmvBclh8v5BW8VSpLb%2BtzEMOplAWlvzgYVo%3D&reserved=0
"""
# Verify that number dimensions requested matches original shape
if len(dimensions) != orig.ndim:
raise UnequalNumDimensions("Number of dimensions must remain the same "
"when calling resample.")
# TODO: Will this be okay for integer (e.g. JPEG 2000) data?
if orig.dtype not in [np.float64, np.float32]:
orig = orig.astype(np.float64)
dimensions = np.asarray(dimensions, dtype=np.float64)
m1 = np.array(minusone, dtype=np.int64) # array(0) or array(1)
offset = np.float64(center * 0.5) # float64(0.) or float64(0.5)
# Resample data
if method in ['nearest', 'linear']:
data = _resample_nearest_linear(orig, dimensions, method,
offset, m1)
elif method == 'spline':
data = _resample_spline(orig, dimensions, offset, m1)
else:
raise UnrecognizedInterpolationMethod(f"Unrecognized interpolation method requested: {method}")
return data
def _resample_nearest_linear(orig, dimensions, method, offset, m1):
"""
Resample Map using either linear or nearest interpolation.
Parameters
----------
orig : array-like
Original data.
dimensions : `tuple`
Dimensions of resampled data.
method : `str`
Interpolation method passed to `~scipy.interpolate.interpn`
offset : `float`
Either 0 or 0.5, depending on whether interpolation is at the edge or
centers of bins.
m1 : 0 or 1
For ``orig.shape = (i,j)`` & new dimensions ``= (x,y)``, if set to `False`
(default) ``orig`` is resampled by factors of ``(i/x) * (j/y)``,
otherwise ``orig`` is resampled by ``(i-1)/(x-1) * (j-1)/(y-1)``.
This prevents extrapolation one element beyond bounds of input array.
"""
old_coords = [np.arange(i, dtype=float) + offset for i in orig.shape]
scale = (orig.shape - m1) / (dimensions - m1)
new_coords = [(np.arange(dimensions[i], dtype=float) + offset) * scale[i] for i in
range(len(dimensions))]
new_coords = np.stack(np.meshgrid(*new_coords, indexing='ij'), axis=-1)
# fill_value = None extrapolates outside the domain
new_data = scipy.interpolate.interpn(old_coords, orig, new_coords,
method=method, bounds_error=False,
fill_value=None)
return new_data
def _resample_spline(orig, dimensions, offset, m1):
"""
Resample Map using spline-based interpolation.
"""
nslices = [slice(0, j) for j in list(dimensions)]
newcoords = np.mgrid[nslices]
newcoords_dims = list(range(newcoords.ndim))
# make first index last
newcoords_dims.append(newcoords_dims.pop(0))
newcoords_tr = newcoords.transpose(newcoords_dims)
# makes a view that affects newcoords
newcoords_tr += offset
deltas = (np.asarray(orig.shape) - m1) / (dimensions - m1)
newcoords_tr *= deltas
newcoords_tr -= offset
return scipy.ndimage.map_coordinates(orig, newcoords)
def reshape_image_to_4d_superpixel(img, dimensions, offset):
"""
Re-shape the two-dimensional input image into a four-dimensional array
whose first and third dimensions express the number of original pixels in
the "x" and "y" directions that form one superpixel. The reshaping makes it
very easy to perform operations on superpixels.
An application of this reshaping is the following. Let's say you have an
array::
x = np.array([[0, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 1],
[0, 0, 0, 0, 1, 1],
[1, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 0]])
and you want to sum over 2x2 non-overlapping sub-arrays. For example, you
could have a noisy image and you want to increase the signal-to-noise ratio.
Summing over all the non-overlapping 2x2 sub-arrays will create a
superpixel array of the original data. Every pixel in the superpixel array
is the sum of the values in a 2x2 sub-array of the original array.
This summing can be done by reshaping the array::
y = x.reshape(3,2,3,2)
and then summing over the 1st and third directions::
y2 = y.sum(axis=3).sum(axis=1)
which gives the expected array::
array([[0, 3, 2],
[2, 0, 4],
[1, 2, 2]])
Parameters
----------
img : `numpy.ndarray`
A two-dimensional `numpy.ndarray` of the form ``(y, x)``.
dimensions : array-like
A two element array-like object containing integers that describe the
superpixel summation in the ``(y, x)`` directions.
offset : array-like
A two element array-like object containing integers that describe
where in the input image the array reshaping begins in the ``(y, x)``
directions.
Returns
-------
A four dimensional `numpy.ndarray` that can be used to easily create
two-dimensional arrays of superpixels of the input image.
"""
# make sure the input dimensions are integers
dimensions = [int(dim) for dim in dimensions]
# New dimensions of the final image
na = int(np.floor((img.shape[0] - offset[0]) / dimensions[0]))
nb = int(np.floor((img.shape[1] - offset[1]) / dimensions[1]))
# Reshape up to a higher dimensional array which is useful for higher
# level operations
return (img[int(offset[0]):int(offset[0] + na * dimensions[0]),
int(offset[1]):int(offset[1] + nb * dimensions[1])]).reshape(na, dimensions[0], nb, dimensions[1])
class UnrecognizedInterpolationMethod(ValueError):
"""
Unrecognized interpolation method specified.
"""
class UnequalNumDimensions(ValueError):
"""
Number of dimensions does not match input array.
"""
# [Continuum Slicer] -----------------------------------------------
#This takes the input 3D sube for just the continuum spatial maps (which are scaled to a photon count and correctly sizes according to the pixel scale)
# It cuts the images up into the amount of slices as defined by the user inputs
#and saves these "contcutouts" = continuum cutouts
# -----------------------------------------------------------------------------
def continuumslicer(contdata_listphoton, numberIFUslices):
contcutouts = [[] for _ in range(0,len(contdata_listphoton))]
for j in range(0, len(contdata_listphoton)):
#retrieve image size
xlength = contdata_listphoton[j].shape[1]
ylength = contdata_listphoton[j].shape[0]
#xcenter and ycenter are the centers of each slice
#its a little weird but it works
# +-------+-------+
# | | |
# | | |
# | | |
# | | |
# | | |
# | | |
# | | |
# +---|----+-------+
# |
# ^
#if my image is 8 pixels across, and I want 2 IFS slices, then xcenter = 2
#2 pixels to the center of each slice
ycenter = ylength/(numberIFUslices*2)
xcenter = xlength/(numberIFUslices*2)
#each image needs to be split into 100 IFS slices, then j iterates to the next image
for i in range(0,numberIFUslices):
#cut the slice
contcutout = Cutout2D(contdata_listphoton[j], (xcenter, ylength/2), (ylength, xlength/numberIFUslices))
#save the data, move to the next center and repeat
data_to_save = contcutout.data
ycenter = ycenter + (ylength/numberIFUslices)
xcenter = xcenter + (xlength/numberIFUslices)
contcutouts[j].append(
data_to_save
)
#this is how I made a movie showin the cuts across each slice for image number 400 (replace 400 if have a really small bandpass of something)
'''
if j ==400:
plt.imshow(contdata_listphoton[j], origin = 'lower', cmap = 'Blues_r')
contcutout.plot_on_original(color = 'gray')
plt.savefig(f"continuumcutouts/{i}.png")
plt.close()
'''
#cutouts[0][2] represents the 1st image (H1), and the 2nd cutout/slice
time1 = datetime.now()
e = time1.strftime("%H:%M:%S")
print("just got through continuum cutouts completely, current time:", e)
return contcutouts
# [Image resampling methods] -----------------------------------------------
#This is basically the same function as continuumslicer but for the emission lines
#it's a little more complicated becuase we have multiple images for multiple emsisions, so have to have an extra loop in there
#I am sure there is a way to combine these functions but I do not feel like it!
#But yeah, this will cut up each photon-calibrated spatial map for each emission line, according to the number of IFS sluces
#will save everything in a list
# ---------------------------------------------------------------------------
def ifuslicer(scaledHRIdata, numberIFUslices, lines):
cutouts_dict = {}
#start by making empty lists of things
for emissionlinenames, HRIlistforeachline in zip(lines, scaledHRIdata):
cutouts_dict[emissionlinenames] = [[] for _ in range(len(HRIlistforeachline))]
rebinned_cutouts_dict = copy.deepcopy(cutouts_dict)
counter = 0
#top loop goes through each emission line
for j, ionname in zip(range(0, len(scaledHRIdata)), lines):
#this loop goes through all of the spatial maps associated with that ion
for k in range(0, len(scaledHRIdata[counter])):
xlength = scaledHRIdata[j][k].shape[1]
ylength = scaledHRIdata[j][k].shape[0]
#These are the centers of each slice
ycenter = ylength/(numberIFUslices*2)
xcenter = xlength/(numberIFUslices*2)
#cutting them out as last function did
for i in range(0,numberIFUslices):
cutout = Cutout2D(scaledHRIdata[j][k], (xcenter, ylength/2), (ylength, xlength/numberIFUslices))
data_to_save = cutout.data
ycenter = ycenter + (ylength/numberIFUslices)
xcenter = xcenter + (xlength/numberIFUslices)
#this will show you one IFS slice for every spatial map for one emission line
#if you have less than 35 IFS slices, then change the i
'''
if i == 35:
plt.imshow(scaledHRIdata[j][k], origin = 'lower', cmap = 'Blues_r')
cutout.plot_on_original(color = 'gray')
plt.xticks([])
plt.yticks([])
plt.xlim(0, scaledHRIdata[j][k].shape[1] - 1)
plt.ylim(0, scaledHRIdata[j][k].shape[0] - 1)
plt.colorbar()
plt.show()
'''
cutouts_dict[ionname][k].append(data_to_save