Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove creation of stray fits file #1338

Merged
merged 1 commit into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 32 additions & 66 deletions romancal/lib/psf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,15 @@
"""

import logging
import os

import astropy.units as u
import numpy as np
import webbpsf
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.nddata import CCDData, bitmask
from astropy.nddata import bitmask
from astropy.table import Table
from photutils.background import LocalBackground
from photutils.detection import DAOStarFinder
from photutils.psf import (
GriddedPSFModel,
IterativePSFPhotometry,
PSFPhotometry,
SourceGrouper,
)
from photutils.psf import IterativePSFPhotometry, PSFPhotometry, SourceGrouper
from roman_datamodels.datamodels import ImageModel
from roman_datamodels.dqflags import pixel
from webbpsf import conf, gridded_library, restart_logging
Expand Down Expand Up @@ -60,13 +53,11 @@


def create_gridded_psf_model(
path_prefix,
filt,
detector,
oversample=11,
fov_pixels=9,
sqrt_n_psfs=2,
overwrite=False,
buffer_pixels=100,
instrument_options=None,
logging_level=None,
Expand All @@ -77,10 +68,6 @@

Parameters
----------
path_prefix : str or Path-like
Prefix to the output file path for the gridded PSF model
FITS file. A suffix denoting the detector name will
be appended.
filt : str
Filter name, starting with "F". For example: `"F184"`.
detector : str
Expand All @@ -95,8 +82,6 @@
sqrt_n_psfs : int, optional
Square root of the number of PSFs to calculate, distributed uniformly
across the detector. Default is 4.
overwrite : bool, optional
Overwrite output file if one already exists. Default is False.
buffer_pixels : int, optional
Calculate a grid of PSFs distributed uniformly across the detector
at least ``buffer_pixels`` away from the detector edges. Default is 100.
Expand Down Expand Up @@ -126,9 +111,6 @@
raise ValueError(f"`sqrt_n_psfs` must be an integer, got {sqrt_n_psfs}.")
n_psfs = int(sqrt_n_psfs) ** 2

# webbpsf appends "_sca??.fits" to the requested path:
expected_output_path = f"{path_prefix}_{detector.lower()}.fits"

# Choose pixel boundaries for the grid of PSFs:
start_pix = 0
stop_pix = 4096
Expand All @@ -144,54 +126,38 @@
# generate PSFs over a grid of detector positions [pix]
model_psf_centroids = [(int(x), int(y)) for y in pixel_range for x in pixel_range]

if not os.path.exists(expected_output_path) or overwrite:
if logging_level is None:
# pass along logging level from __name__'s logger to WebbPSF:
logging_level = logging.getLevelName(log.level)

# set the WebbPSF logging level (similar to webbpsf.utils.setup_logging):
conf.logging_level = logging_level
restart_logging(verbose=False)

wfi = webbpsf.roman.WFI()
wfi.filter = filt

if instrument_options is not None:
wfi.options.update(instrument_options)

# Initialize the PSF library
inst = gridded_library.CreatePSFLibrary(
instrument=wfi,
filter_name=filt,
detectors=detector.upper(),
num_psfs=n_psfs,
oversample=oversample,
fov_pixels=fov_pixels,
add_distortion=False,
crop_psf=False,
save=True,
filename=path_prefix,
overwrite=overwrite,
verbose=False,
)

inst.location_list = model_psf_centroids
if logging_level is None:
# pass along logging level from __name__'s logger to WebbPSF:
logging_level = logging.getLevelName(log.level)

Check warning on line 131 in romancal/lib/psf.py

View check run for this annotation

Codecov / codecov/patch

romancal/lib/psf.py#L131

Added line #L131 was not covered by tests

# set the WebbPSF logging level (similar to webbpsf.utils.setup_logging):
conf.logging_level = logging_level
restart_logging(verbose=False)

wfi = webbpsf.roman.WFI()
wfi.filter = filt

if instrument_options is not None:
wfi.options.update(instrument_options)

Check warning on line 141 in romancal/lib/psf.py

View check run for this annotation

Codecov / codecov/patch

romancal/lib/psf.py#L141

Added line #L141 was not covered by tests

# Initialize the PSF library
inst = gridded_library.CreatePSFLibrary(
instrument=wfi,
filter_name=filt,
detectors=detector.upper(),
num_psfs=n_psfs,
oversample=oversample,
fov_pixels=fov_pixels,
add_distortion=False,
crop_psf=False,
save=False,
verbose=False,
)

# Create the PSF grid:
gridmodel = inst.create_grid()
inst.location_list = model_psf_centroids

elif os.path.exists(expected_output_path):
logging.log(
logging.INFO,
f"Loading existing gridded PSF model from {expected_output_path}",
)
psf_model = CCDData.read(expected_output_path, unit=u.electron / u.s, ext=0)
psf_model.meta = dict(psf_model.meta)
psf_model.meta["oversampling"] = oversample
psf_model.meta["grid_xypos"] = np.array(
[list(tup)[::-1] for tup in model_psf_centroids]
)
gridmodel = GriddedPSFModel(psf_model)
# Create the PSF grid:
gridmodel = inst.create_grid()

return gridmodel, model_psf_centroids

Expand Down
8 changes: 0 additions & 8 deletions romancal/lib/tests/test_psf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
Unit tests for the Roman source detection step code
"""

import os
import tempfile
from copy import deepcopy

import numpy as np
Expand Down Expand Up @@ -64,18 +62,12 @@ def setup_inputs(
fov_pixels=15,
)

dir_path = tempfile.gettempdir()
filename_prefix = f"psf_model_{webbpsf_config['filt']}"
file_path = os.path.join(dir_path, filename_prefix)

# compute gridded PSF model:
psf_model, centroids = create_gridded_psf_model(
file_path,
webbpsf_config["filt"],
webbpsf_config["detector"],
oversample=webbpsf_config["oversample"],
fov_pixels=webbpsf_config["fov_pixels"],
overwrite=True,
logging_level="ERROR",
)

Expand Down
9 changes: 0 additions & 9 deletions romancal/source_catalog/source_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import logging
import warnings
from pathlib import Path
from typing import List

import astropy.units as u
Expand Down Expand Up @@ -1172,12 +1171,9 @@ def do_psf_photometry(self) -> None:
filt = self.model.meta.basic.optical_element
detector = "SCA02"
# prefix of the temporary FITS file that will contain the gridded PSF model
path_prefix = "tmp"
gridded_psf_model, _ = psf.create_gridded_psf_model(
path_prefix=path_prefix,
filt=filt,
detector=detector,
overwrite=True,
logging_level="ERROR",
)

Expand All @@ -1200,11 +1196,6 @@ def do_psf_photometry(self) -> None:
for old_name, new_name in old_name_to_new_name_mapping.items():
setattr(self, new_name, psf_photometry_table[old_name])

# remove temporary file containing gridded_psf_model
filepath = Path().cwd().glob(f"{path_prefix}*{detector.lower()}*.fits")
for filename in filepath:
filename.unlink(missing_ok=True)

@lazyproperty
def catalog(self):
"""
Expand Down
2 changes: 0 additions & 2 deletions romancal/source_detection/source_detection_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,8 @@ def process(self, input):
log.info("Constructing a gridded PSF model.")
detector = input_model.meta.instrument["detector"].replace("WFI", "SCA")
gridded_psf_model, _ = psf.create_gridded_psf_model(
path_prefix="tmp",
filt=filt,
detector=detector,
overwrite=True,
logging_level="ERROR",
)

Expand Down