ioos_qc package

IOOS QARTOD and other Quality Control tests implemented in Python.

Subpackages

Submodules

ioos_qc.argo module

Tests based on the ARGO QC manual.

ioos_qc.argo._pressure_flag_by_direction(inp, valid, flag_arr, pres_reversal, direction)[source]

Flagging logic for pressure_increasing_test based on direction.

Return type:

None

ioos_qc.argo.duplicate_timestamp_test(tinp)[source]

Flags duplicate timestamps in the provided array.

If duplicate timestamps are found, they are flagged as SUSPECT.

Parameters:

tinp (Sequence[Real]) – Time input data as a numeric numpy array or list of real numbers.

Returns:

A masked array of flag values equal in size to that of the input tinp.

Return type:

flag_arr

ioos_qc.argo.pressure_increasing_test(inp, direction='auto', pres_reversal=20)[source]

Checks for monotonic series of pressure values with user-defined reversal threshold.

This differs from qartod.pressure_test, as it keeps a running log of all previous pressure values and compares the min/max against it.

Flags that fail this test are returned as FAIL, otherwise they are returned as PASS. Data points that are missing for calculations are returned as MISSING.

‘For near-surface profiles, this test should be run from the deepest pressure to the shallowest pressure. For all other profiles, this test should be run from the middle of the profile to the shallowest pressure, and from the middle of the profile to the deepest pressure. The middle of the profile is the pressure at length(profile)/2’

See Wong et al. 2025 (Argo quality control manual v3.9):

http://dx.doi.org/10.13155/33951

Parameters:
  • inp (Sequence[Real]) – Sequence of real numbers for the input pressure array, in units of dbar.

  • direction (str) – String of AUV direction “up” or “down”. “up” indicates going from deep to shallow, or the upcast (optional). For old functionality, select “auto” to estimate the sign of the change in pressure. Defaults to “auto”.

  • pres_reversal (float) – Float of the user-defined pressure reversal threshold, in dbar (optional). Defaults to 20 dbar (see quality control manual above).

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

ioos_qc.argo.speed_test(lon, lat, tinp, suspect_threshold, fail_threshold)[source]

Checks that the calculated speed between two points is within reasonable bounds.

This test calculates a speed between subsequent points by
  • using latitude and longitude to calculate the distance between points

  • calculating the time difference between those points

  • checking if distance/time_diff exceeds the given threshold(s)

Missing and masked data is flagged as UNKNOWN.

If this test fails, it typically means that either a position or time is bad data, or that a platform is mislabeled.

Ref: ARGO QC Manual: 5. Impossible speed test

Parameters:
  • lon (Sequence[Real]) – Longitudes as a numeric numpy array or a list of numbers.

  • lat (Sequence[Real]) – Latitudes as a numeric numpy array or a list of numbers.

  • tinp (Sequence[Real]) – Time data as a sequence of datetime objects compatible with pandas DatetimeIndex. This includes numpy datetime64, python datetime objects and pandas Timestamp object. ie. pd.DatetimeIndex([datetime.utcnow(), np.datetime64(), pd.Timestamp.now()]) If anything else is passed in the format is assumed to be seconds since the unix epoch.

  • suspect_threshold (float) – A float value representing a speed, in meters per second. Speeds exceeding this will be flagged as SUSPECT.

  • fail_threshold (float) – A float value representing a speed, in meters per second. Speeds exceeding this will be flagged as FAIL.

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

ioos_qc.axds module

Tests based on the IOOS QARTOD manuals.

ioos_qc.axds.valid_range_test(inp, *, valid_span, dtype=None, start_inclusive=True, end_inclusive=False)[source]

Checks that values are within a min/max range. This is not unlike a qartod.gross_range_test with fail and suspect bounds being equal, except that here we specify the inclusive range that should pass instead of the exclusive bounds which should fail. This also supports datetime-like objects where as the qartod.gross_range_test method only supports numerics.

Given a 2-tuple of minimum/maximum values, flag data outside of the given range as FAIL data. Missing and masked data is flagged as UNKNOWN. The first span value is treated as inclusive and the second span valid is treated as exclusive. To change this behavior you can use the parameters start_inclusive and end_inclusive.

Parameters:
  • (Sequence[any]) (inp) – Data as a sequence of objects compatible with the fail_span objects

  • (Tuple[any (fail_span) – 2-tuple range which to flag outside data as FAIL. Objects should be of equal format to that of the inp parameter as they will be checked for equality without type conversion.

  • any]) – 2-tuple range which to flag outside data as FAIL. Objects should be of equal format to that of the inp parameter as they will be checked for equality without type conversion.

  • (np.dtype) (dtype) – Optional. If your data is not already numpy-typed you can specify its dtype here.

  • (bool) (end_inclusive) – Optional. If the starting span value should be inclusive (True) or exclusive (False).

  • (bool) – Optional. If the ending span value should be inclusive (True) or exclusive (False).

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

np.ma.core.MaskedArray

ioos_qc.config module

QC Config objects.

Module to store the different QC modules in ioos_qc

ioos_qc.config.tw(namedtuple)

The TimeWindow namedtuple definition

class ioos_qc.config.Call(stream_id, call, context=<factory>, attrs=<factory>)[source]

Bases: object

property args: tuple
attrs: dict
call: partial
config()[source]
Return type:

dict

context: Context
property func: str
property is_aggregate: bool
property kwargs: dict
property method: str
property method_path: str
property module: str
property region
run(**passedkwargs)[source]
stream_id: str
property window
class ioos_qc.config.Config(source, default_stream_key='_stream')[source]

Bases: object

A class to load any ioos_qc configuration setup into a list of callable objects that will run quality checks. The resulting list of quality checks parsed from a config file can be appended and edited until they are ready to be run. On run the checks are consolidated into an efficient structure for indexing the dataset (stream) it is run against so things like subsetting by time and space only happen once for each test in the same Context.

How the individual checks are collected is up to each individual Stream implementation, this class only pairs various formats and versions of a config into a list of Call objects.

add(source)[source]

Adds a source of calls to this Config. See extract_calls for information on the types of objects accepted as the source parameter. The changes the internal .calls attribute and returns None.

Parameters:

([any]) (source) –

The source of Call objects, this can be a:
  • Call object

  • list of Call objects

  • list of objects with the ‘calls’ attribute

  • Config object

  • Object with the ‘calls’ attribute

Return type:

None

property aggregate_calls
property calls
calls_by_stream_id(stream_id)[source]
Return type:

list[Call]

property contexts

Group the calls into context groups and return them.

has(stream_id, method)[source]
property stream_ids

Return a list of unique stream_ids for the Config.

class ioos_qc.config.Context(window=<factory>, region=None, attrs=<factory>)[source]

Bases: object

attrs: dict
region: GeometryCollection = None
window: TimeWindow
class ioos_qc.config.ContextConfig(source)[source]

Bases: object

A collection of a Region, a TimeWindow and a list of Config objects.

Defines a set of quality checks to run against multiple input streams. This can include a region and a time window to subset any DataStreams by before running checks.

region: None
window:
    starting: 2020-01-01T00:00:00Z
    ending: 2020-04-01T00:00:00Z
streams:
    variable1:    # stream_id
        qartod:   # Config
            location_test:
                bbox: [-80, 40, -70, 60]
    variable2:    # stream_id
        qartod:   # Config
            gross_range_test:
                suspect_span: [1, 11]
                fail_span: [0, 12]
Helper methods exist to run this check against a different inputs:
  • pandas.DataFrame, dask.DataFrame, netCDF4.Dataset, xarray.Dataset, ERDDAP URL

config(OrderedDict)

dict representation of the parsed ContextConfig source

region(GeometryCollection)

A shapely object representing the valid geographic region

window(namedtuple)

A TimeWindow object representing the valid time period

streams(OrderedDict)

dict representation of the parsed Config objects

add(source)[source]

Adds a source of calls to this ContextConfig. See extract_calls for information on the types of objects accepted as the source parameter. The changes the internal .calls attribute and returns None.

Parameters:

([any]) (source) –

The source of Call objects, this can be a:
  • Call object

  • list of Call objects

  • list of objects with the ‘calls’ attribute

  • Config object

  • Object with the ‘calls’ attribute

Return type:

None

property calls
context

Calls This parses through available checks and selects the actual test functions to run, but doesn’t actually run anything. It just sets up the object to be run later by iterating over the configs.

class ioos_qc.config.NcQcConfig(*args, **kwargs)[source]

Bases: Config

class ioos_qc.config.QcConfig(source, default_stream_key='_stream')[source]

Bases: Config

run(**passedkwargs)[source]
ioos_qc.config.extract_calls(source)[source]

Extracts call objects from a source object.

Parameters:

([any]) (source) –

The source of Call objects, this can be a:
  • Call object

  • list of Call objects

  • list of objects with the ‘calls’ attribute

  • NewConfig object

  • Object with the ‘calls’ attribute

Returns:

List of extracted Call objects

Return type:

List[Call]

ioos_qc.config.tw

alias of TimeWindow

ioos_qc.gliders module

Deprecated module. Consider using ARGO instead.

ioos_qc.gliders.pressure_check(inp)[source]

ioos_qc.plotting module

ioos_qc.plotting.bokeh_multi_plot(stream, results, title, **kwargs)[source]
ioos_qc.plotting.bokeh_multi_var(stream, results, title)[source]
ioos_qc.plotting.bokeh_plot(data, var_name, results, title, module, test_name)[source]
ioos_qc.plotting.bokeh_plot_collected_result(cr)[source]
ioos_qc.plotting.bokeh_plot_collected_results(results, **kwargs)[source]
ioos_qc.plotting.bokeh_plot_var(time, data, results, title, module, test_name)[source]

Method to plot QC results using Bokeh.

ioos_qc.qartod module

Tests based on the IOOS QARTOD manuals.

class ioos_qc.qartod.ClimatologyConfig(members=None)[source]

Bases: object

Legacy config object for the climatology test.

Parameters:
  • tspan – 2-tuple range. If period is defined, then this is a numeric range. If period is not defined, then its a date range.

  • fspan – (optional) 2-tuple range of valid values. This is passed in as the fail_span to the gross_range_test.

  • vspan – 2-tuple range of valid values. This is passed in as the suspect_span to the gross_range test.

  • zspan – (optional) Vertical (depth) range, in meters positive down

  • period –

    (optional) The unit the tspan argument is in. Defaults to datetime object but can also be any attribute supported by a pandas Timestamp object.

    See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.html

    Options:
    • year

    • week / weekofyear

    • day_of_year

    • day_of_week

    • quarter

add(tspan, vspan, fspan=None, zspan=None, period=None)[source]
Return type:

None

check(tinp, inp, zinp)[source]
static convert(config)[source]
mem

alias of window

property members
values(tind, zind=None)[source]
Parameters:

tind (Timestamp) – Value to test for inclusion between time bounds

ioos_qc.qartod.FLAGS

alias of QartodFlags

class ioos_qc.qartod.QartodFlags[source]

Bases: object

Primary flags for QARTOD.

FAIL = 4
GOOD = 1
MISSING = 9
SUSPECT = 3
UNKNOWN = 2
ioos_qc.qartod.aggregate(results)[source]

Runs qartod_compare against all other qartod tests in results.

Return type:

MaskedArray

ioos_qc.qartod.attenuated_signal_test(inp, tinp, suspect_threshold, fail_threshold, test_period=None, min_obs=None, min_period=None, check_type='std')[source]

Check for near-flat-line conditions using a range or standard deviation.

Missing and masked data is flagged as UNKNOWN.

Parameters:
  • inp (Sequence[Real]) – Input data as a numeric numpy array or a list of numbers.

  • tinp (Sequence[Real]) – Time input data as a numpy array of dtype datetime64.

  • suspect_threshold (Real) – Any calculated value below this amount will be flagged as SUSPECT. In observations units.

  • fail_threshold (Real) – Any calculated values below this amount will be flagged as FAIL. In observations units.

  • test_period (Real | None) – Length of time to test over in seconds [optional]. Otherwise, will test against entire inp.

  • min_obs (Real | None) – Minimum number of observations in window required to calculate a result [optional]. Otherwise, test will start at beginning of time series. Note: you can specify either min_obs or min_period, but not both.

  • min_period (int | None) – Minimum number of seconds in test_period required to calculate a result [optional]. Otherwise, test will start at beginning of time series. Note: you can specify either min_obs or min_period, but not both.

  • check_type (str) – Either ‘std’ (default) or ‘range’, depending on the type of check you wish to perform.

Returns:

A masked array of flag values equal in size to that of the input. This array will always contain only a single unique value since all input data is flagged together.

Return type:

flag_arr

ioos_qc.qartod.check_span(arr)[source]

Check that a span has 2 values and return it sorted as a Span(minv, maxv).

Return type:

Span

ioos_qc.qartod.climatology_config(config)[source]

Validate and normalise a climatology configuration.

Each entry (“window”) of the config is a dict with the keys below. The returned list has the same shape, with every span sorted into a Span(minv, maxv) namedtuple and missing optional keys set to None.

Note: If the user specifies a legacy ClimatologyConfig object, it will also be accepted.

Parameters:

config (Sequence[dict]) –

A sequence of dicts, one per climatology window:
  • tspan - 2-tuple time range (inclusive). Dates if period is

    not given, otherwise numbers in units of period.

  • vspan - 2-tuple range of valid values. Outside is SUSPECT.

  • fspan - (optional) 2-tuple range. Outside is FAIL. Must contain vspan.

  • zspan - (optional) 2-tuple depth range (inclusive), meters positive down.

  • period - (optional) Any pandas.DatetimeIndex attribute:

    month, quarter, day_of_year, day_of_week, year, or week/weekofyear (ISO week).

Returns:

A list of validated window dicts.

Return type:

windows

ioos_qc.qartod.climatology_test(config, inp, tinp, zinp=None)[source]

Checks that values fall within seasonal (and optionally depth-dependent) ranges.

Each window of the config selects the points that fall within its tspan (and zspan, if given) and runs the gross_range_test on them, using vspan as the suspect span and fspan (if given) as the fail span. Windows are applied in order, so a point covered by more than one window keeps the flag from the last one.

Parameters:
  • config (Sequence[dict]) – A sequence of dicts, one per climatology window. See climatology_config for the accepted keys.

  • inp (Sequence[Real]) – Input data as a numeric numpy array or a list of numbers.

  • tinp (Sequence[Real]) – Time data as a sequence of datetime objects compatible with pandas DatetimeIndex. This includes numpy datetime64, python datetime objects and pandas Timestamp object. If anything else is passed in the format is assumed to be seconds since the unix epoch.

  • zinp (Sequence[Real] | None) – (optional) Z (depth) data, in meters positive down, as a numeric numpy array or a list of numbers. Windows with a zspan only flag points with a valid depth.

Returns:

A masked array of flag values equal in size to that of the input (GOOD, UNKNOWN, SUSPECT, FAIL, MISSING).

Return type:

flag_arr

Examples

Define your config for temporal and (optionally) depth ranges. In this example: The winter and spring months for the first 100 m.

>>> config = [
...     {"tspan": (1, 3), "period": "month", "vspan": (10, 13), "zspan": (0, 100)},
...     {"tspan": (4, 6), "period": "month", "vspan": (11, 14), "fspan": (5, 20), "zspan": (0, 100)},
... ]
>>> tinp = ["2024-02-01", "2024-02-01", "2024-05-01", "2024-05-01", "2024-08-01", "2024-02-01"]
>>> climatology_test(
...     config,
...     inp=[12, 14, 12, 25, 12, np.nan],
...     tinp=np.array(tinp, dtype="datetime64[ns]"),
...     zinp=[5, 5, 5, 5, 5, 5],
... )
masked_array(data=[1, 3, 1, 4, 2, 9],
             mask=False,
       fill_value=np.uint64(999999),
            dtype=uint8)
ioos_qc.qartod.data_reception_test(tinp, fail_span=6, from_time=None)[source]

Checks for data timestamps to be within a certain amount of time of present.

For most use cases, this test is intended for data centers or streams.

Timestamps that are further away in time from the from_time variable than that designated by fail_span are flagged as FAIL. Data points that are newer than from_time are not considered for this test and are passed through as GOOD. Any missing and masked data is flagged as UNKNOWN.

Parameters:
  • tinp (Sequence[Real]) – Time input data as a numeric numpy array or list of real numbers.

  • fail_span (Real) – A numeric value in hours which, if data is older than, is flagged as FAIL.

  • from_time (Real | None) – A timestamp which, if defined, is used to anchor measurements against. Defaults to current date and time. [optional]

Returns:

A masked array of flag values equal in size to that of the input tinp.

Return type:

flag_arr

ioos_qc.qartod.density_inversion_test(inp, zinp, suspect_threshold=None, fail_threshold=None)[source]

With few exceptions, potential water density will increase with increasing pressure. When vertical profile data is obtained, this test is used to flag as failed T, C, and SP observations, which yield densities that do not sufficiently increase with pressure. A small operator-selected density threshold (DT) allows for micro-turbulent exceptions. This test can be run on downcasts, upcasts, or down/up cast results produced in real time.

Both Temperature and Salinity should be flagged based on the result of this test.

Ref: Manual for Real-Time Quality Control of in-situ Temperature and Salinity Data, Version 2.0, January 2016

Parameters:
  • inp (Sequence[Real]) – Potential density values as a numeric numpy array or a list of numbers.

  • zinp (Sequence[Real]) – Corresponding depth/pressure values for each density.

  • suspect_threshold (float | None) – A float value representing a maximum potential density(or sigma0) variation to be tolerated, downward density variation exceeding this will be flagged as SUSPECT.

  • fail_threshold (float | None) – A float value representing a maximum potential density(or sigma0) variation to be tolerated, downward density variation exceeding this will be flagged as FAIL.

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

Example

Because this test does not know if the first or second point exceeds is responsible when a change in density is triggered, it flags both points surrounding said change in density. The same goes for NaN values.

>>> pressure = [0,    5,     10,   15,    20,     25,   20,    15,   10,   5,     0   ]
>>> sigma0 =   [14.5, 14.52, 15.1, 15.15, np.nan, 15.7, 15.65, 15.0, 16.1, 15.12, 14.5]
>>> flags = qartod.density_inversion_test(sigma0, pressure, suspect_threshold=0.03, fail_threshold=0.01)
>>> flags
masked_array(data=[3, 3, 1, 1, 9, 9, 1, 4, 4, 1, 1],
         mask=False,
   fill_value=999999)

Flags are applied in the order PASS, SUSPECT, FAIL, and MISSING. Due to multiple flags being written, it is possible for flags to be overwritten (1 –> 3 –> 4).

>>> sigma0 =   [14.5, 14.52, 15.1, 15.15, np.nan, 15.7, 15.65, 15.0, 16.1, 16.08, 14.5]
>>> flags = qartod.density_inversion_test(sigma0, pressure, suspect_threshold=0.03, fail_threshold=0.01)
>>> flags
masked_array(data=[3, 3, 1, 1, 9, 9, 1, 4, 4, 3, 1],
         mask=False,
   fill_value=999999)
ioos_qc.qartod.flat_line_test(inp, tinp, suspect_threshold, fail_threshold, tolerance=0)[source]

Check for consecutively repeated values within a tolerance. Missing and masked data is flagged as UNKNOWN. More information: https://github.com/ioos/ioos_qc/pull/11.

Parameters:
  • inp (Sequence[Real]) – Input data as a numeric numpy array or a list of numbers.

  • tinp (Sequence[Real]) – Time data as a sequence of datetime objects compatible with pandas DatetimeIndex. This includes numpy datetime64, python datetime objects and pandas Timestamp object. ie. pd.DatetimeIndex([datetime.utcnow(), np.datetime64(), pd.Timestamp.now()]) If anything else is passed in the format is assumed to be seconds since the unix epoch.

  • suspect_threshold (int) – The number of seconds within tolerance to allow before being flagged as SUSPECT.

  • fail_threshold (int) – The number of seconds within tolerance to allow before being flagged as FAIL.

  • tolerance (Real) – The tolerance that should be exceeded between consecutive values. To determine if the current point n should be flagged, we use a rolling window, with endpoint at point n, and calculate the range of values in the window. If that range is less than tolerance, then the point is flagged.

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

ioos_qc.qartod.gross_range_test(inp, fail_span, suspect_span=None)[source]

Checks that values are within reasonable range bounds.

Given a 2-tuple of minimum/maximum values, flag data outside of the given range as FAIL data. Optionally also flag data which falls outside of a user defined range as SUSPECT. Missing and masked data is flagged as MISSING.

Parameters:
  • inp (Sequence[Real]) – Input data as a numeric numpy array or a list of numbers.

  • fail_span (tuple[Real, Real]) – 2-tuple range which to flag outside data as FAIL.

  • suspect_span (tuple[Real, Real] | None) – 2-tuple range which to flag outside data as SUSPECT. [optional]

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

Examples

Note that any input inp should be a sequence of numerical values that can be converted to numpy.

>>> flags = gross_range_test(inp=[1, 2, 3, 4, 8], fail_span=(0, 5), suspect_span=(1, 4))
>>> flags
masked_array(data=[1, 1, 1, 1, 4],
            mask=False,
    fill_value=np.uint64(999999),
            dtype=uint8)
ioos_qc.qartod.impossible_date_test(tinp, fail_span=None)[source]

Confirms that the date and time for the data are reasonable.

Given an array of time data, this test breaks the data down into a series of sub-tests. These tests are similar to those outlined in test 1.2 of the GTSPP RTQC Manual (IOC, 2010). * The year is either present or in the past. * (Optional) The time data is within a user-defined tolerance. Data deemed to have failed any or all of these tests are flagged as FAIL. Any missing and masked data is flagged as UNKNOWN.

Parameters:
  • tinp (Sequence[Real]) – Time input data as a numeric numpy array or list of real numbers.

  • fail_span (tuple[Real, Real] | None) – 2-tuple range which to flag outside data as FAIL. [optional]

Returns:

A masked array of flag values equal in size to that of the input tinp.

Return type:

flag_arr

ioos_qc.qartod.location_bounds_test(lon, lat, shape, flag_area='outside')[source]

Checks the locations against a defined shape.

Given vectors of longitude and latitude of equal size, this test will flag inside (flag_area = “inside”) or outside (flag_area = “outside”) of a designated area (shape).

Items found to violate this rule are flagged as FAIL. If NaNs are found in either the longitude or latitude, the point is flagged as MISSING. Otherwise, the point is flagged as PASS.

Points that fall exactly on a shape’s border are considered “outside” the shape, unless flag_area is set to “inside”.

Parameters:
  • lon (Sequence[Real]) – Longitudes as a numeric numpy array or list of numbers.

  • lat (Sequence[Real]) – Latitudes as a numperic numpy array or list of numbers.

  • shape (Polygon | Sequence[tuple[Real, Real]]) – A shapely.Polygon object or sequence of tuples defining the geographic bounds for flagging. These shapes are constructed using (lon, lat) pairs.

  • flag_area (str) – Instructions for flagging the “inside” or “outside” of the shape, as a string. Defaults to “outside”.

Returns:

A masked array of flag values.

Return type:

flag_arr

Example

When flagging outside of a designated area, where the first and last point are outside:

>>> shape = Polygon(((-78.696116, 24.562267),(-77.844899, 23.543749),(-77.506013, 24.707798)))
>>> lat = np.array([25.169938,  24.316908,  24.316908,])
>>> lon = np.array([-78.680106, -78.151764, -77.167128,])
>>> flags = location_bounds_test(lon=lon, lat=lat, shape=shape, flag_area="outside")
>>> flags
masked_array(data=[4, 1, 4],
         mask=False,
   fill_value=np.uint64(999999),
        dtype=uint8)

Flagging inside the designated area can be done by changing flag_area to ‘inside’.

>>> flags = location_bounds_test(lon=lon, lat=lat, shape=shape, flag_area="inside")
>>> flags
masked_array(data=[1, 4, 1],
         mask=False,
   fill_value=np.uint64(999999),
        dtype=uint8)
ioos_qc.qartod.location_on_land_test(lon, lat)[source]

Checks that the location is not on land.

Checks that the coordinates given in latitude and longitude are not on land using the University of Hawaii GSHHG database.

https://www.soest.hawaii.edu/pwessel/gshhg/

Coordinates identified to be on land are flagged as FAIL. Otherwise, flags are returned as PASS.

Parameters:
  • lon (Sequence[Real]) – Longitudes as a numeric numpy array or list of numbers.

  • lat (Sequence[Real]) – Latitudes as a numperic numpy array or list of numbers.

Returns:

A masked array of flag values.

Return type:

flag_arr

Example

Given 5 points, where indexes 0 and 3 are on land:

>>> lat = np.array([61.4, 0, 38.045286,  38.244164,  29.282811])
>>> lon = np.array([87.4, 0, 141.287681, 140.838304, -94.779981])
>>> flags = location_on_land_test(lon=lon, lat=lat)
>>> flags
masked_array(data=[4, 1, 1, 4, 1],
             mask=[False, False, False, False, False],
       fill_value=np.uint64(999999),
            dtype=uint8)
ioos_qc.qartod.location_test(lon, lat, range_max=None, range_method='haversine')[source]

Checks that a location is within reasonable bounds.

Checks that longitude and latitude are within reasonable bounds of lon = [-180, 180] and lat = [-90, 90]. Points outside of these bounds are flagged as FAIL.

Optionally, check for a maximum range parameter in great circle distance (meters) between points. If this amount is exceeded, data are flagged as SUSPECT. If this range is specified, it defaults to the ‘haversine’ algorithm for quick distance estimates.

Missing data are flagged as MISSING. All other points are flagged as PASS.

Note that this test returns flags based on both latitude and longitude but does not flag the individual streams.

To check flags within a designated area, see the location_bounds_test. To check for locations on land, see the location_on_land_test.

Parameters:
  • lon (Sequence[Real]) – Longitudes as a numeric numpy array or list of numbers.

  • lat (Sequence[Real]) – Latitudes as a numperic numpy array or list of numbers.

  • range_max (Real | None) – The maximum allowed distance between points as expressed in meters [optional].

  • range_method (str) – Algorithm ‘haversine’ or ‘wgs84` for calculating distance between points. Defaults to haversine for speed. Choose wgs84 for higher accuracy [optional].

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

ioos_qc.qartod.percentile_range_test(inp, low_percentile=5, hi_percentile=95, pad=0.0)[source]

Checks for statistically abnormal values in the array.

Given an array of numeric values, this test identifies abnormal high and low values at statistical percentiles. These default to the 5th and 95th percentiles for the data if not user-defined. In addition, the user may specify a padding value for additional coverage.

If the point’s (value < low_percentile_value - pad) or (high_percentile value + pad < value) then the point is flagged as SUSPECT. Points within the data which are NaN are flagged as MISSING. Otherwise, points are flagged as PASS.

Parameters:
  • inp (Sequence[Real]) – Input array as a numeric numpy array or list of real numbers.

  • low_percentile (Real) – A user-defined low-percentile numeric bound, defaults to 5 (optional).

  • hi_percentile (Real) – A user-defined high-percentile numeric bound, defaults to 95 (optional).

  • pad (Real) – A user-defined, numeric padding value for adding atop the hi/low percentile values. Defaults to 0 (optional).

Returns:

A masked array of flag values equal in size to that of the input inp.

Return type:

flag_arr

Examples

Say we have some values that we are expecting to be clusered around a specific range and we want to flag potential outliers that exceed the largest values in the data array including a little wiggle room.

>>> data = np.array([4.1, 4.0, 4.3, 4.5, 6.1, 6.2])
>>> flags = percentile_range_test(data)
>>> flags
masked_array(data=[1, 3, 1, 1, 1, 3],
         mask=False,
   fill_value=np.uint64(999999),
        dtype=uint8)

This has flagged the statistically lowest and highest value as SUSPECT with no padding specified.

ioos_qc.qartod.pressure_test(inp, direction, pad=0.01, *, assess_floating=False, breakout=0.025)[source]

Checks for for continuous monotonic sequences in the provided data.

Intended for use on the pressure array, inp. The input array is differentiated and values that do not increase or decrease (specified in direction) by at least the tolerance value pad are flagged as SUSPECT. Any NaNs found in the input are flagged MISSING. Otherwise, values in the array are flagged as PASS.

If the input is relatively unchanging (i.e., neutral buoyancy, at rest), these values should fall within the user-designated pad parameter. An optional test can be performed by setting assess_floating to True, which uses breakout as the designated ‘breakout’ requirement.

Input arrays should be for a single PROFILE_NUMBER, be it the “downglide” or “upglide” (see the OG1.0 methodology documentation for more information: https://oceangliderscommunity.github.io/OG-format-user-manual/OG_Format.html)

Parameters:
  • inp (Sequence[Real]) – Data vector to be flagged, as an array-like sequence of real numbers.

  • direction (str) – String that declares which direction the glider is going. Options of “down” (pressure increasing), “up” (pressure decreasing)

  • pad (float) – Float of “unmoving allowance”. If inp changes by more than pad, it is considered moving and flagging changes. Defaults to 0.01.

  • assess_floating (bool) – Bool, specifying whether to run an additional flagging routine (optional) Defaults to False.

  • breakout (float) – Float representing the required change in the inp variable to break the assess_floating routine (optional). Defaults to 0.025.

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

Examples

>>> arr = np.array([1, 1.009, 1.02, 2, np.nan, 2.001, 7, 0, 2])
>>> print(np.diff(arr))
[ 0.009  0.011  0.98     nan    nan  4.999 -7.     2.   ]

When using the default pressure test settings (pad=0.1, float test is off) we expect points to be flagged if they are not exceeding a pres. tolerance. >>> flags = pressure_test(arr, “down”) >>> print(flags) [3 3 1 1 9 1 1 3 1]

Meanwhile, a more strict padding will flag more points >>> flags = pressure_test(arr, “down”, pad=0.1) >>> print(flags) [3 3 3 1 9 1 1 3 1]

To look for a purely monotonic sequence, where pressure is simply increasing/decreasing, remove the padding altogether by setting it to 0. >>> flags = pressure_test(arr, “down”, pad=0.0) >>> print(flags) [1 1 1 1 9 1 1 3 1]

An extra (optional) test can be performed to detect periods where the array is floating or unchanging with a second, stricter tolerance. As per the first example: >>> flags = pressure_test(arr, “down”, assess_floating=True) >>> print(flags) [3 3 3 1 9 1 1 3 1]

ioos_qc.qartod.qartod_compare(vectors)[source]

Aggregates an array of flags by precedence into a single array.

Parameters:

vectors (Sequence[Sequence[Real]]) – An array of uniform length arrays representing individual flags

Returns:

A masked array of aggregated flag data.

Return type:

flag_arr

ioos_qc.qartod.rate_of_change_test(inp, tinp, threshold, fail_threshold=None)[source]

Checks the first order difference of a series of values to see if there are any values exceeding a threshold defined by the inputs. These are then marked as SUSPECT. It is up to the test operator to determine an appropriate threshold value for the absolute difference not to exceed. Threshold is expressed as a rate in observations units per second. There is an optional fail_threshold parameter that can be set by the user. If the first order difference of a series of values exceeds this higher threshold, the data point is marked as FAIL. Missing and masked data is flagged as UNKNOWN.

Parameters:
  • inp (Sequence[Real]) – Input data as a numeric numpy array or a list of numbers.

  • tinp (Sequence[Real]) – Time data as a sequence of datetime objects compatible with pandas DatetimeIndex. This includes numpy datetime64, python datetime objects and pandas Timestamp object. ie. pd.DatetimeIndex([datetime.utcnow(), np.datetime64(), pd.Timestamp.now()]) If anything else is passed in the format is assumed to be seconds since the unix epoch.

  • threshold (float) – A float value representing a rate of change over time, in observation units per second. Rates exceeding this will be flagged as SUSPECT.

  • fail_threshold (float | None) – A float value representing a rate of change over time, in observation units per second. Rates exceeding this will be flagged as FAIL.

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

ioos_qc.qartod.span

alias of Span

ioos_qc.qartod.spike_test(inp, suspect_threshold=None, fail_threshold=None, method='average')[source]

Check for spikes by checking neighboring data against thresholds.

Determine if there is a spike at data point n-1 by subtracting the midpoint of n and n-2 and taking the absolute value of this quantity, and checking if it exceeds a low or high threshold (default). Values which do not exceed either threshold are flagged GOOD, values which exceed the low threshold are flagged SUSPECT, and values which exceed the high threshold are flagged FAIL. Missing and masked data is flagged as UNKNOWN.

Parameters:
  • inp (Sequence[Real]) – Input data as a numeric numpy array or a list of numbers.

  • suspect_threshold (Real | None) – The SUSPECT threshold value, in observations units.

  • fail_threshold (Real | None) – The FAIL threshold value, in observations units.

  • method (str) –

    [‘average’(default),’differential’] optional input to assign the method used to detect spikes.
    • ”average”: Determine if there is a spike at data point n-1 by subtracting

      the midpoint of n and n-2 and taking the absolute value of this quantity, and checking if it exceeds a low or high threshold.

    • ”differential”: Determine if there is a spike at data point n by calculating the difference

      between n and n-1 and n+1 and n variation. To considered, (n - n-1)*(n+1 - n) should be smaller than zero (in opposite direction).

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

ioos_qc.qartod.syntax_test(inp, nchar, lentype='char', delimiter=None)[source]

Checks for raw data formatting and flags if data are the incorrect length.

For an array of raw data (either a single line or rows of messages), it loops through the number of lines and assigns a flag GOOD (1) if nchar equals the specified length of length type lentype or flag FAIL (4) if not equal. If a delimiter string is specified, it instead uses the number of items present in line.

Parameters:
  • inp (Sequence[str]) – Raw data sequence to be counted. Must have a shape attribute.

  • nchar (Real) – Designated tolerance or number of characters expected for testing.

  • lentype (str) – A string designating either “char” or “byte” to clarify unit for counting. Defaults to “char”.

  • delimiter (str | None) – A string describing the delimiter in each line, if any. Leave blank if not delimited.

Returns:

A masked array of flag values equal in size to that of the input.

Return type:

flag_arr

Example

Not specifying a lentype, the test defaults to count characters. A flag value of 1 passes.

>>> data = np.array(["data,string"])
>>> flags = qartod.syntax_test(data, nchar=11)
>>> flags
masked_array(data=[1],
            mask=False,
    fill_value=np.uint64(999999),
            dtype=uint8)

For working with HEX ASCII bytes, specify lentype to be byte.

>>> data2 = np.array(["0AEE61"])
>>> flags = qartod.syntax_test(data2, nchar=3, lentype="byte")
>>> flags
masked_array(data=[1],
            mask=False,
    fill_value=np.uint64(999999),
            dtype=uint8)

For the same data, specifying a delimiter now has the test count elements.

>>> flags = qartod.syntax_test(data, nchar=2, delimiter=",")
>>> flags
masked_array(data=[1],
            mask=False,
    fill_value=np.uint64(999999),
            dtype=uint8)
ioos_qc.qartod.time_gap_test(tinp, fail_span=2)[source]

Checks for gaps in the data time that exceed a specific threshold.

The data tinp is differentiated and those changes in time are compared against the time threshold fail_span. If the difference in time between points exceeds the value of fail_span, the following data point is flagged as FAIL. The first point inherits the flag of the second point, unless the second point is UNKNOWN or MISSING. Any missing and masked data is flagged as UNKNOWN.

Parameters:
  • tinp (Sequence[Real]) – Time input data as a numeric numpy array or list of real numbers.

  • fail_span (Real) – A numeric value for time duration in hours which, if timestamps jump by more than between points, flags following data point as FAIL.

Returns:

A masked array of flag values equal in size to that of the input tinp.

Return type:

flag_arr

ioos_qc.results module

class ioos_qc.results.CallResult(package, test, function, results)[source]

Bases: NamedTuple

function: callable

Alias for field number 2

package: str

Alias for field number 0

results: ndarray

Alias for field number 3

test: str

Alias for field number 1

class ioos_qc.results.CollectedResult(stream_id, package, test, function, results=None, data=None, tinp=None, zinp=None, lat=None, lon=None)[source]

Bases: object

data: ndarray = None
function: callable
function_name()[source]
Return type:

str

property hash_key: str
lat: ndarray = None
lon: ndarray = None
package: str
results: MaskedArray = None
stream_id: str
test: str
tinp: ndarray = None
zinp: ndarray = None
class ioos_qc.results.ContextResult(stream_id, results, subset_indexes, data, tinp, zinp, lat, lon)[source]

Bases: NamedTuple

data: ndarray

Alias for field number 3

lat: ndarray

Alias for field number 6

lon: ndarray

Alias for field number 7

results: list[CallResult]

Alias for field number 1

stream_id: str

Alias for field number 0

subset_indexes: ndarray

Alias for field number 2

tinp: ndarray

Alias for field number 4

zinp: ndarray

Alias for field number 5

ioos_qc.results.collect_results(results, how='list')[source]
ioos_qc.results.collect_results_dict(results)[source]

Turns a list of ContextResult objects into a dictionary of test results by combining the subset_index information in each ContextResult together into a single array of results. This is mostly here for historical purposes. Users should migrate to using the Result objects directly.

ioos_qc.results.collect_results_list(results)[source]

Turns a list of ContextResult objects into an iterator of CollectedResult objects by combining the subset_index information in each ContextResult together into a single array of results.

ioos_qc.stores module

class ioos_qc.stores.BaseStore[source]

Bases: object

save(*args, **kwargs)[source]

Serialize results to a store. This could save a file or publish messages.

Return type:

None

property stream_ids: list[str]

A list of stream_ids to save to the store.

class ioos_qc.stores.CFNetCDFStore(results, axes=None)[source]

Bases: BaseStore

save(path_or_ncd, dsg, *, config, dsg_kwargs=None, write_data=False, include=None, exclude=None, compute_aggregate=False)[source]

Serialize results to a store. This could save a file or publish messages.

property stream_ids: list[str]

A list of stream_ids to save to the store.

class ioos_qc.stores.NetcdfStore[source]

Bases: object

save(path_or_ncd, config, results)[source]

Updates the given netcdf with test configuration and results. If there is already a variable for a given test, it will update that variable with the latest results. Otherwise, it will create a new variable.

Parameters:
  • path_or_ncd – path or netcdf4 Dataset in which to store results

  • results – output of run()

class ioos_qc.stores.PandasStore(results, axes=None)[source]

Bases: BaseStore

Store results in a dataframe.

compute_aggregate(name='rollup')[source]

Internally compute the total aggregate and add it to the results.

Return type:

None

save(*, write_data=False, write_axes=True, include=None, exclude=None)[source]

Serialize results to a store. This could save a file or publish messages.

Return type:

DataFrame

property stream_ids: list[str]

A list of stream_ids to save to the store.

ioos_qc.stores.column_from_collected_result(cr)[source]

ioos_qc.streams module

class ioos_qc.streams.BaseStream(*args, **kwargs)[source]

Bases: object

Each stream should define how to return a list of datastreams along with their time and depth association. Each of these streams will passed through quality control configurations and returned back to it. Each stream needs to also define what to do with the resulting results (how to store them.).

data(stream_id)[source]

Return the data array from the source dataset based on stream_id. This is useful when plotting QC results.

Return type:

None

run(config)[source]

Iterate over the configs, splitting the streams up by geographic and time window before applying the individual config using QcConfig.run(). Store results for future usage.

Return type:

None

time()[source]

Return the time array from the source dataset. This is useful when plotting QC results.

Return type:

None

class ioos_qc.streams.NetcdfStream(path_or_ncd, time=None, z=None, lat=None, lon=None)[source]

Bases: object

data(stream_id)[source]
run(config)[source]
time()[source]
class ioos_qc.streams.NumpyStream(inp=None, time=None, z=None, lat=None, lon=None, geom=None)[source]

Bases: object

data()[source]
run(config)[source]
time()[source]
class ioos_qc.streams.PandasStream(df, time=None, z=None, lat=None, lon=None, geom=None)[source]

Bases: object

data(stream_id)[source]
run(config)[source]
time()[source]
class ioos_qc.streams.XarrayStream(path_or_ncd, time=None, z=None, lat=None, lon=None)[source]

Bases: object

data(stream_id)[source]
run(config)[source]
time()[source]

ioos_qc.utils module

Utilities.

class ioos_qc.utils.GeoNumpyDateEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: GeoJSONEncoder

Encode numpy dates for geospatial formats.

default(obj)[source]

If input object is an ndarray it will be converted into a list.

Return type:

Any

ioos_qc.utils.add_flag_metadata(**kwargs)[source]

Add flag metadata.

ioos_qc.utils.cf_safe_name(name)[source]

Make CF safe names.

Return type:

str

ioos_qc.utils.check_timestamps(times, max_time_interval=None)[source]

Sanity checks for timestamp arrays.

Checks that the times supplied are in monotonically increasing chronological order, and optionally that time intervals between measurements do not exceed a value max_time_interval. Note that this is not a QARTOD test, but rather a utility test to make sure times are in the proper order and optionally do not have large gaps prior to processing the data.

Parameters:
  • times (ndarray) – Input array of timestamps

  • max_time_interval (Real) – The interval between values should not exceed this value. [optional]

Return type:

bool

ioos_qc.utils.dict_depth(d)[source]

Get the depth of a dict.

ioos_qc.utils.dict_update(d, u)[source]

Update value of a nested dictionary of varying depth.

Return type:

Mapping

ioos_qc.utils.great_circle_distance(lat_arr, lon_arr)[source]

Compute great circle distances.

ioos_qc.utils.isfixedlength(lst, length)[source]

Check if a list has the correct length.

Return type:

bool

ioos_qc.utils.isnan(v)[source]

Return True if a value is NaN.

Return type:

bool

ioos_qc.utils.load_config_as_dict(source)[source]

Load an object as a config dict. The source can be a dict, OrderedDict, YAML string, JSON string, a StringIO, or a file path to a valid YAML or JSON file.

Return type:

OrderedDict

ioos_qc.utils.load_config_from_xarray(source)[source]

Load an xarray dataset as a config dict.

ioos_qc.utils.mapdates(dates)[source]

Map dates objects to datetime64[ns].

ioos_qc.utils.openf(p, **kwargs)[source]

Allow one-line-lambdas to read file contents.