Metadata-Version: 2.2
Name: rnba
Version: 0.1.0
Summary: Recurrent Neural Blackboard Architecture - a simulation framework for neuro-cognitive modelling.
Author-Email: RNBA Contributors <m.dekamps@leeds.ac.uk>
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Project-URL: Homepage, https://github.com/RNBA/RNBA
Project-URL: Repository, https://github.com/RNBA/RNBA
Project-URL: Documentation, https://github.com/RNBA/RNBA#readme
Project-URL: Issues, https://github.com/RNBA/RNBA/issues
Requires-Python: >=3.8
Requires-Dist: numpy>=1.24.0
Requires-Dist: scipy>=1.10.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: black>=22.0; extra == "dev"
Requires-Dist: mypy>=0.990; extra == "dev"
Provides-Extra: viz
Requires-Dist: graphviz>=0.20; extra == "viz"
Requires-Dist: matplotlib>=3.7; extra == "viz"
Provides-Extra: all
Requires-Dist: pytest>=7.0; extra == "all"
Requires-Dist: black>=22.0; extra == "all"
Requires-Dist: mypy>=0.990; extra == "all"
Requires-Dist: graphviz>=0.20; extra == "all"
Requires-Dist: matplotlib>=3.7; extra == "all"
Description-Content-Type: text/markdown

# RNBA

# Replication of the Recurrent Neural Blackboard Architecture

In the paper [Sentences as connection paths: A neural language architecture of sentence structure in the brain (2022)](https://arxiv.org/abs/2206.01725), van der Velde presents a proposal for language representation in the brain. The model is a considerable extenstion of an earlier one [(van der Velde and de Kamps, 2006)](http://cambridge.org/core/journals/behavioral-and-brain-sciences/article/abs/neural-blackboard-architectures-of-combinatorial-structures-in-cognition/6A23B94D3E292F3B1F89D5745726E1CD). The simulations supporting the 2022 paper have been made public [(van der Velde, 2025)](https://doi.org/10.5281/zenodo.15472419). This project is a reimplementation of these simulations, with the aims of providing a pedagogical introduction to the paper and providing improved visualization of both the architecture. 

The simulations are represented as is. The design decisions behind the original simulations are not questioned here, but where issues arise that may confuse the replication, they will be discussed.

## Purpose of this Repository
The simulations that were made available on Zenodo [(van der Velde, 2025)](https://doi.org/10.5281/zenodo.15472419) serve the important purpose of making the simulations of van der Velde (2022) reproducible, but they are not very transparent in exposing the computational elements of the RNBA. The simulator presented here serves a dual purpose:
- To serve as departure point for extensions of the RNBA architecture that are investigated at the University of Leeds
- To make the computational structure of the RNBA architecture more transparent than shown in the Zenodo repository, so that new resaerchers can get up to speed more quickly. To this end, there are a number of jupyter notebooks that can be found in the
examples folders.

## Quick and Dirty Installation
1. Clone the repository
2. Open a terminal in the root which is ${YOUR_PATH}/RNBA, where ${YOUR_PATH} is the path of where you decided to place the clone.
3. Create a virtual environment: 'python3 -m venv .venv'
4. Activate it: 'source .venv/bin/activate'
5. Install it in the virtual environment: 'pip install -e .' (Mind the dot!)


## 'Quick' Start 
Well it's not quick. It takes 15 minutes to run. Nevertheless, we would recommend you run this after installing the code.


The file 'examples/example_qa_simulation.py' is a faithful replication of the Zenobo
simulation that is perfomed in 'RNBA24_sim_QA_3NVN.py'. It follows a the 
following workflow:
1. Read in a file containing the complete architecture of the neural blackboard (this is the file RNBA_arch_SGall_SNB15.txt)
2. A bindings file RNBA_SGall_SNB15_Bindings_Sentence_3NVN.txt, which contains instructions to pre-store bindings in the network, which emulates the situation where previously sentence have been read into the network. 
3. Read in so-called instruction files. These files determine the timings of switching certain populations on and off at predefined times, for example gating populations or populations representing the activation of words during the use of the blackboard. The file 'QA_3NVN_O_success.txt' and the file QA_3NVN_O_fail.txt are
examples of *instruction files*.  A full description of both instruction file formats (QA and SGall), including all recognised commands and the clock model, is in [docs/instruction-file-formats.md](docs/instruction-file-formats.md).
4. Run the simulation.
5. Inspect the simulation results, which is produced in the directory 'example_qa_output ', in the form of two plots: open 'qa_3nvn_word_populations_success.png' and 'open qa_3nvn_word_populations_fail.png',
which replicate Fig 4 in van der Velde (2026)




## Examples

See the `examples/` folder for Jupyter notebooks demonstrating RNBA usage:

- **Example_01_WilsonCowan.ipynb**: Two-population excitatory/inhibitory (E/I) circuit demonstrating Wilson-Cowan dynamics with external input.
- **Example_02_BasicCircuits.ipynb**: Complete RNBA circuit architecture including Wilson-Cowan populations, Working Memory, Gating circuits, and Binding circuits. Demonstrates the four fundamental circuit types from the original simulations.

For further examples, see the README.md in the examples folder.
### Programmatic Architecture Build

The repository includes a script that programmatically rebuilds the architecture from the analysis text file:

```bash
python examples/example_network_creation.py
```

This script:
- Loads `examples/RNBA_arch_SGall_SNB15.txt`
- Builds a `Network` using the current core primitives/wrappers as family coverage references
- Creates network nodes with **canonical runtime IDs** (row indices as strings)
- Tracks architecture row IDs (`idx`) to descriptive `pop_id` labels
- Reconstructs connectivity from the text specification and reports summary counts

Validation tests for this flow are in `tests/test_example_network_creation.py`.

### Node Naming Conventions (row_id vs pop_id)

RNBA uses **two complementary naming schemes**:

- **Canonical runtime ID (row_id):** for **normal populations**, the node name is the row index as a string (e.g., `"158"`). This is the stable, unique ID used by `load_architecture` and runtime networks.
- **Descriptive label (pop_id):** a human-readable role name such as `GC_start_G1`, `SA_WM_SG1Verb_B9`, etc. These repeat across rows, so **pop_id alone is not unique** for normal populations.
- **Unique descriptive label:** `pop_id[row_id]` (e.g., `GC_start_G1[158]`) is unique and readable; this is what the converter emits when relabeling traces.
- **External inputs:** their runtime name **is** `pop_id` (these are unique).

**Conversion helpers:**

- `rnba.converters.architecture.parse_architecture_txt` + `build_row_index_map` → `row_map[idx].pop_id`
- `rnba.converters.architecture.relabel_trace_headers` → `pop_id[row_id]` labels
- After `load_architecture`, `net.population_metadata[str(idx)]["pop_id"]` yields the label for a node.

## Documentation

Project documentation lives in the docs/ folder:
- Analysis: docs/analysis/
- Design notes: docs/design/
- Circuit library design and implementation status: docs/design/CIRCUIT_LIBRARY_DESIGN.md

### Circuit Factory Functions

The circuit library provides factory functions that create topologically identical circuits with different template names. This naming convention supports explicit traceability to roles in `RNBA_arch_SGall_SNB15.txt`.

**Core topologies:**
- `create_gating_circuit` / `create_inhibgate_circuit` / `create_gate_sg_cm_circuit` / `create_gate_sg_w_circuit` / `create_gate_lma_w_pos_circuit` / `create_linked_bgate_dtoh_circuit` — all gating topology (differ only in template name)
- `create_wm_circuit` — working memory topology
- `create_bgate_circuit` — binding gate topology
- `create_linked_bgate_circuit` — linked binding gate topology
- `create_sg_core_circuit` — SG competition/bridge core topology

**Naming convention:** When building the full architecture programmatically (as in `example_network_creation.py`), circuit names are deliberately chosen to match their architectural roles. For example:
- A gate intended for SG→CM binding uses `create_gate_sg_cm_circuit()` to register with template name `"Gate_SG_CM_circuit"`
- A gate intended for SG→W binding uses `create_gate_sg_w_circuit()` to register with template name `"Gate_SG_W_circuit"`

This makes instantiated circuit names traceable to specific roles in the architecture specification.

Example:

```python
from rnba.circuits import create_gating_circuit, create_gate_sg_cm_circuit
from rnba.network import Network

net = Network()

# For a generic gate role
net.register_circuit(create_gating_circuit(w_internal=0.2))

# For explicit SG→CM role (same topology, different template name for traceability)
net.register_circuit(create_gate_sg_cm_circuit(w_internal=0.2))

# Both create instances with names matching their architectural intent
instance1 = net.instantiate_circuit("Gating_circuit", "gate_0")
instance2 = net.instantiate_circuit("Gate_SG_CM_circuit", "sg_cm_gate_0")
```

### Network Visualization

The RNBA package includes a **graphviz-based visualization module** (`rnba.visualize`) that renders networks as diagrams. This is useful for understanding network architecture and debugging connectivity.

**Features:**
- **Detailed view**: Visualizes all nodes (populations) and connections in your network
- **Abstract view**: Shows circuits as single boxes (aggregate view of circuit-level architecture)
- Color-codes nodes by type (red=excitatory, blue=inhibitory, gray=other)
- Shows connection weights and direction
- Groups nodes by circuit instance with light gray boxes
- Supports multiple layout directions (top-to-bottom, left-to-right)
- Exports to PNG, SVG, PDF, and other formats

**Two Visualization Modes:**

1. **Detailed View** (default): Shows all nodes and populations within each circuit
   - Useful for understanding internal circuit dynamics
   - Color-coded by excitatory/inhibitory type
   - Displays all internal and cross-circuit connections

2. **Abstract View** (`abstract_circuits=True`): Shows circuits as single boxes
   - High-level circuit architecture overview
   - Perfect for understanding inter-circuit communication flow
   - Much smaller diagrams (ideal for complex networks)
   - Both circuit instances and standalone nodes shown as boxes

**Quick start:**
```bash
# Install visualization dependencies
pip install -e ".[viz]"

# Requires graphviz system package:
# macOS: brew install graphviz
# Ubuntu/Debian: sudo apt-get install graphviz
# Windows: https://graphviz.org/download/

# Run the demo to see both visualization modes
python examples/demo_network_visualization.py
```

This generates PNG diagrams of the example_2 network in your current directory (both detailed and abstract views).

**Usage in your code:**
```python
from rnba.visualize import visualize_network

# Detailed view (all nodes and populations)
visualize_network(
    network=my_network,
    output_file="my_network_detailed",
    format="png",
    show_weights=True,
    group_by_circuit=True,
    rankdir="TB"  # "TB" for top-to-bottom, "LR" for left-to-right
)

# Abstract view (circuits as boxes)
visualize_network(
    network=my_network,
    output_file="my_network_abstract",
    format="png",
    show_weights=True,
    abstract_circuits=True,  # <-- Enable abstract circuit-level view
    rankdir="TB"
)
```

**When to use each view:**
- **Detailed**: Debugging internal circuit connectivity, understanding population dynamics
- **Abstract**: Getting high-level overview of circuit architecture, understanding inter-circuit communication patterns

See `tests/test_visualize.py` for additional examples.

### Full-Scale Architecture Visualisation

The graphviz module above is suited to small hand-built networks and circuit diagrams. For the full RNBA architecture (16,000–32,000 populations), a separate pipeline exists that uses **GEXF + ForceAtlas 2 (Gephi) + matplotlib**.

The complete pipeline — including all automated steps, the manual Gephi layout step, FA2 settings, output file descriptions, and instructions for what to do when the architecture changes — is documented and driven by:

```bash
bash examples/visualize_architecture.sh
```

That script is the authoritative runbook for full-scale network visualisation. It produces:
- Grey GEXF files for import into Gephi (automated)
- Coloured circle GEXF files with external populations on a ring (automated, requires committed FA2 exports)
- Rendered PNGs at 300 dpi for both the 16k and 32k E/I layouts

### SNB15 Schematic Visualisation (Collapsed Motif View)

The repository also includes a standalone schematic renderer:
- rnba/schematic_visualization.py

This script produces the compact SNB15 motif-style figures used during gate-marker
and linked-binding visual checks.

From the repository root, use these exact commands:

Generate the 4-row view:

python -m rnba.schematic_visualization --first-rows 4 --formats png --basename word_assemblies_schematic_first4

Generate the full 15-row view:

python -m rnba.schematic_visualization --formats png --basename word_assemblies_schematic_full15

### Reference Plots (Canonical Commands)

For future reproducibility, these are the two exact reference renders.

1) Colour plot with SG competition in full mode:

```bash
source .venv/bin/activate && python -m rnba.schematic_visualization --show-control-nodes --show-output-path --show-sg-competition --sg-competition-mode full --formats pdf --basename word_assemblies_schematic_controls_flow_option3a_interleaved_v21_sgcomp_full
```

Expected output file:

- `word_assemblies_schematic_controls_flow_option3a_interleaved_v21_sgcomp_full.pdf`

2) Dark-mode plot without SG competition:

```bash
source .venv/bin/activate && python -m rnba.schematic_visualization --show-control-nodes --show-output-path --activity-flow-theme --formats pdf --basename word_assemblies_schematic_controls_flow_dark_option3a_interleaved_v22_no_sgcomp
```

Expected output file:

- `word_assemblies_schematic_controls_flow_dark_option3a_interleaved_v22_no_sgcomp.pdf`

### Running Examples

```bash
# Install the package in development mode
pip install -e ".[dev]"

# Launch Jupyter and navigate to examples/
jupyter notebook examples/
```

Each notebook is self-contained and can be executed end-to-end (Ctrl+Shift+Enter or Cmd+Shift+Enter).

## Development

**Experiments folder**: The `experiments/` directory (not version-controlled) is a scratch space for developing new use cases and prototypes before promoting polished examples to the `examples/` folder.

## Quickstart

**Run tests:**
```bash
# All tests (unit + integration)
pytest tests/ -v

# Unit tests only (skip slower integration tests)
pytest tests/ -m "not integration" -v

# Integration tests only
pytest tests/integration/ -v
```

**Explore examples:**
```bash
# Install the package in development mode with dev dependencies
pip install -e ".[dev]"

# Launch Jupyter and explore examples/
jupyter notebook examples/
```

**Build architecture network programmatically:**
```bash
# Build from architecture text with canonical row_id node names
python examples/example_network_creation.py

# Optional: verify node/connectivity equivalence test
pytest tests/test_example_network_creation.py -v
```

**Visualize networks:**
```bash
# Install with visualization dependencies
pip install -e ".[viz]"

# Note: Also requires graphviz system package
# macOS: brew install graphviz
# Ubuntu/Debian: sudo apt-get install graphviz

# Visualize the example_2 network
python examples/demo_network_visualization.py
```

License: MIT
