Skip to main content

Python SDK

MOISSCode can be embedded directly in any Python application, giving you full access to 20 clinical modules, the DSL interpreter, and the type system.

Installation

From source (development):

git clone https://github.com/aethryva/MOISSCode.git
cd MOISSCode
pip install -e .

Quick Start (5 Lines)

from moisscode import StandardLibrary, Patient

lib = StandardLibrary()
p = Patient(bp=85, hr=110, rr=24, gcs=14, lactate=3.2, sex='M')
print(lib.scores.qsofa(p))

Public API

from moisscode import (
MOISSCodeLexer, # Tokenizer
MOISSCodeParser, # AST parser
MOISSCodeInterpreter, # Runtime engine
Patient, # Patient dataclass
StandardLibrary, # 20-module library
__version__, # Current version string
)

Creating Patient Objects

The Patient dataclass holds all clinical data points that modules consume:

from moisscode import Patient

patient = Patient(
name="Jane Doe",
age=67,
weight=72.0,
bp=88, # Systolic blood pressure (mmHg)
hr=115, # Heart rate (bpm)
rr=26, # Respiratory rate (breaths/min)
temp=38.9, # Temperature (Celsius)
spo2=92, # Oxygen saturation (%)
gcs=13, # Glasgow Coma Scale (3-15)
lactate=4.1, # Serum lactate (mmol/L)
sex='F' # 'M' or 'F'
)

All fields are optional. Modules will use only the fields they need.


Using Modules Directly (Without the DSL)

The StandardLibrary gives you access to all 20 modules as Python objects. No interpreter or DSL syntax required.

from moisscode import StandardLibrary
lib = StandardLibrary()

Clinical Scores (lib.scores)

from moisscode import Patient, StandardLibrary
lib = StandardLibrary()
p = Patient(bp=85, hr=110, rr=24, gcs=14, lactate=3.2, sex='M')

result = lib.scores.qsofa(p)
# Returns: {'score': 2, 'risk': 'High', 'criteria_met': ['sbp', 'rr']}

sofa = lib.scores.sofa(p)
news = lib.scores.news2(p)

Pharmacokinetics (lib.pk)

# Weight based dosing
dose = lib.pk.calculate_dose("Vancomycin", weight_kg=70)

# Dose validation with safety limits
check = lib.pk.validate_dose("Vancomycin", 1.0, "g", weight=70)
# Returns: {'safe': True, 'warnings': [], ...}

# Drug interaction checking
interactions = lib.pk.check_interactions(["Warfarin", "Aspirin"])

# List all available drugs
drugs = lib.pk.list_drugs()

Lab Interpretation (lib.lab)

# Single test interpretation
result = lib.lab.interpret("WBC", 18.5)
# Returns: {'value': 18.5, 'unit': '10^3/uL', 'flag': 'HIGH', ...}

# Full panel interpretation
cbc = lib.lab.panel("CBC", {
"WBC": 18.5, "RBC": 4.2, "Hgb": 12.1, "Hct": 36, "Plt": 250
})

# GFR calculation
gfr = lib.lab.gfr(creatinine=2.1, age=68, sex='M')

Microbiology (lib.micro)

# Organism lookup
org = lib.micro.get_organism("E. coli")

# Empiric therapy
therapy = lib.micro.empiric_therapy("UTI")

# Susceptibility interpretation
result = lib.micro.interpret_susceptibility("E. coli", "Ciprofloxacin", mic=0.5)

Genomics (lib.genomics)

# CYP450 metabolizer phenotyping
phenotype = lib.genomics.get_phenotype("CYP2D6", "*1/*4")

# Pharmacogenomic dosing recommendation
rec = lib.genomics.get_recommendation("CYP2C19", "Clopidogrel", "*2/*2")

Biochemistry (lib.biochem)

# Enzyme kinetics
kinetics = lib.biochem.michaelis_menten(substrate_conc=5.0, enzyme="Lactate Dehydrogenase")

# Metabolic pathway simulation
pathway = lib.biochem.simulate_pathway("Glycolysis")

Epidemiology (lib.epi)

# SIR model
sir = lib.epi.sir_model(population=1000000, infected=100, r0=2.5)

# Outbreak metrics
metrics = lib.epi.outbreak_metrics(cases=500, deaths=12, population=100000, days=30)

Nutrition (lib.nutrition)

# Basal metabolic rate
bmr = lib.nutrition.harris_benedict(weight=70, height=175, age=45, sex='M')

# BMI with classification
bmi = lib.nutrition.bmi(weight=70, height=1.75)

FHIR R4 (lib.fhir)

from moisscode import Patient
p = Patient(name="Jane Doe", age=67, sex='F')

# Generate FHIR Patient resource
patient_resource = lib.fhir.to_fhir(p)

# Create medication request
med = lib.fhir.medication_request("Vancomycin", "1g IV q12h")

# Full bundle
bundle = lib.fhir.create_bundle([patient_resource, med])

Glucose / Diabetes (lib.glucose)

# HbA1c estimation from average glucose
a1c = lib.glucose.estimate_a1c(avg_glucose=180)

# CGM analytics
readings = [120, 145, 180, 95, 110, 200, 160, 130, 105, 90]
variability = lib.glucose.glycemic_variability(readings)

Chemistry (lib.chem)

# Drug likeness scoring (Lipinski Rule of Five)
score = lib.chem.lipinski("Aspirin")

# Compound lookup
compound = lib.chem.get_compound("Metformin")

Signal Processing (lib.signal)

# ECG peak detection
ecg_data = [0.1, 0.3, 0.8, 1.2, 0.9, 0.2, 0.1, 0.3, 0.7, 1.1]
peaks = lib.signal.detect_peaks(ecg_data, sample_rate=250)

# Heart rate variability
hrv = lib.signal.hrv_analysis([0.8, 0.85, 0.78, 0.82, 0.9])

ICD Coding (lib.icd)

# Code lookup
code = lib.icd.lookup("I21.0")

# Search by description
results = lib.icd.search("myocardial infarction")

# DRG grouping
drg = lib.icd.drg_lookup("MS-DRG 291")

Finance (lib.finance)

# CPT code lookup
cpt = lib.finance.cpt_lookup("99291")

# Cost estimation
cost = lib.finance.estimate_cost(["99291", "71046", "36556"])

Database (lib.db)

# Store and retrieve patient data (SQLite)
lib.db.store_patient({"name": "Jane Doe", "mrn": "12345"})
patients = lib.db.query_patients(mrn="12345")

I/O (lib.io)

# Read clinical data from CSV
data = lib.io.read_csv("vitals.csv")

# Export to JSON
lib.io.write_json("output.json", results)

Research (lib.research)

# De-identification (Safe Harbor)
clean = lib.research.deidentify({"name": "Jane Doe", "mrn": "12345", "age": 67})

# Sample size calculation
n = lib.research.sample_size(effect_size=0.5, alpha=0.05, power=0.8)

Scientific Papers (lib.papers)

# Generate LaTeX manuscript
latex = lib.papers.generate(
title="Sepsis Early Warning Protocol",
format="ieee",
sections={"abstract": "...", "methods": "...", "results": "..."}
)

KAE (lib.kae)

# Kalman Adaptive Estimator for biomarker tracking
estimate = lib.kae.estimate(
measurements=[3.2, 3.5, 4.1, 3.8],
timestamps=[0, 60, 120, 180]
)

MOISS (lib.moiss)

# Multi-Organ Intervention State Space classification
classification = lib.moiss.classify(
organ_states={"cardiovascular": 0.7, "respiratory": 0.4, "renal": 0.8}
)

Executing DSL Protocols Programmatically

If you want to run .moiss protocol files from Python:

from moisscode import MOISSCodeLexer, MOISSCodeParser, MOISSCodeInterpreter

code = open('my_protocol.moiss').read()

tokens = MOISSCodeLexer().tokenize(code)
program = MOISSCodeParser(tokens).parse_program()
events = MOISSCodeInterpreter().execute(program)

# Process events
for e in events:
if e['type'] == 'ALERT':
print(f"Alert: {e['message']} ({e['severity']})")
elif e['type'] == 'ADMINISTER':
print(f"Drug: {e['drug']} at {e['dose']}")

Injecting Patient Data into Protocols

from moisscode import MOISSCodeInterpreter, Patient

patient = Patient(
name="Jane Doe", age=67, weight=72.0,
bp=88, hr=115, rr=26, temp=38.9,
spo2=92, gcs=13, lactate=4.1, sex='F'
)

interp = MOISSCodeInterpreter()
interp.scope['p'] = {'type': 'Patient', 'value': patient}

# The protocol will use your injected patient
events = interp.execute(program)

Event Types

Events returned by execute() contain structured clinical output:

TypeFieldsDescription
LOGmessageInternal log entry
TRACKtarget, raw, kae_pos, kae_velValue tracking with KAE
ADMINISTERdrug, dose, moiss_classDrug administration
ALERTmessage, severityClinical alert
ASSESScondition, score, riskClinical assessment
LETname, valueVariable assignment
FOR_EACHvar, countLoop summary

Professional Use

MOISSCode is professional biomedical software. All clinical outputs should be validated by qualified professionals before patient care application.

See Also