GONetFile Module
This module defines the GONetFile
class, which provides functionality for
handling and processing GONet files. The class encapsulates the properties
and methods required for manipulating the image data (including red, green,
and blue channels) and metadata associated with GONet files.
The module supports various operations on GONet files, including:
Loading image data from original raw (.jpg) or TIFF formats.
Performing arithmetic operations between GONet files and scalar values.
Writing image data to common formats like JPEG, TIFF, and FITS.
Parsing and handling metadata for different file types.
For more info regarding how the raw data is parsed, see GONet Raw Data Format.
The GONetFile
class also includes support for operator overloading, allowing
users to easily perform element-wise operations between GONet files or between
a GONet file and scalar values.
In order to ensure that all arithmetic operations on the image channels are safe and reliable, we cast the red, green, and blue channel arrays to float64 upon initialization. The original pixel data is typically stored as uint12 or uint16, which are prone to overflow or precision loss during common operations like addition, subtraction, or division. By promoting the arrays to float64, we avoid these issues and enable robust numerical processing — particularly important for calibration, normalization, or stacked image analysis. This casting ensures consistency and protects users from subtle bugs that can arise from working with fixed-width integer types.
Functions
cast()
: Convert a value to a JSON-serializable type if necessary.
Classes
FileType
: Enumeration of file types used in GONet observations.GONetFile
: A class representing a GONet file.
Example usage
gonet_file = GONetFile.from_file('example_image.tiff')
plt.imshow(gonet_file.green)
Functions:
- GONet_Wizard.GONet_utils.src.gonetfile.scale_uint12_to_16bit_range(x)[source]
Linearly scales unsigned 12-bit integer values to the full 16-bit range [0, 65535].
This function maps values from the uint12 range [0, 4095] to the float range [0, 65535], preserving relative magnitudes without rounding or type conversion to integer.
- Parameters:
x (array-like or int) – Input value(s) in the uint12 range [0, 4095]. Can be a scalar or NumPy array.
- Returns:
Scaled value(s) in the float range [0.0, 65535.0]. Output dtype is float64.
- Return type:
np.ndarray or float
- Raises:
ValueError – If any input values are outside the valid uint12 range.
Classes:
- class GONet_Wizard.GONet_utils.src.gonetfile.FileType(value)[source]
Bases:
Enum
Enumeration of file types used in GONet observations.
This enum defines the standard types of data that a GONet file may represent, used for categorizing the file during processing or analysis.
- class GONet_Wizard.GONet_utils.src.gonetfile.GONetFile(filename, red, green, blue, meta, filetype)[source]
Bases:
object
A class representing a GONet file.
This class provides methods for loading, interpreting, and processing GONet image data along with its associated metadata. It supports operations such as reading binary formats, extracting image channels, and converting pixel data into structured arrays.
- RAW_FILE_OFFSET
Offset in bytes to the beginning of the raw data in the file (default: 18711040).
- Type:
- RAW_HEADER_SIZE
Size in bytes of the file header preceding the image data (default: 32768).
- Type:
- RAW_DATA_OFFSET
Offset in bytes to the raw image data, computed as
RAW_FILE_OFFSET
-RAW_HEADER_SIZE
.- Type:
- RELATIVETOEND
Flag used to indicate seeking relative to the end of the file (default: 2).
- Type:
- PADDED_LINE_BYTES
Number of bytes used to store a single image row, including padding (default: 6112).
- Type:
- USED_LINE_BYTES
Number of bytes used to store a single image row, based on 12-bit pixel encoding (default: int(
PIXEL_PER_LINE
* 12 / 8)).- Type:
- CHANNELS
Names of the RGB channels available in the GONet image (default: [‘red’, ‘green’, ‘blue’]).
- __init__(filename, red, green, blue, meta, filetype)[source]
Initialize a
GONetFile
instance with image data and metadata.This constructor sets up the internal state of a GONet file, including its RGB channel data, metadata, and file type classification.
- Parameters:
filename (
str
) – Path or name of the GONet file.red (
numpy.ndarray
) – Pixel data for the red channel. Will be cast to float64.green (
numpy.ndarray
) – Pixel data for the green channel. Will be cast to float64.blue (
numpy.ndarray
) – Pixel data for the blue channel. Will be cast to float64.meta (
dict
orNone
) – Dictionary of extracted metadata, or None if no metadata is available.filetype (
FileType
) – Type of GONet file (e.g.,FileType.SCIENCE
).
- Raises:
TypeError – If input types are incorrect.
ValueError – If image arrays are not 2D.
- property red: ndarray
Get the red channel data from the GONet file.
- Returns:
A 2D array of pixel values corresponding to the red channel.
- Return type:
- property green: ndarray
Get the green channel data from the GONet file.
- Returns:
A 2D array of pixel values corresponding to the green channel.
- Return type:
- property blue: ndarray
Get the blue channel data from the GONet file.
- Returns:
A 2D array of pixel values corresponding to the blue channel.
- Return type:
- property meta: dict
Get the metadata associated with the GONet file.
- Returns:
Dictionary containing metadata fields extracted from the file header or sidecar.
- Return type:
- channel(channel_name)[source]
Retrieve the pixel data for a specified color channel.
This method returns the image data associated with the specified color channel as a
numpy.ndarray
.- Parameters:
channel_name (
str
) – The name of the channel to retrieve. Must be one of'red'
,'green'
, or'blue'
.- Returns:
The pixel data corresponding to the requested color channel.
- Return type:
- Raises:
ValueError – If an invalid channel name is provided.
- write_to_jpeg(output_filename, white_balance=True)[source]
Write the RGB image data to a JPEG file.
This method assumes that the red, green, and blue channels are in the uint16 range [0, 65535], and rescales them to the standard 8-bit range [0, 255] required for JPEG output. Values outside this range are clipped, and the data is converted to 8-bit for JPEG compatibility.
If
white_balance
is True, the method applies red and blue channel gains fromself.meta['WB']
prior to conversion, in order to produce a more natural-looking image. The white balance is expected to be a list or tuple of two floats: [R_gain, B_gain].- Parameters:
- Raises:
ValueError – If
white_balance
is True but the WB metadata is missing or invalid.- Return type:
- write_to_tiff(output_filename, white_balance=True)[source]
Write the RGB image data to a TIFF file.
This method assumes that the red, green, and blue channels are in the uint16 range [0, 65535]. Values outside this range are clipped, and the data is cast to uint16 for TIFF compatibility.
If
white_balance
is True, the method applies red and blue channel gains fromself.meta['JPEG']['WB']
prior to writing, in order to produce a more natural-looking image. The white balance is expected to be a list or tuple of two floats: [R_gain, B_gain].- Parameters:
- Raises:
ValueError – If
white_balance
is True but the WB metadata is missing or invalid.- Return type:
- write_to_fits(output_filename)[source]
Write the image data to a multi-extension FITS file.
This method saves the red, green, and blue channel data into separate HDUs (Header/Data Units) within a single FITS file. The metadata stored in the
meta
attribute is propagated into the FITS headers, adhering to the standard FITS format.- Parameters:
output_filename (
str
) – The full path and filename where the FITS file will be written.- Returns:
This method does not return a value.
- Return type:
None
Notes
The FITS file is created using the
astropy.io.fits
library.Each color channel (red, green, blue) is stored in a separate image extension.
Metadata keys longer than 8 characters or containing lowercase letters or symbols
will be truncated or sanitized to conform to FITS header requirements.
- classmethod from_file(filepath, filetype=FileType.SCIENCE, meta=True)[source]
Create a
GONetFile
instance from a TIFF or JPEG file.This class method reads a GONet image file, extracts the red, green, and blue channel data, and optionally parses the associated metadata. It returns a fully initialized
GONetFile
object.- Parameters:
filepath (
str
orpathlib.Path
) – Full path to the image file. The file must be in .tif, .tiff, or .jpg format.filetype (
FileType
, optional) – Type of the file, chosen from theFileType
enumeration. Defaults toFileType.SCIENCE
.meta (
bool
, optional) – If True (default), metadata will be extracted and included. If False, metadata will be skipped.
- Returns:
A new instance initialized with the file’s pixel data and metadata.
- Return type:
- Raises:
FileNotFoundError – If the specified file does not exist.
ValueError – If the file extension is unsupported (must be .tif, .tiff, .jpg).
Notes
Metadata extraction is supported only for .jpg files. TIFF files are read for image data only.
- static _parse_tiff_file(filepath)[source]
Parse a TIFF file and extract RGB channel data and optional metadata.
This static method reads a TIFF file and separates the image into red, green, and blue channels.
- Parameters:
filepath (
str
) – Path to the TIFF file to be parsed.- Returns:
A NumPy array of shape
(3, H, W)
representing the red, green, and blue channels.- Return type:
:class:
numpy.ndarray
- Raises:
FileNotFoundError – If the file does not exist or is not accessible.
ValueError – If the TIFF file does not contain 3 channels.
- static _parse_raw_file(filepath)[source]
Parse a raw GONet file and extract RGB channel data and optional metadata.
This static method reads a GONet raw file—typically with a .jpg extension but not in standard JPEG format—and extracts the red, green, and blue image channels.
- Parameters:
filepath (
str
) – Path to the raw file to be parsed.- Returns:
A NumPy array of shape
(3, H, W)
representing the red, green, and blue channels.- Return type:
:class:
numpy.ndarray
- Raises:
FileNotFoundError – If the file does not exist or is not accessible.
ValueError – If the file format is incompatible or corrupted.
- static _parse_exif_metadata(exif)[source]
Extract and restructure EXIF metadata from a JPEG file into a structured dictionary.
- _operate(other, op)[source]
Perform an element-wise operation on the current
GONetFile
instance.This internal method supports element-wise operations between the current GONetFile instance and either another GONetFile instance or a scalar value. The operation is applied independently to each color channel (red, green, and blue) using the provided binary operator.
- Parameters:
- Returns:
A new
GONetFile
instance with the operation applied to each channel. Ifother
is a GONetFile, the result has no metadata or file type. Ifother
is a scalar, metadata and file type are preserved.- Return type:
- Raises:
TypeError – If
other
is neither a GONetFile nor a scalar.ValueError – If the operation cannot be broadcast between the channels and
other
.
Notes
This method is primarily used internally to implement operators like __add__, __sub__, etc.
Metadata is only retained when operating with scalars.
- __add__(other)[source]
Add another object to this
GONetFile
instance.This method overloads the
+
operator to support element-wise addition between the currentGONetFile
and either anotherGONetFile
or a scalar value (e.g.,int
,float
). Addition is performed independently on the red, green, and blue channels usingnumpy.add()
.- Parameters:
other (
GONetFile
or scalar) – The operand to add. Can be anotherGONetFile
or a scalar value.- Returns:
A new instance resulting from the addition. If other is a
GONetFile
, the returned object has no metadata or file type.- Return type:
- Raises:
TypeError – If the operation is not supported between the operands.
ValueError – If the image shapes are incompatible.
- __radd__(other)
Add another object to this
GONetFile
instance.This method overloads the
+
operator to support element-wise addition between the currentGONetFile
and either anotherGONetFile
or a scalar value (e.g.,int
,float
). Addition is performed independently on the red, green, and blue channels usingnumpy.add()
.- Parameters:
other (
GONetFile
or scalar) – The operand to add. Can be anotherGONetFile
or a scalar value.- Returns:
A new instance resulting from the addition. If other is a
GONetFile
, the returned object has no metadata or file type.- Return type:
- Raises:
TypeError – If the operation is not supported between the operands.
ValueError – If the image shapes are incompatible.
- __iadd__(other)[source]
Perform in-place addition on this
GONetFile
instance.This method overloads the
+=
operator to support in-place element-wise addition of anotherGONetFile
or a scalar value (e.g.,int
,float
). Addition is performed independently on the red, green, and blue channels usingnumpy.add()
.- Parameters:
other (
GONetFile
or scalar) – The value to add in-place. Can be anotherGONetFile
or a scalar.- Returns:
The modified instance after in-place addition.
- Return type:
- Raises:
TypeError – If the operation is not supported between the operands.
ValueError – If the channel dimensions are incompatible for element-wise addition.
- __mul__(other)[source]
Perform element-wise multiplication using the
*
operator.This method multiplies the red, green, and blue channels of the current
GONetFile
instance with either anotherGONetFile
instance or a scalar (e.g.,int
,float
). The multiplication is performed element-wise usingnumpy.multiply()
.- Parameters:
other (
GONetFile
or scalar) – The object to multiply with. Can be anotherGONetFile
instance or a scalar value.- Returns:
A new
GONetFile
instance containing the result of the multiplication.- Return type:
- Raises:
TypeError – If the operation is not supported between the operands.
ValueError – If the channel dimensions are incompatible for element-wise multiplication.
- __rmul__(other)
Perform element-wise multiplication using the
*
operator.This method multiplies the red, green, and blue channels of the current
GONetFile
instance with either anotherGONetFile
instance or a scalar (e.g.,int
,float
). The multiplication is performed element-wise usingnumpy.multiply()
.- Parameters:
other (
GONetFile
or scalar) – The object to multiply with. Can be anotherGONetFile
instance or a scalar value.- Returns:
A new
GONetFile
instance containing the result of the multiplication.- Return type:
- Raises:
TypeError – If the operation is not supported between the operands.
ValueError – If the channel dimensions are incompatible for element-wise multiplication.
- __sub__(other)[source]
Perform element-wise subtraction using the
-
operator.This method subtracts either another
GONetFile
instance or a scalar (e.g.,int
,float
) from the currentGONetFile
instance. The operation is applied independently to the red, green, and blue channels usingnumpy.subtract()
.- Parameters:
other (
GONetFile
or scalar) – The object to subtract. Can be anotherGONetFile
instance or a scalar value.- Returns:
A new
GONetFile
instance containing the result of the subtraction.- Return type:
- Raises:
TypeError – If the operation is not supported between the operands.
ValueError – If the channel dimensions are incompatible for element-wise subtraction.
- __truediv__(other)[source]
Perform element-wise division using the
/
operator.This method divides the red, green, and blue channels of the current
GONetFile
instance by either anotherGONetFile
instance or a scalar (e.g.,int
,float
). The division is applied usingnumpy.true_divide()
.- Parameters:
other (
GONetFile
or scalar) – The object to divide by. Can be anotherGONetFile
instance or a scalar value.- Returns:
A new
GONetFile
instance containing the result of the division.- Return type:
- Raises:
ZeroDivisionError – If division by zero occurs (e.g., scalar is zero or zero elements in another GONetFile).
TypeError – If the operation is not supported between the operands.