brainx-skill 1.0.13 → 1.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/installation/lib/cli.js +16 -4
- package/installation/lib/literature-mcp.js +536 -0
- package/manifest.json +2 -0
- package/mcp-servers/codex/README.md +24 -4
- package/mcp-servers/codex/UPSTREAM.md +3 -1
- package/mcp-servers/codex/server.mjs +2 -0
- package/mcp-servers/codex/system-prompt.md +30 -19
- package/mcp-servers/codex/test/server.test.mjs +12 -1
- package/mcp-servers/fulltext-resolver/README.md +136 -0
- package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
- package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
- package/mcp-servers/fulltext-resolver/server.mjs +128 -0
- package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
- package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
- package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
- package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
- package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
- package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
- package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
- package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
- package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
- package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
- package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
- package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
- package/package.json +10 -3
- package/skills/bio-neuro-lit/SKILL.md +206 -0
- package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
- package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
- package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
- package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
- package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
- package/skills/brainx-general-guard/SKILL.md +17 -0
- package/skills/brainx-modeling-loop/SKILL.md +33 -20
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +47 -7
- package/skills/brainx-visualization/SKILL.md +157 -0
- package/skills/brainx-visualization/agents/openai.yaml +4 -0
- package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
- package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
- package/skills/package-skills/braincell/SKILL.md +16 -6
- package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
- package/skills/package-skills/braincell/references/braintools/metric.md +152 -0
- package/skills/package-skills/braincell/references/braintools/optimizer.md +179 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: brainx-visualization
|
|
3
|
+
description: Visualize BrainX simulations, training, fitting, and analysis results as diagnostic or publication-ready scientific figures. Use for neural traces, spikes, activity, connectivity, trajectories, distributions, interactive exploration, animations, cellular topology, BrainMass summaries, or figure-integrity review after a BrainX route is selected.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# BrainX visualization
|
|
7
|
+
|
|
8
|
+
## Purpose and boundary
|
|
9
|
+
|
|
10
|
+
Use this skill after selecting the active BrainX modeling route and obtaining the data or run artifacts to visualize. Preserve the biological meaning, axes, units, conditions, observation mapping, and provenance established by that route.
|
|
11
|
+
|
|
12
|
+
Follow this path:
|
|
13
|
+
|
|
14
|
+
`state the figure question -> bind source evidence -> validate the data contract -> choose the highest-level visualization API -> render -> compare with raw values -> export and record provenance`
|
|
15
|
+
|
|
16
|
+
Choose the evidence mode independently from the work type:
|
|
17
|
+
|
|
18
|
+
| Decision | Choices | Rule |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| Evidence mode | `diagnostic`, `final` | Allow unaccepted runs only in diagnostic figures. Use accepted run IDs for final figures unless failed or null evidence is intentionally shown and labeled. |
|
|
21
|
+
| Work type | `audit`, `adapt`, `create` | Preserve originals during audits, preserve scientific meaning during adaptations, and write new plotting code and outputs in the research project rather than the installed skill. |
|
|
22
|
+
|
|
23
|
+
Visualization communicates evidence. It does not decide scientific acceptance or repair an invalid simulation, observation mapping, or statistical comparison.
|
|
24
|
+
|
|
25
|
+
## Underlying mental model
|
|
26
|
+
|
|
27
|
+
A figure maps selected BrainX evidence through declared transformations to visual encodings that answer one scientific question.
|
|
28
|
+
|
|
29
|
+
The active BrainX route defines what every State, event, region, compartment, quantity, and observation means. Never infer that meaning from array shape alone.
|
|
30
|
+
|
|
31
|
+
Define a figure contract before choosing the representation:
|
|
32
|
+
|
|
33
|
+
| Contract field | Required decision |
|
|
34
|
+
|---|---|
|
|
35
|
+
| Question and mode | State one claim, diagnostic question, or comparison and choose `diagnostic` or `final`. |
|
|
36
|
+
| Sources | Record run IDs, artifact paths, hashes, conditions, seeds, checkpoints, and acceptance status. |
|
|
37
|
+
| Data | Record each variable's meaning, shape, axis order, sampling interval, ordering, and physical unit. |
|
|
38
|
+
| Transformations | Declare slicing, alignment, baseline correction, normalization, smoothing, aggregation, exclusions, and observation mapping. |
|
|
39
|
+
| Comparisons | Name controls, interventions, aligned landmarks, and fixed display limits. |
|
|
40
|
+
| Statistics | State the sampling unit, sample size, center, spread, uncertainty definition, and every reduction shown. |
|
|
41
|
+
| Destination | Set diagnostic, report, presentation, single-column paper, or double-column paper output before size and format. |
|
|
42
|
+
|
|
43
|
+
Freeze displayed cases, thresholds, smoothing, aggregation, exclusions, normalization, and axis or color limits before inspecting intervention outcomes. Keep raw per-condition evidence available beside aggregates.
|
|
44
|
+
|
|
45
|
+
## Choose the visualization layer
|
|
46
|
+
|
|
47
|
+
Use the highest-level API that owns the scientific view; package ownership preserves domain semantics that generic plotting cannot recover.
|
|
48
|
+
|
|
49
|
+
| Layer | Use |
|
|
50
|
+
|---|---|
|
|
51
|
+
| Selected package visualization | Use first when BrainCell or BrainMass owns the represented structure, quantity, or analysis result. |
|
|
52
|
+
| `braintools.visualize` | Use for general neural, statistical, model-evaluation, interactive, 3D, styling, and animation workflows. |
|
|
53
|
+
| `matplotlib.pyplot` | Use for simple composition, labels, annotations, and export after the owning helper. Add custom artists only for a verified gap. |
|
|
54
|
+
|
|
55
|
+
Choose a general figure family by question:
|
|
56
|
+
|
|
57
|
+
| Question | Figure family | Required evidence |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| When and where do events or activity occur? | Raster, trace, population activity, histogram, rate map, or activity dashboard | Preserve event representation, time-major axes, recorded interval, units, and neuron or spatial ordering. |
|
|
60
|
+
| What dynamical regime or network structure appears? | Trajectory, phase portrait, tuning curve, ordered matrix, topology, or 3D view | Declare transient removal, coordinate meaning, ordering, layout semantics, and any threshold. |
|
|
61
|
+
| How variable is a result or does an assumption hold? | Distribution, Q-Q, raw samples with interval, box/violin, correlation, or scatter matrix | State sampling unit, `n`, uncertainty, comparison correction, and the exact statistic. |
|
|
62
|
+
| Does a model predict or generalize correctly? | Prediction comparison, residuals, confusion matrix, ROC or precision-recall curve, or learning curve | Separate train and held-out evidence; preserve labels, score meaning, prevalence, folds, and residual units. |
|
|
63
|
+
| Does hover, zoom, depth, or time evolution answer the question? | Plotly interaction, 3D view, or animation | Keep a stable final figure for archival evidence and fix encodings, camera, thresholds, and frame timing across comparisons. |
|
|
64
|
+
|
|
65
|
+
Open the matching general reference before choosing concrete functions:
|
|
66
|
+
|
|
67
|
+
- Open `references/neural-data-visualization.md` for neural events, activity, connectivity, trajectories, tuning, topology, or general 3D data.
|
|
68
|
+
- Open `references/statistical-and-model-visualization.md` for distributions, assumptions, grouped comparisons, regression, residuals, classification evaluation, or learning curves.
|
|
69
|
+
- Open `references/interactive-and-visualization-styling.md` for Plotly exploration, dashboards, themes, palettes, colormaps, export, or animation.
|
|
70
|
+
|
|
71
|
+
## Compose a static neural figure
|
|
72
|
+
|
|
73
|
+
Static helpers render into supplied axes; compose the figure once, pass `ax=` to every helper, export once, and close it after non-interactive output.
|
|
74
|
+
|
|
75
|
+
| API | Description |
|
|
76
|
+
|---|---|
|
|
77
|
+
| `braintools.visualize.spike_raster(...)` | Use for flat spike-time events with matching neuron IDs, or per-neuron spike-train sequences. It returns the Matplotlib axes. |
|
|
78
|
+
| `braintools.visualize.population_activity(...)` | Use for time-major `(time, neurons)` activity or an already aggregated one-dimensional rate. It returns the axes. |
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import matplotlib.pyplot as plt
|
|
82
|
+
import braintools.visualize as btvis
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
assert spike_times.ndim == neuron_ids.ndim == 1
|
|
86
|
+
assert spike_times.shape == neuron_ids.shape
|
|
87
|
+
assert activity.ndim == 2
|
|
88
|
+
assert time.shape == (activity.shape[0],)
|
|
89
|
+
|
|
90
|
+
fig, axes = plt.subplots(2, 1, figsize=(7.0, 5.0), sharex=True)
|
|
91
|
+
btvis.spike_raster(spike_times, neuron_ids, ax=axes[0])
|
|
92
|
+
btvis.population_activity(activity, time=time, ax=axes[1])
|
|
93
|
+
axes[0].set_ylabel("neuron index")
|
|
94
|
+
axes[1].set(xlabel="time (ms)", ylabel="population activity")
|
|
95
|
+
fig.tight_layout()
|
|
96
|
+
fig.savefig("neural-activity.png", dpi=600, bbox_inches="tight")
|
|
97
|
+
plt.close(fig)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Open `references/neural-data-visualization.md` when the event representation differs, the figure requires another neural family, or a 3D view is scientifically necessary.
|
|
101
|
+
|
|
102
|
+
## Prepare final figures
|
|
103
|
+
|
|
104
|
+
Make the evidence readable at its destination size without changing the encoded comparison.
|
|
105
|
+
|
|
106
|
+
- Follow the venue specification first. Otherwise use intentional physical dimensions, prefer PDF or SVG for vector line art, and use sufficient raster resolution.
|
|
107
|
+
- Label axes with units, omit placeholder units for dimensionless values, and use one name for the same quantity throughout a report.
|
|
108
|
+
- Use consistent panel labels, axes, normalization, line and marker hierarchies, and accessible colors. Do not encode a comparison only by hue.
|
|
109
|
+
- Use sequential colormaps for ordered magnitude, diverging colormaps only around a meaningful center, and categorical palettes for unordered conditions.
|
|
110
|
+
- Add labels, legends, colorbars, and panel marks before the final layout pass. Keep legends and grids secondary to the evidence.
|
|
111
|
+
- Reduce overplotting before increasing figure size. Use an inset only when a local difference is scientifically important and unused space is available.
|
|
112
|
+
|
|
113
|
+
Open `references/interactive-and-visualization-styling.md` for scoped styles, palette and colormap selection, interactive export, animation export, and comparison-stable visual settings.
|
|
114
|
+
|
|
115
|
+
## Verify and record the figure
|
|
116
|
+
|
|
117
|
+
Render every export and inspect it against source values before delivery.
|
|
118
|
+
|
|
119
|
+
Verify that the output is nonblank, unclipped, legible at destination size, and free of overlaps. Check axis values, units, event timing, ordering, sample count, summaries, and fixed scales against source arrays. Confirm that smoothing, aggregation, uncertainty, exclusions, interpolation, and overplotting do not hide failures or differences.
|
|
120
|
+
|
|
121
|
+
Create or update `FIGURE_MANIFEST.md` with one entry per figure:
|
|
122
|
+
|
|
123
|
+
```markdown
|
|
124
|
+
## <figure path>
|
|
125
|
+
- Work type, evidence mode, scientific role, and question:
|
|
126
|
+
- Source run IDs, artifacts, hashes, and acceptance status:
|
|
127
|
+
- Variables, axes, ordering, and units:
|
|
128
|
+
- Transformations, smoothing, aggregation, and exclusions:
|
|
129
|
+
- Sample size and uncertainty:
|
|
130
|
+
- Controls and fixed comparison settings:
|
|
131
|
+
- Plotting source, output path, size, format, and resolution:
|
|
132
|
+
- Render and source-value checks:
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Reference routing
|
|
136
|
+
|
|
137
|
+
| Route | Open when | Contains |
|
|
138
|
+
|---|---|---|
|
|
139
|
+
| `references/neural-data-visualization.md` | Selecting neural event, activity, connectivity, dynamical, topology, tuning, spatial, or general 3D figures. | Data contracts, family selection, concrete BrainTools helpers, 3D boundaries, workflows, and comparison rules. |
|
|
140
|
+
| `references/statistical-and-model-visualization.md` | Inspecting distributions or assumptions, comparing groups, diagnosing regression, or evaluating classification and learning behavior. | Statistical helper selection, raw-data and uncertainty rules, residual diagnostics, ROC-versus-precision-recall decisions, and learning-curve interpretation. |
|
|
141
|
+
| `references/interactive-and-visualization-styling.md` | Adding interactive exploration, dashboards, styles, palettes, colormaps, export, or animation. | Plotly return behavior, stable encodings, scoped Matplotlib styles, output decisions, animation data contracts, and performance boundaries. |
|
|
142
|
+
| `skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md` | Visualizing BrainCell morphology branches, CVs, runtime nodes, selector placement, topology layouts, or node and mechanism values. | Branch/CV/node decisions, initialization, physical-versus-topological views, selector coverage, value coloring, and canonical compositions. |
|
|
143
|
+
| `skills/package-skills/brainmass/references/visualization-analysis-api.md` | Computing or plotting BrainMass trajectories, phase portraits, connectivity, FC/FCD, or spectra. | `brainmass.viz`, BrainTools metric selection, time-major and sampling rules, unit boundaries, canonical analysis, and failures. |
|
|
144
|
+
|
|
145
|
+
## Boundaries and common failures
|
|
146
|
+
|
|
147
|
+
- The figure is designed before its question, mode, evidence, and destination are fixed.
|
|
148
|
+
- Biological meaning, time axis, region order, or units are guessed from shape.
|
|
149
|
+
- Dense spike matrices and flat event arrays are sent to the wrong raster representation.
|
|
150
|
+
- Integration `dt` is used after recording subsampling changed the plotted interval.
|
|
151
|
+
- Package-owned morphology, topology, BrainMass analysis, or visualization is rebuilt with generic plotting code.
|
|
152
|
+
- Comparison scales, smoothing, normalization, thresholds, or exclusions vary without disclosure.
|
|
153
|
+
- Aggregate curves hide raw outcomes, sample size, uncertainty, failed runs, or null evidence.
|
|
154
|
+
- A reference figure is cloned without adapting its layout to the scientific role and real data geometry.
|
|
155
|
+
- Existing figures are overwritten, or plotting scripts and outputs are written into the installed skill directory.
|
|
156
|
+
- Diagnostic output is presented as final evidence, or a visual pattern is treated as scientific acceptance.
|
|
157
|
+
- Final artifacts are delivered without source provenance and render inspection.
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Interactive and visualization styling
|
|
2
|
+
|
|
3
|
+
## Purpose and boundary
|
|
4
|
+
|
|
5
|
+
Use this reference for Plotly exploration, neural dashboards, Matplotlib styles, palettes, colormaps, export, and animation. Interaction and motion must expose evidence that is difficult to inspect statically; keep a stable static figure when the destination is a paper or archival report.
|
|
6
|
+
|
|
7
|
+
## Choose interaction, styling, or animation
|
|
8
|
+
|
|
9
|
+
| Need | Use | Preserve |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Hover, zoom, filtering, or trace toggling | Matching `interactive_*` helper | Data meaning, axis units, ordering, fixed comparison ranges, and a static evidence view. |
|
|
12
|
+
| A combined event-level overview | `dashboard_neural_activity(...)` | Per-neuron spike representation, population time alignment, and dashboard source data. |
|
|
13
|
+
| Consistent Matplotlib appearance | `apply_style(...)` or a named style helper | Destination size, readability, scientific encodings, and process-local scope. |
|
|
14
|
+
| Reusable categorical colors | `get_color_palette(...)` | Stable condition-to-color mapping and redundant line or marker encodings. |
|
|
15
|
+
| Scalar, diverging, or cyclic color encoding | Existing or custom colormap | Quantity meaning, neutral point, cyclicity, and fixed limits. |
|
|
16
|
+
| Evolution of a 1D profile or 2D field | `animate_1D(...)`, `animate_2D(...)`, or `animator(...)` | Time-first frames, physical `dt`, fixed axes and color limits, and retained output object. |
|
|
17
|
+
| Custom multi-artist temporal story | Matplotlib `FuncAnimation` | Frame update contract, stable layout, export writer, and numerical source data. |
|
|
18
|
+
|
|
19
|
+
Do not add interaction, 3D rotation, dark styling, or animation as decoration. A view that requires manual interaction to reveal the claimed result is insufficient as the only final evidence.
|
|
20
|
+
|
|
21
|
+
## Explore with interactive figures
|
|
22
|
+
|
|
23
|
+
Interactive BrainTools helpers require Plotly and return Plotly figures. Confirm that Plotly is available before selecting this route; then inspect figures with `.show()`, refine them with Plotly figure methods, and export only after fixing comparison settings.
|
|
24
|
+
|
|
25
|
+
| API | Description |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `interactive_spike_raster(spike_times, neuron_ids=None, ...)` | Use for event-level hover, zoom, time or neuron filtering, and optional coloring by neuron or time. |
|
|
28
|
+
| `interactive_line_plot(x, y, labels=None, ...)` | Use for one or more aligned traces. Legend toggling supports exploration but must not silently redefine the final comparison. |
|
|
29
|
+
| `interactive_heatmap(data, x_labels=None, y_labels=None, ...)` | Use for matrix inspection. Fix `zmin`, `zmax`, label order, and colorscale across comparable matrices. |
|
|
30
|
+
| `interactive_3d_scatter(x, y, z, color=None, size=None, labels=None, ...)` | Use when three coordinates and hover metadata are part of the question. Declare color and size meanings. |
|
|
31
|
+
| `interactive_network(adjacency, positions=None, ...)` | Use for topology exploration. Preserve adjacency direction, positions, threshold, and node or edge encodings. |
|
|
32
|
+
| `interactive_histogram(data, labels=None, bins=30, ...)` | Use to inspect one or more distributions and bin sensitivity. Do not compare quantities with incompatible units on one axis. |
|
|
33
|
+
| `interactive_surface(z, x=None, y=None, ...)` | Use for a scalar surface over declared coordinates. Preserve grid orientation and fixed height/color ranges. |
|
|
34
|
+
| `interactive_correlation_matrix(data, labels=None, method='pearson', ...)` | Use for exact-value hover over correlation structure. Preserve variable orientation and do not infer causality. |
|
|
35
|
+
| `dashboard_neural_activity(spike_times, neuron_ids=None, population_activity=None, time=None, ...)` | Use for a linked overview of spikes and population summaries. Supply either matching flat events or per-neuron sequences and align population activity to `time`. |
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import braintools.visualize as btvis
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
fig = btvis.interactive_heatmap(
|
|
42
|
+
connectivity,
|
|
43
|
+
x_labels=target_labels,
|
|
44
|
+
y_labels=source_labels,
|
|
45
|
+
colorscale="RdBu_r",
|
|
46
|
+
title="source-to-target connectivity",
|
|
47
|
+
)
|
|
48
|
+
fig.update_traces(zmin=-weight_limit, zmax=weight_limit)
|
|
49
|
+
fig.show()
|
|
50
|
+
fig.write_html("connectivity-explorer.html")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
For Plotly static export, use `fig.write_image(...)` with an available image engine. Use `fig.write_html(...)` for a self-contained interactive artifact. Record the visible defaults, filtering state, camera, axis ranges, and color limits in the figure manifest.
|
|
54
|
+
|
|
55
|
+
Subsample dense interactive data only by a declared rule. Validate extrema, labels, and representative points before and after subsampling.
|
|
56
|
+
|
|
57
|
+
## Apply styles without leaking state
|
|
58
|
+
|
|
59
|
+
Matplotlib style helpers modify process-wide defaults; scope them when plotting code shares a process with unrelated figures.
|
|
60
|
+
|
|
61
|
+
| API | Description |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `apply_style(style_name, **kwargs)` | Use as a context manager for `neural`, `publication`, `dark`, or `colorblind`; it restores prior `rcParams` on exit. |
|
|
64
|
+
| `neural_style(...)` | Use for process-wide neural-data defaults only when all subsequent figures should share them. |
|
|
65
|
+
| `publication_style(fontsize=10, figsize=(6, 4), dpi=300, usetex=False)` | Use for process-wide print defaults after the destination size and font constraints are known. Do not enable TeX unless the environment and glyph set are verified. |
|
|
66
|
+
| `dark_style(...)` | Use for screen or projection output with a dark background. Export with matching face colors and do not reuse it blindly for print. |
|
|
67
|
+
| `colorblind_friendly_style()` | Use for the accessible process-wide preset. Preserve redundant line, marker, or direct-label encodings. |
|
|
68
|
+
| `get_color_palette(palette_name, n_colors=None)` | Use for a fixed categorical palette. Save the condition-to-color mapping rather than requesting colors independently per panel. |
|
|
69
|
+
| `create_neural_colormap(name, colors, n_bins=256)` | Use to create a named continuous colormap only when existing maps cannot express the quantity correctly. |
|
|
70
|
+
| `brain_colormaps()` | Use to register the supplied neural colormap set before referring to those names in Matplotlib. |
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import matplotlib.pyplot as plt
|
|
74
|
+
import braintools.visualize as btvis
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
with btvis.apply_style("publication", fontsize=9, dpi=300):
|
|
78
|
+
fig, ax = plt.subplots(figsize=(3.35, 2.4))
|
|
79
|
+
btvis.population_activity(activity, time=time, ax=ax)
|
|
80
|
+
ax.set(xlabel="time (ms)", ylabel="population activity")
|
|
81
|
+
fig.savefig("population-activity.pdf", bbox_inches="tight")
|
|
82
|
+
plt.close(fig)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Follow the destination specification before any preset. Verify the rendered output at final physical size; preset names do not guarantee readable labels, correct fonts, or valid dimensions.
|
|
86
|
+
|
|
87
|
+
## Select colors by data meaning
|
|
88
|
+
|
|
89
|
+
- Use sequential colormaps for ordered magnitude, diverging maps around a meaningful center, and cyclic maps for phase or direction.
|
|
90
|
+
- Use categorical palettes for unordered conditions. Keep each condition's color fixed across all panels and figures.
|
|
91
|
+
- Add a line style, marker, pattern, or direct label when color carries group identity. Check grayscale and color-vision-deficiency legibility.
|
|
92
|
+
- Fix color limits before comparing matrices, surfaces, volumes, or animation frames. Autoscaling each panel or frame destroys magnitude comparison.
|
|
93
|
+
- Label colorbars with quantity and unit. Do not use decorative color variation without a declared encoding.
|
|
94
|
+
- Avoid rainbow maps for ordered scientific values when they introduce false boundaries or nonuniform perceptual changes.
|
|
95
|
+
|
|
96
|
+
## Animate declared temporal data
|
|
97
|
+
|
|
98
|
+
Animation maps the first array dimension to frames; physical frame time and display delay are separate quantities.
|
|
99
|
+
|
|
100
|
+
| API | Description |
|
|
101
|
+
|---|---|
|
|
102
|
+
| `animate_1D(dynamical_vars, static_vars=(), dt=None, frame_delay=50, frame_step=1, save_path=None, show=True, ...)` | Use for one or more `(frames, x)` profiles and optional static one-dimensional references. Supply physical `dt`; the function returns the created figure. |
|
|
103
|
+
| `animate_2D(values, net_size, dt=None, val_min=None, val_max=None, frame_step=1, save_path=None, show=True, ...)` | Use for `(frames, neurons)` values reshapeable to `net_size` or `(frames, height, width)` fields. It returns a `FuncAnimation`; retain it through display or export. |
|
|
104
|
+
| `animator(data, fig, ax, num_steps=False, interval=40, cmap='plasma')` | Use for time-first `(frames, height, width)` image data with existing figure and axes. It returns an `ArtistAnimation`; retain it through display or export. |
|
|
105
|
+
| `matplotlib.animation.FuncAnimation(...)` | Use for coordinated custom artists, sliding windows, dynamic networks, or learning diagnostics that the high-level helpers cannot express. Return every changed artist when using blitting. |
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
import matplotlib.pyplot as plt
|
|
109
|
+
import braintools.visualize as btvis
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
assert field.ndim == 3 # (frames, height, width)
|
|
113
|
+
animation = btvis.animate_2D(
|
|
114
|
+
field,
|
|
115
|
+
net_size=field.shape[1:],
|
|
116
|
+
dt=recorded_dt,
|
|
117
|
+
val_min=fixed_min,
|
|
118
|
+
val_max=fixed_max,
|
|
119
|
+
show=False,
|
|
120
|
+
)
|
|
121
|
+
animation.save("activity.mp4", writer="ffmpeg", fps=20)
|
|
122
|
+
plt.close(animation._fig)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Set `dt` from the recorded interval, not the integration step when monitoring was subsampled. Set `frame_step` as a declared temporal decimation. Keep axis limits, camera, colormap, and value limits constant across frames and comparable animations.
|
|
126
|
+
|
|
127
|
+
Use GIF for short, simple, widely embedded motion; use MP4 for compact presentation video; use HTML for notebook or browser controls. Verify writer availability before a long render. For large animations, update existing artists, enable blitting when compatible, decimate by a declared rule, precompute expensive frame quantities when memory permits, and disable or limit frame caching for streaming data.
|
|
128
|
+
|
|
129
|
+
## Export and verify
|
|
130
|
+
|
|
131
|
+
- Export static line art as PDF or SVG when supported; use intentional pixel dimensions and raster resolution for PNG.
|
|
132
|
+
- Export Plotly HTML when interaction is the deliverable and a static companion when the scientific claim must be visible without interaction.
|
|
133
|
+
- Inspect text, math glyphs, background, transparency, colorbars, hover labels, default camera, and initial animation frame.
|
|
134
|
+
- Check that interaction or animation does not reveal values outside the declared source range or hide condition failures behind filters.
|
|
135
|
+
- Compare representative frames and hover values against source arrays. Check first, middle, and last frames plus extrema.
|
|
136
|
+
- Close Matplotlib figures after non-interactive export and retain animation objects until saving or display completes.
|
|
137
|
+
|
|
138
|
+
## Common failures
|
|
139
|
+
|
|
140
|
+
- Interactive controls define the result, but the saved artifact does not record their state.
|
|
141
|
+
- Plotly figures use different axis or color ranges across conditions.
|
|
142
|
+
- A process-wide style leaks into unrelated figures or overwrites venue settings.
|
|
143
|
+
- Color is the only condition encoding, or a colormap has no relation to the data semantics.
|
|
144
|
+
- Each animation frame autoscales, creating false changes in magnitude.
|
|
145
|
+
- Display `interval` is confused with physical `dt`, or integration `dt` is used after monitor subsampling.
|
|
146
|
+
- An animation object is garbage-collected before display or export completes.
|
|
147
|
+
- Dense data are subsampled without recording the rule or checking retained extrema.
|
|
148
|
+
- Dark output is exported with the wrong face color, or TeX/font settings fail only in the final render.
|
|
149
|
+
- Animation or interaction is used where a static comparison would be clearer and more inspectable.
|
|
150
|
+
|
|
151
|
+
## Tutorial sources
|
|
152
|
+
|
|
153
|
+
- [Interactive visualization](https://brainx.chaobrain.com/braintools/visualize/05_interactive_visualization.html)
|
|
154
|
+
- [Styling and themes](https://brainx.chaobrain.com/braintools/visualize/07_styling_and_themes.html)
|
|
155
|
+
- [Animation and dynamics](https://brainx.chaobrain.com/braintools/visualize/08_animation_and_dynamics.html)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# Neural data visualization
|
|
2
|
+
|
|
3
|
+
## Purpose and boundary
|
|
4
|
+
|
|
5
|
+
Use this reference for general neural events, activity, connectivity, low-dimensional dynamics, stimulus response, topology, and spatial 3D data. Preserve the active BrainX package's variable meanings, units, ordering, and recording interval.
|
|
6
|
+
|
|
7
|
+
Route BrainCell morphology, compartments, runtime nodes, selector placement, or mechanism values directly to `skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md`. Route BrainMass-owned trajectories, phase portraits, connectivity, FC/FCD, or spectra directly to `skills/package-skills/brainmass/references/visualization-analysis-api.md`.
|
|
8
|
+
|
|
9
|
+
## Choose the neural family
|
|
10
|
+
|
|
11
|
+
Select the figure from the data contract and question, not from visual familiarity.
|
|
12
|
+
|
|
13
|
+
| Data contract or question | Use | Preserve |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Selected time-series columns aligned to timestamps | `line_plot(ts, val_matrix, ...)` | Time-major orientation, selected column identities, timestamps, and units. |
|
|
16
|
+
| Flat spike times plus matching neuron IDs, or one spike-time sequence per neuron | `spike_raster(...)` | Event times, neuron identity, filtering ranges, and time unit. |
|
|
17
|
+
| Dense `(time, neuron)` binary or event matrix with timestamps | `raster_plot(ts, sp_matrix, ...)` | Time-major orientation and exact timestamp vector. |
|
|
18
|
+
| Time-major neural activity or an aggregate rate | `population_activity(...)` | Recorded interval, aggregation method, window, and selected neurons. |
|
|
19
|
+
| Spike timing distribution | `isi_distribution(...)` or `spike_histogram(...)` | Whether the quantity is inter-spike interval or event count per time bin. |
|
|
20
|
+
| Spatial firing | `firing_rate_map(...)` | Position-to-rate mapping, grid geometry, interpolation, and rate unit. |
|
|
21
|
+
| Directed weights | `connectivity_matrix(...)` | Rows as presynaptic sources, columns as postsynaptic targets, labels, and normalization. |
|
|
22
|
+
| State evolution | `neural_trajectory(...)` or `phase_portrait(...)` | Time-major samples, selected coordinates, transient rule, and direction of time. |
|
|
23
|
+
| Structural relationships | `network_topology(...)` | Adjacency direction, layout meaning, and declared node or edge encodings. |
|
|
24
|
+
| Ordered stimulus and response | `tuning_curve(...)` | Stimulus order and unit, response unit, repeats, error meaning, and fit family. |
|
|
25
|
+
| Physical depth, mesh, volume, or three-coordinate geometry | Matching 3D helper | Coordinates, camera, thresholds, color normalization, and comparison view. |
|
|
26
|
+
|
|
27
|
+
Do not convert flat events to a dense matrix merely to plot them. Do not use 3D when a 2D projection answers the same question without occlusion.
|
|
28
|
+
|
|
29
|
+
## Visualize spikes and population activity
|
|
30
|
+
|
|
31
|
+
Spike helpers preserve either event-list or dense-matrix representations; population helpers reduce only along the declared neuron axis.
|
|
32
|
+
|
|
33
|
+
| API | Description |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `line_plot(ts, val_matrix, plot_ids=None, ...)` | Use for selected columns of a time-by-value matrix aligned to `ts`. Preserve the meaning and unit of every selected column. |
|
|
36
|
+
| `spike_raster(spike_times, neuron_ids=None, ...)` | Use for flat event arrays with equal lengths or a sequence of per-neuron spike trains. Filter with explicit time or neuron ranges and receive a Matplotlib axes. |
|
|
37
|
+
| `raster_plot(ts, sp_matrix, ...)` | Use for dense `(time, neuron)` spikes aligned to `ts`. Do not pass flat spike-time events. |
|
|
38
|
+
| `population_activity(data, time=None, dt=None, method='mean', window_size=None, ...)` | Use for `(time, neurons)` activity or a one-dimensional aggregate. Prefer the recorded `time`; use `dt` only when it is the actual recorded interval. |
|
|
39
|
+
| `isi_distribution(spike_times, bins=50, max_isi=None, log_scale=False, ...)` | Use for sorted spike times or a list of sorted per-neuron spike-time arrays; it computes successive intervals. Use a per-neuron list to avoid intervals across neuron boundaries, and enable log scale when bin counts span orders of magnitude. |
|
|
40
|
+
| `spike_histogram(spike_times, bins=50, bin_size=None, density=False, ...)` | Use for event counts or density across time. Treat bin count or `bin_size` as a declared temporal-resolution choice. |
|
|
41
|
+
| `firing_rate_map(rates, positions=None, grid_size=None, interpolation='bilinear', ...)` | Use for position-rate pairs or an already shaped map. Declare interpolation and do not imply unsampled spatial resolution. |
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import matplotlib.pyplot as plt
|
|
45
|
+
import braintools.visualize as btvis
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
assert spike_times.shape == neuron_ids.shape
|
|
49
|
+
assert activity.shape[0] == time.size
|
|
50
|
+
|
|
51
|
+
fig, axes = plt.subplots(2, 1, figsize=(7, 5), sharex=True)
|
|
52
|
+
btvis.spike_raster(spike_times, neuron_ids, ax=axes[0])
|
|
53
|
+
btvis.population_activity(activity, time=time, ax=axes[1])
|
|
54
|
+
axes[0].set_ylabel("neuron index")
|
|
55
|
+
axes[1].set(xlabel="time (ms)", ylabel="mean activity")
|
|
56
|
+
fig.tight_layout()
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Compare the raster and population trace against raw event counts in at least one known window. When smoothing population activity, retain the unsmoothed series and record the window or kernel.
|
|
60
|
+
|
|
61
|
+
## Visualize connectivity and dynamics
|
|
62
|
+
|
|
63
|
+
Matrix, trajectory, topology, and tuning figures answer different questions even when derived from the same model.
|
|
64
|
+
|
|
65
|
+
| API | Description |
|
|
66
|
+
|---|---|
|
|
67
|
+
| `connectivity_matrix(weights, pre_labels=None, post_labels=None, center_zero=True, ...)` | Use for source-by-target weights. Center a diverging colormap at zero only when zero is the meaningful neutral value; keep one normalization across comparisons. |
|
|
68
|
+
| `neural_trajectory(data, dims=None, time_color=True, ...)` | Use for `(time, features)` trajectories in two or three selected coordinates. Time coloring and start/end markers expose direction. |
|
|
69
|
+
| `phase_portrait(x, y=None, dx=None, dy=None, trajectory=True, vector_field=False, ...)` | Use for a two-variable trajectory, vector field, or both. Match vector-field and trajectory coordinates, scales, and units. |
|
|
70
|
+
| `network_topology(adjacency, positions=None, layout='spring', ...)` | Use for graph structure. Choose a layout for a declared structural question and state what node size, node color, edge width, and edge color encode. |
|
|
71
|
+
| `tuning_curve(stimulus, response, bins=20, error_bars=True, fit_curve=None, ...)` | Use for response versus ordered stimulus. Use error bars only when repeats define their statistic and use a fit only when its family is scientifically justified. |
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
import matplotlib.pyplot as plt
|
|
75
|
+
import braintools.visualize as btvis
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
assert trajectory.ndim == 2 # (time, features)
|
|
79
|
+
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5))
|
|
80
|
+
btvis.neural_trajectory(trajectory, dims=(0, 1), time_color=True, ax=axes[0])
|
|
81
|
+
btvis.phase_portrait(trajectory[:, :2], trajectory=True, ax=axes[1])
|
|
82
|
+
axes[0].set(xlabel="state 1", ylabel="state 2")
|
|
83
|
+
axes[1].set(xlabel="state 1", ylabel="state 2")
|
|
84
|
+
fig.tight_layout()
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
For repeated conditions, keep coordinates, transient removal, start/end encoding, scales, matrix ordering, network positions, and tuning-curve bins fixed. A force-directed layout is not a biological coordinate system.
|
|
88
|
+
|
|
89
|
+
## Use 3D only for geometric evidence
|
|
90
|
+
|
|
91
|
+
Three-dimensional views are justified when depth, surfaces, volumes, electrodes, or three-coordinate trajectories are part of the question.
|
|
92
|
+
|
|
93
|
+
| API | Description |
|
|
94
|
+
|---|---|
|
|
95
|
+
| `neural_network_3d(layer_sizes, weights=None, activations=None, ...)` | Use for layered architecture and optional weights or activations, not anatomical morphology. |
|
|
96
|
+
| `brain_surface_3d(vertices, faces, values=None, ...)` | Use for a triangular surface mesh and optional vertex values. Validate vertex-face indexing and value alignment. |
|
|
97
|
+
| `connectivity_3d(source_positions, target_positions, connections, ...)` | Use for connections between two 3D point sets. Declare thresholding and edge-strength encoding. |
|
|
98
|
+
| `trajectory_3d(trajectory, time_colors=True, ...)` | Use for `(time, 3)` trajectories. Preserve direction with time color or start/end markers. |
|
|
99
|
+
| `volume_rendering(volume, threshold=None, ...)` | Use for a 3D scalar volume. Declare voxel geometry, threshold, alpha, and normalization. |
|
|
100
|
+
| `electrode_array_3d(electrode_positions, signals=None, ...)` | Use for electrode coordinates and optional aligned signals. Preserve coordinate frame and signal scaling. |
|
|
101
|
+
| `dendrite_tree_3d(segments, diameters=None, ...)` | Use only for generic segment geometry. Use the BrainCell route when segments represent BrainCell morphology or runtime nodes. |
|
|
102
|
+
| `phase_space_3d(x, y, z, time_colors=True, ...)` | Use for three declared dynamical variables. Keep their coordinate meanings and scales explicit. |
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
import matplotlib.pyplot as plt
|
|
106
|
+
import braintools.visualize as btvis
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
assert trajectory_xyz.shape[1] == 3
|
|
110
|
+
fig = plt.figure(figsize=(6, 5))
|
|
111
|
+
ax = fig.add_subplot(111, projection="3d")
|
|
112
|
+
btvis.trajectory_3d(trajectory_xyz, time_colors=True, ax=ax)
|
|
113
|
+
ax.set(xlabel="state 1", ylabel="state 2", zlabel="state 3")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Fix the camera, axis limits, coordinate scaling, threshold, transparency, and color normalization before comparing conditions. Supply a 2D projection when occlusion could hide the relevant structure.
|
|
117
|
+
|
|
118
|
+
## Preserve comparison integrity
|
|
119
|
+
|
|
120
|
+
- Keep time bases, units, neuron and region order, matrix orientation, bins, smoothing, and aggregation fixed across comparable panels.
|
|
121
|
+
- Show raw observations when feasible. Do not let a smoothed population curve, fitted tuning curve, or topology layout stand in for the underlying data.
|
|
122
|
+
- Use a sequential colormap for nonnegative magnitude, a diverging colormap around a meaningful neutral value, and a cyclic colormap for phase.
|
|
123
|
+
- Label every colorbar with the encoded quantity and unit. State the meaning of node, edge, marker, and line encodings.
|
|
124
|
+
- Subsample dense trajectories or edges only by a declared rule. Preserve full data for numerical checks.
|
|
125
|
+
- Verify known events, extrema, connection directions, and start/end states against the source arrays.
|
|
126
|
+
|
|
127
|
+
## Common failures
|
|
128
|
+
|
|
129
|
+
- Time and neuron axes are swapped because shape was treated as meaning.
|
|
130
|
+
- Simulation `dt` is used after monitor subsampling changed the recording interval.
|
|
131
|
+
- Connectivity rows and columns are reversed, or matrices use different orderings across conditions.
|
|
132
|
+
- A diverging colormap is centered at zero when zero has no scientific role.
|
|
133
|
+
- Raster bins, smoothing windows, tuning bins, network layouts, or 3D thresholds change across a comparison.
|
|
134
|
+
- Network positions, trajectory coordinates, or interpolated maps imply biological geometry that the data do not contain.
|
|
135
|
+
- A generic dendrite view duplicates BrainCell-owned morphology visualization.
|
|
136
|
+
|
|
137
|
+
## Tutorial sources
|
|
138
|
+
|
|
139
|
+
- [Neural data visualization](https://brainx.chaobrain.com/braintools/visualize/01_neural_data_visualization.html)
|
|
140
|
+
- [Advanced neural plots](https://brainx.chaobrain.com/braintools/visualize/02_advanced_neural_plots.html)
|
|
141
|
+
- [3D visualization](https://brainx.chaobrain.com/braintools/visualize/06_3d_visualization.html)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Statistical and model visualization
|
|
2
|
+
|
|
3
|
+
## Purpose and boundary
|
|
4
|
+
|
|
5
|
+
Use this reference to inspect distributions and assumptions, compare groups, explore associations, diagnose regression, and evaluate classification or learning behavior. Plot the sampling structure that supports the scientific claim; a visual summary does not replace the statistical analysis.
|
|
6
|
+
|
|
7
|
+
Route BrainMass-owned FC/FCD, spectral, or dynamical summaries to `skills/package-skills/brainmass/references/visualization-analysis-api.md` before plotting them here.
|
|
8
|
+
|
|
9
|
+
## Choose the statistical family
|
|
10
|
+
|
|
11
|
+
Inspect distributions and assumptions before selecting a test or reporting a model score.
|
|
12
|
+
|
|
13
|
+
| Question | Use | Required context |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| What is the shape, spread, or tail behavior? | `distribution_plot(...)` | Sampling unit, `n`, binning or density settings, exclusions, and units. |
|
|
16
|
+
| Is a theoretical distribution plausible? | `qq_plot(...)` | Named reference distribution and whether deviations matter to the planned inference. |
|
|
17
|
+
| How do groups differ? | `box_plot(...)` or `violin_plot(...)` plus raw observations | Independent or paired structure, group sizes, center, spread, uncertainty, and effect size. |
|
|
18
|
+
| Which variables associate? | `correlation_matrix(...)` or `scatter_matrix(...)` | Variable orientation, method, missing-data rule, ordering, and multiple-comparison plan. |
|
|
19
|
+
| Is a relationship fitted adequately? | `regression_plot(...)` plus `residual_plot(...)` | Model family, train/held-out split, confidence meaning, residual definition, and units. |
|
|
20
|
+
| Which classification errors occur? | `confusion_matrix(...)` | Class order, counts versus normalization, prevalence, and decision threshold. |
|
|
21
|
+
| How does a binary ranker perform by threshold? | `roc_curve(...)` or `precision_recall_curve(...)` | Positive class, score direction, prevalence, operating costs, and held-out predictions. |
|
|
22
|
+
| Is performance data-limited, high-variance, or biased? | `learning_curve(...)` | Train sizes or steps, fold dimension, scoring metric, and held-out protocol. |
|
|
23
|
+
|
|
24
|
+
Do not infer causality from correlation. Do not use statistical significance as a substitute for effect size or practical importance.
|
|
25
|
+
|
|
26
|
+
## Inspect distributions and groups
|
|
27
|
+
|
|
28
|
+
Distribution and group figures expose data shape and sampling structure; show raw observations when feasible.
|
|
29
|
+
|
|
30
|
+
| API | Description |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `distribution_plot(data, labels=None, plot_type='hist', bins=30, density=True, fit_normal=False, ...)` | Use for one or more distributions. Choose histogram, density, or both deliberately; treat binning and density estimation as declared transformations. |
|
|
33
|
+
| `qq_plot(data, distribution='norm', ...)` | Use to compare empirical and theoretical quantiles. Interpret systematic deviations, not visual proximity alone. |
|
|
34
|
+
| `box_plot(data, labels=None, showmeans=True, ...)` | Use for robust grouped summaries. Overlay raw observations when their count permits and state whether groups are paired. |
|
|
35
|
+
| `violin_plot(data, labels=None, showmeans=True, showmedians=True, ...)` | Use when distribution shape matters and sample size supports density estimation. Do not imply precision from a small-sample violin. |
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import matplotlib.pyplot as plt
|
|
39
|
+
import braintools.visualize as btvis
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
fig, axes = plt.subplots(1, 2, figsize=(7, 3.2))
|
|
43
|
+
btvis.distribution_plot(residuals, plot_type="hist", bins=30, ax=axes[0])
|
|
44
|
+
btvis.qq_plot(residuals, distribution="norm", ax=axes[1])
|
|
45
|
+
axes[0].set_xlabel("residual (mV)")
|
|
46
|
+
fig.tight_layout()
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Report the sampling unit, `n`, center, spread, uncertainty definition, and effect size beside the plot. Correct multiple comparisons and preserve paired observations rather than plotting paired data as independent groups.
|
|
50
|
+
|
|
51
|
+
## Inspect association and regression
|
|
52
|
+
|
|
53
|
+
Association plots reveal structure; residual plots test whether a fitted relationship leaves systematic error.
|
|
54
|
+
|
|
55
|
+
| API | Description |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `correlation_matrix(data, labels=None, method='pearson', ...)` | Use for pairwise associations with `(observations, variables)` data. Align labels to the variable axis and keep their order fixed. |
|
|
58
|
+
| `scatter_matrix(data, labels=None, diagonal='hist', ...)` | Use for pairwise multivariate inspection with ordinary `(observations, variables)` data. It returns a Matplotlib figure; reduce variables or sample density when unreadable. |
|
|
59
|
+
| `regression_plot(x, y, fit_line=True, confidence_interval=True, ...)` | Use for observations and an optional linear fit. A confidence band is not a prediction interval and the helper does not justify the model family. |
|
|
60
|
+
| `residual_plot(y_true, y_pred, ...)` | Use for aligned truth and prediction arrays. It computes residuals against predictions; preserve target units and observation order. |
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import matplotlib.pyplot as plt
|
|
64
|
+
import braintools.visualize as btvis
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
assert y_true.shape == y_pred.shape
|
|
68
|
+
limits = [min(y_true.min(), y_pred.min()), max(y_true.max(), y_pred.max())]
|
|
69
|
+
fig, axes = plt.subplots(1, 2, figsize=(7, 3.2))
|
|
70
|
+
axes[0].scatter(y_true, y_pred, alpha=0.6)
|
|
71
|
+
axes[0].plot(limits, limits, "k--", linewidth=1)
|
|
72
|
+
btvis.residual_plot(y_true, y_pred, ax=axes[1])
|
|
73
|
+
axes[0].set(xlabel="observed (Hz)", ylabel="predicted (Hz)")
|
|
74
|
+
fig.tight_layout()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Inspect residual center, trend, changing spread, tails, and outliers. Keep train and held-out residuals separate. Use a 1:1 line for observed-versus-predicted comparisons; a fitted regression line answers a different question.
|
|
78
|
+
|
|
79
|
+
## Evaluate classification and learning
|
|
80
|
+
|
|
81
|
+
Model-evaluation figures consume held-out labels, scores, predictions, or fold-wise learning results; never substitute training predictions unless the figure is explicitly diagnostic.
|
|
82
|
+
|
|
83
|
+
| API | Description |
|
|
84
|
+
|---|---|
|
|
85
|
+
| `confusion_matrix(y_true, y_pred, labels=None, normalize=None, ...)` | Use counts for workload and error totals. Use `normalize='true'` for per-true-class recall proportions or `normalize='pred'` for per-predicted-class composition; state the normalization. |
|
|
86
|
+
| `roc_curve(y_true, y_scores, ...)` | Use for binary ranking behavior across thresholds when both classes and ranking tradeoffs are meaningful. ROC can look optimistic under severe imbalance. |
|
|
87
|
+
| `precision_recall_curve(y_true, y_scores, ...)` | Prefer for imbalanced positive-class evaluation or when positive predictions and recall drive the decision. State positive-class prevalence. |
|
|
88
|
+
| `learning_curve(train_sizes, train_scores, validation_scores, ...)` | Use for train and validation score arrays across declared sizes or steps. Preserve fold or repeat dimensions so spread is visible. |
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
import matplotlib.pyplot as plt
|
|
92
|
+
import braintools.visualize as btvis
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
fig, axes = plt.subplots(1, 3, figsize=(10, 3.2))
|
|
96
|
+
btvis.confusion_matrix(y_test, y_pred, normalize="true", ax=axes[0])
|
|
97
|
+
btvis.roc_curve(y_test, y_score, ax=axes[1])
|
|
98
|
+
btvis.precision_recall_curve(y_test, y_score, ax=axes[2])
|
|
99
|
+
fig.tight_layout()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Fix the positive class, score direction, decision threshold, class order, and evaluation cohort before comparing models. Use cross-validation score distributions and paired comparisons rather than presenting one split or one scalar score as definitive.
|
|
103
|
+
|
|
104
|
+
A persistent train-validation gap suggests variance or leakage and requires protocol inspection. Low converged train and validation performance suggests bias, weak features, or an unsuitable metric. A learning curve diagnoses patterns; it does not identify the cause by itself.
|
|
105
|
+
|
|
106
|
+
## Preserve statistical integrity
|
|
107
|
+
|
|
108
|
+
- Display raw observations when feasible and state `n` for every group or condition.
|
|
109
|
+
- Report effect sizes and confidence intervals with exact definitions. Distinguish practical from statistical significance.
|
|
110
|
+
- Correct multiple comparisons and state the correction family. Do not decorate uncorrected pairwise results as discoveries.
|
|
111
|
+
- Preserve paired, repeated-measures, nested, and cross-validation structure in both analysis and display.
|
|
112
|
+
- Keep axes honest. Use a truncated axis only when necessary, conspicuous, and unable to reverse the visual conclusion.
|
|
113
|
+
- Use the same scales, bins, ordering, metric definitions, and encodings across model or condition comparisons.
|
|
114
|
+
- Separate exploratory, training, validation, and held-out test evidence. Record preprocessing and threshold selection provenance.
|
|
115
|
+
- Treat correlation, feature importance, and fitted association as descriptive unless the design supports a causal claim.
|
|
116
|
+
|
|
117
|
+
## Common failures
|
|
118
|
+
|
|
119
|
+
- A mean and error bar hide the raw distribution, group size, or failed runs.
|
|
120
|
+
- Density or violin shape is overinterpreted for a small sample.
|
|
121
|
+
- Paired or nested observations are plotted and tested as independent.
|
|
122
|
+
- Correlation variables or labels use the wrong axis, or correlation is called connectivity or causality.
|
|
123
|
+
- A nonlinear relationship is summarized with an unjustified linear fit.
|
|
124
|
+
- Residuals are inspected only in aggregate, hiding bias or heteroscedasticity.
|
|
125
|
+
- ROC is selected for a highly imbalanced task without a precision-recall view or prevalence context.
|
|
126
|
+
- Confusion matrices use inconsistent class order or undisclosed normalization.
|
|
127
|
+
- Model comparison uses one score, one split, or tuned test-set thresholds.
|
|
128
|
+
- Axis truncation, changing bins, or inconsistent scales exaggerate differences.
|
|
129
|
+
|
|
130
|
+
## Tutorial sources
|
|
131
|
+
|
|
132
|
+
- [Statistical visualization](https://brainx.chaobrain.com/braintools/visualize/03_statistical_visualization.html)
|
|
133
|
+
- [Model evaluation plots](https://brainx.chaobrain.com/braintools/visualize/04_model_evaluation_plots.html)
|