Source benchmarks/approx/hmm.det
(* NEW EXAMPLE:2-state hidden model with state-dependent dwell times.This is essentially a hidden semi Markov model: https://en.wikipedia.org/wiki/Hidden_semi-Markov_model  The system is in one of two hidden states, z = 0 or z = 1.  At each step:    1. The current hidden state produces a discrete observation y.       The probability of y = 1 depends on the current hidden state.    2. We condition on the observation actually seen in `data`.    3. The system spends a random amount of time in the current state.       This "dwell time" is exponentially distributed, with a rate that       depends on the hidden state.    4. The system probabilistically transitions to the next hidden state.    5. We recursively process the remaining observations.  The return value is the SUM of all dwell times along the hidden-state  trajectory.*)(* Look up the i-th element of a list. *)let index = rec index xs => fun i =>  match xs with  [] => 1 / 0  | x :: rest =>      if i < 1 then x else index rest (i - 1)inlet equal = fun x => fun y =>  if x <= y then y <= x else falseinlet emit = 0.05 :: 0.25 :: [] inlet dwell_rate = 0.8 :: 1.2 :: [] inlet trans = 0.05 :: 0.5 :: [] inlet initial_state = 0 inlet data = 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: 0 :: [] inlet hmm = rec hmm z => fun data =>  match data with  [] => 0  | data :: remaining_data =>      (* Discrete observation generated by the current hidden state *)      let y = bernoulli(index emit z) in      let _ = observe(equal y data) in      (* Sample how long the process remains in the current hidden state. *)      let dwell = exponential(index dwell_rate z) in      (* Sample the next hidden state, either 0 or 1. Depends on the current state z. *)      let next_z = bernoulli(index trans z) in      let rest = hmm next_z remaining_data in      (* Return the total elapsed time: *)      dwell + restinhmm initial_state data