This document describes the production batch processing scripts for the Chemical Matcher system. These scripts enable automated matching of lab EDD files, human validation workflows, and continuous learning.
Purpose: Process lab EDD files and generate matched results with confidence scores.
Usage:
# Basic usage with auto-detection
python scripts/11_match_batch.py --input data/raw/lab_edds/sample.xlsx --output results.xlsx
# Specify column and threshold
python scripts/11_match_batch.py --input data.csv --column "Parameter" --output matched.xlsx --confidence-threshold 0.80
# Generate separate review queue
python scripts/11_match_batch.py --input data.xlsx --output matched.xlsx --review-queue review.xlsxFeatures:
- Auto-detects analyte column in Excel/CSV files
- Processes thousands of analytes with progress tracking
- Generates two outputs:
matched_results.xlsx: All results with confidence scoresreview_queue.xlsx: Only flagged/unknown cases (optional)
- Logs all decisions to database for learning
- Provides summary statistics
Output Columns:
Original_Name: Input text as providedMatched_Analyte_ID: REG153_XXX identifierMatched_Preferred_Name: Canonical nameCAS_Number: CAS Registry Number (if available)Confidence: Confidence score (0.0-1.0)Match_Method: exact, fuzzy, semantic, cas_extracted, or unknownReview_Flag: TRUE if human review recommendedTop_3_Candidates: JSON array of alternative matchesResolution_Time_ms: Processing time
Purpose: Ingest human-validated synonyms into the database for Layer 1 learning.
Usage:
# Ingest specific validation file
python scripts/12_validate_and_learn.py --review-queue reports/review_validated.xlsx
# Auto-ingest mode (daily automation)
python scripts/12_validate_and_learn.py --auto-ingestFeatures:
- Supports multiple validation file formats
- Deduplicates existing synonyms
- Marks match decisions as validated
- Tracks retraining trigger threshold (2000+ validations)
- Provides summary statistics
Validation File Format:
Option A: Review Queue Format (from generate_review_queue.py)
raw_variant: Original textchosen_match: Selected preferred name (dropdown)validation_confidence: HIGH, MEDIUM, or LOW
Option B: Simple Format
- Column 1: Variant text
- Column 2: Validated match (preferred name)
Purpose: Generate comprehensive learning health reports for monitoring system maturity.
Usage:
# Generate default weekly report
python scripts/13_generate_learning_report.py
# Generate report for last 14 days
python scripts/13_generate_learning_report.py --days 14
# Generate markdown report to specific location
python scripts/13_generate_learning_report.py --output reports/weekly/report.md --format markdownFeatures:
- Corpus maturity scoring (0-100)
- Match method distribution trends
- Synonym growth tracking
- Threshold calibration status
- Retraining progress indicators
- Actionable recommendations
Report Sections:
- Executive Summary with maturity score
- Match Performance Metrics
- Corpus Growth & Coverage
- Threshold Calibration Status
- Learning Progress Tracking (4 layers)
- Retraining Indicators
- Action Items & Recommendations
Purpose: Evaluate whether neural model retraining is warranted based on multiple trigger conditions.
Usage:
# Run assessment and display results
python scripts/14_check_retraining_need.py
# Save assessment to file
python scripts/14_check_retraining_need.py --output reports/retraining_assessment.txtTrigger Conditions:
- Validation Volume: >= 2000 validated decisions since last training
- Unknown Rate Plateau: Unknown rate not decreasing over time
- Semantic Reliance High: > 30% of matches use semantic matching
- Low Confidence Prevalence: > 20% of matches have confidence 0.75-0.85
Decision Logic:
- RECOMMENDED (≥2 triggers): Retraining strongly recommended
- CONSIDER (1 trigger): Consider retraining if manual load high
- NOT NEEDED (0 triggers): Continue current operations
Exit Codes:
0: Not needed1: Consider (warning)2: Recommended3: Error
Purpose: Generate Excel review queues with intelligent clustering of similar unknown variants.
Usage:
# Generate review queue from last 30 days
python scripts/generate_review_queue.py --output reports/review_queue.xlsx
# Last 7 days with minimum frequency of 2
python scripts/generate_review_queue.py --days 7 --min-frequency 2 --output queue.xlsx
# Include low-confidence matches below 0.80
python scripts/generate_review_queue.py --confidence-threshold 0.80Features:
- Collects unknowns and low-confidence matches
- Clusters similar variants using Levenshtein distance
- Provides top 3 match suggestions per variant
- Generates Excel file with validation dropdowns
- Tracks frequency and lab vendor context
Excel Output Columns:
raw_variant: Variant text to validatefrequency: Number of times observedlab_vendor: Lab that reported it (if known)matrix: Sample matrix (soil, groundwater, etc.)cluster_id: Cluster identifier for groupingsuggested_match_1,confidence_1: Top suggestionsuggested_match_2,confidence_2: Second suggestionsuggested_match_3,confidence_3: Third suggestionchosen_match: [Human fills this] Dropdown of all analytesvalidation_confidence: [Human fills this] HIGH/MEDIUM/LOWnotes: Optional validation notes
Workflow:
- Generate review queue
- Analyst opens Excel file
- Analyst selects
chosen_matchfrom dropdown for each variant - Analyst selects
validation_confidence(HIGH/MEDIUM/LOW) - Save file with "_validated" suffix
- Run
12_validate_and_learn.pyto ingest
Purpose: Windows batch script for daily automation of learning tasks.
Schedule: Run daily at 2 AM using Windows Task Scheduler
Tasks Performed:
Daily (Every Day):
- Step 1: Auto-ingest validated review queues (Layer 1 learning)
- Step 2: Generate learning health report
Monthly (1st of month):
- Step 3: Run threshold calibration (
10_monthly_calibration.py)
Quarterly (1st of Jan/Apr/Jul/Oct):
- Step 4: Run retraining need assessment
Weekly (Mondays):
- Step 5: Generate new review queue for the week
Setup Instructions:
-
Test the script manually:
cd "N:\Central\Staff\KG\Kiefer's Coding Corner\Reg 153 chemical matcher" scripts\daily_learning_loop.bat
-
Create Windows Task Scheduler entry:
- Open Task Scheduler
- Create Basic Task
- Name: "Chemical Matcher Daily Learning"
- Trigger: Daily at 2:00 AM
- Action: Start a program
- Program:
C:\Windows\System32\cmd.exe - Arguments:
/c "N:\Central\Staff\KG\Kiefer's Coding Corner\Reg 153 chemical matcher\scripts\daily_learning_loop.bat" - Run whether user is logged on or not
- Run with highest privileges
-
Verify logs:
- Check
logs/daily_loop/for execution logs - Review
reports/daily/for generated reports
- Check
Monday Morning:
- Review queue generated automatically (via daily_learning_loop.bat)
- Analyst receives email notification (optional, configure separately)
- Analyst opens
reports/daily/validations/review_queue_YYYYMMDD.xlsx
Throughout Week: 4. Analyst validates variants in Excel:
- Select
chosen_matchfrom dropdown - Set
validation_confidence(HIGH/MEDIUM/LOW) - Add notes if needed
- Save completed file as
review_queue_YYYYMMDD_validated.xlsx - Place in
reports/daily/validations/folder
Daily (Automated): 7. Daily loop auto-ingests completed validation files (2 AM) 8. New synonyms added to database (Layer 1 learning) 9. Learning report generated
Monthly (1st of month): 10. Threshold calibration runs automatically 11. Optimal confidence thresholds recalculated
Quarterly (Jan/Apr/Jul/Oct): 12. Retraining assessment runs automatically 13. If recommended, coordinate neural model retraining
# Step 1: Run batch matching
python scripts/11_match_batch.py \
--input "data/raw/lab_edds/ALS_Report_2026_Q1.xlsx" \
--output "reports/ALS_2026_Q1_matched.xlsx" \
--review-queue "reports/ALS_2026_Q1_review.xlsx" \
--confidence-threshold 0.75
# Output:
# - All 5000 analytes processed in ~2 minutes
# - 4200 auto-matched (84%)
# - 350 flagged for review (7%)
# - 450 unknown (9%)
# Step 2: Validate review queue
# Open reports/ALS_2026_Q1_review.xlsx
# Validate the 800 flagged + unknown cases
# Save as reports/ALS_2026_Q1_review_validated.xlsx
# Step 3: Ingest validated synonyms
python scripts/12_validate_and_learn.py \
--review-queue "reports/ALS_2026_Q1_review_validated.xlsx"
# Output:
# - 650 new synonyms added
# - 150 duplicates skipped
# - Retraining progress: 1850/2000 (92.5%)
# Step 4: Re-run batch matching (next time)
# With 650 new synonyms, exact match rate should improve by ~5-10%- Review daily learning loop logs in
logs/daily_loop/ - Check for failed steps or warnings
- Monitor exact match rate trends
- Review weekly learning report in
reports/weekly/ - Validate review queue (15-30 minutes of analyst time)
- Track unknown rate and synonym growth
- Review threshold calibration results
- Assess match method distribution
- Evaluate corpus maturity score
- Review retraining assessment
- If recommended, plan neural model retraining
- Archive old logs and reports
Solution: Explicitly specify column name with --column parameter
python scripts/11_match_batch.py --input file.xlsx --column "Test Parameter" --output results.xlsxCause: Synonyms already exist in database (expected behavior) Action: No action needed - system prevents duplicates
Cause: May need more diverse validation coverage or semantic matching Action:
- Generate targeted review queue
- Focus validation on high-frequency unknowns
- Consider enabling/improving semantic matching
Check:
- Windows Task Scheduler is configured correctly
- Python is accessible from system PATH
- Project directory path is correct
- Database permissions are correct
- Check logs in
logs/daily_loop/
Cause: Large analyte list (>255 chars) triggers reference sheet mode Solution: Analytes are in separate sheet "Analyte Names" - dropdown still works
- Throughput: ~500-1000 analytes/second (mostly exact matches)
- Bottleneck: Fuzzy matching (if many fuzzy matches needed)
- Optimization: Use higher confidence threshold to reduce fuzzy lookups
- Growth Rate: ~500-2000 new synonyms/month (depending on validation rate)
- Index Maintenance: Automatic (SQLite handles this)
- Backup: Recommended weekly backup of
data/reg153_matcher.db
- Target: 50-200 variants per weekly queue
- If too large: Increase
--min-frequencyor reduce--dayslookback - If too small: Decrease
--confidence-thresholdto catch more borderline cases
Adjust based on use case:
High Precision (minimize false positives):
python scripts/11_match_batch.py --input file.xlsx --output results.xlsx --confidence-threshold 0.90
# More cases sent to review, but higher confidence in auto-matchesHigh Recall (minimize unknowns):
python scripts/11_match_batch.py --input file.xlsx --output results.xlsx --confidence-threshold 0.70
# More auto-matches, but some may need manual verification# Windows batch script to process multiple files
for %%f in (data\raw\lab_edds\*.xlsx) do (
python scripts\11_match_batch.py --input "%%f" --output "reports\%%~nf_matched.xlsx"
)Example: Export matched results to CSV for import:
import pandas as pd
# Read matched results
df = pd.read_excel('reports/matched_results.xlsx')
# Filter auto-accepted only
auto_accepted = df[df['Review_Flag'] == False]
# Export for downstream system
auto_accepted.to_csv('exports/auto_matched_for_import.csv', index=False)Planned improvements:
- Email notifications for daily loop completion
- Web dashboard for learning metrics visualization
- Automated backup and archival
- Integration with lab vendor APIs for direct EDD retrieval
- A/B testing framework for threshold optimization
- Semantic matching integration (Layer 2 learning)
- System Architecture: See
LEARNING_SYSTEM_IMPLEMENTATION.md - Matching Engine: See
MATCHING_ENGINE_DELIVERY.md - Database Schema: See
src/database/models.py - API Documentation: See inline docstrings
For questions or issues, contact the Chemical Matcher development team.
Last Updated: February 12, 2026
Version: 1.0