-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_ec_dataset_parallel.sage
More file actions
248 lines (213 loc) · 7.63 KB
/
Copy pathbuild_ec_dataset_parallel.sage
File metadata and controls
248 lines (213 loc) · 7.63 KB
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
import sys
import os
import csv
import json
import argparse
import time
import traceback
from joblib import Parallel, delayed
from sage.all import EllipticCurve, pari, QQ
# ----------------------------------------------------------------------
# Paths
# ----------------------------------------------------------------------
REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
ECDATA_ROOT = os.path.join(REPO_ROOT, "data", "ecdata")
LMFDB_ROOT = os.path.join(REPO_ROOT, "data", "lmfdb")
print(f"ECDATA_ROOT: {ECDATA_ROOT}")
print(f"LMFDB_ROOT: {LMFDB_ROOT}")
# ----------------------------------------------------------------------
# Worker initialization
# ----------------------------------------------------------------------
def init_worker():
"""Initialize PARI defaults for each worker."""
try:
pari.default('two_seconds', 10**9)
pari.default('realprecision', 50)
except:
pass
# ----------------------------------------------------------------------
# Load from local submodules
# ----------------------------------------------------------------------
def load_cremona(label):
"""Load from Cremona ecdata format."""
import re
m = re.match(r"(\d+)([a-z]+)(\d+)", label)
if not m:
return None
N, iso, num = m.groups()
path = os.path.join(ECDATA_ROOT, N, iso, label)
if not os.path.exists(path):
return None
data = {}
try:
with open(path) as f:
for line in f:
line = line.strip()
if line.startswith("a-invariants:"):
parts = line.split(":")[1].strip().split()
data["ainvs"] = [int(x) for x in parts]
elif line.startswith("conductor:"):
data["conductor"] = int(line.split(":")[1])
elif line.startswith("torsion:"):
data["torsion"] = int(line.split(":")[1])
elif line.startswith("tamagawa:"):
data["tamagawa"] = int(line.split(":")[1])
except:
return None
return data if "ainvs" in data else None
def load_lmfdb(label):
"""Load from LMFDB JSON format."""
import re
m = re.match(r"(\d+)([a-z]+)(\d+)", label)
if not m:
return None
N, iso, num = m.groups()
json_path = os.path.join(LMFDB_ROOT, "elliptic_curves", N, iso, f"{label}.json")
if not os.path.exists(json_path):
return None
try:
with open(json_path) as f:
j = json.load(f)
return {
"ainvs": j.get("ainvs"),
"conductor": j.get("conductor"),
"torsion": j.get("torsion_order"),
"tamagawa": j.get("tamagawa_product"),
"rank_lmfdb": j.get("rank"),
}
except:
return None
def load_curve_data(label):
"""Unified loader with fallback."""
d = load_cremona(label)
if d is not None:
return d
return load_lmfdb(label)
# ----------------------------------------------------------------------
# Core computation (safe, single curve)
# ----------------------------------------------------------------------
def compute_one(label):
init_worker()
row = {
"label": label,
"conductor": None,
"discriminant": None,
"j_invariant": None,
"omega_real": None,
"torsion_order": None,
"tamagawa_product": None,
"rank_algebraic": None,
"rank_analytic_pari": None,
"selmer2_rank": None,
"sha_order": None,
"heegner_height": None,
"error": None,
}
try:
data = load_curve_data(label)
if data is None or "ainvs" not in data:
row["error"] = "Curve not found in ecdata or lmfdb"
return row
# Build curve
E = EllipticCurve(data["ainvs"])
# Basic invariants
row["conductor"] = int(E.conductor())
row["discriminant"] = int(E.discriminant())
row["j_invariant"] = int(E.j_invariant())
row["omega_real"] = float(E.period_lattice().real_period())
row["torsion_order"] = int(E.torsion_order())
row["tamagawa_product"] = int(E.tamagawa_product())
# Rank (robust)
try:
E.two_descent(second_limit=20)
row["rank_algebraic"] = int(E.rank(only_use_mwrank=False))
except:
try:
row["rank_algebraic"] = int(E.rank_bound())
except:
row["rank_algebraic"] = None
# Analytic rank via PARI
try:
gE = pari(E)
rdata = gE.ellrankinit()
row["rank_analytic_pari"] = int(gE.ellrank(rdata))
except Exception as e:
row["error"] = f"analytic rank: {str(e)[:100]}"
# Selmer rank
try:
row["selmer2_rank"] = int(E.selmer_rank(2))
except:
pass
# Sha
try:
sha = E.sha()
if sha is not None:
row["sha_order"] = int(sha.order())
except:
pass
# Heegner / generator height
try:
gens = E.gens()
if gens:
row["heegner_height"] = float(E.height(gens[0]))
except:
pass
except Exception as e:
row["error"] = f"General error: {str(e)[:150]}"
print(f"Error processing {label}: {e}", file=sys.stderr)
return row
# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="Safe EC dataset builder")
parser.add_argument("--labels-file", required=True, help="CSV with labels")
parser.add_argument("--output", required=True, help="Output CSV")
parser.add_argument("--workers", type=int, default=2, help="Number of workers (CI: keep low)")
parser.add_argument("--batch-size", type=int, default=100)
args = parser.parse_args()
# Load labels
labels = []
with open(args.labels_file) as f:
reader = csv.DictReader(f)
for r in reader:
lab = r["label"].strip()
if lab:
labels.append(lab)
print(f"Loaded {len(labels)} labels")
print(f"Using {args.workers} workers, batch size {args.batch_size}")
# Prepare output
out_path = args.output
os.makedirs(os.path.dirname(out_path), exist_ok=True)
fieldnames = [
"label", "conductor", "discriminant", "j_invariant", "omega_real",
"torsion_order", "tamagawa_product", "rank_algebraic",
"rank_analytic_pari", "selmer2_rank", "sha_order",
"heegner_height", "error"
]
write_header = not os.path.exists(out_path)
t0 = time.time()
processed = 0
with open(out_path, "a", newline="") as fout:
writer = csv.DictWriter(fout, fieldnames=fieldnames)
if write_header:
writer.writeheader()
# Batch processing
for i in range(0, len(labels), args.batch_size):
batch = labels[i:i + args.batch_size]
# Use 'threading' to avoid pickling issues
if args.workers > 1:
results = Parallel(n_jobs=args.workers, backend="threading")(
delayed(compute_one)(lab) for lab in batch
)
else:
results = [compute_one(lab) for lab in batch]
writer.writerows(results)
fout.flush()
processed += len(batch)
dt = time.time() - t0
print(f"[{processed}/{len(labels)}] processed in {dt:.1f}s")
print(f"\n✅ Done. Total time: {time.time()-t0:.1f}s")
print(f"Output written to: {out_path}")
if __name__ == "__main__":
main()