File size: 5,918 Bytes
17deb50 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | """
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) |