Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
26b3070
Add Sphinx documentation and Read the Docs config
PalashChitnavis Aug 10, 2025
946ec33
Update user guide with usage and issues sections
PalashChitnavis Aug 10, 2025
cb69673
Automate API docs generation in Sphinx config
PalashChitnavis Aug 11, 2025
b5b517c
Remove custom API doc generation from Sphinx config
PalashChitnavis Aug 11, 2025
d31dcc5
Update documentation and add publish guide
PalashChitnavis Aug 18, 2025
4748913
Add examples to documentation
PalashChitnavis Aug 19, 2025
ee55a54
Add developer docs
PalashChitnavis Aug 20, 2025
8d740d8
Add deployment guide and images for GitHub Pages
PalashChitnavis Aug 23, 2025
4c806a2
Revise and expand user documentation for Brian2WASM
PalashChitnavis Aug 23, 2025
6d4fae4
Add detailed docstrings and improve Sphinx config
PalashChitnavis Aug 24, 2025
0827141
Update documentation and add requirements for RTD
PalashChitnavis Aug 28, 2025
f0156c1
Update CLI docstring and remove unused references
PalashChitnavis Aug 28, 2025
8dbe146
Merge branch 'main' into sphinx
PalashChitnavis Aug 28, 2025
7d7fd60
Improve docstrings and Sphinx config
PalashChitnavis Aug 28, 2025
4c38624
Add --skip-install flag to example test command
PalashChitnavis Aug 28, 2025
784ed9e
Remove emoji from status and error messages
PalashChitnavis Aug 28, 2025
b3d69b2
Run tests on push instead of pull request
PalashChitnavis Aug 31, 2025
9ebd7d6
Install local brian2wasm in PR test workflow
PalashChitnavis Aug 31, 2025
813452c
Enable full history and tags in checkout step
PalashChitnavis Aug 31, 2025
25a43b3
Set fixed version for editable install in CI
PalashChitnavis Aug 31, 2025
4350ef7
Update local brian2wasm install in test workflow
PalashChitnavis Aug 31, 2025
ca3fd6e
Install local package with pixi
mstimberg Sep 3, 2025
bcd4455
Make sure that Windows uses nmake
mstimberg Sep 3, 2025
2a73a91
Run tests on pull request events
PalashChitnavis Sep 3, 2025
ba4e6a9
Update setuptools_scm
mstimberg Sep 3, 2025
e1a9eb3
Remove redundant workflow steps
mstimberg Sep 3, 2025
9d6377b
Do not link "advapi32" library
mstimberg Sep 3, 2025
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ examples/output/
*.egg-info
pixi.lock
brian2wasm/_version.py
/dist
/dist

/docs/_build
20 changes: 20 additions & 0 deletions .readthedocs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the OS, Python version and other tools you might need
build:
os: 'ubuntu-22.04'
tools:
python: "3.12"

# Build documentation in the "docs/" directory with Sphinx
sphinx:
configuration: docs/conf.py

python:
install:
- requirements: rtd-requirements.txt
375 changes: 340 additions & 35 deletions brian2wasm/device.py

Large diffs are not rendered by default.

30 changes: 27 additions & 3 deletions brian2wasm/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,31 @@
''')
@check_units(i=1, t=second, result=1)
def send_spike(i, t):
'''
Send a spike message to JavaScript
'''
"""
Send a spike message to JavaScript.

This function injects JavaScript code via Emscripten's ``EM_ASM`` to send a spike event
message to the JavaScript environment, typically for visualization or processing in a
browser-based WebAssembly simulation.

Parameters
----------
i : int
The index of the neuron or synapse emitting the spike.
t : Quantity
The time of the spike event, with units of seconds.

Returns
-------
float
A dummy return value of 0.0, as the function's primary effect is the JavaScript
message dispatch.

Notes
-----
This function is implemented in C++ using the ``@implementation`` decorator, which
defines a JavaScript ``postMessage`` call to send a message of type 'spike' with the
neuron index and time. The Python function body is a no-op (``pass``), as the actual
implementation is handled in C++ and executed in the WebAssembly environment.
"""
pass
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
47 changes: 47 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import sys

sys.path.insert(0, os.path.abspath(".."))


# -- Project information -----------------------------------------------------

project = 'brian2wasm'
copyright = '2025, Palash Chitnavis'
author = 'Palash Chitnavis'
release = '0.1.0'

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx_rtd_theme',
"sphinx.ext.napoleon",
"sphinx.ext.viewcode",
'sphinxcontrib.mermaid',
]

napoleon_google_docstring = False
napoleon_numpy_docstring = True
napoleon_include_private_with_doc = True
napoleon_include_special_with_doc = True

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']



# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
152 changes: 152 additions & 0 deletions docs/developer/compilation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
Compilation and Code Generation Pipeline
=======================================

Overview
--------

The brian2wasm compilation pipeline transforms Brian2 neural network simulations into WebAssembly modules for browser execution. The system consists of three integrated components: template-based code generation, cross-platform build system, and Emscripten compilation toolchain.

Architecture
------------

The pipeline is orchestrated by the :code:`WASMStandaloneDevice` class, which inherits from Brian2's :code:`CPPStandaloneDevice` and redirects simulation execution toward WebAssembly compilation.

.. mermaid::
:align: center

%%{init: {'theme': 'default', 'themeVariables': { 'fontSize': '10px'}}}%%
graph TB

A[Brian2 Simulation Files]
B[array_specs]
C[dynamic_array_specs]
D[networks]
E[synapses]
F[clocks]
G["objects.cpp Template"]
H["objects.h"]
I["objects.cpp"]
J["C++ Functions"]
K["_init_arrays()"]
L["_load_arrays()"]
M["_write_arrays()"]
N["set_variable_by_name()"]

A --> G
B --> G
C --> G
D --> G
E --> G
F --> G
G --> H
G --> I
I --> J
J --> K
J --> L
J --> M
J --> N

Code Generation Templates
-------------------------

Objects Template System
~~~~~~~~~~~~~~~~~~~~~~~

The :code:`objects.cpp` template generates comprehensive C++ simulation code from Brian2 objects. Key components include:

* **Array Management**: Handles static arrays, dynamic arrays (1D/2D), and timed arrays with automatic memory allocation
* **Data Type Mapping**: Converts Brian2 types to C++ equivalents (:code:`double`, :code:`float`, :code:`int32_t`, :code:`int64_t`, :code:`char`)
* **Variable Setting**: Supports both scalar value assignment and binary file loading

The template generates four core functions:

* :code:`_init_arrays()`: Initialize simulation arrays with zero, arange, or file-based data
* :code:`_load_arrays()`: Load static arrays from binary files
* :code:`_write_arrays()`: Export results to browser via Emscripten interface
* :code:`set_variable_by_name()`: Runtime variable modification support

Template Integration
~~~~~~~~~~~~~~~~~~~~

The device generates templates through the :code:`generate_objects_source()` method, passing simulation specifications including array specs, dynamic arrays, networks, and synapses.

Build System
------------

Cross-Platform Makefile Generation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The build system generates platform-specific makefiles using Jinja2 templates:

* **Unix/Linux**: Standard makefile with dependency tracking
* **Windows**: nmake-compatible makefile with explicit compilation rules

Platform detection occurs in the :code:`generate_makefile()` method, which selects appropriate templates based on :code:`os.name`.

Emscripten Configuration
~~~~~~~~~~~~~~~~~~~~~~~~

The build system configures Emscripten with optimized flags:

**Optimization Flags**:
* :code:`-O3`: Maximum optimization
* :code:`-ffast-math`: Fast floating-point operations
* :code:`-fno-finite-math-only`: Preserve NaN/infinity handling

**WebAssembly Flags**:
* :code:`-fwasm-exceptions`: Exception handling support
* :code:`-sALLOW_MEMORY_GROWTH`: Dynamic memory allocation
* :code:`-sMODULARIZE=1`: Modular WebAssembly generation
* :code:`-sENVIRONMENT=worker`: Web Worker compatibility

EMSDK Management
~~~~~~~~~~~~~~~~

The system handles Emscripten SDK activation through preference-based configuration:

* Automatic EMSDK path resolution from preferences or environment variables
* Conditional activation scripts for Unix systems
* Cross-platform compiler flag filtering to remove unsupported options

Compilation Pipeline Flow
-------------------------

1. **Device Activation**: :code:`WASMStandaloneDevice.activate()` configures templater and headers

2. **Code Generation**:
* :code:`generate_objects_source()` creates C++ simulation code
* :code:`generate_makefile()` produces build configuration
* :code:`copy_source_files()` deploys runtime assets

3. **Compilation**: Emscripten compiles C++ to WebAssembly with:
* Object file generation from source files
* Dependency tracking through :code:`make.deps`
* Final linking with JavaScript preamble and preloaded files

4. **Runtime Integration**: Generated :code:`wasm_module.js` integrates with browser runtime through Web Workers

Build Artifacts
---------------

The compilation produces:

* :code:`wasm_module.js`: Main WebAssembly module with JavaScript interface
* :code:`wasm_module.wasm`: WebAssembly bytecode
* :code:`index.html`: Default web interface (auto-generated if not provided)
* Binary result files for simulation output
* Static array files for preloaded data

Progress Reporting
------------------

The system implements C++ to JavaScript communication through Emscripten's :code:`EM_ASM` interface, enabling real-time progress updates during simulation execution.

Configuration
-------------

Key preferences control compilation behavior:

* :code:`devices.wasm_standalone.emsdk_directory`: EMSDK installation path
* :code:`devices.wasm_standalone.emsdk_version`: EMSDK version selection

The pipeline provides a seamless bridge from high-level Brian2 Python code to optimized WebAssembly execution in web browsers.
96 changes: 96 additions & 0 deletions docs/developer/core.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
Core Architecture
=================

The :code:`brian2wasm` architecture is built around a custom Brian2 device that intercepts the normal simulation execution flow and redirects it to WebAssembly compilation. The system transforms Python/Brian2 code into C++, compiles it with Emscripten, and packages the result with JavaScript runtime components for browser execution.

System Overview
---------------

.. mermaid::
:align: center

%%{init: {'theme': 'default', 'themeVariables': { 'fontSize': '7px'}}}%%
graph TB

%% User Interface Layer
subgraph UI[User Interface Layer]
A[Python Script<br/>.py files]
B[CLI Interface<br/>__main__.py]
A --> B
end

%% Core Processing Layer
subgraph CP[Core Processing Layer]
C[WASMStandaloneDevice<br/>device.py]
D[Template System<br/>brian2wasm templates]
E[Code Generation<br/>objects.cpp, makefile]
C --> D
C --> E
end

%% Compilation Layer
subgraph CL[Compilation Layer]
F[Static Assets<br/>brian.js, worker.js]
G[Emscripten Toolchain<br/>emcc, wasm-ld]
end

%% Runtime Layer
subgraph RL[Runtime Layer]
H[WebAssembly Module<br/>wasm_module.js]
I[Development Server<br/>emrun]
J[Browser Environment]
end

%% Connections
B --> C
D --> F
E --> G
F --> J
G --> H
H --> J
I --> J

Device Architecture
-------------------

**Key Device Methods:**

* :code:`activate()` - Sets up the WASM-specific templater and headers
* :code:`generate_objects_source()` - Generates C++ source code with WASM-specific templates
* :code:`copy_source_files()` - Copies JavaScript runtime files to output directory

Template and Asset Management
-----------------------------

The device integrates with Brian2's templating system while adding WebAssembly-specific templates and runtime assets.

**Core Components:**

* :code:`objects.cpp` template - C++ simulation code generation
* :code:`makefile` / :code:`win_makefile` - Cross-platform build configuration
* :code:`worker.js` - Web Worker runtime
* :code:`brian.js` - Main JavaScript interface
* :code:`html_template` - Default web interface

Configuration Management
------------------------

The system uses Brian2's preference system to manage Emscripten SDK configuration and build options.

**Key Configuration Areas:**

* EMSDK path resolution from environment variables
* HTML file configuration for custom interfaces
* Debug/release build flags
* Cross-platform compiler settings

Cross-Platform Support
----------------------

The architecture includes robust cross-platform support with platform-specific adaptations:

* **Windows**: MSVC filtering and :code:`win_makefile` template
* **Unix-like**: Standard flags and :code:`makefile` template
* **Server execution**: Platform-specific :code:`emrun` command handling

The modular design allows for extension and customization while ensuring reliable cross-platform operation across Linux, macOS, and Windows environments.
Loading
Loading