Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing Online Inference with Hidden Markov Models (HMMs) #22

Merged
merged 173 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
173 commits
Select commit Hold shift + click to select a range
0ccc128
Created new HMM package and added to solution
ncguilbeault Jun 4, 2024
2bbab74
Added load HMM module workflow
ncguilbeault Jun 4, 2024
967f85e
Added model parameters class to be used for initializing HMM model
ncguilbeault Jun 4, 2024
5fe0ae3
Moved to Bonsai.ML core namespace
ncguilbeault Jun 5, 2024
4f43fed
Added image
ncguilbeault Jun 5, 2024
cab2f9d
Updated csproj
ncguilbeault Jun 5, 2024
3b76ee3
Updated load hmm module to use main script
ncguilbeault Jun 5, 2024
8d41b1d
Added main script
ncguilbeault Jun 5, 2024
40b4c73
Updated model params class
ncguilbeault Jun 5, 2024
bee4bac
added most likely state class
ncguilbeault Jun 5, 2024
201917e
Updated to remove pydantic data classes
ncguilbeault Jun 5, 2024
5a1a0bb
Added json serialization
ncguilbeault Jun 6, 2024
7674ed8
Updated main python script
ncguilbeault Jun 6, 2024
ac8b0e1
Added state class
ncguilbeault Jun 6, 2024
dd4ab96
updated model params class
ncguilbeault Jun 6, 2024
41f0ea1
Downgraded package version
ncguilbeault Jun 6, 2024
a72b0ce
Updated main python script format
ncguilbeault Jun 6, 2024
feb02fd
Added item to extract means and stds from observations
ncguilbeault Jun 6, 2024
49b283f
Added visualizer to show state observation statistics
ncguilbeault Jun 6, 2024
3db716d
Added update plot call
ncguilbeault Jun 6, 2024
64fb552
Added create HMM workflow
ncguilbeault Jun 12, 2024
d1cfe66
Updated main python script to correctly compute log_alpha for inferri…
ncguilbeault Jun 12, 2024
b688e6d
Added state observation statistics visualizer and workflow
ncguilbeault Jun 12, 2024
d91b117
Updated package to use correct function for online state inference
ncguilbeault Jun 13, 2024
5b787de
Updated bar series base
ncguilbeault Jun 13, 2024
5f496d3
Updated state observation statistics visualizer
ncguilbeault Jun 13, 2024
5e3128b
Added new state probability visualizer
ncguilbeault Jun 13, 2024
5dab879
Updated script to ensure state probabilities attribute
ncguilbeault Jun 13, 2024
fd2df97
Updated bar plot to allow optional stroke color
ncguilbeault Jun 13, 2024
3ca6ae4
index on hidden-markov-models-dev: 4efde25 Updated bar plot to allow …
ncguilbeault Jun 14, 2024
7d2c6c7
Updated create HMM model workflow
ncguilbeault Jun 20, 2024
86d9f19
Updated main python script for running fit asynchronously
ncguilbeault Jun 20, 2024
926e12b
Added fit async workflow
ncguilbeault Jun 20, 2024
59dfd11
Added check fit finished workflow
ncguilbeault Jun 20, 2024
64fce50
Updated model parameters to use shared subject instead of subscribing…
ncguilbeault Jun 20, 2024
ade63bf
Updated state probability visualizer for consistent state labels
ncguilbeault Jun 20, 2024
199ce3c
Added clusters visualizer
ncguilbeault Jun 26, 2024
618b2e9
Updated main python script for clusters visualizer
ncguilbeault Jun 26, 2024
70183ad
Added clusters visualizer include workflow
ncguilbeault Jun 26, 2024
45870a1
Updated run fit async workflow to include vars to estimate
ncguilbeault Jun 26, 2024
2344e2e
Added vars to estimate in fit async function
ncguilbeault Jun 26, 2024
2346fee
Added HMM project to solution
ncguilbeault Jul 1, 2024
9fb3775
Added new observations namespace and expanded observations
ncguilbeault Jun 26, 2024
8207f39
Added tuple type to python helper
ncguilbeault Jul 1, 2024
197da5d
Updated project to target net standard 2.0 fx
ncguilbeault Jul 1, 2024
9a8bc20
Modified observation classes
ncguilbeault Jul 1, 2024
79eed01
Updated create hmm model to accept different observation models
ncguilbeault Jul 1, 2024
3527fd7
Updated main python script for different observation models
ncguilbeault Jul 1, 2024
1b12e55
Removed debugging lines
ncguilbeault Jul 1, 2024
fdf4af6
Updated to string method to include keyword
ncguilbeault Jul 1, 2024
f066532
Removed autoregressive observations
ncguilbeault Jul 1, 2024
d67356e
Modified to use json string converter for enum types
ncguilbeault Jul 1, 2024
54e1d30
Updated main python script to accept observation kwargs
ncguilbeault Jul 9, 2024
30989d2
Updated model parameters to use custom observation type json converter
ncguilbeault Jul 9, 2024
a12d8d0
Added state parameters json converter
ncguilbeault Jul 9, 2024
d318bdf
Updated state parameters to construct observations with optional kwargs
ncguilbeault Jul 9, 2024
531d8cb
Modified if-else statement to use null-coalescing operator
ncguilbeault Jul 9, 2024
e3164b0
Added new autoregressive observations class
ncguilbeault Jul 9, 2024
0097502
Modified existing observation classes to only deserialize params obje…
ncguilbeault Jul 9, 2024
0e5ef41
Added autoregressive observations
ncguilbeault Jul 9, 2024
ac48eff
Added custom observation type json converter
ncguilbeault Jul 9, 2024
52cebf6
Removed version tag from csproj
ncguilbeault Jul 9, 2024
00eb572
Changed name of state observation clusters/statistics to gaussian obs…
ncguilbeault Jul 9, 2024
f56bcfe
Changed names from just observation to observations
ncguilbeault Jul 9, 2024
c0351b3
Modified observations to observations base
ncguilbeault Jul 9, 2024
a3287d6
Updated include workflows with new names
ncguilbeault Jul 9, 2024
d5ade3b
Set batch observations and most probable states to default on init
ncguilbeault Jul 9, 2024
624a441
Updated observations names
ncguilbeault Jul 9, 2024
21b03c3
Updated gaussian observations statistics class and visualizers
ncguilbeault Jul 9, 2024
13dfd5a
Modified python script to infer states from batch after fitting
ncguilbeault Jul 9, 2024
871cd4c
Fixed issue in calculating covariance matrices
ncguilbeault Jul 9, 2024
a3004ef
Update axes titles on change in dimension selection
ncguilbeault Jul 9, 2024
ee6bb67
Updated fitting include workflow to use generalized observation params
ncguilbeault Jul 9, 2024
347cf81
Updated script to use scipy implementation of logsumexp
ncguilbeault Jul 9, 2024
c7ad5d6
Updated language version in csproj
ncguilbeault Jul 9, 2024
1d1ae07
Updated observations to dissociate observations model from observatio…
ncguilbeault Jul 9, 2024
d13cb16
Updated include workflow
ncguilbeault Jul 9, 2024
a3f54a1
Update to only permute if observations are gaussian
ncguilbeault Jul 10, 2024
5ee0ec0
Added new python string builder class
ncguilbeault Jul 10, 2024
b12756b
Updated classes to inherit from python string builder
ncguilbeault Jul 10, 2024
b5b894f
Added XML documentation
ncguilbeault Jul 10, 2024
86a7290
Removed description attributes
ncguilbeault Jul 10, 2024
bf85461
Added categorical observations
ncguilbeault Jul 10, 2024
704d42e
Added transition matrices base class and first transitions model (sta…
ncguilbeault Jul 10, 2024
b396d21
Updated main python script to support custom transition models
ncguilbeault Jul 10, 2024
e164fc7
Updated state parameters to use transitions model
ncguilbeault Jul 10, 2024
1407393
Updated model parameters to use updated state parameters
ncguilbeault Jul 10, 2024
7419f07
Externalized transitions type property in create model include workflow
ncguilbeault Jul 10, 2024
035f8f4
Modified run fit async function call to use transition params keyword
ncguilbeault Jul 10, 2024
bcb437f
Added comma in string builder line
ncguilbeault Jul 10, 2024
143d96e
Updated naming ins state parameters
ncguilbeault Jul 10, 2024
1215592
Fixed LogPs data type
ncguilbeault Jul 10, 2024
4382d03
Updated python helper to handle case when object is none
ncguilbeault Jul 10, 2024
2eefa02
Updated with newest language features
ncguilbeault Jul 10, 2024
d7e3586
Updated main python script to automatically convert lists to numpy ar…
ncguilbeault Jul 10, 2024
9af1146
Added custom JSON converter for model parameters
ncguilbeault Jul 10, 2024
6d5a7bb
Improved document formatting
ncguilbeault Jul 10, 2024
2a520f2
Simplified state parameters object creation
ncguilbeault Jul 10, 2024
8978763
Removed json property attribute on lags property
ncguilbeault Jul 10, 2024
8580067
Changed properties from private set to public set
ncguilbeault Jul 10, 2024
6d94d06
Modified constructor to check args before setting
ncguilbeault Jul 10, 2024
83a16ff
Added check to set value to None if null
ncguilbeault Jul 10, 2024
ec6edd5
Moved read json and write json methods for consistency
ncguilbeault Jul 10, 2024
95c9578
Added quotes to native string data types.
ncguilbeault Jul 10, 2024
df1577c
Added constrained stationary transitions
ncguilbeault Jul 10, 2024
f6a554d
Added sticky transitions model
ncguilbeault Jul 10, 2024
e51d6e0
Added neural network recurrent transitions
ncguilbeault Jul 10, 2024
5bf4142
Updated stationary transitions for consistency
ncguilbeault Jul 10, 2024
39d5328
Added Bonsai scripting to package references
ncguilbeault Jul 11, 2024
a15bc38
Updated main readme to include HMM package
ncguilbeault Jul 11, 2024
40f3fd5
Added HMM docs and basic bonsai workflow
ncguilbeault Jul 11, 2024
787defe
Removed visual c++ redistributable dependency
ncguilbeault Jul 11, 2024
3827cbd
Removed the word powershell
ncguilbeault Jul 11, 2024
8f810e8
Removed unnecessary new keyword
ncguilbeault Jul 11, 2024
7d98c52
Updated bonsai workflow
ncguilbeault Jul 11, 2024
6c4ce19
Changed tip sections for improved readability
ncguilbeault Jul 11, 2024
c768bc9
Changed spaces to tabs
ncguilbeault Jul 11, 2024
00404f5
Modified getting started section to better communicate workflow
ncguilbeault Jul 11, 2024
ae79d49
Added pickle functions to save/load model
ncguilbeault Jul 12, 2024
4d47b1e
Added operator to format a data type to a python list string
ncguilbeault Jul 12, 2024
d48123e
Added comment that it does not support nested enumerables
ncguilbeault Jul 12, 2024
3208ee4
Set default timer frequency to 1s
ncguilbeault Jul 12, 2024
6c03c72
Changed type from long to int
ncguilbeault Jul 15, 2024
e5b6837
Updated HMM model implementation general workflow
ncguilbeault Jul 16, 2024
05007b9
Updated package version
ncguilbeault Jul 16, 2024
6593c57
Added bonsai scriting expressions package because of dependency in in…
ncguilbeault Jul 16, 2024
723a3a1
Added new Bonsai.ML.Python project and moved python helpers from the …
ncguilbeault Sep 2, 2024
c0cdca8
Updated docs with new names
ncguilbeault Sep 2, 2024
3f2b909
Updated project reference to Bonsai.ML.Python
ncguilbeault Sep 2, 2024
51cce87
Updated classes to use same naming convention as SSM package
ncguilbeault Sep 2, 2024
f9fcf50
Added Bonsai.ML.Python import
ncguilbeault Sep 2, 2024
1bb4560
Updated naming to ObservationsModel
ncguilbeault Sep 2, 2024
410b39f
Merged process logic into single class for all classes of observations
ncguilbeault Sep 2, 2024
36c266e
Updated naming to TransitionsModel
ncguilbeault Sep 2, 2024
9ae9ecb
Removed Transitions classes with previous naming convention
ncguilbeault Sep 2, 2024
11158ed
Merged process logic into single class for all types of transitions
ncguilbeault Sep 2, 2024
2eca793
Removed old transitions lookup
ncguilbeault Sep 2, 2024
634d6d5
Downgraded package reference for compatibility
ncguilbeault Sep 2, 2024
5e082ad
Update csproj to reference Bonsai.ML project
ncguilbeault Sep 2, 2024
9cd0ec6
Update include workflow to reference the correct class
ncguilbeault Sep 2, 2024
4834edd
Updated include workflow for correct property naming
ncguilbeault Sep 2, 2024
78aeaf1
Updated naming to avoid clashes with underlying ssm package
ncguilbeault Sep 2, 2024
9cd0de2
Updated to support recurrent neural networks properly
ncguilbeault Sep 2, 2024
458a200
Fixed issue in python class with nonlinearity naming clash
ncguilbeault Sep 3, 2024
349bc9e
Updated variable name
ncguilbeault Sep 3, 2024
9542837
Updated properties to hidden
ncguilbeault Sep 3, 2024
e64824e
Updated build string to fix issue when param is null
ncguilbeault Sep 3, 2024
53e9b77
Updated all names with s for consistency
ncguilbeault Sep 3, 2024
fd01db4
Added abstract python model
ncguilbeault Sep 3, 2024
0ecac05
Update include workflow for new naming
ncguilbeault Sep 3, 2024
c02d662
Fixed issue with retrieving nonlinearity type of nn_recurrent
ncguilbeault Sep 3, 2024
5da19bc
Fixed issue with deserializing observations
ncguilbeault Sep 3, 2024
f680093
Fixed JSON naming
ncguilbeault Sep 3, 2024
46795ec
Hide properties
ncguilbeault Sep 3, 2024
b17377e
Change base model classes to inherit from python model
ncguilbeault Sep 3, 2024
6505dd6
Update observations to reflect new model structure
ncguilbeault Sep 3, 2024
066d86e
Updated wording in README
ncguilbeault Sep 3, 2024
f2ee345
Updated naming to better reflect target type
ncguilbeault Sep 3, 2024
c59dc46
Fixed incorrect naming in XML doc
ncguilbeault Sep 3, 2024
e501bbe
Updated XML doc strings
ncguilbeault Sep 3, 2024
fb25c01
Updated readme
ncguilbeault Sep 4, 2024
585d275
Added Bonsai.ML.Data project for common data tools
ncguilbeault Sep 4, 2024
d1be315
Added array helper to data project
ncguilbeault Sep 4, 2024
a3197bf
Updated projects to utilize shared element icon
ncguilbeault Sep 4, 2024
ba56460
Updated to use Bonsai.ML.Data
ncguilbeault Sep 4, 2024
bdf325c
Moved numpy parser to array tools since this process is more generic …
ncguilbeault Sep 4, 2024
73aa221
Added XML docs
ncguilbeault Sep 4, 2024
2b6ba24
Moved formatter to Bonsai.ML.Python and added support for nesting dat…
ncguilbeault Sep 4, 2024
4be22ea
Removed depth argument
ncguilbeault Sep 4, 2024
028768b
Moved action definitions directly to CreateTypeHandler function.
ncguilbeault Sep 4, 2024
71d71ba
Updated Exception to ArgumentException
ncguilbeault Sep 5, 2024
b08e183
Updated to pass arguments in exception
ncguilbeault Sep 5, 2024
7e3e7cf
Update hmm docs
ncguilbeault Sep 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Bonsai.ML.sln
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bonsai.ML.HiddenMarkovModels", "src\Bonsai.ML.HiddenMarkovModels\Bonsai.ML.HiddenMarkovModels.csproj", "{BAD0A733-8EFB-4EAF-9648-9851656AF7FF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bonsai.ML.Python", "src\Bonsai.ML.Python\Bonsai.ML.Python.csproj", "{39A4414F-52B1-42D7-82FA-E65DAD885264}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bonsai.ML.Data", "src\Bonsai.ML.Data\Bonsai.ML.Data.csproj", "{A135C7DB-EA50-4FC6-A6CB-6A5A5CC5FA13}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -42,6 +48,18 @@ Global
{81DB65B3-EA65-4947-8CF1-0E777324C082}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81DB65B3-EA65-4947-8CF1-0E777324C082}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81DB65B3-EA65-4947-8CF1-0E777324C082}.Release|Any CPU.Build.0 = Release|Any CPU
{BAD0A733-8EFB-4EAF-9648-9851656AF7FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAD0A733-8EFB-4EAF-9648-9851656AF7FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAD0A733-8EFB-4EAF-9648-9851656AF7FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAD0A733-8EFB-4EAF-9648-9851656AF7FF}.Release|Any CPU.Build.0 = Release|Any CPU
{39A4414F-52B1-42D7-82FA-E65DAD885264}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{39A4414F-52B1-42D7-82FA-E65DAD885264}.Debug|Any CPU.Build.0 = Debug|Any CPU
{39A4414F-52B1-42D7-82FA-E65DAD885264}.Release|Any CPU.ActiveCfg = Release|Any CPU
{39A4414F-52B1-42D7-82FA-E65DAD885264}.Release|Any CPU.Build.0 = Release|Any CPU
{A135C7DB-EA50-4FC6-A6CB-6A5A5CC5FA13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A135C7DB-EA50-4FC6-A6CB-6A5A5CC5FA13}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A135C7DB-EA50-4FC6-A6CB-6A5A5CC5FA13}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A135C7DB-EA50-4FC6-A6CB-6A5A5CC5FA13}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -51,6 +69,9 @@ Global
{17AABD18-E275-4409-9E33-3D755B809FF6} = {12312384-8828-4786-AE19-EFCEDF968290}
{196AA5C7-AE8A-477B-B01A-B94676EC60EE} = {12312384-8828-4786-AE19-EFCEDF968290}
{81DB65B3-EA65-4947-8CF1-0E777324C082} = {461FE3E2-21C4-47F9-8405-DF72326AAB2B}
{BAD0A733-8EFB-4EAF-9648-9851656AF7FF} = {12312384-8828-4786-AE19-EFCEDF968290}
{39A4414F-52B1-42D7-82FA-E65DAD885264} = {12312384-8828-4786-AE19-EFCEDF968290}
{A135C7DB-EA50-4FC6-A6CB-6A5A5CC5FA13} = {12312384-8828-4786-AE19-EFCEDF968290}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B6468F13-97CD-45E0-9E1E-C122D7F1E09F}
Expand Down
8 changes: 5 additions & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@
<PackageIcon>icon.png</PackageIcon>
<IncludeSymbols>true</IncludeSymbols>
<RepositoryType>git</RepositoryType>
<VersionPrefix>0.2.0</VersionPrefix>
<VersionPrefix>0.3.0</VersionPrefix>
<VersionSuffix></VersionSuffix>
<LangVersion>9.0</LangVersion>
<LangVersion>12.0</LangVersion>
</PropertyGroup>

<ItemGroup>
<Content Include="..\..\LICENSE" PackagePath="/" />
<Content Include="..\..\icon.png" PackagePath="/" />
<None Include="..\..\README.md" Pack="True" PackagePath="/" />
<EmbeddedResource Include="..\..\elementIcon.svg" >
<LogicalName>$(RootNamespace).$(MSBuildProjectName).svg</LogicalName>
</EmbeddedResource>
</ItemGroup>
</Project>
44 changes: 36 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,44 @@
# Bonsai - Machine Learning

The Bonsai.ML project is a collection of packages with reactive infrastructure for adding machine learning algorithms in Bonsai. Below you will find the list of packages (and the included subpackages) currently available within the Bonsai.ML collection.
The **Bonsai.ML** project is a collection of packages designed to integrate machine learning algorithms with Bonsai. This document provides an overview of the available packages and their functionalities.

* Bonsai.ML - provides core functionality across all Bonsai.ML packages.
* Bonsai.ML.LinearDynamicalSystems - package for performing inference of linear dynamical systems. Interfaces with the [lds_python](https://github.com/joacorapela/lds_python) package.
- *Bonsai.ML.LinearDynamicalSystems.Kinematics* - subpackage included in the LinearDynamicalSystems package which supports using the Kalman Filter to infer kinematic data.
- *Bonsai.ML.LinearDynamicalSystems.LinearRegression* - subpackage included in the LinearDynamicalSystems package which supports using the Kalman Filter to perform Bayesian linear regression.
* Bonsai.ML.Visualizers - provides a set of visualizers for dynamic graphing/plotting.
## Core Packages

- **Bonsai.ML**
Provides common tools and functionality.

- **Bonsai.ML.Data**
Provides common tools and functionality for working with data.

- **Bonsai.ML.Python**
Provides common tools and functionality for C# packages to interface with Python.

## Available Packages

### Bonsai.ML.LinearDynamicalSystems
Facilitates inference using linear dynamical systems (LDS). It interfaces with the [lds_python](https://github.com/joacorapela/lds_python) package using the [Bonsai - Python Scripting](https://github.com/bonsai-rx/python-scripting) library.

- **Bonsai.ML.LinearDynamicalSystems.Kinematics**
Supports the use of the Kalman Filter for inferring kinematic data.

- **Bonsai.ML.LinearDynamicalSystems.LinearRegression**
Utilizes the Kalman Filter to perform online Bayesian linear regression.

### Bonsai.ML.HiddenMarkovModels
Facilitates inference using Hidden Markov Models (HMMs). It interfaces with the [ssm](https://github.com/lindermanlab/ssm) package using the [Bonsai - Python Scripting](https://github.com/bonsai-rx/python-scripting) library.

- **Bonsai.ML.HiddenMarkovModels.Observations**
Provides functionality for specifying different types of observations.

- **Bonsai.ML.HiddenMarkovModels.Transitions**
Provides functionality for specifying different types of transition models.

### Bonsai.ML.Visualizers
Graphing and plotting library for visualizing data.

> [!NOTE]
> Bonsai.ML packages are installed through Bonsai's integrated package manager and are typically available for use immediately. However, certain packages may require additional steps for installation. See the dedicated package section for specific guides and documentation.
> Bonsai.ML packages can be installed through Bonsai's integrated package manager and are generally ready for immediate use. However, some packages may require additional installation steps. Refer to the specific package section for detailed installation guides and documentation.

## Acknowledgments

Development of this package was supported by funding from the Biotechnology and Biological Sciences Research Council [grant number BB/W019132/1].
Development of the Bonsai.ML package is supported by the Biotechnology and Biological Sciences Research Council [grant number BB/W019132/1].
47 changes: 47 additions & 0 deletions docs/articles/HiddenMarkovModels/hmm-getting-started.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Getting Started

The workflow starts with creating a python runtime, followed by loading the ssm package, referred to as the HMM module. After this, you can instantiate the HMM model and pass it observations of data to perform inference. Since this package relies on communication between Bonsai and Python, the observations that the model uses must be formatted into a valid string representation of a Python data type, namely a list of numbers.

## Workflow

```mermaid

flowchart LR

A(["Create Python Runtime"])
B(["Load HMM Module"])
C(["Create HMM"])
D(["Generate Observations"])
E(["Infer Hidden State"])

A --> B
B --> C
C --> D
D --> E

```

> [!NOTE]
> Due to the way Bonsai.ML interacts with Python, it is necessary for the first two steps to complete before instantiating the model. It is important to know that the initialization of the Python runtime, loading the module, and creating the model takes time to complete, and that only once the model has been created can inference be performed.

## Implementation

Below is a simplified Bonsai workflow that implements the core logic of the package.

:::workflow
![HMM Implementation](~/workflows/HMMImplementation.bonsai)
:::

A `CreateRuntime` node is used to initialize a python runtime engine, which gets passed to a `BehaviorSubject` called `PythonEngine`. Bonsai's `CreateRuntime` node should automatically detect the python virtual environment if it was activated in the same terminal that was used to launch Bonsai, otherwise the path to the virtual environment can be specified in the `CreateRuntime` node by setting the `PythonHome` property.

Next, the `PythonEngine` node is passed to a `LoadHMMModule` node which will load the ssm package into the python environment.

Once the HMM module has been initialized, the `CreateHMM` node instantiates a python instance of the HMM model. Here, you can specify the initialization parameters of the model and provide a `ModelName` parameter that gets used to reference the model in other parts of the Bonsai workflow.

It is crucial that the `Data` are formatted into a string that the model can use, namely a string representing a Python list. For example, if you pass a Tuple with 2 items as your data, then the formatter should look something like `"[" + Item1.ToString() + Item2.ToString() + "]"`. The output of this should be used as your observations into the model, so connect your data source to a `Subject` named `Data` and modify the `FormatToPython` node to fit with your data.

`Observations` are then passed to an `InferState` node, which will use the specified model (given by the `ModelName` property) to infer the latent state of the model and outputs the `StateProbabilities`, or probabilities of being in each state given the observation.

### Further Examples

For further examples and demonstrations for how this package works, see the [Bonsai - Machine Learning Examples](~/examples/README.md) section.
134 changes: 134 additions & 0 deletions docs/articles/HiddenMarkovModels/hmm-overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Bonsai.ML.HiddenMarkovModels Overview

The HiddenMarkovModels package provides a Bonsai interface to interact with the [ssm](https://github.com/lindermanlab/ssm) package.

## General Guide

Since the package relies on both Bonsai and Python, installation steps for both are required. Detailed instructions are provided for installing the package in a new environment, integrating it with existing workflows, and running examples from the example folder.

- To install the package for integrating with existing workflows, see the [Installation Guide](#installation-guide).
- To get started with integrating the package into workflows, see the [Getting Started](hmm-getting-started.md) section.
- To test the specific examples provided, check out the [Examples](~/examples/README.md) tab.

## Installation Guide

### Dependencies

To get started, you must install the following tools:

- [Python (v3.10)](https://www.python.org/downloads/)
- [dotnet-sdk (v8)](https://dotnet.microsoft.com/en-us/download)
- [Git](https://git-scm.com/downloads)
- [Bonsai-Rx Templates tool](https://www.nuget.org/packages/Bonsai.Templates)

> [!TIP]
> Install Python through the standard installer and add to the system PATH.

### Installation Guide - Windows

#### Creating New Project Environment

1. Open the terminal and create a project folder:
```cmd
cd ~\Desktop
mkdir HiddenMarkovModels
cd .\HiddenMarkovModels
```

2. Create a Python virtual environment:
```cmd
python -m venv .venv
```

3. Create a Bonsai environment:
```cmd
dotnet new bonsaienv
```

#### Python Environment Setup

1. Activate the Python environment:
```cmd
.\.venv\Scripts\activate
```

2. Install the ssm package:
```cmd
pip install numpy cython
pip install ssm@git+https://github.com/lindermanlab/ssm@6c856ad3967941d176eb348bcd490cfaaa08ba60
```

3. Verify installation:
```python
import ssm
```

#### Bonsai Environment Setup

1. Launch Bonsai:
```cmd
.bonsai\Bonsai.exe
```

2. Install the `Bonsai.ML.HiddenMarkovModels` package from the Package Manager.
> [!TIP]
> You can quickly search for the package by entering `Bonsai.ML.HiddenMarkovModels` into the search bar.

### Installation Guide - Linux

#### Creating New Project Environment

1. Create a project folder:
```cmd
cd ~/Desktop
mkdir HiddenMarkovModels
cd HiddenMarkovModels
```

2. Create a Python virtual environment:
```cmd
python3 -m venv .venv
```
> [!TIP]
> Install the virtual environment package if needed:
> ```cmd
> sudo apt install python3.10-venv
> ```

3. Create a Bonsai environment:
```cmd
dotnet new bonsaienv
```
> [!NOTE]
> This step uses the [Bonsai Linux Environment Template tool](https://github.com/ncguilbeault/bonsai-linux-environment-template) for easy creation of bonsai environments on Linux.
> See [this discussion](https://github.com/orgs/bonsai-rx/discussions/1101) for more information on getting Bonsai running on Linux.

#### Python Environment Setup

1. Activate the Python environment:
```cmd
source .venv/bin/activate
```

2. Install the ssm package:
```cmd
pip install numpy cython
pip install ssm@git+https://github.com/lindermanlab/ssm@6c856ad3967941d176eb348bcd490cfaaa08ba60
```

3. Verify installation:
```python
import ssm
```

#### Bonsai Environment Setup

1. Activate and launch Bonsai:
```cmd
source .bonsai/activate
bonsai
```

2. Install the `Bonsai.ML.HiddenMarkovModels` package from the Package Manager.
> [!TIP]
> You can quickly search for the package by entering `Bonsai.ML.HiddenMarkovModels` into the search bar.
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ python3 -m venv .venv
dotnet new bonsaienvl
```

When prompted, enter yes to run the powershell setup script.
When prompted, enter yes to run the setup script.

### Python Environment Setup Guide

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ To get started, you must install the following tools:
- [dotnet-sdk (v8)](https://dotnet.microsoft.com/en-us/download)
- [Git](https://git-scm.com/downloads)
- [Bonsai-Rx Templates tool](https://www.nuget.org/packages/Bonsai.Templates)
- [Microsoft Visual C++ Redistributable](https://aka.ms/vs/16/release/vc_redist.x64.exe)

> [!WARNING]
> Be sure to check the specific python version and dotnet-sdk version you have installed, as different version than the ones we recommend may or may not work with this guide.
Expand All @@ -32,7 +31,7 @@ python -m venv .venv
```

> [!TIP]
> If receive an error that says, `python cannot be found`, check to ensure that python is available on the system path. If you just installed python, it may be necessary to restart the terminal.
> If you receive an error that says, `python cannot be found`, check to ensure that python is available on the system path. If you just installed python, it may be necessary to restart the terminal.

3. Create a bonsai environment. When prompted, enter yes to run the powershell setup script.

Expand Down
7 changes: 6 additions & 1 deletion docs/articles/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,9 @@
- name: Installing on Linux
href: LinearDynamicalSystems/lds-installation-guide-linux.md
- name: Getting Started
href: LinearDynamicalSystems/lds-getting-started.md
href: LinearDynamicalSystems/lds-getting-started.md
- name: HiddenMarkovModels
- name: Overview
href: HiddenMarkovModels/hmm-overview.md
- name: Getting Started
href: HiddenMarkovModels/hmm-getting-started.md
56 changes: 56 additions & 0 deletions docs/workflows/HMMImplementation.bonsai
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<WorkflowBuilder Version="2.8.5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:py="clr-namespace:Bonsai.Scripting.Python;assembly=Bonsai.Scripting.Python"
xmlns:rx="clr-namespace:Bonsai.Reactive;assembly=Bonsai.Core"
xmlns:p1="clr-namespace:Bonsai.ML.HiddenMarkovModels;assembly=Bonsai.ML.HiddenMarkovModels"
xmlns="https://bonsai-rx.org/2018/workflow">
<Workflow>
<Nodes>
<Expression xsi:type="Combinator">
<Combinator xsi:type="py:CreateRuntime" />
</Expression>
<Expression xsi:type="rx:BehaviorSubject">
<Name>PythonEngine</Name>
</Expression>
<Expression xsi:type="SubscribeSubject">
<Name>PythonEngine</Name>
</Expression>
<Expression xsi:type="IncludeWorkflow" Path="Bonsai.ML.HiddenMarkovModels:LoadHMMModule.bonsai" />
<Expression xsi:type="IncludeWorkflow" Path="Bonsai.ML.HiddenMarkovModels:CreateHMM.bonsai">
<Name>hmm</Name>
<NumStates>2</NumStates>
<Dimensions>2</Dimensions>
<ObservationsType>Gaussian</ObservationsType>
<TransitionsType>Stationary</TransitionsType>
</Expression>
<Expression xsi:type="SubscribeSubject">
<Name>Data</Name>
</Expression>
<Expression xsi:type="Combinator">
<Combinator xsi:type="p1:FormatToPythonList" />
</Expression>
<Expression xsi:type="rx:BehaviorSubject">
<Name>Observation</Name>
</Expression>
<Expression xsi:type="SubscribeSubject">
<Name>Observation</Name>
</Expression>
<Expression xsi:type="IncludeWorkflow" Path="Bonsai.ML.HiddenMarkovModels:InferState.bonsai">
<Name>hmm</Name>
</Expression>
<Expression xsi:type="rx:BehaviorSubject">
<Name>InferredState</Name>
</Expression>
</Nodes>
<Edges>
<Edge From="0" To="1" Label="Source1" />
<Edge From="2" To="3" Label="Source1" />
<Edge From="3" To="4" Label="Source1" />
<Edge From="5" To="6" Label="Source1" />
<Edge From="6" To="7" Label="Source1" />
<Edge From="8" To="9" Label="Source1" />
<Edge From="9" To="10" Label="Source1" />
</Edges>
</Workflow>
</WorkflowBuilder>
File renamed without changes
Loading
Loading