# czonios/pso-rs architecture

> Architecture diagram of the GitHub repository czonios/pso-rs, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-02-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/czonios/pso-rs
- Repository: https://github.com/czonios/pso-rs

## Overview

##### Project type & purpose (what you’re diagramming)
This is a **Rust library crate** (published on crates.io) that provides an **easy-to-use Particle Swarm Optimization (PSO) implementation**. It also contains **example/driver binaries** under `src/bin` to run PSO on concrete objective functions (Rosenbrock, Lennard‑Jones), plus tests.

##### File-tree-driven component identification
From the tree:

- `Cargo.toml`
Defines the crate, dependencies (not shown here but README indicates `rand`, `rayon`, `indicatif`).
- `src/lib.rs`
The crate root: typically re-exports modules and defines the public surface (`run`, `init`, types).
- `src/pso.rs`
Core PSO algorithm engine (iteration loop, swarm update, evaluation scheduling, termination handling).
- `src/model.rs`
Data model and configuration: likely `Config`, `Model`, getters like `get_f_best`, `get_x_best`, plus types like `Particle = Vec<f64>`.
- `src/bin/main.rs`
Example binary: Rosenbrock objective; demonstrates library usage.
- `src/bin/e_lj.rs`
Example binary: Lennard‑Jones objective; demonstrates library usage.
- `src/tests/pso.rs`
Library tests validating correctness/behavior.
- `screenshots/*`
Non-functional artifact (progress bar GIF shown in README).

- The **library is the product**; binaries are **consumers/examples**.
- The PSO engine is **generic over user-provided objective function** (function pointer/closure).
- There is **parallel computation** for objective evaluation (Rayon).
- There is **random initialization** (rand).
- There is **progress reporting** (indicatif), likely optional/toggleable via `Config`.

##### README-driven runtime and interaction insights
- User defines:
- `objective_function(p: &Particle, flat_dim: usize, dimensions: &Vec<usize>) -> f64`
- optional `terminate(f_best: f64) -> bool`
- User creates `Config` (dimensions, bounds, `t_max`, plus defaults).
- User calls either:
- `pso_rs::run(config, objective_function, Some(terminate)) -> Result<PSO, …>`
- or `pso_rs::init(config, objective_function) -> Result<PSO, …>` then `pso.run(...)`
- Output is a `pso` object containing `model`, from which user reads:
- `model.get_f_best()`, `model.get_x_best()`

Performance notes to encode:
- Objective evaluation across particles is **parallelized**.

##### `run()`
- validates config (bounds/dim match, etc.)
- allocates `Model` (flat particle buffers)
- initializes particles (rand) within bounds
##### Main loop `t = 0..t_max`
- fork: compute objective for each particle (**Rayon parallel iterator**)
- join: collect fitnesses
- update per-particle bests + global best in `Model`
- update velocities/positions (PSO equations)
- clamp/handle bounds
- call termination callback (if provided)
- update progress bar (indicatif)
##### User reads `model.get_f_best()` / `model.get_x_best()`

**Concurrency notation:**
- Everything else is sequential control flow.

##### Labels
- Use **file/module names** for internal components (`pso.rs`, `model.rs`, `lib.rs`).
- Use **API function signatures** on edges when helpful (e.g., `run(config, objective_fn, terminate_fn)`).

- `pso-rs` --(calls objective fn)--> `User objective_function`
- `pso-rs` --(calls terminate fn)--> `User terminate()`

##### “Don’t overthink it” decomposition (explicitly separate components)
Even if the code is small, it’s better to split:
- Config vs runtime state vs result accessors inside `model.rs`.
- Example binaries as separate consumers (they matter for understanding how the crate is used).

- [ ] The crate is a **library** with **two example binaries**
- [ ] Public entrypoints: **`run()`** and **`init()` + `PSO.run()`**
- [ ] Injected **objective function** callback (and optional termination callback)
- [ ] `Config` controls dimensions/bounds/t_max and defaults
- [ ] `Model` stores best-so-far and best position; returned to user
- [ ] **Rayon parallel region** for objective evaluation (core performance feature)
- [ ] **rand** used during initialization (and possibly stochastic updates)
- [ ] **indicatif** used for progress reporting
- [ ] Tests depend on public API

## Diagram (Mermaid)

```mermaid
flowchart TD

%% =======================
%% View A: Package / Context
%% =======================
subgraph "A) Package / Context (crate boundary + consumers + deps)"
direction TB

UA["User Application"]:::external

subgraph "Example Binaries (first-party consumers)"
direction TB
EX1["Rosenbrock Runner (src/bin/main.rs)"]:::example
EX2["Lennard-Jones Runner (src/bin/e_lj.rs)"]:::example
end

subgraph "pso-rs Library Crate"
direction TB

MAN["Crate Manifest (Cargo.toml)"]:::manifest

subgraph "Public API Surface (facade)"
direction TB
LIB["lib.rs (Public Facade)"]:::api
API_RUN["run(config, objective_fn, terminate_fn?)"]:::api
API_INIT["init(config, objective_fn) -> PSO"]:::api
API_PSO_RUN["PSO.run(terminate_fn?)"]:::api
API_TYPES["Types: Config, Model, Particle=Vec<f64>"]:::api
end

subgraph "Internal Implementation"
direction TB
PSO_ENGINE["pso.rs (PSO Engine)"]:::engine
MODEL_CFG["model.rs (Model + Config)"]:::model
end
end

subgraph "External Crates"
direction TB
CR_RAND["rand (RNG)"]:::extdep
CR_RAYON["rayon (parallel iterators)"]:::extdep
CR_INDICATIF["indicatif (progress reporting)"]:::extdep
end

UA -->|"calls run/init"| LIB
EX1 -->|"calls run/init"| LIB
EX2 -->|"calls run/init"| LIB

LIB -->|"exposes"| API_RUN
LIB -->|"exposes"| API_INIT
LIB -->|"exposes"| API_PSO_RUN
LIB -->|"re-exports"| API_TYPES

LIB -->|"delegates_to"| PSO_ENGINE
LIB -->|"uses types"| MODEL_CFG

PSO_ENGINE -->|"uses"| CR_RAND
PSO_ENGINE -->|"uses"| CR_RAYON
PSO_ENGINE -->|"uses"| CR_INDICATIF

MAN -->|"declares deps"| CR_RAND
MAN -->|"declares deps"| CR_RAYON
MAN -->|"declares deps"| CR_INDICATIF
end

%% =======================
%% View B: Module / Container (crate internals)
%% =======================
subgraph "B) Module / Container (internal architecture)"
direction TB

subgraph "lib.rs (Facade)"
direction TB
FACADE["Public Facade\n- run()\n- init()\n- re-exports"]:::api
end

subgraph "pso.rs (Algorithm Engine)"
direction TB
ENG_INIT["Swarm initialization\n(with bounds + RNG)"]:::engine
ENG_LOOP["Main iteration loop\n(t = 0..t_max)"]:::engine
ENG_EVAL["Objective evaluation\n(orchestration)"]:::engine
ENG_UPDATE["Velocity/position update\n+ bounds handling"]:::engine
ENG_TERM["Termination hook\n(optional callback)"]:::engine
ENG_PROG["Progress reporting\n(optional)"]:::engine
end

subgraph "model.rs (State + Policy)"
direction TB
CFG["Config\n- dimensions/shape\n- bounds\n- t_max\n- toggles"]:::model
MODEL["Model (Swarm State Store)\n- particles (flat Vec<f64>)\n- velocities\n- personal bests\n- global best"]:::model
GETTERS["Getters\nget_f_best()\nget_x_best()"]:::model
end

FACADE -->|"creates/validates"| CFG
FACADE -->|"allocates/returns"| MODEL
FACADE -->|"drives"| ENG_INIT
FACADE -->|"drives"| ENG_LOOP

ENG_INIT -->|"reads"| CFG
ENG_INIT -->|"writes"| MODEL

ENG_LOOP -->|"calls"| ENG_EVAL
ENG_EVAL -->|"updates bests"| MODEL
ENG_LOOP -->|"calls"| ENG_UPDATE
ENG_UPDATE -->|"mutates"| MODEL
ENG_LOOP -->|"calls"| ENG_TERM
ENG_LOOP -->|"calls"| ENG_PROG

MODEL -->|"exposes"| GETTERS
end

%% =======================
%% View C: Runtime Execution / Dataflow
%% =======================
subgraph "C) Runtime Execution / Dataflow (PSO run lifecycle)"
direction TB

UCFG["User constructs Config\n(dimensions/bounds/t_max/flags)"]:::external
UOBJ{{"User objective_function(p: &Particle, flat_dim, dimensions) -> f64"}}:::callback
UTERM{{"User terminate(f_best) -> bool (optional)"}}:::callback

ENTRY["run(config, objective_fn, terminate_fn?)\nOR init(config, objective_fn) + PSO.run()"]:::api

ALLOC["Validate config + allocate Model\n(flat particle buffers)"]:::engine
RAND_INIT["Randomize initial swarm\nwithin bounds (rand)"]:::engine

ITER["For each iteration t\nuntil t_max or terminate()"]:::engine

subgraph "Parallel Region: Evaluate all particles"
direction TB
PAR_START["Spawn parallel work (rayon)"]:::parallel
PAR_WORK["Map objective_fn over N particles\n(fitness per particle)"]:::parallel
PAR_JOIN["Join + collect fitnesses"]:::parallel
end

BESTS["Update personal bests + global best\nin Model"]:::engine
UPDATE["Update velocities/positions\n+ clamp/handle bounds"]:::engine
TERMCHK["If terminate_fn provided:\ncall terminate(f_best)"]:::engine
PROGRESS["Update progress bar (indicatif)\n(if enabled)"]:::engine

RETURN["Return PSO/Result with Model"]:::api
READOUT["User reads results:\nmodel.get_f_best()\nmodel.get_x_best()"]:::external

UCFG -->|"passes"| ENTRY
UOBJ -->|"passed into"| ENTRY
UTERM -->|"passed into"| ENTRY

ENTRY -->|"calls into"| ALLOC
ALLOC -->|"creates"| RAND_INIT
RAND_INIT -->|"produces"| ITER

ITER -->|"enter"| PAR_START
PAR_START -->|"parallel_iter"| PAR_WORK
PAR_WORK -.->|"callback"| UOBJ
PAR_WORK -->|"fitnesses"| PAR_JOIN

PAR_JOIN -->|"feeds"| BESTS
BESTS -->|"then"| UPDATE
UPDATE -->|"then"| TERMCHK
TERMCHK -.->|"callback"| UTERM
TERMCHK -->|"then"| PROGRESS
PROGRESS -->|"loop"| ITER

ITER -->|"done"| RETURN
RETURN -->|"exposes"| READOUT
end

%% =======================
%% Tests + Artifacts
%% =======================
subgraph "Tests & Artifacts"
direction TB
TESTS["tests/pso.rs (Test Harness)"]:::test
SS["screenshots/ (README media artifacts)"]:::artifact
end

TESTS -->|"uses public API"| LIB

%% =======================
%% Click Events (from component_mapping)
%% =======================
click MAN "https://github.com/czonios/pso-rs/blob/master/Cargo.toml"
click LIB "https://github.com/czonios/pso-rs/blob/master/src/lib.rs"
click PSO_ENGINE "https://github.com/czonios/pso-rs/blob/master/src/pso.rs"
click MODEL_CFG "https://github.com/czonios/pso-rs/blob/master/src/model.rs"
click EX1 "https://github.com/czonios/pso-rs/blob/master/src/bin/main.rs"
click EX2 "https://github.com/czonios/pso-rs/blob/master/src/bin/e_lj.rs"
click TESTS "https://github.com/czonios/pso-rs/blob/master/tests/pso.rs"
click SS "https://github.com/czonios/pso-rs/tree/master/screenshots/"

%% =======================
%% Styles
%% =======================
classDef external fill:#f2f2f2,stroke:#666,stroke-width:1.5px,color:#111
classDef example fill:#e8f1ff,stroke:#2f6feb,stroke-width:1.5px,color:#0b1a33
classDef manifest fill:#fff1cc,stroke:#c18401,stroke-width:1.5px,color:#3b2a00
classDef api fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#0b1a33
classDef engine fill:#ffe6cc,stroke:#f97316,stroke-width:1.5px,color:#3b1f00
classDef model fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#052e16
classDef extdep fill:#eeeeee,stroke:#6b7280,stroke-width:1.5px,color:#111
classDef callback fill:#f3e8ff,stroke:#7c3aed,stroke-width:1.5px,color:#2e1065
classDef parallel fill:#ffe0f0,stroke:#be185d,stroke-width:1.5px,color:#3b001d
classDef test fill:#e0f2fe,stroke:#0284c7,stroke-width:1.5px,color:#082f49
classDef artifact fill:#f5f5f5,stroke:#9ca3af,stroke-width:1.5px,color:#111
```
