HFjr65's picture
Create Gemini
17deb50 verified
Raw History Blame Contribute Delete
5.92 kB
"""
Research OS Core (single-file version)
- HPC-friendly (Slurm compatible)
- Job queue (SQLite)
- Fault tolerance (checkpoint + idempotency)
- Experiment runner
- Bayesian/LLM hook (optional stub)
"""
import os
import json
import uuid
import sqlite3
import random
# =========================================================
# JOB QUEUE
# =========================================================
class JobQueue:
def __init__(self, db="jobs.db"):
self.conn = sqlite3.connect(db)
self._init()
def _init(self):
self.conn.execute("""
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
payload TEXT,
status TEXT
)
""")
def submit(self, payload):
job_id = str(uuid.uuid4())
self.conn.execute(
"INSERT INTO jobs VALUES (?, ?, ?)",
(job_id, json.dumps(payload), "queued")
)
self.conn.commit()
return job_id
def fetch_next(self):
cur = self.conn.execute(
"SELECT id, payload FROM jobs WHERE status='queued' LIMIT 1"
)
row = cur.fetchone()
if not row:
return None
job_id, payload = row
self.conn.execute(
"UPDATE jobs SET status='running' WHERE id=?",
(job_id,)
)
self.conn.commit()
return job_id, json.loads(payload)
# =========================================================
# CHECKPOINTING (fault tolerance)
# =========================================================
def checkpoint_path(job_id):
os.makedirs("checkpoints", exist_ok=True)
return f"checkpoints/{job_id}.json"
def save_checkpoint(job_id, state):
with open(checkpoint_path(job_id), "w") as f:
json.dump(state, f)
def load_checkpoint(job_id):
path = checkpoint_path(job_id)
if not os.path.exists(path):
return None
with open(path) as f:
return json.load(f)
# =========================================================
# EXPERIMENT CORE (toy simulation placeholder)
# =========================================================
def run_experiment(graph_type, seed):
random.seed(seed)
return {
"graph_type": graph_type,
"seed": seed,
"mean_degree": random.gauss(5, 2),
"var_degree": random.random() * 2
}
# =========================================================
# SAFE EXECUTION (idempotent + checkpointed)
# =========================================================
def result_path(job_id):
os.makedirs("results", exist_ok=True)
return f"results/{job_id}.json"
def is_done(job_id):
return os.path.exists(result_path(job_id))
def save_result(job_id, result):
with open(result_path(job_id), "w") as f:
json.dump(result, f)
def run_safe(job_id, payload):
if is_done(job_id):
print(f"[SKIP] {job_id} already done")
return None
state = load_checkpoint(job_id)
if state is None:
state = payload
try:
result = run_experiment(
state["graph_type"],
state["seed"]
)
save_checkpoint(job_id, {"status": "done"})
save_result(job_id, result)
return result
except Exception as e:
save_checkpoint(job_id, {
"status": "failed",
"error": str(e),
"state": state
})
raise
# =========================================================
# SIMPLE BAYESIAN POLICY (optional exploration)
# =========================================================
class BayesianPolicy:
def __init__(self):
self.scores = {"ER": 1.0, "WS": 1.0, "BA": 1.0}
def update(self, result):
g = result["graph_type"]
self.scores[g] += result["mean_degree"]
def sample(self):
total = sum(self.scores.values())
r = random.uniform(0, total)
acc = 0
for k, v in self.scores.items():
acc += v
if acc >= r:
return k
# =========================================================
# HYPOTHESIS ENGINE (LLM placeholder)
# =========================================================
def generate_hypothesis(result):
"""
Replace with LLM call if desired.
"""
if result["mean_degree"] > 6:
return "High connectivity regime may emerge under current parameters"
if result["var_degree"] > 1:
return "System shows high structural variance sensitivity"
return "Baseline regime stable"
def next_experiment(policy):
return {
"graph_type": policy.sample(),
"seed": random.randint(0, 10000)
}
# =========================================================
# MAIN LOOP (HPC OR LOCAL)
# =========================================================
def run_cycle(n=10):
q = JobQueue()
policy = BayesianPolicy()
results = []
# submit jobs
for _ in range(n):
job = {
"graph_type": policy.sample(),
"seed": random.randint(0, 10000)
}
q.submit(job)
# execute jobs
while True:
job = q.fetch_next()
if job is None:
break
job_id, payload = job
result = run_safe(job_id, payload)
if result:
policy.update(result)
results.append(result)
print("HYPOTHESIS:", generate_hypothesis(result))
return results
# =========================================================
# CLI ENTRY (for Slurm / local run)
# =========================================================
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
run_cycle(10)
else:
graph = sys.argv[1]
seed = int(sys.argv[2])
job_id = sys.argv[3]
result = run_safe(job_id, {
"graph_type": graph,
"seed": seed
})
print(result)