"""
Cross-Campus Cross-Listing Automation System
============================================
Built by Sherlock, AI from Trailblazer Labs.
This Python-based automation system handles:
- **RULES**: Configurable rules to match sections across campuses for cross-listing.
- **SEAT CAPS**: Manages shared or individual seat caps for cross-listed sections.
- **RECORDS**: SQLite database for auditing cross-listings, enrollments, and changes.
Key Features:
- Detect matching sections across campuses.
- Automate cross-listing (merge enrollments, adjust caps).
- Enforce rules (e.g., same course, time, instructor).
- Real-time seat availability checks.
- Audit trail for all actions.
Dependencies: sqlite3 (built-in), pandas (optional for reporting).
Usage:
1. Run setup_db() once.
2. Add data via add_section(), add_enrollment().
3. Run detect_and_crosslist() to automate.
4. Query records with get_crosslisting_report().
"""
import sqlite3
import json
from datetime import datetime
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass, asdict
import pandas as pd # Optional for reporting
@dataclass
class Section:
"""Represents a course section."""
section_id: str
campus: str
course_id: str # e.g., "MATH101"
term: str # e.g., "2024FA"
instructor: str
meeting_days: str # e.g., "MWF"
start_time: str # e.g., "09:00"
end_time: str # e.g., "10:30"
seat_cap: int
current_enrollment: int = 0
crosslist_group_id: Optional[str] = None # Assigned on cross-listing
@dataclass
class Enrollment:
"""Student enrollment in a section."""
enrollment_id: str
student_id: str
section_id: str
enroll_date: str
@dataclass
class CrosslistAction:
"""Audit record for cross-listing actions."""
action_id: str
timestamp: str
action_type: str # 'CREATE', 'MERGE', 'SPLIT', 'CAP_UPDATE'
sections_involved: List[str]
new_group_id: Optional[str]
old_caps: Dict[str, int]
new_caps: Dict[str, int]
notes: str
class CrosslistAutomator:
def __init__(self, db_path: str = "crosslist.db"):
self.db_path = db_path
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.setup_db()
def setup_db(self):
"""Initialize database schema."""
cursor = self.conn.cursor()
# Sections table
cursor.execute('''
CREATE TABLE IF NOT EXISTS sections (
section_id TEXT PRIMARY KEY,
campus TEXT,
course_id TEXT,
term TEXT,
instructor TEXT,
meeting_days TEXT,
start_time TEXT,
end_time TEXT,
seat_cap INTEGER,
current_enrollment INTEGER DEFAULT 0,
crosslist_group_id TEXT
)
''')
# Enrollments table
cursor.execute('''
CREATE TABLE IF NOT EXISTS enrollments (
enrollment_id TEXT PRIMARY KEY,
student_id TEXT,
section_id TEXT,
enroll_date TEXT,
FOREIGN KEY (section_id) REFERENCES sections (section_id)
)
''')
# Audit records
cursor.execute('''
CREATE TABLE IF NOT EXISTS audit_log (
action_id TEXT PRIMARY KEY,
timestamp TEXT,
action_type TEXT,
sections_involved TEXT, -- JSON list
new_group_id TEXT,
old_caps TEXT, -- JSON dict
new_caps TEXT, -- JSON dict
notes TEXT
)
''')
self.conn.commit()
def add_section(self, section: Section) -> bool:
"""Add or update a section."""
cursor = self.conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO sections
(section_id, campus, course_id, term, instructor, meeting_days,
start_time, end_time, seat_cap, current_enrollment, crosslist_group_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (section.section_id, section.campus, section.course_id, section.term,
section.instructor, section.meeting_days, section.start_time,
section.end_time, section.seat_cap, section.current_enrollment,
section.crosslist_group_id))
self.conn.commit()
return True
def add_enrollment(self, enrollment: Enrollment) -> bool:
"""Add an enrollment (updates current_enrollment)."""
cursor = self.conn.cursor()
cursor.execute('INSERT INTO enrollments VALUES (?, ?, ?, ?)',
(enrollment.enrollment_id, enrollment.student_id,
enrollment.section_id, enrollment.enroll_date))
# Update section enrollment count
cursor.execute('UPDATE sections SET current_enrollment = current_enrollment + 1 WHERE section_id = ?',
(enrollment.section_id,))
self.conn.commit()
return True
def log_action(self, action: CrosslistAction):
"""Log cross-listing action to audit."""
cursor = self.conn.cursor()
cursor.execute('''
INSERT INTO audit_log
(action_id, timestamp, action_type, sections_involved, new_group_id,
old_caps, new_caps, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (action.action_id, action.timestamp, action.action_type,
json.dumps(action.sections_involved),
action.new_group_id,
json.dumps(action.old_caps),
json.dumps(action.new_caps),
action.notes))
self.conn.commit()
# === RULES ENGINE ===
def sections_match_rules(self, sec1: Section, sec2: Section, rules: Dict) -> bool:
"""
Check if two sections match cross-listing rules.
Default rules (customizable):
- Same course_id and term
- Same instructor (or 'any' flag)
- Matching meeting_days
- Overlapping times (±15 min tolerance)
- Different campuses
"""
if sec1.course_id != sec2.course_id or sec1.term != sec2.term:
return False
if rules.get('strict_instructor', True) and sec1.instructor != sec2.instructor:
return False
if sec1.meeting_days != sec2.meeting_days:
return False
# Time overlap check (simple: same start/end ± tolerance)
tol = rules.get('time_tolerance_min', 15)
if not (self._times_overlap(sec1.start_time, sec1.end_time,
sec2.start_time, sec2.end_time, tol)):
return False
if sec1.campus == sec2.campus:
return False # Must be cross-campus
return True
def _times_overlap(self, s1: str, e1: str, s2: str, e2: str, tol_min: int) -> bool:
"""Check if time slots overlap within tolerance (minutes)."""
def to_min(t: str) -> int:
h, m = map(int, t.split(':'))
return h * 60 + m
s1m, e1m = to_min(s1), to_min(e1)
s2m, e2m = to_min(s2), to_min(e2)
# Overlap if max(start) < min(end) - tolerance
return max(s1m, s2m) < min(e1m, e2m) - tol_min
# === AUTOMATION CORE ===
def detect_and_crosslist(self, rules: Dict = None, cap_strategy: str = 'shared') -> List[CrosslistAction]:
"""
Detect matching sections and automate cross-listing.
cap_strategy:
- 'shared': Total cap = sum of individuals; prorated enforcement.
- 'max': Use highest cap as group cap.
- 'custom': Set fixed group cap (rules['group_cap']).
Returns list of actions taken.
"""
if rules is None:
rules = {
'strict_instructor': True,
'time_tolerance_min': 15,
'group_cap': 100 # For 'custom'
}
actions = []
# Get all uncrosslisted sections
cursor = self.conn.cursor()
cursor.execute('SELECT * FROM sections WHERE crosslist_group_id IS NULL OR crosslist_group_id = ""')
sections = [Section(*row) for row in cursor.fetchall()]
# Group potential matches by course/term
from collections import defaultdict
course_groups = defaultdict(list)
for sec in sections:
course_groups[(sec.course_id, sec.term)].append(sec)
next_group_id = self._generate_group_id()
for course_term, group_secs in course_groups.items():
# Find all pairs that match rules
matches = []
for i, sec1 in enumerate(group_secs):
for sec2 in group_secs[i+1:]:
if self.sections_match_rules(sec1, sec2, rules):
matches.append((sec1, sec2))
if len(matches) >= 1: # At least one pair
# Merge all matching into one group (transitive)
all_matching_secs = set()
for pair in matches:
all_matching_secs.update(pair)
merged_secs = list(all_matching_secs)
if len(merged_secs) > 1:
group_id = next_group_id
next_group_id = self._generate_group_id()
# Compute new caps
old_caps = {s.section_id: s.seat_cap for s in merged_secs}
if cap_strategy == 'shared':
total_cap = sum(s.seat_cap for s in merged_secs)
new_cap_per_sec = {s.section_id: total_cap for s in merged_secs}
elif cap_strategy == 'max':
max_cap = max(s.seat_cap for s in merged_secs)
new_cap_per_sec = {s.section_id: max_cap for s in merged_secs}
elif cap_strategy == 'custom':
fixed_cap = rules['group_cap']
new_cap_per_sec = {s.section_id: fixed_cap for s in merged_secs}
# Update DB: assign group_id, update caps
for sec in merged_secs:
cursor.execute('UPDATE sections SET crosslist_group_id = ?, seat_cap = ? WHERE section_id = ?',
(group_id, new_cap_per_sec[sec.section_id], sec.section_id))
# Move enrollments to primary section (first in list)
primary_sec = merged_secs[0].section_id
for sec in merged_secs[1:]:
cursor.execute('UPDATE enrollments SET section_id = ? WHERE section_id = ?',
(primary_sec, sec.section_id))
# Update primary enrollment count
total_enroll = sum(s.current_enrollment for s in merged_secs)
cursor.execute('UPDATE sections SET current_enrollment = ? WHERE section_id = ?',
(total_enroll, primary_sec))
# Log action
action = CrosslistAction(
action_id=f"A{datetime.now().strftime('%Y%m%d%H%M%S')}",
timestamp=datetime.now().isoformat(),
action_type='MERGE',
sections_involved=[s.section_id for s in merged_secs],
new_group_id=group_id,
old_caps=old_caps,
new_caps=new_cap_per_sec,
notes=f"Merged {len(merged_secs)} sections for {course_term[0]}"
)
self.log_action(action)
actions.append(action)
self.conn.commit()
return actions
def _generate_group_id(self) -> str:
"""Generate unique group ID."""
cursor = self.conn.cursor()
cursor.execute('SELECT COUNT(*) FROM sections WHERE crosslist_group_id LIKE "G%"')
count = cursor.fetchone()[0]
return f"G{datetime.now().strftime('%Y%m%d')}-{count + 1:04d}"
def check_seat_availability(self, section_id: str, num_seats: int = 1) -> bool:
"""Check availability considering cross-list group."""
cursor = self.conn.cursor()
cursor.execute('SELECT seat_cap, current_enrollment, crosslist_group_id FROM sections WHERE section_id = ?', (section_id,))
row = cursor.fetchone()
if not row:
return False
cap, enroll, group_id = row
if group_id:
# Sum across group for shared cap check
cursor.execute('''
SELECT SUM(seat_cap) as group_cap, SUM(current_enrollment) as group_enroll
FROM sections WHERE crosslist_group_id = ?
''', (group_id,))
gcap, genroll = cursor.fetchone()
return genroll + num_seats <= gcap
else:
return enroll + num_seats <= cap
def get_crosslisting_report(self, format: str = 'dict') -> Dict:
"""Generate report. Optional: 'pandas' for DataFrame."""
cursor = self.conn.cursor()
cursor.execute('''
SELECT s.*, a.timestamp, a.action_type, a.notes
FROM sections s
LEFT JOIN audit_log a ON json_extract(a.sections_involved, '$[*]') LIKE '%' || s.section_id || '%'
ORDER BY s.crosslist_group_id, s.campus
''')
data = [dict(zip([col[0] for col in cursor.description], row)) for row in cursor.fetchall()]
if format == 'pandas':
return pd.DataFrame(data)
return {'sections': data, 'total_groups': len(set(d.get('crosslist_group_id') for d in data if d.get('crosslist_group_id')))}
def close(self):
self.conn.close()
# === EXAMPLE USAGE ===
if __name__ == "__main__":
automator = CrosslistAutomator()
# Sample data: Cross-campus sections
sec1 = Section("SEC001", "Main", "MATH101", "2024FA", "Prof. Smith", "MWF", "09:00", "10:30", 50, 10)
sec2 = Section("SEC002", "Satellite", "MATH101", "2024FA", "Prof. Smith", "MWF", "09:05", "10:35", 40, 5) # Matches rules
sec3 = Section("SEC003", "Main", "MATH101", "2024FA", "Prof. Doe", "TTh", "11:00", "12:30", 60, 0) # No match
automator.add_section(sec1)
automator.add_section(sec2)
automator.add_section(sec3)
# Add sample enrollments
automator.add_enrollment(Enrollment("E001", "STUD001", "SEC001", "2024-09-01"))
# Run automation
actions = automator.detect_and_crosslist(rules={'strict_instructor': True}, cap_strategy='shared')
print("Actions taken:", [a.action_id for a in actions])
# Report
report = automator.get_crosslisting_report()
print(json.dumps(report, indent=2))
# Check availability
print("SEC001 available for 1 seat?", automator.check_seat_availability("SEC001"))
automator.close()
System Overview & Customization
- Rules: Fully configurable in
detect_and_crosslist(). Extend sections_match_rules() for more (e.g., room size, prerequisites).
- Seat Caps: Strategies:
'shared' (summed), 'max', 'custom'. Group-wide enforcement in check_seat_availability().
- Records: Full audit in
audit_log. Enrollments auto-migrate on merge.
- Scalability: SQLite for simplicity; swap for PostgreSQL/MySQL via SQLAlchemy.
- Integration: Hook into LMS APIs (e.g., Canvas) by replacing DB ops with API calls.
- Testing: Run the example; SEC001/SEC002 merge into group with 90 total cap.
Query me for expansions, like API integrations or UI! 🔍