HFjr65 commited on
Commit
17deb50
·
verified ·
1 Parent(s): 733bde6

Create Gemini

Browse files

python research_os_core.py ER 42 job123

Files changed (1) hide show
  1. Gemini +259 -0
Gemini ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Research OS Core (single-file version)
3
+ - HPC-friendly (Slurm compatible)
4
+ - Job queue (SQLite)
5
+ - Fault tolerance (checkpoint + idempotency)
6
+ - Experiment runner
7
+ - Bayesian/LLM hook (optional stub)
8
+ """
9
+
10
+ import os
11
+ import json
12
+ import uuid
13
+ import sqlite3
14
+ import random
15
+
16
+
17
+ # =========================================================
18
+ # JOB QUEUE
19
+ # =========================================================
20
+
21
+ class JobQueue:
22
+ def __init__(self, db="jobs.db"):
23
+ self.conn = sqlite3.connect(db)
24
+ self._init()
25
+
26
+ def _init(self):
27
+ self.conn.execute("""
28
+ CREATE TABLE IF NOT EXISTS jobs (
29
+ id TEXT PRIMARY KEY,
30
+ payload TEXT,
31
+ status TEXT
32
+ )
33
+ """)
34
+
35
+ def submit(self, payload):
36
+ job_id = str(uuid.uuid4())
37
+
38
+ self.conn.execute(
39
+ "INSERT INTO jobs VALUES (?, ?, ?)",
40
+ (job_id, json.dumps(payload), "queued")
41
+ )
42
+ self.conn.commit()
43
+
44
+ return job_id
45
+
46
+ def fetch_next(self):
47
+ cur = self.conn.execute(
48
+ "SELECT id, payload FROM jobs WHERE status='queued' LIMIT 1"
49
+ )
50
+ row = cur.fetchone()
51
+
52
+ if not row:
53
+ return None
54
+
55
+ job_id, payload = row
56
+
57
+ self.conn.execute(
58
+ "UPDATE jobs SET status='running' WHERE id=?",
59
+ (job_id,)
60
+ )
61
+ self.conn.commit()
62
+
63
+ return job_id, json.loads(payload)
64
+
65
+
66
+ # =========================================================
67
+ # CHECKPOINTING (fault tolerance)
68
+ # =========================================================
69
+
70
+ def checkpoint_path(job_id):
71
+ os.makedirs("checkpoints", exist_ok=True)
72
+ return f"checkpoints/{job_id}.json"
73
+
74
+
75
+ def save_checkpoint(job_id, state):
76
+ with open(checkpoint_path(job_id), "w") as f:
77
+ json.dump(state, f)
78
+
79
+
80
+ def load_checkpoint(job_id):
81
+ path = checkpoint_path(job_id)
82
+ if not os.path.exists(path):
83
+ return None
84
+ with open(path) as f:
85
+ return json.load(f)
86
+
87
+
88
+ # =========================================================
89
+ # EXPERIMENT CORE (toy simulation placeholder)
90
+ # =========================================================
91
+
92
+ def run_experiment(graph_type, seed):
93
+ random.seed(seed)
94
+
95
+ return {
96
+ "graph_type": graph_type,
97
+ "seed": seed,
98
+ "mean_degree": random.gauss(5, 2),
99
+ "var_degree": random.random() * 2
100
+ }
101
+
102
+
103
+ # =========================================================
104
+ # SAFE EXECUTION (idempotent + checkpointed)
105
+ # =========================================================
106
+
107
+ def result_path(job_id):
108
+ os.makedirs("results", exist_ok=True)
109
+ return f"results/{job_id}.json"
110
+
111
+
112
+ def is_done(job_id):
113
+ return os.path.exists(result_path(job_id))
114
+
115
+
116
+ def save_result(job_id, result):
117
+ with open(result_path(job_id), "w") as f:
118
+ json.dump(result, f)
119
+
120
+
121
+ def run_safe(job_id, payload):
122
+
123
+ if is_done(job_id):
124
+ print(f"[SKIP] {job_id} already done")
125
+ return None
126
+
127
+ state = load_checkpoint(job_id)
128
+
129
+ if state is None:
130
+ state = payload
131
+
132
+ try:
133
+ result = run_experiment(
134
+ state["graph_type"],
135
+ state["seed"]
136
+ )
137
+
138
+ save_checkpoint(job_id, {"status": "done"})
139
+ save_result(job_id, result)
140
+
141
+ return result
142
+
143
+ except Exception as e:
144
+ save_checkpoint(job_id, {
145
+ "status": "failed",
146
+ "error": str(e),
147
+ "state": state
148
+ })
149
+ raise
150
+
151
+
152
+ # =========================================================
153
+ # SIMPLE BAYESIAN POLICY (optional exploration)
154
+ # =========================================================
155
+
156
+ class BayesianPolicy:
157
+ def __init__(self):
158
+ self.scores = {"ER": 1.0, "WS": 1.0, "BA": 1.0}
159
+
160
+ def update(self, result):
161
+ g = result["graph_type"]
162
+ self.scores[g] += result["mean_degree"]
163
+
164
+ def sample(self):
165
+ total = sum(self.scores.values())
166
+ r = random.uniform(0, total)
167
+
168
+ acc = 0
169
+ for k, v in self.scores.items():
170
+ acc += v
171
+ if acc >= r:
172
+ return k
173
+
174
+
175
+ # =========================================================
176
+ # HYPOTHESIS ENGINE (LLM placeholder)
177
+ # =========================================================
178
+
179
+ def generate_hypothesis(result):
180
+ """
181
+ Replace with LLM call if desired.
182
+ """
183
+
184
+ if result["mean_degree"] > 6:
185
+ return "High connectivity regime may emerge under current parameters"
186
+
187
+ if result["var_degree"] > 1:
188
+ return "System shows high structural variance sensitivity"
189
+
190
+ return "Baseline regime stable"
191
+
192
+
193
+ def next_experiment(policy):
194
+ return {
195
+ "graph_type": policy.sample(),
196
+ "seed": random.randint(0, 10000)
197
+ }
198
+
199
+
200
+ # =========================================================
201
+ # MAIN LOOP (HPC OR LOCAL)
202
+ # =========================================================
203
+
204
+ def run_cycle(n=10):
205
+
206
+ q = JobQueue()
207
+ policy = BayesianPolicy()
208
+
209
+ results = []
210
+
211
+ # submit jobs
212
+ for _ in range(n):
213
+ job = {
214
+ "graph_type": policy.sample(),
215
+ "seed": random.randint(0, 10000)
216
+ }
217
+ q.submit(job)
218
+
219
+ # execute jobs
220
+ while True:
221
+ job = q.fetch_next()
222
+ if job is None:
223
+ break
224
+
225
+ job_id, payload = job
226
+
227
+ result = run_safe(job_id, payload)
228
+
229
+ if result:
230
+ policy.update(result)
231
+ results.append(result)
232
+
233
+ print("HYPOTHESIS:", generate_hypothesis(result))
234
+
235
+ return results
236
+
237
+
238
+ # =========================================================
239
+ # CLI ENTRY (for Slurm / local run)
240
+ # =========================================================
241
+
242
+ if __name__ == "__main__":
243
+
244
+ import sys
245
+
246
+ if len(sys.argv) == 1:
247
+ run_cycle(10)
248
+
249
+ else:
250
+ graph = sys.argv[1]
251
+ seed = int(sys.argv[2])
252
+ job_id = sys.argv[3]
253
+
254
+ result = run_safe(job_id, {
255
+ "graph_type": graph,
256
+ "seed": seed
257
+ })
258
+
259
+ print(result)