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.

SCIENCE

Represents a science frame (standard observational data).

Type:

FileType

FLAT

Represents a flat field frame (used for pixel response correction).

Type:

FileType

BIAS

Represents a bias frame (used for sensor readout offset correction).

Type:

FileType

DARK

Represents a dark frame (used to correct for dark current noise).

Type:

FileType

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:

int

RAW_HEADER_SIZE

Size in bytes of the file header preceding the image data (default: 32768).

Type:

int

RAW_DATA_OFFSET

Offset in bytes to the raw image data, computed as RAW_FILE_OFFSET - RAW_HEADER_SIZE.

Type:

int

RELATIVETOEND

Flag used to indicate seeking relative to the end of the file (default: 2).

Type:

int

PIXEL_PER_LINE

Number of pixels per image row (default: 4056).

Type:

int

PIXEL_PER_COLUMN

Number of pixels per image column (default: 3040).

Type:

int

PADDED_LINE_BYTES

Number of bytes used to store a single image row, including padding (default: 6112).

Type:

int

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:

int

CHANNELS

Names of the RGB channels available in the GONet image (default: [‘red’, ‘green’, ‘blue’]).

Type:

list of str

__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 or None) – Dictionary of extracted metadata, or None if no metadata is available.

  • filetype (FileType) – Type of GONet file (e.g., FileType.SCIENCE).

Raises:
property filename: str

Get the filename of the GONet file.

Returns:

The name or path of the file associated with this GONetFile instance.

Return type:

str

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:

numpy.ndarray

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:

numpy.ndarray

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:

numpy.ndarray

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:

dict

property filetype: FileType

Get the file type of the GONet file.

Returns:

The type of the file, such as SCIENCE, FLAT, etc.

Return type:

FileType

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:

numpy.ndarray

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 from self.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:
  • output_filename (str) – Path where the resulting JPEG file will be saved.

  • white_balance (bool, optional) – Whether to apply white balance using gains from metadata (default is False).

Raises:

ValueError – If white_balance is True but the WB metadata is missing or invalid.

Return type:

None

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 from self.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:
  • output_filename (str) – Path where the resulting TIFF file will be saved.

  • white_balance (bool, optional) – Whether to apply white balance using gains from metadata (default is True).

Raises:

ValueError – If white_balance is True but the WB metadata is missing or invalid.

Return type:

None

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 or pathlib.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 the FileType enumeration. Defaults to FileType.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:

GONetFile

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:
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.

Parameters:

exif (dict) – A dictionary containing raw EXIF metadata extracted from the JPEG file.

Returns:

A structured metadata dictionary, with JPEG-related keys under ‘JPEG’.

Return type:

dict

_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:
  • other (GONetFile or scalar) – The operand for the operation. This can be another GONetFile instance or a scalar (e.g., int or float).

  • op (function) – A binary operator function (e.g., numpy.add(), numpy.multiply()) that performs the desired operation between corresponding pixel arrays.

Returns:

A new GONetFile instance with the operation applied to each channel. If other is a GONetFile, the result has no metadata or file type. If other is a scalar, metadata and file type are preserved.

Return type:

GONetFile

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 current GONetFile and either another GONetFile or a scalar value (e.g., int, float). Addition is performed independently on the red, green, and blue channels using numpy.add().

Parameters:

other (GONetFile or scalar) – The operand to add. Can be another GONetFile 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:

GONetFile

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 current GONetFile and either another GONetFile or a scalar value (e.g., int, float). Addition is performed independently on the red, green, and blue channels using numpy.add().

Parameters:

other (GONetFile or scalar) – The operand to add. Can be another GONetFile 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:

GONetFile

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 another GONetFile or a scalar value (e.g., int, float). Addition is performed independently on the red, green, and blue channels using numpy.add().

Parameters:

other (GONetFile or scalar) – The value to add in-place. Can be another GONetFile or a scalar.

Returns:

The modified instance after in-place addition.

Return type:

GONetFile

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 another GONetFile instance or a scalar (e.g., int, float). The multiplication is performed element-wise using numpy.multiply().

Parameters:

other (GONetFile or scalar) – The object to multiply with. Can be another GONetFile instance or a scalar value.

Returns:

A new GONetFile instance containing the result of the multiplication.

Return type:

GONetFile

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 another GONetFile instance or a scalar (e.g., int, float). The multiplication is performed element-wise using numpy.multiply().

Parameters:

other (GONetFile or scalar) – The object to multiply with. Can be another GONetFile instance or a scalar value.

Returns:

A new GONetFile instance containing the result of the multiplication.

Return type:

GONetFile

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 current GONetFile instance. The operation is applied independently to the red, green, and blue channels using numpy.subtract().

Parameters:

other (GONetFile or scalar) – The object to subtract. Can be another GONetFile instance or a scalar value.

Returns:

A new GONetFile instance containing the result of the subtraction.

Return type:

GONetFile

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 another GONetFile instance or a scalar (e.g., int, float). The division is applied using numpy.true_divide().

Parameters:

other (GONetFile or scalar) – The object to divide by. Can be another GONetFile instance or a scalar value.

Returns:

A new GONetFile instance containing the result of the division.

Return type:

GONetFile

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.

__getitem__(key)[source]

Slice the GONetFile spatially.

This allows spatial slicing of the pixel data (red, green, blue channels) using standard NumPy-style indexing. The result is a new GONetFile instance.

Parameters:

key (slice, int, or tuple) – Slice or index to apply, e.g., [:, 10:20].

Returns:

A new instance with sliced red, green, and blue arrays.

Return type:

GONetFile

Raises:

TypeError – If the key is invalid or cannot be applied.