Metadata-Version: 2.4
Name: seabass-utils
Version: 0.0.6
Summary: Collection of tools to work with SeaBASS files.
Author-email: "Michael A. Maniscalco" <michael.a.maniscalco@nasa.gov>, James Allen <james.g.allen-1@nasa.gov>, SeaBASS Team <seabass@seabass.gsfc.nasa.gov>, Inia Soto Ramos <inia.m.sotoramos@nasa.gov>, Joel Scott <joel.scott@nasa.gov>
License: NASA Goddard Space Flight Center (GSFC) Software distribution policy for Public Domain Software
        
        All software tools referenced code is in the public domain, available without fee for educational, research, non-commercial and commercial purposes. Users may distribute 
        this code to third parties provided that this statement appears on all copies and that no charge is made for such copies.
        
        NASA GSFC MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THE SOFTWARE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. NEITHER NASA GSFC NOR 
        THE U.S. GOVERNMENT SHALL BE LIABLE FOR  ANY DAMAGE SUFFERED BY THE USER OF THIS SOFTWARE.
        
        
Keywords: SeaBASS
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: numpy>=1.24
Requires-Dist: requests
Requires-Dist: pandas>=2.0
Requires-Dist: netCDF4>=1.6
Requires-Dist: earthaccess>=0.9
Requires-Dist: xarray>=2023.1.0
Provides-Extra: wrappers
Requires-Dist: pandas>=2.1.0; extra == "wrappers"
Requires-Dist: numpy<2.5,>=1.22; extra == "wrappers"
Provides-Extra: mapping
Requires-Dist: pandas>=2.1.0; extra == "mapping"
Requires-Dist: numpy<2.5,>=1.22; extra == "mapping"
Requires-Dist: matplotlib<3.11; extra == "mapping"
Requires-Dist: cartopy<0.25; extra == "mapping"
Requires-Dist: shapely; extra == "mapping"
Requires-Dist: geopandas; extra == "mapping"
Provides-Extra: sza
Requires-Dist: pandas>=2.1.0; extra == "sza"
Requires-Dist: numpy<2.5,>=1.22; extra == "sza"
Requires-Dist: pvlib; extra == "sza"
Requires-Dist: timezonefinder; extra == "sza"
Requires-Dist: pytz; extra == "sza"
Provides-Extra: histo
Requires-Dist: pandas>=2.1.0; extra == "histo"
Requires-Dist: numpy<2.5,>=1.22; extra == "histo"
Requires-Dist: timezonefinder; extra == "histo"
Requires-Dist: pytz; extra == "histo"
Requires-Dist: matplotlib<3.11; extra == "histo"
Requires-Dist: seaborn; extra == "histo"
Provides-Extra: matchups
Requires-Dist: numpy>=1.24; extra == "matchups"
Requires-Dist: requests; extra == "matchups"
Requires-Dist: pandas>=2.0; extra == "matchups"
Requires-Dist: netCDF4>=1.6; extra == "matchups"
Requires-Dist: earthaccess>=0.9; extra == "matchups"
Provides-Extra: all
Requires-Dist: pandas>=2.1.0; extra == "all"
Requires-Dist: beautifulsoup4; extra == "all"
Requires-Dist: earthaccess>=0.9; extra == "all"
Requires-Dist: requests; extra == "all"
Requires-Dist: shapely; extra == "all"
Requires-Dist: geopandas; extra == "all"
Requires-Dist: matplotlib<3.11; extra == "all"
Requires-Dist: timezonefinder; extra == "all"
Requires-Dist: pytz; extra == "all"
Requires-Dist: pvlib; extra == "all"
Requires-Dist: numpy<2.5,>=1.22; extra == "all"
Requires-Dist: cartopy<0.25; extra == "all"
Requires-Dist: seaborn; extra == "all"
Requires-Dist: xarray>=2023.1.0; extra == "all"

# seabass-utils.0.0.6

## Overview
`seabass-utils` is a collection of Python utilities developed to assist with SeaBASS data processing, file manipulation, and mapping tasks, originally developed at NASA Goddard Space Flight Center (GSFC).

## Included Modules

| Module                         | Description                                                                           |
| ------------------------------ | ------------------------------------------------------------------------------------- |
| `fd_matchup.py`                | Search the NASA EarthData for satellite overpass granules given lat/lon/datetime.     | 
| `mk_matchup.py`                | Creates satellite in situ matchup OB.DAAC L2 netCDF file and lat/lon/datetime.        |
| `sb_change_exts.py`            | Utility to modify file extensions and /data_file_name headers for SeaBASS text files. |
| `sb_get_files.py`              | Download SeaBASS files based on urls, filenames, partial strings.                     |
| `sb_histotime.py`              | Generates histogram-style local v UTC time summaries from SeaBASS data files.         |
| `sb_mapper.py`                 | Reads lat/lon/date/time data and creates color plots.                                 |
| `sb_read.py`                   | Read local SeaBASS files or stream direct from url into data matrices and metadata    |
| `sb_add_sza.py`                | Daylight and Solar Zenith Angle (SZA) filtering utilities for spatial-temporal data.  |
| `sb_translate_binary_flags.py` | Converts binary flags used in SeaBASS NOMAD files into human-readable format.         |
| `write_sb_lite.py`             | Writes SeaBASS-style files from pandas DataFrames. Input format for level2gen IOPmodel|

### Installation
* requires-python = ">=3.8","<=3.14.6"

`seabass-utils` supports a **minimal install** and optional "extras" that enable
the heavier tools. The minimal install includes only `sb_read`, `fd_matchup`, and `mk_matchup` (described above) and depend on the following: "numpy>=1.24", "requests", "pandas>=2.0", "netCDF4>=1.6", "earthaccess>=0.9".

#### Minimal install (`sb_read`, `fd_matchup`, and `mk_matchup` only)
```bash
pip install --extra-index-url https://oceandata.sci.gsfc.nasa.gov/fileshare/oceanpy/ seabass-utils 
```

and import as:
```python
from seabass_utils import sb_read

data = sb_read("myfile.sb")
```

#### Full install (all tools)

```
pip install --extra-index-url https://oceandata.sci.gsfc.nasa.gov/fileshare/oceanpy/ seabass-utils[all]
```
#### Targeted extras
Install only what a specific tool needs:

| Extra      | Enables                           | Example                              |
| ---------- | --------------------------------- | ------------------------------------ |
| `mapping`  | `sb_mapper` (map plots)           | `pip install seabass-utils[mapping]`  |
| `sza`      | `sb_add_sza` (solar zenith angle) | `pip install seabass-utils[sza]`      |
| `getfiles` | `sb_get_files` (downloads)        | `pip install seabass-utils[getfiles]` |
| `histo`    | `sb_histotime` (time histograms)  | `pip install seabass-utils[histo]`    |
| `wrappers` | `sb_wrappers` (DataFrame tools)   | `pip install seabass-utils[wrappers]` |

Extras can be combined:
```bash
pip install --extra-index-url https://oceandata.sci.gsfc.nasa.gov/fileshare/oceanpy/ seabass-utils[mapping,sza]
```

## Submodules

#### fd_matchup and mk_matchup

`fd_matchup` can be used to identify lat/lon/date-time where there are NASA OB.DAAC L2
overpass granules. The results of fd_matchup can help filter down lat/lon/date-time before
running the `mk_matchup` utility. From the commandline both programs accept SeaBASS files as input,
and also accept pandas dataframes as input when imported and run from Python/Jupyter. 

**OCSSW toolkit (required by `mk_matchup`)**
`mk_matchup` utilizes the OCSSW `val_extract` binary, so OCSSW must be
installed and its environment available. Full instructions:

<https://nasa.github.io/oceandata-notebooks/notebooks/oci/oci_ocssw_install.html>

**New OCSSW install:**

```bash
wget -q -nc https://oceandata.sci.gsfc.nasa.gov/manifest/install_ocssw
wget -q -nc https://oceandata.sci.gsfc.nasa.gov/manifest/manifest.py
chmod +x install_ocssw
export OCSSWROOT=${OCSSWROOT:-/tmp/ocssw}
export TAG="$(./install_ocssw --list_tags | grep '^V' | tail -n 1)"
./install_ocssw --tag=$TAG --seadas --oci
```

**Update an OCSSW existing install:**

```bash
export OCSSWROOT=${OCSSWROOT:-/tmp/ocssw}
export TAG="$(install_ocssw --list_tags | grep '^V' | tail -n 1)"
install_ocssw --tag=$TAG --seadas --oci
```

Before running `mk_matchup`, set `OCSSWROOT` to your install location. The tool
automatically sources `$OCSSWROOT/OCSSW_bash.env` at runtime.

> **Note:** OCSSW support requires a Unix-like environment (Linux/macOS) with
> `bash` available. Native Windows is not supported for `mk_matchup`.

**Usage**
* `fd_matchup` — find matching granules

**Command line:**

```bash
# Point + time
fd_matchup --sat modist --slat 23.0 --slon 170.0 \
    --stime 2015-11-16T09:00:00Z --max_time_diff 8

# Bounding box + time range
fd_matchup --sat modist \
    --stime 2015-11-15T09:00:00Z --etime 2015-11-17T09:00:00Z \
    --slat 23.0 --elat 25.0 --slon 170.0 --elon 175.0

# From a SeaBASS file (optionally download the granules)
fd_matchup --sat modist --seabass_file mysbfile.sb \
    --max_time_diff 4 --get_data /path/to/output
```

**From Python / Jupyter:**

```python
import fd_matchup as fd

# Point + time
granlinks = fd.search_matchup(
    sat="modist",
    slat=23.0,
    slon=170.0,
    stime="2015-11-16T09:00:00Z",
    max_time_diff=8,
)

# SeaBASS file (optionally download the data)
granlinks = fd.search_matchup(
    sat="modist",
    seabass_file="mysbfile.sb",
    max_time_diff=4,
    get_data="/path/to/output",  # omit to just list links
)
```

Supported satellites (`--sat`): `modisa`, `modist`, `viirsn`, `viirsj1`,
`viirsj2`, `goci`, `meris`, `czcs`, `octs`, `seawifs`, `oci`, `spexone`,
`harp2`, `hawkeye`, `hico`, `olcis3a`, `olcis3b`.

### `mk_matchup` — make match-ups

**Command line:**

```bash
mk_matchup \
    --sat_file /path/to/PACE_OCI.20250927T172454.L2.OC_AOP.V3_2.nc \
    --seabass_file /path/to/inputfile_L2_Rrs.sb
```

Optional flags: `--odir`, `--box_size` (odd int 3–11, default 5),
`--min_valid_sat_pix` (0–100, default 50.0), `--max_time_diff`
(0–36 hrs, default 3.0), `--max_coeff_variation` (0.0–1.0, default 0.15),
`--slat/--elat/--slon/--elon` (override file lat/lons), `--verbose`.

**From Python / Jupyter:**

```python
from mk_matchup import run_matchup

# SeaBASS-file mode
results = run_matchup(
    sat_file="/path/to/L2.nc",
    seabass_file="/path/to/input.sb",
)

# Granule-carrying DataFrame mode (granules downloaded via earthaccess)
results = run_matchup(
    dataframe=fd_results,  # DataFrame with a 'sat_granule' column
    dir_sat_files="nc_data",  # cache directory for downloaded granules
)
```

`run_matchup()` supports three input modes, selected automatically:

1. **SeaBASS-file mode** — pass `seabass_file` + `sat_file`.
2. **Plain DataFrame mode** — pass `dataframe` (with lat/lon + date/time) +
   `sat_file`.
3. **Granule-carrying DataFrame mode** — pass a `dataframe` containing a
   `sat_granule` column plus `dir_sat_files`; missing granules are downloaded
   via `earthaccess`.

**Exclusion criteria**

`mk_matchup` applies the exclusion criteria described in:

> S.W. Bailey and P.J. Werdell, "A multi-sensor approach for the on-orbit
> validation of ocean color satellite data products", Rem. Sens. Environ. 102,
> 12–23 (2006).

Notes:

- The coefficient of variation is computed using available Rrs (405–570 nm) and
  AOT (860–900 nm), excluding MODIS Rrs land bands at 469 nm and 555 nm.
- Rrs and AOT are only in the OC L2 suite; other file types (SST, IOP, etc.)
  skip the coefficient-of-variation test.
- For SST file types, use the `qual_sst_max`/`qual_sst_mean` fields to screen
  quality (0 = best, 4 = worst).

**Warnings:**

- This tool does **not** adjust in-situ data to water-leaving values.
- It does **not** account for potential oversampling in time or space.
- If successive calls are made for a single in-situ file with multiple valid
  overpasses, only the last call's data is saved to the output file — this may
  not be the best-quality match in space/time.

**Troubleshooting**

**`FileNotFoundError: 'val_extract'` or a MatchupError about OCSSW**
OCSSW is not installed or `OCSSWROOT` is unset/invalid. See the OCSSW section
above and set `OCSSWROOT`.

**`OSError: NetCDF: HDF error` when opening a satellite file**
Either the granule is corrupt/incompletely downloaded (re-download it), or an
OCSSW HDF5/NetCDF library is conflicting with your Python `netCDF4` build via
`LD_LIBRARY_PATH`. If the latter, scope OCSSW's environment to the `val_extract`
subprocess rather than merging it into the whole Python process.


#### sb_change_exts
**Purpose**
When preparing SeaBASS files for submission this can be run to change file extensions to `.sb` and add the correct filename to the `/data_file_name` header.

**Usage**
* This can be run from the commandline as follows with the script checking if it is given a path to a text file before then going to check if it was provided a directory path instead.
```bash
./sb_change_exts <YOUR_DIRECTORY_NAME>
./sb_change_exts <YOUR_FILE_NAME>

```

* When importing and running within python, the class `FileExtensionProcessor` is utilized along with 3 successive functions
  
```python
import os
from seabass_utils.sb_change_exts import FileExtensionProcessor
from pathlib import Path

# Set the directory containing your .sb files    
current_directory = "dirpath")
    
# debug =True or False - highly recommended to run with debug = True initially
debug = True

# initiate class
processor = FileExtensionProcessor(current_directory)
processor.collect_input_files()
processor.reduce_ext_and_check_collisions()
processor.process(debug)
```
**Additional details**
* If the file or directory exists, the following steps are performed on each file:
The first is check performed on the file list created from the user-supplied directory. If a single file is passed as an argument, the check will be performed on the single file. The function `reduce_ext_and_check_collisions` regexes against a known set of file extensions and recursively removes file extensions from the end of the file until either the file no longer has an extension or all extensions to the right of the non-matching extension are gone.  During the collision checking process, a list of new filenames are written to a logfile at the location `/tmp/change_ext_filenames.json`. This file can be viewed in the event of the script exiting with potential file name collisions, and will easily indicate where the collision will occur. The log file will be overwritten on each subsequent run - overwrite is performed as an auto-cleanup measure and because this logfile is not vital. An additional check is performed in to evaluate if file is utf-8 encoded and begins with the line `/begin_header`. If it is not, no further processing of the file occurs, and next file is loaded for reading. This step ensures any important non-data files in the submitted directory are preserved. The file is copied to `/tmp` directory to preserve the original in the source directory. After temp file creation is verified, the new file name is joined with the original path, the function `set_header_name` changes the header line `/data_file_name` within the file to match the filename, and a file ending in `.copy` is written to with the new data. After successful writing to the `.copy` file, the original `.copy` file overwrites the temp file. Note: header name change is always performed and matches it to filename. Temp file is moved from `/tmp` to original location in the function `replace_orig_file`. If original file ends in `.sb`, it is overwritten. If original file does not end in `.sb`, new file is placed in source directory and original file is deleted. Running in debug mode leaves the original files in the /tmp directory rather than removing it.

#### sb_get_files
**Purpose**
Downloads a list of SeaBASS files from an input text file or a filename
string. If URLs or base filenames without file hashes are given, the program looks
up the hashed filename from CMR. Some filenames may have duplicates in CMR
(uncommon), which can yield unwanted files. It handles both regular SeaBASS data files 
and .tgz.sb bundle files, extracting and organizing them for downstream use.  

**Command-line usage**
REQUIRED inputs, either 1) or 2):
    1) -l, --lis_file     ASCII text file containing a list of file URLs
    2) -s, --file_string  text string naming a SeaBASS file or bundle

Optional inputs:
    -g, --get_associated  retrieve associated archive tgz.sb bundles
    -o, --out_dir         output directory for downloaded/extracted files
    -t, --timeout         per-request timeout in seconds (default: 120)
    -r, --retries         retry attempts per CMR query (default: 6)

Example usage:
    sb_get_files --lis_file=mylist.txt
    sb_get_files --file_string=TaraEuropa_InLine_ACS3_2023..._v20250203.sb

**Python usage**
```python
from seabass_utils import sb_get_files

search_urls = [
    "https://oceandata.sci.gsfc.nasa.gov/getfile/c59661282d_ArcticCC_Norton_Sound_2022_ap_st01_Rep2_R1.sb",
    "https://oceandata.sci.gsfc.nasa.gov/getfile/c59661282d_ArcticCC_Norton_Sound_2022_ap_st01_Rep1_R1.sb",
]

sb_get_files(search_urls, get_associated=False)

# Use simplified alternative sb_download()
sb_download(search_urls, "test_data")
```
* All regular SeaBASS data files (.sb) are saved directly to out_dir
* The related documents bundles (tgz.sb) for all downloaded SeaBASS files are fetched

All downloaded .tgz.sb files are:
* Only downloaded once per call
* Renamed to .tgz and moved into out_dir/bundles/
* Extracted into directories named after the bundle
* Flattened to remove nested "associated" folders

#### sb_histotime
**Description**
Reads all SeaBASS (*.sb) files in a directory and compares the distribution of
sampling times in GMT and local time to help identify files whose times may not
be recorded in GMT.

For each observation:
- Assumes times are recorded in GMT.
- Rounds times to the nearest hour for visualization.
- Removes duplicate latitude/longitude/date/time records.
- Converts GMT to local time using the observation latitude, longitude, and date.

If latitude/longitude are not present in the data matrix, the script uses the
south_latitude and west_longitude header values. If date or time are not present
in the data matrix, end_date and end_time header values are used instead.

Produces a comparison plot of hourly sampling frequencies in GMT and local time.
The plot may be displayed, saved as `tz_check.png`, or both.

Input:
    Path to a directory containing SeaBASS (*.sb) files.

Options:
    -d, --display    Display the comparison plot.
    -o, --output     Save the plot to the specified output path/filename.
    -v, --verbose    Print detailed processing information.

Either `-d` or `-o` must be specified. Both may be used together.

Examples

Display the plot:
    sb_histotime -i ./ -d

Save the plot to a specific file:
    sb_histotime -i ./ -o /path/to/my_plot.png

Display and save the plot:
    sb_histotime -i ./ -d -o my_plot.png

Display with verbose output:
    sb_histotime -i ./ -d -v

```python
from sb_histotime import compare_gmt_local

gmt, local, fig = compare_gmt_local(my_df, verbose=True)
fig.savefig("out.png")
```
#### sb_mapper
**Description**
* Designed to plot the geographic locations of observations contained in one or more SeaBASS (.sb) files.
* Reads latitude and longitude coordinates directly from SeaBASS files, using matrix coordinates when available and header coordinates otherwise.
* Removes duplicate rows of date, time, lat, lon, station.
* Automatically determines an appropriate map extent or can display a global map.
* Observation locations are colored by sampling date, with a shared colorbar showing temporal progression.
* Can be used from the command line to map a SeaBASS file or directory of files, or imported into Python to plot one or two pandas DataFrames.
* The output map is saved as a high-resolution PNG file.

**Usage**
* `sb_mapper` usage from commandline:
| Argument       | Description                                                      |
| -------------- | ---------------------------------------------------------------- |
| `--input`      | **Required.** SeaBASS file or directory containing `.sb` files.  |
| `--recursive`  | Search all subdirectories for `.sb` files.                       |
| `--output`     | Output PNG filename. Default: `map.png`.                         |
| `--global-map` | Plot a global map instead of automatically zooming to the data.  |
| `--add-labels` | Label stations on the map when station information is available. |

```bash
# Map all SeaBASS files in the current directory:
sb_mapper --input .

# Recursively search all subdirectories:
sb_mapper --input . --recursive

# Create a global map and save to a custom filename:
sb_mapper --input . --global-map --output cruise_map.png

# Include station labels
sb_mapper --input . --global-map --output cruise_map.png --add_labels
```

**Importable functions: `sb_to_coord_df` and `plot_coords`**
* Read one or more SeaBASS files and returns a pandas DataFrame containing the observations with `sb_to_coord_df()`
| Argument     | Description                                                     |
| ------------ | --------------------------------------------------------------- |
| `input_path` | Path to a SeaBASS file or directory of SeaBASS files.           |
| `recursive`  | If `True`, recursively searches subdirectories for `.sb` files. |
Returns pandas DataFrame of unique rows of date, time, lat, lon, station from all SeaBASS files suitable for use with plot_coords()

```python
sb_to_coord_df(input_path, recursive=False)
```

* **`plot_coords()`**
```python
plot_coords(dataframe1, dataframe2=None, ...)
```
Plots one or two pandas DataFrames containing geographic coordinates.

**Required DataFrame columns**
* lat
* lon

**Optional columns**
* station (used for station labels)
* quality (non-zero values are plotted as flagged observations)
* date (yyyymmdd)
* time (hh:mm:ss)

**Arguments**
| Argument             | Description                                                                 |
| -------------------- | --------------------------------------------------------------------------- |
| `dataframe1`         | Primary DataFrame to plot.                                                  |
| `dataframe2`         | Optional second DataFrame for comparison.                                   |
| `title`              | Figure title.                                                               |
| `isGlobal`           | Plot a global map instead of an automatically fitted map.                   |
| `addLegend`          | Display the legend.                                                         |
| `save_name`          | Output filename. If `None`, the figure is not saved.                        |
| `labels`             | Legend labels for each DataFrame.                                           |
| `markers`            | Marker styles for each DataFrame.                                           |
| `sizes`              | Marker sizes for each DataFrame.                                            |
| `cmap`               | Matplotlib colormap used to color points by sampling date.                  |
| `add_station_labels` | Annotate stations on the map.                                               |
| `station_col`        | Name of the station column.                                                 |
| `start_margin`       | Initial map margin (degrees) when automatically determining the map extent. |
| `max_margin`         | Maximum margin allowed while searching for nearby land.                     |
| `step`               | Margin increment used during automatic extent calculation.                  |
| `fig_scale`          | Proportional scale factor for the whole figure. 1.0 =   10x10 inch          |

```
# Load functions to read and map SeaBASS files:
from seabass_utils.sb_mapper import sb_to_coord_df, plot_coords

df = sb_to_coord_df(".", recursive=True)

plot_coords(
    df,
    title="Station Locations",
    save_name="map.png",
)

# Plot existing pandas DataFrames:
from seabass_utils.sb_mapper import plot_coords
plot_coords(
    dataframe1,
    dataframe2,
    labels=("Dataset 1", "Dataset 2"),
    title="Comparison Map",
    save_name="comparison_map.png",
)
```

#### sb_read
**Description**
Read or stream an FCHECK-verified SeaBASS formatted data file.

Returned data structures:
.filename  = name of data file
.headers   = dictionary of header entry and value, keyed by header entry
.comments  = list of strings containing the comment lines from the header information
.missing   = fill value as a float used for missing data, read from header
.variables = dictionary of field name and unit, keyed by field name
.data      = dictionary of data values, keyed by field name, returned as a list
.length    = number of rows in the data matrix (i.e. the length of each list in data)
.bdl       = fill value as a float used for below detection limit, read from header (empty if missing or N/A)
.adl       = fill value as a float used for above detection limit, read from header (empty if missing or N/A)

Returned sub-functions:
.fd_datetime()                                  - Converts date and time information from the file's data matrix to a Python
                                                    list of datetime objects
.addDataToOutput(irow,var_name,units,var_value) - Adds or appends single data point to data matrix given row index, field name,
                                                    field units, and data value, handling fields & units headers and missing values
.writeSBfile(ofile)                             - Writes headers, comments, and data into a SeaBASS file specified by ofile

**Usage**
```python
from seabass_utils import sb_read

# Read a SeaBASS file
sb_data = sb_read.read_sb("example.sb")

# Access data as pandas DataFrame
new_df = pd.DataFrame(sb_data.data)
print(new_df.head())

# metadata headers related to datafile
data_loaded.headers
```

#### sb_add_sza
**Description**
* Daylight filtering utilities for spatial-temporal datasets using pvlib. Designed to parse UTC timestamps from date/time columns and filter out night-time observations using vectorized Solar Zenith Angle (SZA) calculations.

**Functions**
* `add_sza_col(dfp, date_col='date', time_col='time')`: Clean raw time strings (handling [GMT] tags and decimal seconds) and combine them into timezone-aware UTC datetimes.  
* `add_sza_col(dfp, datetime_col, lat_col='lat', lon_col='lon', sza_threshold=90.83, retain_all=False)`: Calculates the local SZA. Filters data below the threshold or simply appends an SZA_local column to the DataFrame.  

```python
import pandas as pd
from seabass-utils.sb_add_sza import parse_utc_timestamps, add_sza_col

# Parse raw timestamps first
df_parsed = parse_utc_timestamps(raw_df, date_col="date", time_col="time")

# Scenario A: Calculate SZA and retain all rows (annotates with 'SZA_local')
df_annotated = add_sza_col(df_parsed, datetime_col="utc_datetime", retain_all=True)

# Scenario B: Calculate SZA and strictly filter to daylight hours (SZA < 90.83)
df_daylight_only = add_sza_col(df_parsed, datetime_col="utc_datetime", retain_all=False)

# Scenario C: Filter to strict daylight/solar limits (e.g., SZA < 70)
df_strict = add_sza_col(
    df_parsed, datetime_col="utc_datetime", sza_threshold=70.0, retain_all=False
)
```

#### sb_translate_binary_flags

Designed to translate SeaBASS NOMAD file binary flags expressed as an integer (i.e., a mask) into their components, or vice versa.

In SeaBASS files, the column 'flags' or 'flag' contains integer values that describe the corresponding data.
Flags can describe simply an individual data point measurement, or a more complex numerical flag can describe an entire row of data in NOMAD (in which case the flags for multiple data points are combined).
An example flag for a data row could be 16577 . That integer is formed from the components:
   2^0 (AOP) + 2^6 (KD) + 2^7 (CAST) + 2^14 (ES),
Which suggests that a row of data (in NOMAD) consisted of water-leaving radiances (AOP), included Kd, was derived from a cast measurement, and surface-irradiance was measured

How to use this script:
This script will help users lookup the relationship between SeaBASS Validation "flags" (or flag) which are numerical bitwise numbers corresponding to specific flags that are true for a given data row or data point.

Some of the older NOMAD flags are no longer critical (i.e., #0-#6 were used for station info, rather than point-based information) and a few others might be rarely used going forward.

* Example command line usage:
```shell
python3 sb_translate_binary_flags.py --binary-flag 386
python3 sb_translate_binary_flags.py --components 'CHL,DISCRETE,CAST'
```

* Example python script usage:
```python
# Use specific functions
flag = sb_translate_binary_flags.translate_binary_flag_to_components(386)
print("flag to components   :")
print(flag)

flag = sb_translate_binary_flags.translate_components_to_binary_flag(["CHL", "CAST"])
print("component to flag   :")
print(flag)

# Call main programmatically
print("Run main   :")
sb_translate_binary_flags.main(["--components", "CHL,DISCRETE,CAST"])
```

#### write_sb_lite
* Description:
Writes pandas dataframe to seabass-lite style file to run in with General Inherent Optical Property (GIOP) in l2gen

* Parameters:
    df (pd.DataFrame): dataframe containing the data
    sensor (str): sensor name to include in the SeaBASS header (e.g., OCIS, etc.).
    filename (str): output file path

* Format:
The file format follows SeaBASS-lite conventions, including:
SeaBASS-style header enclosed between /begin_header and /end_header
/fields= line derived from DataFrame column names
Missing values (nan) converted to -9999 before writing output
Comma-delimited data matrix

* Example usage:
```python
import pandas as pd
from sb_handler import write_sb_lite

df = pd.DataFrame({"wavelength": [412, 443, 490], "Rrs": [0.0023, 0.0041, 0.0052]})

write_sb_lite(df, sensor="OCIS", filename="giop_input.sb")
```

## Dependencies

`seabass-utils` uses a layered dependency model so that the minimal install stays
lightweight while heavier tools can be added via extras (see the **Installation**
section for the corresponding `pip install seabass-utils[<extra>]` commands).

**Minimal install (`sb_read` only)**
`sb_read` relies only on the Python standard library (`re`, `collections`,
`datetime`, `copy`, `math`) plus:
- `requests` — used only when streaming SeaBASS files directly from a URL

**Optional extras**
The following packages are pulled in only by the relevant extra:
- `pandas>=2.1.0`
- `numpy<2.5,>=1.22`
- `geopandas`
- `matplotlib<3.11`
- `cartopy<0.25`
- `shapely`
- `timezonefinder`
- `pytz`
- `pvlib`
- `beautifulsoup4`
- `seaborn`

Install `seabass-utils[all]` to pull in every optional dependency at once.

## Software Usage Policy
NASA Goddard Space Flight Center (GSFC) Software distribution policy for Public Domain Software

All software tools referenced code is in the public domain, available without fee for educational, research, non-commercial and commercial purposes. Users may distribute 
this code to third parties provided that this statement appears on all copies and that no charge is made for such copies.

NASA GSFC MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THE SOFTWARE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. NEITHER NASA GSFC NOR 
THE U.S. GOVERNMENT SHALL BE LIABLE FOR  ANY DAMAGE SUFFERED BY THE USER OF THIS SOFTWARE.

* For issues or suggestions contact Michael A. Maniscalco NASA-OEL/ SSAI michael.a.maniscalco@nasa.gov and 
seabass@seabass.gsfc.nasa.gov
