Skip to content

Commit

Permalink
PR change requests by lukas.
Browse files Browse the repository at this point in the history
  • Loading branch information
kenfus committed Nov 17, 2023
1 parent 8aaf707 commit 6f46f51
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 88 deletions.
59 changes: 38 additions & 21 deletions karabo/examples/ImageMosaicker.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"source": [
"from karabo.imaging.image import Image\n",
"\n",
"\n",
"# Render plots inline\n",
"%matplotlib inline"
]
Expand All @@ -42,16 +41,34 @@
{
"cell_type": "code",
"execution_count": 2,
"id": "39b35a84",
"metadata": {},
"outputs": [],
"source": [
"restored = Image.read_from_file(\"data/restored.fits\")"
"# Load example fits\n",
"from karabo.data.external_data import (\n",
" SingleFileDownloadObject,\n",
" cscs_karabo_public_base_url,\n",
")\n",
"\n",
"example_fits = SingleFileDownloadObject(\n",
" remote_file_path=\"restored_filtered_example_gleam.fits\",\n",
" remote_base_url=cscs_karabo_public_base_url,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "39b35a84",
"metadata": {},
"outputs": [],
"source": [
"restored = Image.read_from_file(example_fits.get())"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "13458a73",
"metadata": {},
"outputs": [
Expand Down Expand Up @@ -79,7 +96,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 5,
"id": "72758c5b",
"metadata": {},
"outputs": [],
Expand All @@ -90,7 +107,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"outputs": [
{
Expand All @@ -99,7 +116,7 @@
"4"
]
},
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -110,7 +127,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 7,
"metadata": {},
"outputs": [
{
Expand All @@ -130,7 +147,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 8,
"metadata": {},
"outputs": [
{
Expand All @@ -150,7 +167,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"outputs": [
{
Expand All @@ -170,7 +187,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 10,
"metadata": {},
"outputs": [
{
Expand Down Expand Up @@ -198,7 +215,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 11,
"id": "e1c94edb",
"metadata": {},
"outputs": [],
Expand All @@ -208,7 +225,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 12,
"id": "d48ea5a4",
"metadata": {},
"outputs": [],
Expand All @@ -219,7 +236,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 13,
"metadata": {},
"outputs": [
{
Expand All @@ -240,7 +257,7 @@
},
{
"cell_type": "code",
"execution_count": 20,
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -250,7 +267,7 @@
},
{
"cell_type": "code",
"execution_count": 31,
"execution_count": 15,
"metadata": {},
"outputs": [
{
Expand All @@ -259,7 +276,7 @@
"Text(0.5, 1.0, 'Image footprint')"
]
},
"execution_count": 31,
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
},
Expand Down Expand Up @@ -293,7 +310,7 @@
},
{
"cell_type": "code",
"execution_count": 32,
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -303,7 +320,7 @@
},
{
"cell_type": "code",
"execution_count": 33,
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -313,7 +330,7 @@
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 18,
"metadata": {},
"outputs": [
{
Expand All @@ -334,7 +351,7 @@
},
{
"cell_type": "code",
"execution_count": 35,
"execution_count": 19,
"metadata": {},
"outputs": [
{
Expand All @@ -343,7 +360,7 @@
"Text(0.5, 1.0, 'Image footprint')"
]
},
"execution_count": 35,
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
},
Expand Down
102 changes: 46 additions & 56 deletions karabo/imaging/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,34 +28,21 @@

matplotlib.use(previous_backend)

# Parameters to copy from the original header to the cutout header
HEADER_KEYS_TO_COPY_AFTER_CUTOUT = [
"CTYPE3",
"CRPIX3",
"CDELT3",
"CRVAL3",
"CUNIT3",
"CTYPE4",
"CRPIX4",
"CDELT4",
"CRVAL4",
"CUNIT4",
"BMAJ",
"BMIN",
"BPA",
]


class Image(KaraboResource):
def __init__(
self,
path: Optional[Union[str, FilePathType]] = None,
data: Optional[np.ndarray[np.float_]] = None, # type: ignore
data: Optional[NDArray[np.float_]] = None,
header: Optional[fits.header.Header] = None,
**kwargs: Any,
) -> None:
self._fh_prefix = "image"
self._fh_verbose = False

if path is not None and (data is not None or header is not None):
raise RuntimeError("Provide either path or both data and header.")

Check warning on line 44 in karabo/imaging/image.py

View check run for this annotation

Codecov / codecov/patch

karabo/imaging/image.py#L44

Added line #L44 was not covered by tests

if path is not None:
self.path = path
self.data, self.header = fits.getdata(
Expand All @@ -77,10 +64,10 @@ def __init__(
restored_fits_path = os.path.join(fh.subdir, "image.fits")

# Write the FITS file
self.write_to_file(restored_fits_path, overwrite=True)
self.write_to_file(restored_fits_path)
self.path = restored_fits_path
else:
raise ValueError("Either path or both data and header must be provided.")
raise RuntimeError("Provide either path or both data and header.")

Check warning on line 70 in karabo/imaging/image.py

View check run for this annotation

Codecov / codecov/patch

karabo/imaging/image.py#L70

Added line #L70 was not covered by tests

self._fname = os.path.split(self.path)[-1]

Expand All @@ -105,9 +92,8 @@ def write_to_file(
) -> None:
"""Write an `Image` to `path` as .fits"""
check_ending(path=path, ending=".fits")
dir_name = os.path.dirname(path)
if dir_name != "" and not os.path.exists(dir_name):
os.makedirs(dir_name)
dir_name = os.path.abspath(os.path.dirname(path))
os.makedirs(dir_name, exist_ok=True)
fits.writeto(
filename=str(path),
data=self.data,
Expand Down Expand Up @@ -198,8 +184,24 @@ def cutout(
def update_header_from_image_header(
new_header: fits.header.Header,
old_header: fits.header.Header,
keys_to_copy: List[str] = HEADER_KEYS_TO_COPY_AFTER_CUTOUT,
keys_to_copy: Optional[List[str]] = None,
) -> fits.header.Header:
if keys_to_copy is None:
keys_to_copy = [
"CTYPE3",
"CRPIX3",
"CDELT3",
"CRVAL3",
"CUNIT3",
"CTYPE4",
"CRPIX4",
"CDELT4",
"CRVAL4",
"CUNIT4",
"BMAJ",
"BMIN",
"BPA",
]
for key in keys_to_copy:
if key in old_header and key not in new_header:
new_header[key] = old_header[key]
Expand All @@ -220,7 +222,8 @@ def split_image(self, N: int, overlap: int = 0) -> List[Image]:
overlap : int, optional
The number of pixels by which adjacent image sections will overlap.
Default is 0, meaning no overlap.
Default is 0, meaning no overlap. Negative overlap means that there
will be empty sections between the cutouts.
Returns
-------
Expand Down Expand Up @@ -251,6 +254,8 @@ def split_image(self, N: int, overlap: int = 0) -> List[Image]:
>>> len(cutouts)
16 # because 4x4 grid
"""
if N < 1:
raise ValueError("N must be >= 1")

Check warning on line 258 in karabo/imaging/image.py

View check run for this annotation

Codecov / codecov/patch

karabo/imaging/image.py#L258

Added line #L258 was not covered by tests
_, _, x_size, y_size = self.data.shape
x_step = x_size // N
y_step = y_size // N
Expand Down Expand Up @@ -504,22 +509,29 @@ class ImageMosaicker:
A class to handle the combination of multiple images into a single mosaicked image.
See: https://reproject.readthedocs.io/en/stable/mosaicking.html
Attributes
Parameters
More information on the parameters can be found in the documentation:
https://reproject.readthedocs.io/en/stable/api/reproject.mosaicking.reproject_and_coadd.html # noqa: E501
However, here the most common to tune are explained.
----------
reproject_function : callable
reproject_function : callable, optional
The function to use for the reprojection.
combine_function : {'mean', 'sum', 'median', 'first', 'last', 'min', 'max'}
The type of function to use for combining the values into the final image.
match_background : bool
match_background : bool, optional
Whether to match the backgrounds of the images.
background_reference : None or int
The index of the reference image for background matching.
background_reference : None or int, optional
If None, the background matching will make it so that the average of the
corrections for all images is zero.
If an integer, this specifies the index of the image to use as a reference.
hdu_in : int or str, optional
Specifies the HDU to use from the input FITS files or HDUList.
If one or more items in input_data is a FITS file or an HDUList instance,
specifies the HDU to use.
hdu_weights : int or str, optional
Specifies the HDU to use from the input weights FITS files or HDUList.
kwargs : dict
Additional keyword arguments to pass to the reprojection function.
If one or more items in input_weights is a FITS file or an HDUList instance,
specifies the HDU to use.
**kwargs : dict, optional
Additional keyword arguments to be passed to the reprojection function.
Methods
-------
Expand All @@ -541,28 +553,6 @@ def __init__(
hdu_weights: Optional[Union[int, str]] = None,
**kwargs: Any,
):
"""
Parameters
----------
reproject_function : callable, optional
The function to use for the reprojection.
combine_function : {'mean', 'sum', 'median', 'first', 'last', 'min', 'max'}
The type of function to use for combining the values into the final image.
match_background : bool, optional
Whether to match the backgrounds of the images.
background_reference : None or int, optional
If None, the background matching will make it so that the average of the
corrections for all images is zero.
If an integer, this specifies the index of the image to use as a reference.
hdu_in : int or str, optional
If one or more items in input_data is a FITS file or an HDUList instance,
specifies the HDU to use.
hdu_weights : int or str, optional
If one or more items in input_weights is a FITS file or an HDUList instance,
specifies the HDU to use.
**kwargs : dict, optional
Additional keyword arguments to be passed to the reprojection function.
"""
self.reproject_function = reproject_function
self.combine_function = combine_function
self.match_background = match_background
Expand Down
Binary file removed karabo/test/data/restored.fits
Binary file not shown.
Loading

0 comments on commit 6f46f51

Please sign in to comment.