### Example: Using Types enum Source: https://github.com/actigraph/pygt3x Shows how to access enum members, their values, and iterate over all event types. ```python from pygt3x import Types print(Types.Activity) # Types.Activity print(Types.Activity.value) # 0 print(Types(26)) # Types.Activity2 # Reflect over every event type id for t in Types: print(t.name, t.value) ``` -------------------------------- ### Example — calibrate raw samples Source: https://github.com/actigraph/pygt3x Complete example showing how to create a CalibrationV2Service with a calibration dictionary for sample_rate=100 and calibrate raw acceleration samples. Prints the calibrated result. ```python import numpy as np from pygt3x.calibration import CalibrationV2Service calibration = { "offsetX_100": 0, "offsetY_100": 0, "offsetZ_100": 0, "sensitivityXX_100": 100, "sensitivityYY_100": 100, "sensitivityZZ_100": 100, "sensitivityXY_100": 0, "sensitivityXZ_100": 0, "sensitivityYZ_100": 0, } svc = CalibrationV2Service(calibration, sample_rate=100) raw = np.array([[1000, 1000, 1000], [500, 500, 500]]) cal = svc.calibrate_samples(raw) print(cal) ``` -------------------------------- ### Example — temperature data with and without calibration Source: https://github.com/actigraph/pygt3x Shows how to read temperature data with and without calibration using FileReader. Prints the first rows of the calibrated DataFrame. ```python from pygt3x.reader import FileReader with FileReader("device.agdc") as reader: calibrated = reader.temperature_to_pandas(calibrate=True) raw = reader.temperature_to_pandas(calibrate=False) print(calibrated.head()) ``` -------------------------------- ### Example — Create Header from raw bytes Source: https://github.com/actigraph/pygt3x Creates a Header instance from an 8-byte raw bytes object and prints its fields. The example uses all-zero bytes, so separator, event_type, timestamp, and payload_size are all 0. ```python from pygt3x.components import Header raw = bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) h = Header(raw) print(h.separator, h.event_type, h.timestamp, h.payload_size) ``` -------------------------------- ### Example — error handling for missing calibration keys Source: https://github.com/actigraph/pygt3x Shows that constructing CalibrationV2Service with an incomplete calibration dictionary raises KeyError, which can be caught and handled. ```python from pygt3x.calibration import CalibrationV2Service try: CalibrationV2Service({"offsetX_100": 0}, sample_rate=100) except KeyError as exc: print("Missing calibration key:", exc) ``` -------------------------------- ### Example: Read Info from a GT3X zip file Source: https://github.com/actigraph/pygt3x Opens a GT3X archive with zipfile.ZipFile and calls Info.read_zip to parse the info.txt entry, then prints sample_rate, serial_number, and start_date. ```python from zipfile import ZipFile from pygt3x.components import Info with ZipFile("device.gt3x") as zf: info = Info.read_zip(zf) print(info.sample_rate, info.serial_number, info.start_date) ``` -------------------------------- ### Example — construct and validate RawEvent Source: https://github.com/actigraph/pygt3x Constructs a RawEvent with a header, payload, and checksum, then prints whether the checksum is valid. ```python from pygt3x.components import Header, RawEvent header = Header(b"\x00" + bytes([0x00]) + b"\x00\x00\x00\x00" + b"\x00\x00") # payload/checksum that yield a valid event: evt = RawEvent(header=header, payload=b"\x00\x00\x00", checksum=b"\xFF") print(evt.is_checksum_valid) ``` -------------------------------- ### Read temperature data with FileReader Source: https://github.com/actigraph/pygt3x/blob/main/README.md Opens a GT3X/AGDC file with FileReader and exports temperature data to a pandas DataFrame using temperature_to_pandas(). ```python from pygt3x.reader import FileReader with FileReader("FILENAME") as reader: df = reader.temperature_to_pandas() print(df.head(5)) ``` -------------------------------- ### Iterate log events example Source: https://github.com/actigraph/pygt3x Example usage of LogReader to iterate events from a log.bin file inside a GT3X zip archive. Checks checksum validity and prints event type and payload size for each event. ```python from zipfile import ZipFile from pygt3x.reader import LogReader from pygt3x.components import RawEvent with ZipFile("device.gt3x") as zf: with zf.open("log.bin", "r") as f: reader = LogReader(f) while True: event = reader.read_event() if event is None: break if not event.is_checksum_valid: print("bad checksum at", event.header.timestamp) print(event.header.event_type, len(event.payload)) ``` -------------------------------- ### Read calibrated accelerometer data with FileReader Source: https://github.com/actigraph/pygt3x/blob/main/README.md Opens a GT3X/AGDC file with FileReader, checks if idle sleep mode was used, and exports calibrated accelerometer data to a pandas DataFrame. ```python from pygt3x.reader import FileReader # Read raw data and calibrate, then export to pandas data frame with FileReader("FILENAME") as reader: was_idle_sleep_mode_used = reader.idle_sleep_mode_activated df = reader.to_pandas() print(df.head(5)) ``` -------------------------------- ### Catch built-in exceptions when reading a GT3X file Source: https://github.com/actigraph/pygt3x Consumer code catches built-in exceptions because pygt3x defines no custom exceptions. The example handles NotImplementedError for unsupported calibration, and FileNotFoundError, BadZipFile, or OSError for file opening failures. ```python from zipfile import BadZipFile from pygt3x.reader import FileReader try: with FileReader("device.gt3x") as reader: df = reader.to_pandas(calibrate=True) except NotImplementedError: print("calibration method unsupported") except (FileNotFoundError, BadZipFile, OSError) as exc: print("could not open file:", exc) ``` -------------------------------- ### Import pygt3x and Types Source: https://github.com/actigraph/pygt3x Import the top-level package and the Types enum. ```python import pygt3x from pygt3x import Types ``` -------------------------------- ### CalibrationV2Service constructor Source: https://github.com/actigraph/pygt3x Creates a CalibrationV2Service for applying acceleration calibration. Requires a calibration dictionary with all offset and sensitivity keys suffixed with the sample rate. ```APIDOC ## CalibrationV2Service(calibration, sample_rate) ### Description Initializes a calibration service for V2 calibration. The calibration dictionary must contain all offset* and sensitivity* keys suffixed with the sample rate. ### Parameters - **calibration** (Dict[str, int]) - Required - Calibration data with keys like `offsetX_{sr}`, `sensitivityXX_{sr}`, etc. - **sample_rate** (int) - Required - Sample rate used to suffix the calibration keys. ### Returns A CalibrationV2Service instance. ``` -------------------------------- ### CalibrationV2Service.__init__ Source: https://github.com/actigraph/pygt3x Initializes a CalibrationV2Service instance with zeroed offset vector and sensitivity matrix, then applies the provided calibration data and sample rate. ```APIDOC ## CalibrationV2Service.__init__ ### Description Initializes a CalibrationV2Service instance with zeroed offset vector and sensitivity matrix, then applies the provided calibration data and sample rate. ### Method Constructor ### Parameters - `calibration` (Dict[str, int]) - Required - Calibration info mapping (see keys below) - `sample_rate` (int) - Required - Samples per second ### Response No return value. Sets `self.offset_vector` (np.ndarray) and `self.sensitivity_matrix` (np.ndarray). ``` -------------------------------- ### FileReader constructor Source: https://github.com/actigraph/pygt3x Creates a FileReader instance for reading GT3X/AGDC files. Configuration is passed via constructor options. ```APIDOC ## FileReader(file_name, num_rows=None) ### Description Initializes a FileReader to read a GT3X/AGDC file. The file format is auto-detected on entering the context. ### Parameters - **file_name** (str) - Required - Input GT3X/AGDC file path. - **num_rows** (Optional[int]) - Optional - Number of events to read; `None` reads all events. ### Returns A FileReader instance. ``` -------------------------------- ### CalibrationV2Service.__init__ Source: https://github.com/actigraph/pygt3x Constructor that initializes offset_vector and sensitivity_matrix as zero arrays, then calls set_calibration to populate them from the calibration dictionary and sample rate. ```python def __init__(self, calibration: Dict[str, int], sample_rate: int): """Initialise fields.""" self.offset_vector = np.array([[0, 0, 0]]) self.sensitivity_matrix = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) self.set_calibration(calibration, sample_rate) ``` -------------------------------- ### LogReader.__init__ Source: https://github.com/actigraph/pygt3x Initializes a LogReader instance with an IO stream for log.bin file data. ```APIDOC ## LogReader.__init__ ### Description Initializes a LogReader instance with an IO stream for log.bin file data. ### Method Constructor ### Parameters #### Parameters - **source** (IO stream) - Required - IO stream for `log.bin` file data ### Response No return value. ``` -------------------------------- ### FileReader.__init__ Source: https://github.com/actigraph/pygt3x Initializes a FileReader instance with the given GT3X/AGDC file path and optional row limit. The object is not populated until the context is entered. ```APIDOC ## FileReader.__init__ ### Description Initializes a FileReader instance with the given GT3X/AGDC file path and optional row limit. The object is not populated until the context is entered. ### Method Constructor ### Signature ```python def __init__(self, file_name: str, num_rows: Optional[int] = None): ``` ### Parameters - **file_name** (str) - Required - Input GT3X/AGDC file path - **num_rows** (Optional[int]) - Optional - Number of events to read. When `None`, all events are read. ### Attributes Set - **self.acceleration** (np.ndarray shape (0, 5)) - Accelerometer samples: `[Timestamp, X, Y, Z, IdleSleepMode]` - **self.temperature** (np.ndarray shape (0, 3)) - Temperature samples: `[Timestamp, TemperatureMCU, TemperatureADXL]` - **self.idle_sleep_mode_activated** (None, later bool) - Whether ISM was activated on the device - **self.num_rows** (Optional[int]) - Event row limit - **self.nhanes** (None, later bool) - `True` for legacy V1/NHANES files ### Throws - `FileNotFoundError`/`zipfile.BadZipFile` when the file cannot be opened as a zip archive. - `KeyError` is caught internally to distinguish between V1 and V2 formats. ### Example ```python import os from pygt3x.reader import FileReader with FileReader("device.gt3x") as reader: print("ISM activated:", reader.idle_sleep_mode_activated) print("Sample rate:", reader.info.sample_rate) print(reader.acceleration.shape) # (N, 5) df = reader.to_pandas() print(df.head()) ``` ### Example (limited rows and error handling) ```python from pygt3x.reader import FileReader try: with FileReader("device.gt3x", num_rows=100) as reader: df = reader.to_pandas(calibrate=False) except (FileNotFoundError, OSError) as exc: print("Could not open file:", exc) ``` ``` -------------------------------- ### Import CalibrationV2Service Source: https://github.com/actigraph/pygt3x Import path for the CalibrationV2Service class from the pygt3x calibration module. ```python from pygt3x.calibration import CalibrationV2Service ``` -------------------------------- ### FileReader.__init__ signature Source: https://github.com/actigraph/pygt3x Constructor signature for FileReader. Parameters: file_name (str, required) and num_rows (Optional[int], default None). ```python def __init__(self, file_name: str, num_rows: Optional[int] = None): ``` -------------------------------- ### LogReader.__init__ signature Source: https://github.com/actigraph/pygt3x Constructor signature for LogReader. Accepts an IO stream for log.bin file data. ```python def __init__(self, source): ``` -------------------------------- ### read_nhanes_payload Source: https://github.com/actigraph/pygt3x Reads the entire `activity.bin` stream, unpacks the bit-packed acceleration, divides by `NHANES_SCALE` (341) and rounds to 3 decimals, reorders columns, and stamps a time column. ```APIDOC ## `read_nhanes_payload` ### Description Reads the entire `activity.bin` stream, unpacks the bit-packed acceleration, divides by `NHANES_SCALE` (341) and rounds to 3 decimals, reorders columns via `data[:, [1, 0, 2]]`, and stamps a time column. Returns `numpy.ndarray` shape `(-1, 5)`: `[time, Y-org.. , ..., idle=0]`. Time = `(cumcount / sample_rate) + start_date / 1e9`. ### Parameters - `source` (IO stream) - Required - IO stream for `activity.bin` file data - `start_date` (`int`) - Required - Start date in nanoseconds - `sample_rate` (`float`) - Required - Sampling rate ### Returns `numpy.ndarray` shape `(-1, 5)` ``` -------------------------------- ### CalibrationV2Service Source: https://github.com/actigraph/pygt3x Service object for calibration math. ```APIDOC ## CalibrationV2Service ### Description Service object for calibration math. ``` -------------------------------- ### FileReader.to_pandas(calibrate=True) Source: https://github.com/actigraph/pygt3x Exports the acceleration data as a pandas DataFrame. Acceleration calibration is applied when calibrate=True and the file is not a legacy V1/NHANES file. ```APIDOC ## FileReader.to_pandas(calibrate=True) ### Description Returns the acceleration data as a pandas DataFrame. If calibrate is True and the file is not a V1/NHANES file, acceleration calibration is applied. ### Parameters - **calibrate** (bool) - Optional - Default `True`. Apply acceleration calibration. ### Returns pandas.DataFrame containing acceleration data. ``` -------------------------------- ### RawEvent.__post_init__ Source: https://github.com/actigraph/pygt3x Verifies the event's checksum upon construction. The checksum is recomputed by XOR-reducing the header separator, event_type, little-endian timestamp, little-endian payload_size, and payload bytes, then negating with ~... & 0xFF, and compared to the stored checksum. ```APIDOC ## RawEvent.__post_init__ ### Description Verifies the event's checksum upon construction. The checksum is recomputed by XOR-reducing the header separator, event_type, little-endian timestamp, little-endian payload_size, and payload bytes, then negating with ~... & 0xFF, and compared to the stored checksum. ### Method Constructor (dataclass __post_init__) ### Parameters #### Constructor Fields (all required) - **header** (Header) - Required - The event header - **payload** (bytes) - Required - Log event payload byte array - **checksum** (bytes) - Required - Log event checksum (1 byte) #### Computed Field (init=False) - **is_checksum_valid** (bool) - True when the payload checksum matches the stored byte ### Response #### Success Response - **is_checksum_valid** (bool) - True when the payload checksum matches the stored byte ### Request Example ```python from pygt3x.components import Header, RawEvent header = Header(b"\x00" + bytes([0x00]) + b"\x00\x00\x00\x00" + b"\x00\x00") # payload/checksum that yield a valid event: evt = RawEvent(header=header, payload=b"\x00\x00\x00", checksum=b"\xFF") print(evt.is_checksum_valid) ``` ``` -------------------------------- ### Basic usage of FileReader as context manager Source: https://github.com/actigraph/pygt3x Opens a GT3X file and prints ISM activation, sample rate, acceleration shape, and a pandas DataFrame preview. ```python import os from pygt3x.reader import FileReader with FileReader("device.gt3x") as reader: print("ISM activated:", reader.idle_sleep_mode_activated) print("Sample rate:", reader.info.sample_rate) print(reader.acceleration.shape) # (N, 5) df = reader.to_pandas() print(df.head()) ``` -------------------------------- ### calibrate_temperature method definition Source: https://github.com/actigraph/pygt3x Defines the method signature for calibrating temperature data. Applies linear gain for calibration method 1, otherwise raises NotImplementedError. ```python def calibrate_temperature(self): ``` -------------------------------- ### Info dataclass definition and read_zip static method Source: https://github.com/actigraph/pygt3x Defines the Info dataclass with fields for device metadata and the read_zip static method that parses info.txt (UTF-8 with BOM) as key:value lines. Numeric fields missing from the file default to 0 or None; malformed numeric values raise ValueError. TimeZone values containing colons are rejoined. ```python @dataclass class Info: acceleration_max: float acceleration_min: float acceleration_scale: float age: Optional[float] battery_voltage: float board_revision: Optional[str] device_type: Optional[str] dominance: Optional[str] download_date: Optional[int] firmware: Optional[str] height: Optional[float] last_sample_time: int limb: Optional[str] mass: Optional[float] race: Optional[str] sample_rate: int serial_number: Optional[str] sex: Optional[str] side: Optional[str] start_date: int stop_date: int subject_name: Optional[str] timezone: Optional[str] unexpected_resets: Union[str, int] @staticmethod def read_zip(zip_file): """Parse info.txt and returns an Info object.""" ``` -------------------------------- ### Catch KeyError for missing calibration keys in CalibrationV2Service Source: https://github.com/actigraph/pygt3x Use this snippet to catch KeyError when initializing CalibrationV2Service with an incomplete calibration dictionary. The error occurs for missing offset*_{sr} or sensitivity*_{sr} keys when calibrationMethod == 2. ```python from pygt3x.calibration import CalibrationV2Service try: CalibrationV2Service({}, sample_rate=100) except KeyError as exc: print("Missing calibration key:", exc) ``` -------------------------------- ### Header.__init__ Source: https://github.com/actigraph/pygt3x Unpacks an 8-byte GT3X log event header into its component fields. This constructor is part of the public pygt3x.components module and is used to parse raw header bytes. ```APIDOC ## Header.__init__ ### Description Unpacks an 8-byte GT3X log event header into its component fields. ### Method Constructor ### Signature ```python Header(header_bytes: bytes) ``` ### Parameters - **header_bytes** (bytes) - Required - 8 raw bytes unpacked with `struct.unpack(" struct.error (needs 8 bytes) except struct.error as exc: print("malformed header", exc) ``` ``` -------------------------------- ### Import FileReader from pygt3x.reader Source: https://github.com/actigraph/pygt3x Import path for the FileReader class. ```python from pygt3x.reader import FileReader ``` -------------------------------- ### Import Info from pygt3x.components Source: https://github.com/actigraph/pygt3x Import path for the Info class, which parses the info.txt entry from a GT3X archive. ```python from pygt3x.components import Info ``` -------------------------------- ### FileReader.__enter__ signature Source: https://github.com/actigraph/pygt3x Signature for the __enter__ method. ```python def __enter__(self): ``` -------------------------------- ### Import LogReader Source: https://github.com/actigraph/pygt3x Import path for the LogReader class from the pygt3x.reader module. ```python from pygt3x.reader import LogReader ``` -------------------------------- ### unpack_bitpack_temperature Source: https://github.com/actigraph/pygt3x Unpacks temperature data stored as sets of 3 bytes. The first byte selects the sensor, and the next two bytes are unpacked according to the sensor type. ```APIDOC ## `unpack_bitpack_temperature` ### Description Unpacks temperature stored as sets of 3 bytes. Iterates groups of 3 bytes; the first byte selects the sensor and the next two bytes are unpacked from `source[i*3+1:(i+1)*3]`: - sensor `0` → unsigned `