pyEDITH 1.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,874 @@
1
+ import numpy as np
2
+ from scipy.interpolate import interp1d
3
+ import astropy.units as u
4
+ import astropy.constants as const
5
+ from .units import *
6
+ from . import utils
7
+ from astropy.coordinates import SkyCoord
8
+ import logging
9
+
10
+ logger = logging.getLogger("pyEDITH")
11
+ # def calc_flux_zero_point_synphot(lam: u.Quantity):
12
+
13
+ # # calculates a zeropoint Vega spectrum using boxcar filters
14
+ # from synphot import SourceSpectrum, SpectralElement, Observation, Box1D
15
+ # from synphot.exceptions import DisjointError
16
+ # import numpy as np
17
+ # import astropy.units as u
18
+
19
+ # # load the vega spectrum
20
+ # vega = SourceSpectrum.from_vega()
21
+
22
+ # # convert wavelength grid to angstrom
23
+ # lam = lam.to(u.AA)
24
+ # dlam = np.gradient(lam)
25
+ # dlam = dlam.to(u.AA)
26
+
27
+ # vega_fluxes = np.empty(len(lam))
28
+
29
+ # # treat the wavelength bins as box filters
30
+ # for i in range(len(lam)):
31
+ # filt_ctr = lam[i]
32
+ # filt_width = dlam[i]
33
+
34
+ # # boxcar filter
35
+ # boxcar = Box1D(amplitude=1, x_0=filt_ctr.value, width=filt_width.value)
36
+ # filt = SpectralElement(boxcar, wavelengths=lam)
37
+
38
+ # # calculate an observation of Vega with filter
39
+ # try:
40
+ # obs = Observation(vega, filt, binset=lam)
41
+ # except :
42
+ # #print("Box filter extends beyond wavelength range. Setting flux as nan for this spectral bin.")
43
+ # vega_fluxes[i] = np.nan
44
+ # continue
45
+
46
+ # # integrate observation
47
+ # flux_photlam = obs.effstim(flux_unit="photlam")
48
+
49
+ # # convert to pyEDITH units
50
+ # flux = flux_photlam.to(u.photon/u.s/u.cm**2/u.nm)
51
+
52
+ # vega_fluxes[i] = flux.value
53
+
54
+ # return vega_fluxes * u.photon/u.s/u.cm**2/u.nm
55
+
56
+
57
+ def calc_flux_zero_point(
58
+ lambd: u.Quantity,
59
+ output_unit: str = "pcgs",
60
+ perlambd: bool = False,
61
+ AB: bool = False,
62
+ ) -> u.Quantity:
63
+ """
64
+ Calculate the flux zero point for given wavelengths.
65
+
66
+ This function calculates the flux zero point for a given set of wavelengths.
67
+ By default, it returns Johnson zero points. If the 'AB' flag is set, it will
68
+ return AB flux zero points.
69
+
70
+ Parameters
71
+ ----------
72
+ lambd : astropy.units.Quantity
73
+ Wavelengths. Must be in units of length.
74
+ output_unit : str, optional
75
+ Output unit type. Possible values are:
76
+ - "jy" for output in Jy
77
+ - "cgs" for output in erg s^-1 cm^-2 Hz^-1
78
+ - "pcgs" for output in photons s^-1 cm^-2 Hz^-1
79
+ Default is "pcgs".
80
+ perlambd : bool, optional
81
+ If True, convert all output values to per wavelength instead of per frequency.
82
+ Default is False.
83
+ AB : bool, optional
84
+ If True, use AB magnitude system instead of Johnson.
85
+ Default is False.
86
+
87
+ Returns
88
+ -------
89
+ astropy.units.Quantity
90
+ Flux zero points for the given wavelengths in the specified units.
91
+
92
+ Raises
93
+ ------
94
+ ValueError
95
+ If output_unit is not specified or is invalid, or if incompatible options are selected.
96
+ """
97
+
98
+ if output_unit not in ["jy", "cgs", "pcgs"]:
99
+ raise ValueError(
100
+ 'Invalid output_unit value. Possible values are: "jy" for output in Jy, '
101
+ '"cgs" for output in erg s^-1 cm^-2 Hz^-1, '
102
+ '"pcgs" for output in photons s^-1 cm^-2 Hz^-1.'
103
+ )
104
+
105
+ if output_unit == "jy" and perlambd:
106
+ raise ValueError("Cannot set Jy and perlambd")
107
+
108
+ # Ensure lambd is in the correct units (cm for CGS)
109
+ lambd = lambd.to(CM)
110
+
111
+ # Convert constants to CGS
112
+ h_cgs = const.h.cgs.value
113
+ c_cgs = const.c.cgs.value
114
+
115
+ # Calculate the zero point
116
+ if AB:
117
+ # AB magnitude system
118
+ f0 = 3631 * JANSKY # AB zero point
119
+ else:
120
+ # Johnson magnitude system
121
+ known_lambd = (
122
+ np.array(
123
+ [0.36, 0.44, 0.55, 0.71, 0.97, 1.25, 1.60, 2.22, 3.54, 4.80, 10.6, 21.0]
124
+ )
125
+ * WAVELENGTH
126
+ )
127
+ known_zeropoint_jy = (
128
+ np.array([1823, 4130, 3781, 2941, 2635, 1603, 1075, 667, 288, 170, 36, 9.4])
129
+ * JANSKY
130
+ )
131
+
132
+ # Interpolation in log-log space
133
+ interp = interp1d(
134
+ np.log10(known_lambd.value),
135
+ np.log10(known_zeropoint_jy.value),
136
+ kind="cubic",
137
+ fill_value="extrapolate",
138
+ )
139
+ logf0 = interp(np.log10(lambd.to_value(WAVELENGTH)))
140
+ f0 = 10.0**logf0 * JANSKY
141
+
142
+ # Convert to desired output units
143
+ if output_unit == "cgs":
144
+ # Convert to erg / (s * cm^2 * Hz)
145
+ f0 = f0.to(SPECTRAL_FLUX_DENSITY_CGS)
146
+ elif output_unit == "pcgs":
147
+ # Convert to photons / (s * cm^2 * Hz)
148
+ f0 = f0.to(
149
+ PHOTON_FLUX_DENSITY_HZ,
150
+ equivalencies=u.spectral_density(lambd),
151
+ )
152
+
153
+ # Convert to per wavelength if requested
154
+ if perlambd:
155
+ if output_unit == "cgs":
156
+ f0 = f0.to(
157
+ SPECTRAL_FLUX_DENSITY_CGS_WAVELENGTH,
158
+ equivalencies=u.spectral_density(lambd),
159
+ )
160
+ elif output_unit == "pcgs":
161
+ f0 = f0.to(
162
+ PHOTON_FLUX_DENSITY_CGS_WAVELENGTH,
163
+ equivalencies=u.spectral_density(lambd),
164
+ )
165
+
166
+ logger.info(f"Flux zero point calculated at {lambd} in units of {f0.unit}")
167
+
168
+ return f0
169
+
170
+
171
+ def calc_exozodi_flux(
172
+ M_V: u.Quantity,
173
+ vmag: u.Quantity,
174
+ nexozodis: u.Quantity,
175
+ lambd: u.Quantity,
176
+ lambdmag: u.Quantity,
177
+ ) -> u.Quantity:
178
+ """
179
+ Calculate the exozodiacal light flux for given stellar and observational parameters.
180
+
181
+ This function computes the exozodiacal light flux for a set of stars, taking into
182
+ account their absolute and apparent magnitudes, the number of exozodis, and the
183
+ observational wavelengths.
184
+
185
+ Parameters
186
+ ----------
187
+ M_V : Quantity
188
+ V band absolute magnitude of stars.
189
+ vmag : Quantity
190
+ V band apparent magnitude of stars.
191
+ nexozodis : Quantity
192
+ Number of exozodis for each star.
193
+ lambd : Quantity
194
+ Wavelength in microns (vector of length nlambd).
195
+ lambdmag : Quantity
196
+ Apparent magnitude of stars at each lambd (array nlambd).
197
+ F0lambd : Quantity
198
+ Flux zero point at wavelength lambd (vector of length nlambd).
199
+
200
+ Returns
201
+ -------
202
+ Quantity
203
+ Exozodi surface brightness in units of photons s^-1 cm^-2 arcsec^-2 nm^-1 / F0.
204
+ This is equivalent to 10^(-0.4*magOmega_EZ).
205
+
206
+ """
207
+
208
+ if len(lambd) > 1:
209
+ if len(lambd) != lambdmag.shape[0]:
210
+ raise ValueError(
211
+ "ERROR. lambdmag must have dimensions nstars x nlambd, where nlambd is the length of lambd."
212
+ )
213
+
214
+ vmag_1zodi = (
215
+ 22.0 * SURFACE_BRIGHTNESS
216
+ ) # V band surface brightness of 1 zodi in mag arcsec^-2
217
+ vflux_1zodi = 10.0 ** (
218
+ -0.4 * vmag_1zodi.value
219
+ ) # V band flux (modulo the F0 factor out front)
220
+
221
+ M_V_sun = 4.83 * MAGNITUDE # V band absolute magnitude of Sun
222
+
223
+ # Now, multiply by the ratio of the star's counts received at lambd to those
224
+ # received at V band
225
+ nlambd = len(lambd)
226
+
227
+ flux_exozodi_lambd = np.zeros((nlambd)) * DIMENSIONLESS # modulo factor F0
228
+
229
+ # Adjust flux for each wavelength
230
+ for ilambd in range(nlambd):
231
+ flux_exozodi_lambd[ilambd] = (
232
+ nexozodis
233
+ * vflux_1zodi
234
+ * 10.0 ** (-0.4 * (M_V - M_V_sun).value)
235
+ * 10.0 ** (-0.4 * (lambdmag[ilambd] - vmag).value)
236
+ )
237
+
238
+ return (
239
+ flux_exozodi_lambd * INV_SQUARE_ARCSEC
240
+ ) # CONVERTING FROM FLUX TO SURFACE BRIGHTNESS (modulo F0 that gets multiplied later)
241
+
242
+
243
+ def calc_zodi_flux(
244
+ dec: u.Quantity,
245
+ ra: u.Quantity,
246
+ lambd: u.Quantity,
247
+ F0: u.Quantity,
248
+ # starshade: bool = False,
249
+ # ss_elongation: u.Quantity = None,
250
+ ) -> u.Quantity:
251
+ """
252
+
253
+ Calculate the zodiacal light flux for given celestial coordinates and wavelengths.
254
+
255
+ This function computes the zodiacal light flux based on the target's position in the sky,
256
+ observation wavelengths, and whether a starshade is used. It uses the model from
257
+ Leinert et al. (1998) to calculate the zodiacal light intensity.
258
+
259
+ Parameters
260
+ ----------
261
+ dec : Quantity
262
+ Declination of targets in degrees (J2000 equatorial coordinate).
263
+ ra : Quantity
264
+ Right ascension of targets in degrees (J2000 equatorial coordinate).
265
+ lambd : Quantity
266
+ Wavelengths in microns (vector of length nlambd).
267
+ F0 : Quantity
268
+ Flux zero points at wavelengths lambd (vector of length nlambd).
269
+
270
+ Returns
271
+ -------
272
+ np.ndarray
273
+ Zodi surface brightness in units of photons s^-1 cm^-2 arcsec^-2 nm^-1 / F0.
274
+ This is equivalent to 10^(-0.4*magOmega_ZL).
275
+ - Multiply by F0 to get photons s^-1 cm^-2 arcsec^-2 nm^-1
276
+ - Multiply by energy of photons to get erg s^-1 cm^-2 arcsec^-2 nm^-1
277
+ The output array has dimensions (nlambd, nstars).
278
+
279
+ Raises
280
+ ------
281
+ ValueError
282
+ If F0 and lambd have different lengths, or if starshade mode is inconsistent with ss_elongation.
283
+
284
+ Note
285
+ ----
286
+ - The function uses the zodiacal light model from Leinert et al. (1998).
287
+ - For coronagraph mode, it assumes observations near solar longitude of 135 degrees.
288
+ - Starshade functionality is currently not fully implemented.
289
+
290
+ References:
291
+
292
+ Leinert, C., et al. (1998). The 1997 reference of diffuse night sky brightness.
293
+ Astronomy and Astrophysics Supplement Series, 127(1), 1-99.
294
+ """
295
+
296
+ # if starshade and ss_elongation is None:
297
+ # raise ValueError(
298
+ # "ERROR. You have set the STARSHADE flag. Must specify SS_ELONGATION in degrees."
299
+ # )
300
+ # if not starshade and ss_elongation is not None:
301
+ # raise ValueError(
302
+ # "ERROR. You must enable STARSHADE mode if you are setting SS_ELONGATION in degrees."
303
+ # )
304
+
305
+ # Convert equatorial coordinates to ecliptic coordinates
306
+ coords = SkyCoord(ra=ra, dec=dec, frame="icrs")
307
+ ecl_coords = coords.barycentrictrueecliptic
308
+ beta = ecl_coords.lat.rad
309
+
310
+ # all we need is the sine of the latitude
311
+ # Use absolute value of the sin of beta (symmetry about ecliptic plane)
312
+ sinbeta = np.abs(np.sin(beta))
313
+
314
+ # SOURCE: Leinert et al. (1998)
315
+ # Define solar longitude and beta values for interpolation
316
+ beta_vector = np.array([0.0, 5, 10, 15, 20, 25, 30, 45, 60, 75]) * DEG
317
+ sollong_vector = (
318
+ np.array(
319
+ [
320
+ 0,
321
+ 5,
322
+ 10,
323
+ 15,
324
+ 20,
325
+ 25,
326
+ 30,
327
+ 35,
328
+ 40,
329
+ 45,
330
+ 60,
331
+ 75,
332
+ 90,
333
+ 105,
334
+ 120,
335
+ 135,
336
+ 150,
337
+ 165,
338
+ 180.0,
339
+ ]
340
+ )
341
+ * DEG
342
+ )
343
+
344
+ # Table 17 values (assumed to be in some brightness units)
345
+ table17 = (
346
+ np.array(
347
+ [
348
+ [-1, -1, -1, 3140, 1610, 985, 640, 275, 150, 100],
349
+ [-1, -1, -1, 2940, 1540, 945, 625, 271, 150, 100],
350
+ [-1, -1, 4740, 2470, 1370, 865, 590, 264, 148, 100],
351
+ [11500, 6780, 3440, 1860, 1110, 755, 525, 251, 146, 100],
352
+ [6400, 4480, 2410, 1410, 910, 635, 454, 237, 141, 99],
353
+ [3840, 2830, 1730, 1100, 749, 545, 410, 223, 136, 97],
354
+ [2480, 1870, 1220, 845, 615, 467, 365, 207, 131, 95],
355
+ [1650, 1270, 910, 680, 510, 397, 320, 193, 125, 93],
356
+ [1180, 940, 700, 530, 416, 338, 282, 179, 120, 92],
357
+ [910, 730, 555, 442, 356, 292, 250, 166, 116, 90],
358
+ [505, 442, 352, 292, 243, 209, 183, 134, 104, 86],
359
+ [338, 317, 269, 227, 196, 172, 151, 116, 93, 82],
360
+ [259, 251, 225, 193, 166, 147, 132, 104, 86, 79],
361
+ [212, 210, 197, 170, 150, 133, 119, 96, 82, 77],
362
+ [188, 186, 177, 154, 138, 125, 113, 90, 77, 74],
363
+ [179, 178, 166, 147, 134, 122, 110, 90, 77, 73],
364
+ [179, 178, 165, 148, 137, 127, 116, 96, 79, 72],
365
+ [196, 192, 179, 165, 151, 141, 131, 104, 82, 72],
366
+ [230, 212, 195, 178, 163, 148, 134, 105, 83, 72],
367
+ ]
368
+ )
369
+ * SPECTRAL_RADIANCE
370
+ )
371
+ # For coronagraph, assume observations near solar longitude of 135 degrees
372
+ j = np.argmin(np.abs(sollong_vector - 135 * DEG))
373
+ k = np.argmin(np.abs(sollong_vector - 90 * DEG))
374
+
375
+ # Interpolate to get zodi brightness factor
376
+ from scipy.interpolate import interp1d
377
+
378
+ interp = interp1d(
379
+ np.sin(beta_vector),
380
+ table17[j] / table17[k, 0],
381
+ kind="cubic",
382
+ fill_value="extrapolate",
383
+ )
384
+ f = interp(sinbeta) * DIMENSIONLESS
385
+
386
+ # Wavelength dependence (fits to Table 19 in Leinert et al 1998)
387
+ zodi_lambd = (
388
+ np.array(
389
+ [
390
+ 0.2,
391
+ 0.3,
392
+ 0.4,
393
+ 0.5,
394
+ 0.7,
395
+ 0.9,
396
+ 1.0,
397
+ 1.2,
398
+ 2.2,
399
+ 3.5,
400
+ 4.8,
401
+ 12,
402
+ 25,
403
+ 60,
404
+ 100,
405
+ 140,
406
+ ]
407
+ )
408
+ * WAVELENGTH
409
+ )
410
+ zodi_blambd = (
411
+ np.array(
412
+ [
413
+ 2.5e-8,
414
+ 5.3e-7,
415
+ 2.2e-6,
416
+ 2.6e-6,
417
+ 2.0e-6,
418
+ 1.3e-6,
419
+ 1.2e-6,
420
+ 8.1e-7,
421
+ 1.7e-7,
422
+ 5.2e-8,
423
+ 1.2e-7,
424
+ 7.5e-7,
425
+ 3.2e-7,
426
+ 1.8e-8,
427
+ 3.2e-9,
428
+ 6.9e-10,
429
+ ]
430
+ )
431
+ * SPECTRAL_RADIANCE
432
+ )
433
+
434
+ # Convert to erg s^-1 cm^-2 arcsec^-2 nm^-1
435
+ zodi_blambd = zodi_blambd.to(SPECTRAL_RADIANCE_CGS)
436
+
437
+ # Interpolate to get zodi brightness at desired wavelengths
438
+ interp = interp1d(
439
+ np.log10(zodi_lambd.value), np.log10(zodi_blambd.value), kind="cubic"
440
+ )
441
+ blambd = 10 ** interp(np.log10(lambd.to_value(WAVELENGTH))) * zodi_blambd.unit
442
+
443
+ # Convert to photon flux
444
+ # I90fabsfco = blambd / (u.h * u.c / lambd)
445
+
446
+ I90fabsfco = blambd.to(
447
+ PHOTON_SPECTRAL_RADIANCE,
448
+ equivalencies=u.spectral_density(lambd),
449
+ )
450
+ # Divide by F0
451
+ I90fabsfco = I90fabsfco / F0
452
+
453
+ # Calculate final zodi flux
454
+ nlambd = len(lambd)
455
+ flux_zodi = u.Quantity(np.zeros((nlambd)), unit=I90fabsfco.unit)
456
+ for ilambd in range(nlambd):
457
+ flux_zodi[ilambd] = f * I90fabsfco[ilambd]
458
+
459
+ return flux_zodi # 1/arcsec^2 (UNITS OF SPECTRAL RADIANCE)
460
+
461
+
462
+ class AstrophysicalScene:
463
+ """
464
+ A class representing an astrophysical scene for exoplanet observation simulations.
465
+
466
+ This class encapsulates various astrophysical parameters and methods to calculate
467
+ zodi and exozodi fluxes for a set of target stars and their potential exoplanets.
468
+
469
+ Parameters
470
+ ----------
471
+ dist : float
472
+ Distance to stars in parsecs
473
+ vmag : float
474
+ Stellar magnitudes at V band
475
+ mag : ndarray
476
+ Stellar magnitudes at desired wavelengths
477
+ stellar_angular_diameter_arcsec : float
478
+ Angular diameter of stars in arcseconds
479
+ nzodis : float
480
+ Amount of exozodi around target stars in "zodis"
481
+ ra : float
482
+ Right ascension of target stars in degrees
483
+ dec : float
484
+ Declination of target stars in degrees
485
+ separation : float
486
+ Separation of planets in arcseconds
487
+ xp : float
488
+ X-coordinate of planets in arcseconds
489
+ yp : float
490
+ Y-coordinate of planets in arcseconds
491
+ deltamag : ndarray
492
+ Magnitude difference between planets and host stars
493
+ min_deltamag : float
494
+ Brightest planet to resolve at the IWA
495
+ F0V : float
496
+ Flux zero point for V band
497
+ F0 : ndarray
498
+ Flux zero points for prescribed wavelengths
499
+ M_V : float
500
+ Absolute V band magnitudes of target stars
501
+ Fzodi_list : ndarray
502
+ Zodiacal light fluxes
503
+ Fexozodi_list : ndarray
504
+ Exozodiacal light fluxes
505
+ Fbinary_list : ndarray
506
+ Binary star fluxes (currently ignored)
507
+ Fp_over_Fs : ndarray
508
+ Flux of planets
509
+
510
+ """
511
+
512
+ def __init__(self):
513
+ """
514
+ Initialize the AstrophysicalScene object with default values for output arrays.
515
+ """
516
+ # Constants
517
+ # Zero Point Flux in the V Band
518
+ self.F0V = (
519
+ calc_flux_zero_point(
520
+ lambd=0.55 * WAVELENGTH, output_unit="pcgs", perlambd=True
521
+ )
522
+ ).to(
523
+ PHOTON_FLUX_DENSITY, equivalencies=u.spectral_density(0.55 * WAVELENGTH)
524
+ ) # convert to photons cm^-2 nm^-1 s^-1
525
+ return
526
+
527
+ def load_configuration(self, parameters: dict) -> None:
528
+ """
529
+ Load configuration parameters for the simulation from a dictionary.
530
+
531
+ This method initializes various attributes of the AstrophysicalScene object
532
+ using the provided parameters dictionary.
533
+
534
+ Parameters
535
+ ----------
536
+ parameters : dict
537
+ A dictionary containing simulation parameters including target star
538
+ parameters, planet parameters, and observational parameters.
539
+ Returns
540
+ -------
541
+ None
542
+
543
+ Raises
544
+ ------
545
+ ValueError
546
+ If a required parameter is missing from the input dictionary.
547
+ """
548
+
549
+ # -------- INPUTS ---------
550
+
551
+ # distance to star (pc) # used to be (ntargs array) now scalar
552
+ self.dist = parameters["distance"] * DISTANCE
553
+
554
+ # Calculate zero point flux at lambda
555
+ if "F0" in parameters.keys():
556
+ self.F0 = parameters["F0"] * PHOTON_FLUX_DENSITY
557
+ else:
558
+ self.F0 = calc_flux_zero_point(
559
+ lambd=parameters["wavelength"] * WAVELENGTH,
560
+ output_unit="pcgs",
561
+ perlambd=True,
562
+ ).to(
563
+ PHOTON_FLUX_DENSITY,
564
+ equivalencies=u.spectral_density(parameters["wavelength"] * WAVELENGTH),
565
+ ) # [nlambda]
566
+
567
+ # look for delta_mag_min or Fp_min/Fs. If not there, default to vals. This hides this feature from the user.
568
+ if "delta_mag_min" in parameters:
569
+ self.min_deltamag = parameters["delta_mag_min"] * MAGNITUDE
570
+ else:
571
+ self.min_deltamag = 26 * MAGNITUDE
572
+ if "Fp_min/Fs" in parameters:
573
+ self.Fp_min_over_Fs = parameters["Fp_min/Fs"] * DIMENSIONLESS
574
+ else:
575
+ self.Fp_min_over_Fs = 1e-10 * DIMENSIONLESS
576
+
577
+ # Determine if user provided magnitudes or fluxes
578
+
579
+ if all(param in parameters for param in ["magV", "mag", "delta_mag"]):
580
+ # User provided magnitudes
581
+ # stellar mag (not absolute mag!!) at V band # used to be (ntargs array) now scalar
582
+ self.vmag = parameters["magV"] * MAGNITUDE
583
+
584
+ # stellar mag at desired lambd # used to be (ntargs array) now scalar
585
+ self.mag = parameters["mag"] * MAGNITUDE
586
+
587
+ # difference in mag between planet and host star
588
+ # (nmeananom x norbits x ntargs array)
589
+ self.deltamag = parameters["delta_mag"] * MAGNITUDE
590
+
591
+ # brightest planet to resolve w/ photon counting detector evaluated at
592
+ # the IWA, sets the time between counts (ntargs array)
593
+
594
+ # Convert magnitudes to RELATIVE fluxes (modulo F0)
595
+ self.Fs_over_F0 = 10 ** (-0.4 * self.mag.value) * DIMENSIONLESS
596
+ self.Fp_over_Fs = 10 ** (-0.4 * self.deltamag.value) * DIMENSIONLESS
597
+ self.Fp_min_over_Fs = 10 ** (-0.4 * self.min_deltamag.value) * DIMENSIONLESS
598
+
599
+ elif all(param in parameters for param in ["Fstar_10pc", "Fp/Fs"]):
600
+
601
+ # Load fluxes
602
+ Fstar_10pc = parameters["Fstar_10pc"] * PHOTON_FLUX_DENSITY
603
+
604
+ if (
605
+ "FstarV_10pc" not in parameters
606
+ and parameters["observing_mode"] == "IFS"
607
+ ):
608
+ logger.warning(
609
+ "`FstarV_10pc` not specified in parameters. Calculating internally..."
610
+ )
611
+ # from synphot import SourceSpectrum, SpectralElement, Observation
612
+ # from synphot.models import Empirical1D
613
+ # # if given a spectrum, calculate the v-band flux using synphot
614
+ # tempSpec = SourceSpectrum(Empirical1D, points=parameters["wavelength"] * WAVELENGTH, lookup_table=Fstar_10pc)
615
+ # johnson_v = SpectralElement.from_filter('johnson_v')
616
+ # obsTemp = Observation(tempSpec, johnson_v)
617
+ #
618
+ # # unit conversion is necessary because V-band flux is in units of [photons/s/cm^2],
619
+ # # and not PHOTON_FLUX_DENSITY since an integration over wavelength was performed.
620
+ # # Doing this to make the units line up.
621
+ # Fstar_V_10pc = obsTemp.integrate(flux_unit=PHOTON_FLUX_DENSITY).value * PHOTON_FLUX_DENSITY
622
+
623
+ # the above is for calculating the zero-point over a bandpass. What is actually going on here is
624
+ # that the zeropoint calculation is for a single wavelength, lam=0.55 um.
625
+ # let's change this up and interpolate
626
+ func = interp1d(parameters["wavelength"], Fstar_10pc)
627
+ Fstar_V_10pc = (
628
+ func(0.55) * PHOTON_FLUX_DENSITY
629
+ ) # interpolate to single wavelength, not a bandpass
630
+
631
+ elif (
632
+ "FstarV_10pc" not in parameters
633
+ and parameters["observing_mode"] == "IMAGER"
634
+ ):
635
+ raise ValueError("FstarV_10pc missing in parameters.")
636
+ else:
637
+ Fstar_V_10pc = parameters["FstarV_10pc"] * PHOTON_FLUX_DENSITY
638
+
639
+ Fstar_absolute = Fstar_10pc * (10 * DISTANCE / self.dist) ** 2
640
+
641
+ Fstar_V_absolute = Fstar_V_10pc * (10 * DISTANCE / self.dist) ** 2
642
+
643
+ self.Fp_over_Fs = parameters["Fp/Fs"] * DIMENSIONLESS
644
+ # Convert to relative fluxes (used internally)
645
+ self.Fs_over_F0 = (Fstar_absolute / self.F0).to(DIMENSIONLESS)
646
+
647
+ # Calculate vmag (needed for zodi)
648
+ self.vmag = -2.5 * np.log10(Fstar_V_absolute / self.F0V) * MAGNITUDE
649
+ self.mag = -2.5 * np.log10(Fstar_absolute / self.F0) * MAGNITUDE
650
+
651
+ # Calculate deltamag and min_deltamag (used only to validate)
652
+ self.deltamag = -2.5 * np.log10(self.Fp_over_Fs) * MAGNITUDE
653
+ self.min_deltamag = -2.5 * np.log10(self.Fp_min_over_Fs) * MAGNITUDE
654
+ else:
655
+ missing_mag_params = [
656
+ param
657
+ for param in ["magV", "mag", "delta_mag"]
658
+ if param not in parameters
659
+ ]
660
+ missing_flux_params = [
661
+ param
662
+ for param in ["Fstar_10pc", "FstarV_10pc", "Fp/Fs"]
663
+ if param not in parameters
664
+ ]
665
+
666
+ raise ValueError(
667
+ f"Insufficient parameters provided. You must provide either:\n"
668
+ f"1. All magnitude parameters: {', '.join(['magV', 'mag', 'delta_mag'])}\n"
669
+ f" Missing: {', '.join(missing_mag_params)}\n"
670
+ f"OR\n"
671
+ f"2. All flux parameters: {', '.join(['Fstar_10pc', 'FstarV_10pc', 'Fp/Fs',])}\n"
672
+ f" Missing: {', '.join(missing_flux_params)}"
673
+ )
674
+
675
+ # convert stellar radius into stellar angular diameter (in arcsec)
676
+ stellar_radius_arcsec = (
677
+ to_arcsec(
678
+ (parameters["stellar_radius"] * const.R_sun).to(LENGTH),
679
+ (self.dist.to(LENGTH)),
680
+ )
681
+ * ARCSEC
682
+ )
683
+
684
+ # angular diameter of star (arcsec) # used to be (ntargs array) now scalar
685
+ self.stellar_angular_diameter_arcsec = 2 * stellar_radius_arcsec
686
+
687
+ # amount of exozodi around target star ("zodis") # used to be (ntargs array) now scalar
688
+ self.nzodis = parameters["nzodis"] * ZODI
689
+
690
+ # right ascension of target star used to estimate zodi (deg) # used to be (ntargs array) now scalar
691
+ self.ra = parameters["ra"] * DEG
692
+
693
+ # declination of target star used to estimate zodi (deg) # used to be (ntargs array) now scalar
694
+ self.dec = parameters["dec"] * DEG
695
+
696
+ # Planet parameters
697
+ # separation of planet (arcseconds) (nmeananom x norbits x ntargs array)
698
+ # NOTE FOR NOW IT IS ASSUMED TO BE ON THE X AXIS
699
+ # SO THAT XP = SP (input) and YP = 0
700
+
701
+ if "separation" in parameters.keys():
702
+ self.separation = parameters["separation"] * ARCSEC
703
+ elif "semimajor_axis" in parameters.keys():
704
+ self.separation = (
705
+ to_arcsec(
706
+ (parameters["semimajor_axis"] * const.au).to(LENGTH),
707
+ (self.dist.to(LENGTH)),
708
+ )
709
+ * ARCSEC
710
+ )
711
+ else:
712
+ raise ValueError(
713
+ "Either separation [arcsec] or semimajor_axis [AU] must be provided."
714
+ )
715
+
716
+ self.xp = self.separation.copy()
717
+ self.yp = self.separation.copy() * 0.0
718
+
719
+ # set the exozodi PPF
720
+ if "ez_PPF" in parameters.keys():
721
+ if not isinstance(parameters["ez_PPF"], (list, np.ndarray)):
722
+ self.ez_PPF = parameters["ez_PPF"] * np.ones_like(self.Fp_over_Fs)
723
+ else:
724
+ assert len(parameters["ez_PPF"]) == len(
725
+ self.Fp_over_Fs
726
+ ), "length of ez_PPF does not match length of Fp_over_Fs"
727
+ self.ez_PPF = np.array(parameters["ez_PPF"])
728
+ else:
729
+ logger.warning(
730
+ "ez_PPF not set. Assuming EZ subtraction to Poisson limit (ez_PPF = inf)"
731
+ )
732
+ self.ez_PPF = np.inf * np.ones_like(self.Fp_over_Fs)
733
+
734
+ def calculate_zodi_exozodi(self, parameters: dict) -> None:
735
+ """
736
+ Calculate zodiacal and exozodiacal light fluxes for the given observation.
737
+
738
+ This method computes the flux zero points, zodiacal light fluxes, and
739
+ exozodiacal light fluxes for the target stars based on the provided
740
+ observation parameters.
741
+
742
+ Parameters
743
+ ----------
744
+ parameters : dict
745
+ A dictionary containing simulation parameters including target star
746
+ parameters, planet parameters, and observational parameters.
747
+ Must include a "wavelength" key containing the wavelength array
748
+
749
+ Returns
750
+ -------
751
+ None
752
+
753
+ Raises
754
+ ------
755
+ AttributeError
756
+ If the scene has not been properly configured (missing required attributes)
757
+ KeyError
758
+ If parameters dictionary is missing required keys
759
+
760
+ """
761
+ # Validate that scene has been properly configured
762
+ required_attributes = ["vmag", "dist", "dec", "ra", "F0", "nzodis", "mag"]
763
+ missing_attrs = [
764
+ attr for attr in required_attributes if not hasattr(self, attr)
765
+ ]
766
+ if missing_attrs:
767
+ raise AttributeError(
768
+ f"AstrophysicalScene must be configured before calculating zodi/exozodi. "
769
+ f"Missing attributes: {', '.join(missing_attrs)}. "
770
+ f"Please call load_configuration() first."
771
+ )
772
+
773
+ # Validate parameters dictionary
774
+ if "wavelength" not in parameters:
775
+ raise KeyError("parameters dictionary must contain 'wavelength' key")
776
+
777
+ # calculate flux at zero point for the V band and the prescribed lambda
778
+
779
+ self.M_V = (
780
+ self.vmag - 5.0 * np.log10(self.dist.value) * MAGNITUDE + 5.0 * MAGNITUDE
781
+ ) # calculate absolute V band mag of target
782
+
783
+ self.Fzodi_list = calc_zodi_flux(
784
+ self.dec, self.ra, parameters["wavelength"] * WAVELENGTH, self.F0
785
+ ) # [nlambda]
786
+
787
+ self.Fexozodi_list = calc_exozodi_flux(
788
+ self.M_V,
789
+ self.vmag,
790
+ self.nzodis,
791
+ parameters["wavelength"] * WAVELENGTH,
792
+ self.mag,
793
+ ) # [nlambda]
794
+
795
+ self.Fbinary_list = (
796
+ np.full((len(parameters["wavelength"])), 0.0) * DIMENSIONLESS
797
+ ) # this code ignores stray light from binaries # [nlambda]
798
+
799
+ def validate_configuration(self):
800
+ """
801
+ Check that mandatory variables are there and have the right format.
802
+ There can be other variables, but they are not needed for the calculation.
803
+ """
804
+ expected_args = {
805
+ "dist": DISTANCE,
806
+ # "vmag": MAGNITUDE,
807
+ # "mag": MAGNITUDE,
808
+ "stellar_angular_diameter_arcsec": ARCSEC,
809
+ "nzodis": ZODI,
810
+ "ra": DEG,
811
+ "dec": DEG,
812
+ "separation": ARCSEC,
813
+ "xp": ARCSEC,
814
+ "yp": ARCSEC,
815
+ # "deltamag": MAGNITUDE,
816
+ # "min_deltamag": MAGNITUDE,
817
+ "F0V": PHOTON_FLUX_DENSITY,
818
+ "F0": PHOTON_FLUX_DENSITY,
819
+ # "M_V": MAGNITUDE,
820
+ "Fzodi_list": INV_SQUARE_ARCSEC,
821
+ "Fexozodi_list": INV_SQUARE_ARCSEC,
822
+ "Fbinary_list": DIMENSIONLESS,
823
+ "Fp_over_Fs": DIMENSIONLESS,
824
+ "Fs_over_F0": DIMENSIONLESS,
825
+ "ez_PPF": DIMENSIONLESS,
826
+ }
827
+ utils.validate_attributes(self, expected_args)
828
+
829
+ def regrid_spectra(self, parameters, observation):
830
+ """function to re-grid onto a new wavelength grid if the user specified this option"""
831
+ # spectra to regrid: F0, Fzodi_list, Fexozodi_list, Fbinary_list, Fp_over_Fs, Fs_over_F0
832
+ logger.info("Re-gridding spectra onto ETC wavelength grid...")
833
+ self.F0 = utils.regrid_spec_gaussconv(
834
+ parameters["wavelength"],
835
+ self.F0,
836
+ observation.wavelength.value,
837
+ observation.delta_wavelength.value,
838
+ )
839
+ self.Fzodi_list = utils.regrid_spec_gaussconv(
840
+ parameters["wavelength"],
841
+ self.Fzodi_list,
842
+ observation.wavelength.value,
843
+ observation.delta_wavelength.value,
844
+ )
845
+ self.Fexozodi_list = utils.regrid_spec_gaussconv(
846
+ parameters["wavelength"],
847
+ self.Fexozodi_list,
848
+ observation.wavelength.value,
849
+ observation.delta_wavelength.value,
850
+ )
851
+ self.Fbinary_list = utils.regrid_spec_gaussconv(
852
+ parameters["wavelength"],
853
+ self.Fbinary_list,
854
+ observation.wavelength.value,
855
+ observation.delta_wavelength.value,
856
+ )
857
+ self.Fp_over_Fs = utils.regrid_spec_gaussconv(
858
+ parameters["wavelength"],
859
+ self.Fp_over_Fs,
860
+ observation.wavelength.value,
861
+ observation.delta_wavelength.value,
862
+ )
863
+ self.Fs_over_F0 = utils.regrid_spec_gaussconv(
864
+ parameters["wavelength"],
865
+ self.Fs_over_F0,
866
+ observation.wavelength.value,
867
+ observation.delta_wavelength.value,
868
+ )
869
+ self.ez_PPF = utils.regrid_spec_gaussconv(
870
+ parameters["wavelength"],
871
+ self.ez_PPF,
872
+ observation.wavelength.value,
873
+ observation.delta_wavelength.value,
874
+ )