This vignette walks through the Hidden Markov Model (HMM) workflow in FlyDreamR, including fitting and plotting.
Fit an HMM
After preparing your dataset with HMMDataPrep(), you can
fit an HMM using:
-
HMMbehavr()(single-threaded) -
HMMbehavrFast()(parallel; faster on multi-core machines)
# Load demo data
meta_file <- system.file("extdata", "Metadata_Monitor1.csv", package = "FlyDreamR")
data_dir <- system.file("extdata", package = "FlyDreamR")
dt <- HMMDataPrep(
metafile_path = meta_file,
result_dir = data_dir,
ldcyc = 12,
day_range = c(1, 2)
)
# Serial: choose 3, 4, or 5 states (default: 4)
res <- HMMbehavr(behavtbl = dt, it = 100, ldcyc = 12, n_states = 4)
# Parallel
res_prl <- HMMbehavrFast(behavtbl = dt, it = 100, ldcyc = 12,
n_cores = 4, n_states = 4)
# Check any fly-days that could not be fitted
res$QualityReportQualityReport has one row per attempted fly-day. Check
status, reason_code, and reason
before interpreting the plots or summaries. Failed fly-days do not
contribute fitted states. State labels are ordered by activity; the
biological descriptions used for the original four-state model should
not be assumed for three- or five-state fits.
Plot HMM state profiles
FlyDreamR provides convenient plotting helpers:
-
HMMplot()for heatmap hypnograms -
HMMFacetedPlot()to facet individual hypnograms -
HMMSinglePlot()to save individual hypnograms to disk
# Heatmap hypnograms
HMMplot(res)
# Use a different built-in palette
HMMplot(res, color_palette = "AG")
# Compare serial vs parallel fits
library(patchwork)
HMMplot(res, color_palette = "AG") / HMMplot(res_prl, color_palette = "AG")
# User-defined colors
HMMplot(
res,
color_palette = "user",
user_colors = c(
"State0" = "#FF0060",
"State1" = "#F6FA70",
"State2" = "#00DFA2",
"State3" = "#0079FF"
)
)
# Faceted + save-to-disk helpers
HMMFacetedPlot(res)
HMMSinglePlot(res)Summarize time spent in each state
TimeSpentInEachState summarizes how many minutes each
fly spent in each inferred state per day and phase.
VITERBIDecodedProfile contains the full minute-by-minute
decoded state sequence for every fly.
The HMM results typically include:
-
TimeSpentInEachState(summaries) -
VITERBIDecodedProfile(decoded state sequences) -
QualityReport(fit status and reason for each fly-day)
You can visualize time spent per state with ggplot2:
ggplot2::ggplot(res$TimeSpentInEachState,
ggplot2::aes(x = state_name, y = time_spent, fill = state_name)) +
ggplot2::geom_boxplot(width = 0.35, outliers = FALSE) +
ggplot2::facet_grid(day ~ phase, scales = "free_y") +
ggplot2::theme_minimal()