CLI and API reference

CLI reference

actinet

[INFO] Failed to extract font properties from /usr/share/fonts/truetype/noto/NotoColorEmoji.ttf: In FT2Font: Can not load face.  Unknown file format.
[WARNING] Matplotlib is building the font cache; this may take a moment.
[INFO] generated new fontManager
usage: actinet [-h] [--outdir OUTDIR] [--classifier CLASSIFIER] [--no-hmm]
               [--require-sleep-above REQUIRE_SLEEP_ABOVE]
               [--single-sleep-block] [--force-download]
               [--pytorch-device PYTORCH_DEVICE] [--sample-rate SAMPLE_RATE]
               [--exclude-first-last {first,last,both}]
               [--exclude-wear-below EXCLUDE_WEAR_BELOW]
               [--csv-start-row CSV_START_ROW] [--csv-txyz CSV_TXYZ]
               [--csv-txyz-idxs CSV_TXYZ_IDXS]
               [--csv-date-format CSV_DATE_FORMAT]
               [--calibration-stdtol-min CALIBRATION_STDTOL_MIN]
               [--plot-activity] [--cache-classifier]
               [--model-repo-path MODEL_REPO_PATH] [--quiet]
               [filepath]

A tool to predict activities from accelerometer data using a self-supervised
ResNet-18 model

positional arguments:
  filepath              Enter file to be processed

optional arguments:
  -h, --help            show this help message and exit
  --outdir OUTDIR, -o OUTDIR
                        Enter folder location to save output files
  --classifier CLASSIFIER, -c CLASSIFIER
                        Enter custom activity classifier file to use. Default:
                        walmsley (Walmsley2020 annotations of activity
                        intensity). Can also enter path to local classifier
                        (.joblib.lzma) file.
  --no-hmm              Disable HMM post-processing
  --require-sleep-above REQUIRE_SLEEP_ABOVE
                        Require sleep blocks to exceed a minimum duration,
                        otherwise be classified as sedentary. Pass values as
                        strings, e.g.: '2H', '30min'. Default: None (no
                        requirement)
  --single-sleep-block  Recognise only one sleep block per day, all other
                        sleep blocks will be converted to sedentary
  --force-download      Force download of classifier file
  --pytorch-device PYTORCH_DEVICE, -d PYTORCH_DEVICE
                        Pytorch device to use, e.g.: 'cpu' or 'cuda:0'.
                        Default: 'mps' if available, otherwise 'cpu'
  --sample-rate SAMPLE_RATE, -r SAMPLE_RATE
                        Sample rate for measurement, otherwise inferred.
  --exclude-first-last {first,last,both}, -e {first,last,both}
                        Exclude first, last or both days of data. Default:
                        None (no exclusion)
  --exclude-wear-below EXCLUDE_WEAR_BELOW, -w EXCLUDE_WEAR_BELOW
                        Exclude days with wear time below threshold. Pass
                        values as strings, e.g.: '12H', '30min'. Default: None
                        (no exclusion)
  --csv-start-row CSV_START_ROW
                        Row number to start reading a CSV file. Default: 1
                        (First row)
  --csv-txyz CSV_TXYZ   Column names for time, x, y, z in CSV files. Comma-
                        separated string. Default: 'time,x,y,z'
  --csv-txyz-idxs CSV_TXYZ_IDXS
                        Column indices for time,x,y,z (0-indexed, e.g.,
                        '0,1,2,3'). Overrides --csv-txyz.
  --csv-date-format CSV_DATE_FORMAT
                        Date time format for csv file when reading a csv file.
                        See https://docs.python.org/3/library/datetime.html#st
                        rftime-and-strptime-format-codes for more possible
                        codes.Default: '%Y-%m-%d %H:%M:%S.%f' (e.g.
                        '2023-10-01 12:34:56.789')
  --calibration-stdtol-min CALIBRATION_STDTOL_MIN
                        Minimum standard deviation tolerance (g) for detecting
                        stationary periods for calibration. Default: None
  --plot-activity, -p   Plot the predicted activity labels
  --cache-classifier    Download and cache classifier file and model modules
                        for offline usage
  --model-repo-path MODEL_REPO_PATH, -m MODEL_REPO_PATH
                        Enter repository of ssl model
  --quiet, -q           Suppress output

accPlot

usage: accPlot [-h] [--plotFile output file] [--showFileName True/False]
               [--showFirstNDays days]
               input file

A script to plot acc time series data.

positional arguments:
  input file            input .csv.gz time series file to plot

optional arguments:
  -h, --help            show this help message and exit
  --plotFile output file
                        output .png file to plot to
  --showFileName True/False
                        Toggle showing filename as title in output image
                        (default : False)
  --showFirstNDays days
                        Show just first n days

actinet-collate-outputs

usage: actinet-collate-outputs [-h] [--outfile OUTFILE] outputs

positional arguments:
  outputs               Directory containing JSON files.

optional arguments:
  -h, --help            show this help message and exit
  --outfile OUTFILE, -o OUTFILE
                        Output CSV filename.

API reference

class actinet.models.ActivityClassifier(device='cpu', batch_size=512, window_sec=30, weights_path=None, labels=[], repo_tag='v1.0.0', hmm_params=None, hmm_ignore_transition_gaps=False, hmm_handle_sleep_transitions=False, verbose=False)

Implement a ResNet-18 based Activity Classifier with model saving/loading and optional HMM smoothing.

fit(X, Y, groups=None, T=None, weights_path='models/weights.pt', model_repo_path=None, n_splits=5)

Fit the ActivityClassifier to the provided data by training the model.

Parameters
  • X (numpy.ndarray) – The training accelerometer data [x,y,z] with shape (rows, window_len, 3)

  • Y (numpy.ndarray) – Ground truth labels of the training data with shape (rows, )

  • groups (numpy.ndarray, optional) – Participant labels for the training data with shape (rows, )

  • T (numpy.ndarray, optional) – Time at each observation with shape (rows, )

  • weights_path (str, optional) – Path to save the model weights

  • model_repo_path (str, optional) – Path to the ssl-wearables model repository (https://github.com/OxWearables/ssl-wearables)

  • n_splits (int, optional) – Number of splits for cross-validation

load_model(model_repo_path=None)

Load SSL model reposiotory from specified path. (https://github.com/OxWearables/ssl-wearables)

Parameters

model_repo_path (str, optional) – Path to the ssl-wearables model repository

predict(X, T=None, hmm_smothing=True, sleep_tol=None, remove_naps=False)

Use the ActivityClassifier to make predictions on input accelerometer data.

Parameters
  • X (numpy.ndarray) – The input accelerometer data [x,y,z] with shape (rows, window_len, 3)

  • T (numpy.ndarray, optional) – Time at each observation with shape (rows, )

  • hmm_smothing (bool, optional) – Whether to apply HMM smoothing to the predictions

  • sleep_tol (str, optional) – Time threshold for sleep periods to be considered valid (e.g., ‘30min’)

predict_from_frame(data, sample_freq, hmm_smothing=True, sleep_tolerance=None, remove_naps=False)

Use the ActivityClassifier to make predictions on input accelerometer data.

Parameters
  • data (pandas.DataFrame) – The training accelerometer data [x,y,z]

  • sample_freq (int or float) – Sampling frequency of the accelerometer data

  • hmm_smothing (bool, optional) – Whether to apply HMM smoothing to the predictions

  • sleep_tolerance (str, optional) – Time threshold for sleep periods to be considered valid (e.g., ‘30min’)

  • remove_naps (bool, optional) – Whether to remove nap periods from the predictions

save(output_path)

Save the ActivityClassifier model to a .lzma file.

Parameters

output_path (str) – lzma file location

class actinet.hmm.HMM(prior=None, emission=None, transition=None, labels=None, uniform_prior=True, ignore_transition_gaps=False, handle_sleep_transitions=False)

Implement a basic hidden Markov model (HMM) with parameter saving/loading https://en.wikipedia.org/wiki/Hidden_Markov_model.

display(labels, precision=3)

Print the model parameters in a readable format.

Parameters
  • labels (list/dict) – List of label names in expected order

  • precision (int) – Number of decimal places to print

fit(Y_prob, Y_true, groups=None, T=None, interval=None)

Fit a HMM to the provided data by calculating the prior, transition and emission matrices.

Parameters
  • Y_prob (numpy.ndarray) – Observation probabilities

  • Y_true (numpy.ndarray) – Ground truth labels

  • groups (numpy.ndarray, optional) – Group labels for the data, if applicable

  • T (numpy.ndarray, optional) – Time at each observation

  • interval (int or float, optional) – Expected time interval between observations in seconds

load(path)

Load model parameters from a Numpy npz file.

Parameters

path (str) – npz file location

predict(y_obs, t=None, interval=None, uniform_prior=None)

Predict sequence of activities using viterbi algorithm, while restoring labels after gaps in data.

Parameters
  • y_obs (numpy.ndarray) – Predicted observations

  • t (numpy.ndarray, optional) – Time at each observation

  • interval (int or float, optional) – Expected time interval between observations in seconds

  • uniform_prior (bool, optional) – Assume uniform priors.

Returns

Smoothed sequence of activities

Return type

np.ndarray

save(path)

Save model parameters to a Numpy npz file.

Parameters

path (str) – npz file location

viterbi(y_obs, uniform_prior=None)

Perform HMM smoothing over observations via Viteri algorithm https://en.wikipedia.org/wiki/Viterbi_algorithm.

Parameters
  • y_obs (numpy.ndarray) – Predicted observations

  • uniform_prior (bool, optional) – Assume uniform priors

Returns

Smoothed sequence of activities

Return type

np.ndarray