Methods Reference

Complete alphabetical reference of all methods in the TrialManager class. Methods are organized by category for easier navigation.

Initialization Methods

initializeExperiment()

PUBLIC
export function initializeExperiment(): void

Top-level function that sets up event listeners and orchestrates the experiment initialization sequence.

Returns

void - No return value

initWebGazer()

ASYNC
async initWebGazer(): Promise<void>

Initializes WebGazer with enhanced configuration including ridge regression, TFFacemesh tracking, and adaptive sampling.

Returns

Promise<void> - Resolves when initialization complete

initializeExclusions()

ASYNC
async initializeExclusions(): Promise<void>

Dynamically imports object exclusion rules based on selected test type (Shapes/Colors/Abstract/Pictures).

Returns

Promise<void> - Resolves after exclusions loaded

showInitialsDialog()

ASYNC
async showInitialsDialog(): Promise<void>

Displays modal dialog for collecting participant initials, test type, and trial count.

Returns

Promise<void> - Resolves when dialog submitted

setupImages()

ASYNC
async setupImages(): Promise<void>

Loads all stimulus images for selected test type. Image counts: Abstract (403), Shapes (193), Colors (10), Pictures (10).

Returns

Promise<void> - Resolves when all images loaded

Throws

Error - If unknown test type or image loading fails

Calibration Methods

startCalibrationPhase()

ASYNC
async startCalibrationPhase(): Promise<void>

Executes 9-point calibration sequence with automatic validation and refinement.

Returns

Promise<void> - Resolves when calibration complete

validateCalibration()

ASYNC
async validateCalibration(): Promise<number>

Tests calibration quality at 5 validation points and returns normalized quality score (0-1).

Returns

Promise<number> - Quality score: 1 - (avgError / 200)

measureCalibrationError(point)

ASYNC
async measureCalibrationError(point: Object): Promise<number>

Measures average prediction error at a specific screen point by collecting 10 samples.

Parameters

point (Object)

Screen coordinates to test: {x: number, y: number}

Returns

Promise<number> - Average error distance in pixels

refineCalibration()

ASYNC
async refineCalibration(): Promise<void>

Adds 3 refinement calibration points in high-error areas. Called automatically if quality < 0.75.

Returns

Promise<void> - Resolves when refinement complete

quickRecalibration()

ASYNC
async quickRecalibration(): Promise<void>

Performs fast 3-point recalibration. Called automatically every 10 trials during experiments.

Returns

Promise<void> - Resolves when recalibration complete

runCalibrationSequence(points, showCount)

ASYNC
async runCalibrationSequence(points: Array, showCount: boolean = true): Promise<void>

Internal helper that displays calibration points sequentially and records clicks.

Parameters

points (Array)

Array of calibration points: [{x: 0-1, y: 0-1}, ...]

showCount (boolean, optional)

Whether to display remaining point counter. Default: true

Returns

Promise<void> - Resolves when all points clicked

Gaze Processing Methods

processGazeData(gazePoint, trialStartTime)

PUBLIC
processGazeData(gazePoint: Object, trialStartTime: number): void

Core gaze processing pipeline: outlier detection → head pose compensation → Kalman filtering → data enrichment → storage.

Parameters

gazePoint (Object)

Raw gaze coordinates: {x: number, y: number}

trialStartTime (number)

Trial start timestamp (milliseconds since epoch)

Returns

void - Stores data in currentGazeData and allGazeData

initKalmanFilter()

PUBLIC
initKalmanFilter(): void

Initializes Kalman filter states for X and Y coordinates with tuned parameters (q=0.01, r=0.1).

Returns

void - Sets this.kalmanX and this.kalmanY

kalmanFilter(measurement, kalmanState)

PUBLIC
kalmanFilter(measurement: number, kalmanState: Object): number

Applies Kalman filter algorithm to smooth a single coordinate measurement.

Parameters

measurement (number)

Raw measured value (x or y coordinate)

kalmanState (Object)

Filter state object: {q, r, p, x, k}

Returns

number - Filtered coordinate value

compensateForHeadMovement(gazePoint, headPoseData)

PUBLIC
compensateForHeadMovement(gazePoint: Object, headPoseData: Object): Object

Applies head pose compensation and Kalman filtering to raw gaze coordinates.

Parameters

gazePoint (Object)

Raw gaze point: {x: number, y: number}

headPoseData (Object, optional)

Head pose angles (currently used for logging only)

Returns

Object - Compensated coordinates: {x: number, y: number}

isOutlier(gazePoint)

PUBLIC
isOutlier(gazePoint: Object): boolean

Detects outliers based on off-screen position (±100px buffer) or excessive velocity (>500px jumps).

Parameters

gazePoint (Object)

Gaze point to check: {x: number, y: number}

Returns

boolean - true if point is outlier, false otherwise

calculateHeadPose(faceMesh)

PUBLIC
calculateHeadPose(faceMesh: Array): Object | null

Calculates head pose angles (roll, pitch, yaw) and face distance from TFFacemesh 468-point landmarks.

Parameters

faceMesh (Array)

Facial landmark array from TFFacemesh (468 points)

Returns

Object | null - Head pose data: {roll, pitch, yaw, distance} or null if invalid

extractHeadPoseFeatures(faceMesh)

PUBLIC
extractHeadPoseFeatures(faceMesh: Array): Object

Extracts raw head pose angles from key facial landmarks (nose: 1, left eye: 33, right eye: 263).

Parameters

faceMesh (Array)

Facial landmark array

Returns

Object - Raw angles: {roll: number, pitch: number, yaw: number}

calculateFaceDistance(faceMesh)

PUBLIC
calculateFaceDistance(faceMesh: Array): number

Calculates approximate face distance from camera using inter-eye distance as proxy.

Parameters

faceMesh (Array)

Facial landmark array

Returns

number - Distance metric (larger = closer to camera)

shouldProcessSample(data)

PUBLIC
shouldProcessSample(data: Object): boolean

Implements adaptive sampling: 60fps (16ms) for fast movement (>100px/s), 30fps (33ms) for slow movement.

Parameters

data (Object)

Gaze data with coordinates: {x: number, y: number}

Returns

boolean - true if sample should be processed, false to skip

Trial Management Methods

startExperiment()

ASYNC
async startExperiment(): Promise<void>

Main experiment loop. Executes all trials with periodic recalibration, then saves/exports data.

Returns

Promise<void> - Resolves when experiment complete and data saved

runTrial(trialType)

ASYNC
async runTrial(trialType: number): Promise<void>

Executes a single trial: display sample object → delay → display test objects → collect gaze data → store results.

Parameters

trialType (number)

Trial type: 1 (target + 2 identical foils) or 2 (target + 2 different foils)

Returns

Promise<void> - Resolves when trial complete

Utility Methods

seededRandom(seed)

PUBLIC
seededRandom(seed: number): Function

Creates a deterministic pseudo-random number generator seeded by participant ID.

Parameters

seed (number)

Seed value (typically participant ID)

Returns

Function - PRNG function returning values 0-1

generateFileName()

PUBLIC
generateFileName(): string

Generates data export filename with format: {INITIALS}_{ISO_TIMESTAMP}_data.json

Returns

string - Generated filename

Example Output

"PS_2025-01-26T15-30-45-123Z_data.json"

shuffleArray(array)

PUBLIC
shuffleArray(array: Array): Array

Fisher-Yates shuffle algorithm for randomizing array order in-place.

Parameters

array (Array)

Array to shuffle

Returns

Array - Shuffled array (same reference)

getRandomObjectNumber(exclude)

PUBLIC
getRandomObjectNumber(exclude: Array): number

Selects random object number from valid range, excluding specified objects.

Parameters

exclude (Array)

Array of object numbers to exclude from selection

Returns

number - Random object number (1 to totalImages)

getExcludedObjects(objectNum)

PUBLIC
getExcludedObjects(objectNum: number): Array

Retrieves list of objects that should not appear together with specified object (perceptually similar items).

Parameters

objectNum (number)

Object number to get exclusions for

Returns

Array - Array of excluded object numbers

createImage(objectNum)

PUBLIC
createImage(objectNum: number): HTMLImageElement

Creates HTMLImageElement for specified object with proper path and class.

Parameters

objectNum (number)

Object number (1 to totalImages)

Returns

HTMLImageElement - Configured image element

showCentered(element)

PUBLIC
showCentered(element: HTMLElement): void

Positions element at center of test container and displays it.

Parameters

element (HTMLElement)

Element to center and show

Returns

void - Modifies DOM directly

showBlackScreen(duration)

PUBLIC
showBlackScreen(duration: number = 1000): void

Displays black overlay screen for specified duration (inter-stimulus interval).

Parameters

duration (number, optional)

Display duration in milliseconds. Default: 1000

Returns

void - Screen removed automatically after duration

hide(element)

PUBLIC
hide(element: HTMLElement): void

Hides element by setting display style to "none".

Parameters

element (HTMLElement)

Element to hide

Returns

void - Modifies element style

positionTestObjects(objects)

PUBLIC
positionTestObjects(objects: Array): void

Positions array of 3 test objects horizontally (left, center, right) and vertically centered.

Parameters

objects (Array)

Array of 3 HTMLElements to position

Returns

void - Modifies element positions

Layout

objects[0]: left   (containerWidth/2 - 200 - 30% offset)
objects[1]: center (containerWidth/2 - 200)
objects[2]: right  (containerWidth/2 - 200 + 30% offset)

See Also