Repository navigation
Developer & Deployment Guide
This guide details the repository structure, local development environment setup, unit testing protocols, database migration strategies, and production deployment procedures for BioLabCalc and its Electronic Lab Notebook (ELN) / Multi-Modal LIMS subsystem.
The codebase follows modern Python packaging standards with clear architectural separation between core biophysical calculators, the ELN subsystem, analytical parsers, and browser assets:
biolabcalc_repository/
βββ src/
β βββ biolabcalc/
β βββ __init__.py <- Package root and version exports
β βββ cli.py <- Click/argparse CLI entrypoint (29 commands)
β βββ easy.py <- High-level convenience API for Jupyter / IPython
β βββ molecular_weight.py <- MW, isotopic distribution, and elemental formula
β βββ protein.py <- Extinction coefficients (e280), pI, Net charge
β βββ buffers.py <- Recipe generator, dilution (C1V1), pH Henderson-Hasselbalch
β βββ cloning.py <- Gibson assembly, Golden Gate Type IIS, restriction digest
β βββ pcr.py <- SantaLucia thermodynamics, primer annealing, Q5/Taq
β βββ gels.py <- Agarose / SDS-PAGE band simulation & Rf mapping
β βββ western_blot.py <- Membrane transfer scaling, antibody dilution math
β βββ fluorescence.py <- Fluorophore excitation/emission spectra & FRET overlap
β βββ ecoli_growth.py <- Bacterial doubling kinetics, OD600 biomass modeling
β βββ precipitation.py <- Ethanol/isopropanol/NaOAc desalting stoichiometry
β βββ eln/ <- Electronic Lab Notebook & LIMS Subsystem
β βββ server.py <- Dual-engine server launcher (Uvicorn ASGI / HTTP fallback)
β βββ api/ <- REST routing, WebSockets, and authentication
β β βββ app.py <- FastAPI application factory
β β βββ router.py <- Unified API route aggregator
β β βββ websocket_manager.py<- Real-time client state broadcaster
β β βββ routes/ <- Domain-specific endpoint handlers (sops, inventory, etc.)
β βββ parsers/ <- Analytical instrument file decoders
β β βββ fplc_parser.py <- ΓKTA UNICORN (.res, .csv, .zip) multi-channel reader
β β βββ nanodrop_parser.py <- Thermo NanoDrop UV-Vis spectral curve extractor
β β βββ biorad_parser.py <- Bio-Rad Image Lab (.scn) & 16-bit TIFF densitometer
β β βββ abf_parser.py <- Pure-Python Axon Binary Format (ABF v1/v2, ATF) decoder
β β βββ doc_parser.py <- Protocol Markdown and table structure parser
β β βββ ocr_engine.py <- HITL OCR engine with biochemical entity disambiguation
β βββ rag/ <- Local intelligence & retrieval-augmented generation
β β βββ chunker.py <- Laboratory entity extractor & semantic chunker
β β βββ hybrid_search.py <- BM25 + dense vector Reciprocal Rank Fusion engine
β β βββ local_llm.py <- Local inference client (Ollama/GGUF) + offline fallback
β β βββ synthesizer.py <- Contextual citation synthesizer with footnotes
β βββ schema/ <- Relational models, DDL, and database engines
β β βββ database.py <- Dual database abstraction (custom SQLite ORM + PostgreSQL)
β β βββ ddl.sql <- PostgreSQL 16+ pgvector production DDL (21 tables)
β β βββ models.py <- Declarative entity models
β βββ services/ <- Core business logic & GxP governance
β β βββ audit_service.py <- SHA-256 cryptographically chained immutable ledger
β β βββ sop_service.py <- SOP versioning, PI sign-offs, and execution forks
β β βββ inventory_service.py<- 6-tier freezer hierarchy, 2D grid, sample lineage
β β βββ campaign_service.py <- Multi-day experimental campaign management
β β βββ fplc_service.py <- Fraction collection and chromatogram integration
β βββ storage/ <- Content-Addressed Storage (CAS)
β β βββ blob_store.py <- SHA-256 sharded file storage (local & S3/MinIO)
β β βββ preview_generator.py<- Web preview downsampling for large analytical files
β βββ web/ <- Single-Page Application assets
β βββ templates/index.html<- Unified HTML5 laboratory workspace
β βββ static/ <- Canvases, timers, freezer grids, and stylesheets
βββ tests/ <- Test suite
βββ pyproject.toml <- Build configuration, dependencies, and entrypoints
βββ README.md <- Repository overview
Clone the repository and install in editable mode with development dependencies:
# Clone the repository
git clone https://github.com/your-org/biolabcalc.git
cd biolabcalc
# Create and activate an isolated Python virtual environment
python -m venv venv
source venv/bin/activate # On Windows: .\venv\Scripts\activate
# Install package in editable mode with development and ELN extras
pip install -e ".[dev,eln]"The repository maintains exhaustive test coverage across all calculators, parsers, and ELN services using Python's standard unittest framework:
# Execute entire test suite
python -m unittest discover tests
# Run ELN test suites
python -m unittest tests/test_eln_services_and_api.py
python -m unittest tests/test_eln_parsers.py
python -m unittest tests/test_eln_rag.py
python -m unittest tests/test_eln_schema.py
python -m unittest tests/test_eln_integration.pyWhile the zero-dependency SQLite engine is optimal for local evaluation, high-throughput multi-user enterprise deployments should run on PostgreSQL 16+ with the pgvector extension.
Connecting to PostgreSQL requires SQLAlchemy and psycopg2-binary, installed via pip install "biolabcalc[eln]". When using file-based SQLite, WAL mode (PRAGMA journal_mode = WAL;) and a 30-second busy timeout are automatically enabled to ensure reliable concurrency, while in-memory SQLite connections are guarded by thread synchronization locks.
CREATE DATABASE eln_production;
\c eln_production;
-- Enable required extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "vector";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
CREATE EXTENSION IF NOT EXISTS "btree_gin";Apply the complete 21-table production schema located at src/biolabcalc/eln/schema/ddl.sql:
psql -U postgres -d eln_production -f src/biolabcalc/eln/schema/ddl.sqlLaunch the ELN server targeting the PostgreSQL database:
biolabcalc eln --db "postgresql://eln_user:secret_password@localhost:5432/eln_production" --port 8080Or export the standard environment variable:
export DATABASE_URL="postgresql://eln_user:secret_password@localhost:5432/eln_production"
biolabcalc elnCreate a docker-compose.yml to provision PostgreSQL with pgvector alongside the BioLabCalc ELN application container:
version: '3.8'
services:
db:
image: pgvector/pgvector:pg16
restart: always
environment:
POSTGRES_DB: eln_production
POSTGRES_USER: eln_admin
POSTGRES_PASSWORD: secure_biolab_password
volumes:
- pgdata:/var/lib/postgresql/data
- ./src/biolabcalc/eln/schema/ddl.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "5432:5432"
eln:
build: .
restart: always
depends_on:
- db
environment:
DATABASE_URL: postgresql://eln_admin:secure_biolab_password@db:5432/eln_production
BIOLABCALC_STORAGE_DIR: /data/storage
BIOLABCALC_AUDIT_LOG: /data/storage/audit_ledger.jsonl
volumes:
- eln_data:/data/storage
ports:
- "8080:8080"
command: ["biolabcalc", "eln", "--host", "0.0.0.0", "--port", "8080", "--no-browser"]
volumes:
pgdata:
eln_data:Launch the cluster:
docker-compose up -dFor standard bare-metal or virtual server deployments running on Ubuntu / Debian / RHEL:
Create /etc/systemd/system/biolabcalc-eln.service:
[Unit]
Description=BioLabCalc Electronic Lab Notebook & LIMS Service
After=network.target postgresql.service
[Service]
Type=simple
User=biolab
Group=biolab
WorkingDirectory=/opt/biolabcalc
Environment="PATH=/opt/biolabcalc/venv/bin:/usr/bin"
Environment="DATABASE_URL=postgresql://eln_user:secret@localhost:5432/eln_production"
Environment="BIOLABCALC_STORAGE_DIR=/var/lib/biolabcalc/data"
ExecStart=/opt/biolabcalc/venv/bin/biolabcalc eln --host 127.0.0.1 --port 8080 --no-browser
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.targetEnable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable --now biolabcalc-eln.serviceDeploy Nginx in front of BioLabCalc to manage SSL/TLS termination, request buffering, client upload limits, and WebSocket upgrade protocols:
server {
listen 80;
server_name eln.lab.institution.edu;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name eln.lab.institution.edu;
ssl_certificate /etc/letsencrypt/live/eln.lab.institution.edu/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/eln.lab.institution.edu/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Allow large instrument file uploads (FPLC runs, gel micrographs up to 500 MB)
client_max_body_size 500M;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket support for real-time timer sync and live updates
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
}When running the embedded SQLite engine in multi-threaded laboratory setups, enable Write-Ahead Logging (WAL) mode to permit concurrent readers during writes:
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA cache_size = -64000; -- 64 MB memory cache
PRAGMA foreign_keys = ON;Content-Addressed Storage automatically deduplicates uploads based on SHA-256 hash digests. To remove unreferenced "orphan" blobs (e.g. from deleted temporary drafts):
from biolabcalc.eln.storage.blob_store import BlobStore
store = BlobStore(base_dir="/var/lib/biolabcalc/data/blobs")
# Enumerate all physical blobs
all_blobs = store.list_blobs()
print(f"Total stored blobs: {len(all_blobs)}")-
Database Backup: Standard automated PostgreSQL dumps:
pg_dump -U eln_admin -Fc eln_production > /backup/eln_$(date +%Y%m%d_%H%M%S).dump
-
CAS Blob Synchronization: Because blobs are immutable and named by SHA-256 hashes, they can be synchronized incrementally to cold storage (e.g. AWS S3 Glacier or NAS) using
rsyncor S3 sync:rsync -av --ignore-existing /var/lib/biolabcalc/data/blobs/ /mnt/backup_nas/blobs/
Many academic and biotechnology wet-labs share experimental data via a local network drive (e.g., Windows SMB UNC paths \\server\share\biolabcalc_data, mapped drives like Z:\lab_data, or NFS/POSIX /mnt/lab_share).
Standard SQLite databases running in Write-Ahead Logging (WAL) mode can experience file locking errors over network filesystems because SQLite's -shm shared-memory indexing requires OS-level shared memory that does not span network boundaries.
BioLabCalc resolves this automatically when a network path is designated:
-
Network-Safe Pragmas:
PRAGMA journal_mode = DELETE; -- Avoids -shm shared-memory file creation PRAGMA busy_timeout = 60000; -- 60s lock queue wait time for concurrent writes PRAGMA locking_mode = NORMAL; -- Allows concurrent multi-user reads
-
Cross-Process Advisory File Locking: Critical sections (such as migrations and batch operations) use
.locktokens with exponential backoff and stale-lock recovery. -
Optimistic Concurrency Control (OCC): Entries track UUID
version_tokenstamps; simultaneous modifications trigger conflict detection rather than silent data overwrites.
Run the automated configuration wizard:
python run.py setup --shared-dir "Z:\BioLabCalc_Data" --role "Active Researcher"Or manually configure config.yaml:
database:
storage_mode: "network_share"
shared_folder_path: "Z:\\BioLabCalc_Data"
lock_timeout_seconds: 60For laboratory workstations connected to scientific instruments where users lack administrator privileges or a local Python environment, BioLabCalc provides a standalone portable bundle.
Generate the zero-install bundle:
python scripts/package_portable.pyThis prepares dist/biolabcalc_portable/ containing:
-
run_lab.batβ One-click Windows desktop launcher. -
run_lab.shβ One-click macOS / Linux desktop launcher. -
config.yaml.exampleβ Preset configuration template. -
README_PORTABLE.txtβ Zero-admin quickstart instructions.
- Copy
biolabcalc_portableto the workstation desktop, USB drive, or shared network drive. - Double-click
run_lab.bat(or execute./run_lab.sh). - If no
config.yamlis detected, the setup wizard will launch in the browser or terminal to select your shared laboratory folder.
To assist bench researchers and lab managers when network drives disconnect or permissions fail, BioLabCalc includes an automated diagnostic recorder.
Any unhandled exception, network share disconnect, lock collision, or file permission issue is intercepted by biolabcalc.diagnostics:
- Plain-English Explanations: Converts complex tracebacks into actionable guidance.
- Sanitized Logs: Masks sensitive paths, user directories, and IP addresses.
-
Persistent Logs: Writes to
failures.logandfailures.jsonl. -
Git-Ignored Protection: All diagnostic logs are strictly excluded in
.gitignoreto prevent committing laboratory operational data.
Inspect recent laboratory operational issues:
# View last 10 diagnostic reports with remediation suggestions
python run.py diagnostics
# View raw JSON output for automation
python run.py diagnostics --json
# Clear failure history
python run.py diagnostics --clear- Electronic Lab Notebook (ELN) β System architecture and server options.
- GxP Compliance & Audit Trails β 21 CFR Part 11 ledger verification commands.
- RAG & Local AI Assistant β Configuring local LLM endpoints (Ollama, vLLM).
BioLabCalc Documentation Wiki | Licensed under the MIT License | GitHub Repository Research Use Only (RUO). Not intended for clinical or diagnostic procedures.
- Core Calculators & Stoichiometry
- Solution Prep & Spectroscopy
- Buffers & Precipitation
- Protein Quantification & Assays
- Fluorophores & Dye Labeling
- Molecular Cloning & Assembly
- Plasmid Engineering & Workbench
- PCR Kinetics & Primer Design
- In Vitro Transcription (IVT)
- Western Blotting Suite
- Bacterial Growth & Kinetics
- ELN System Architecture
- SOP & Protocol Management
- Instrument Data Parsers
- Inventory & Freezer LIMS
- Local RAG Knowledge Engine
- GxP Compliance & Audit Trails