-
Notifications
You must be signed in to change notification settings - Fork 241
Expand file tree
/
Copy pathmain.py
More file actions
2204 lines (2056 loc) · 93 KB
/
Copy pathmain.py
File metadata and controls
2204 lines (2056 loc) · 93 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Blueprint is about p-adic fields (aka local number fields)
# Author: John Jones
import os
import yaml
from flask import abort, render_template, request, url_for, redirect, make_response
from sage.all import (
PolynomialRing, ZZ, QQ, RR, latex, cached_function, Integers, euler_phi, is_prime)
from sage.plot.all import line, points, text, Graphics, polygon
from lmfdb import db
from lmfdb.app import app
from lmfdb.utils import (
web_latex, coeff_to_poly, teXify_pol, display_multiset, display_knowl,
parse_inertia, parse_newton_polygon, parse_bracketed_posints, parse_floats,
parse_regex_restricted, parse_padicsubfields,
parse_galgrp, parse_ints, clean_input, parse_rats, parse_noop, flash_error,
SearchArray, TextBox, TextBoxWithSelect, SubsetBox, SelectBox, SneakyTextBox,
HiddenBox, TextBoxNoEg, CountBox, to_dict, comma,
search_wrap, count_wrap, embed_wrap, Downloader, StatsDisplay, totaler, proportioners, encode_plot,
EmbeddedSearchArray, integer_options,
redirect_no_cache, raw_typeset)
from lmfdb.utils.place_code import CodeSnippet
from psycodict.utils import SearchParsingError, range_formatter
from lmfdb.utils.display_stats import NO_SEARCH_QUERY
from lmfdb.utils.interesting import interesting_knowls
from lmfdb.utils.search_columns import SearchColumns, LinkCol, MathCol, ProcessedCol, MultiProcessedCol, RationalListCol, PolynomialCol, eval_rational_list
from lmfdb.utils.search_parsing import QQ_DEC_RE, QQ_RE, search_parser
from lmfdb.api import datapage
from lmfdb.logger import logger
from lmfdb.local_fields import local_fields_page
from lmfdb.local_fields.family import pAdicSlopeFamily, FAMILY_RE, latex_content, content_unformatter
from lmfdb.groups.abstract.main import abstract_group_display_knowl
from lmfdb.galois_groups.transitive_group import (
transitive_group_display_knowl, group_display_inertia,
knowl_cache, galdata, galunformatter,
group_pretty_and_nTj, WebGaloisGroup)
from lmfdb.number_fields.web_number_field import (
WebNumberField, string2list, nf_display_knowl)
import re
OLD_LF_RE = re.compile(r'^\d+\.\d+\.\d+\.\d+$')
NEW_LF_RE = re.compile(r'^\d+\.\d+\.\d+\.\d+[a-z]+\d+\.\d+$')
def get_bread(breads=[]):
bc = [("$p$-adic fields", url_for(".index"))]
bc.extend(breads)
return bc
def learnmore_list():
return [('Source and acknowledgments', url_for(".source")),
('Completeness of the data', url_for(".cande")),
('Reliability of the data', url_for(".reliability")),
('$p$-adic field labels', url_for(".labels_page"))]
# Return the learnmore list with the matchstring entry removed
def learnmore_list_remove(matchstring):
return [t for t in learnmore_list() if t[0].find(matchstring) < 0]
def display_poly(coeffs):
return web_latex(coeff_to_poly(coeffs))
def format_coeffs(coeffs):
return latex(coeff_to_poly(coeffs))
def lf_formatfield(coef):
coef = string2list(coef)
thefield = WebNumberField.from_coeffs(coef)
thepoly = coeff_to_poly(coef)
thepolylatex = '$%s$' % latex(coeff_to_poly(coef))
if thefield._data is None:
return raw_typeset(thepoly, thepolylatex)
return nf_display_knowl(thefield.get_label(),thepolylatex)
# Takes a string '[2,5/2]'
def artin2swan(li):
if li is not None:
l1 = li.replace('[', '')
l1 = l1.replace(']', '')
l1 = l1.replace(' ', '')
if l1 == '':
return []
return '[' + ','.join([str(QQ(z)-1) for z in l1.split(',')]) + ']'
def hidden2swan(hid):
if hid is not None:
parts = hid.split(']')
a = parts[0].replace('[', '')
a = a.replace(' ', '')
if a == '':
return hid
return '[' + ','.join([str(QQ(z)-1) for z in a.split(',')]) + ']' + parts[1]
def local_algebra_data(labels):
labs = labels.split(',')
f1 = labs[0].split('.')
labs = sorted(labs, key=lambda u: (int(j) for j in u.split('.')), reverse=True)
ans = '<div align="center">'
ans += '$%s$-adic algebra' % str(f1[0])
ans += '</div>'
ans += '<p>'
ans += "<table class='ntdata'><th>Label<th>Polynomial<th>$e$<th>$f$<th>$c$<th>$G$<th>Artin slopes"
if all(OLD_LF_RE.fullmatch(lab) for lab in labs):
fall = {rec["old_label"]: rec for rec in db.lf_fields.search({"old_label":{"$in": labs}})}
elif all(NEW_LF_RE.fullmatch(lab) for lab in labs):
fall = {rec["new_label"]: rec for rec in db.lf_fields.search({"new_label":{"$in": labs}})}
else:
fall = {}
for lab in labs:
if OLD_LF_RE.fullmatch(lab):
fall[lab] = db.lf_fields.lucky({"old_label":lab})
elif NEW_LF_RE.fullmatch(lab):
fall[lab] = db.lf_fields.lucky({"new_label":lab})
else:
fall[lab] = None
for lab in labs:
f = fall[lab]
if f is None:
ans += '<tr><td>Invalid label %s</td></tr>' % lab
continue
if f.get('new_label'):
l = str(f['new_label'])
else:
l = str(f['old_label'])
ans += '<tr><td><a href="%s">%s</a><td>' % (url_for_label(l), l)
ans += format_coeffs(f['coeffs'])
ans += '<td>%d<td>%d<td>%d<td>' % (f['e'], f['f'], f['c'])
ans += transitive_group_display_knowl(f['galois_label'])
if f.get('slopes') and f.get('t') and f.get('u'):
ans += '<td>$' + show_slope_content(f['slopes'],f['t'],f['u'])+'$'
ans += '</table>'
if len(labs) != len(set(labs)):
ans += '<p>Fields which appear more than once occur according to their given multiplicities in the algebra'
return ans
def local_field_data(label):
if OLD_LF_RE.fullmatch(label):
f = db.lf_fields.lucky({"old_label": label})
elif NEW_LF_RE.fullmatch(label):
f = db.lf_fields.lucky({"new_label": label})
else:
return "Invalid label %s" % label
nicename = ''
if f['n'] < 3:
nicename = ' = ' + prettyname(f)
ans = '$p$-adic field %s%s<br><br>' % (label, nicename)
ans += r'Extension of $\Q_{%s}$ defined by %s<br>' % (str(f['p']),web_latex(coeff_to_poly(f['coeffs'])))
gn = f['n']
ans += 'Degree: %s<br>' % str(gn)
ans += 'Ramification index $e$: %s<br>' % str(f['e'])
ans += 'Residue field degree $f$: %s<br>' % str(f['f'])
ans += 'Discriminant ideal: $(p^{%s})$ <br>' % str(f['c'])
if f.get('galois_label') is not None:
gt = int(f['galois_label'].split('T')[1])
ans += 'Galois group $G$: %s<br>' % group_pretty_and_nTj(gn, gt, True)
else:
ans += 'Galois group $G$: not computed<br>'
ans += '<div align="right">'
ans += '<a href="%s">%s home page</a>' % (str(url_for("local_fields.by_label", label=label)),label)
ans += '</div>'
return ans
def lf_display_knowl(label, name=None):
if name is None:
name = label
return '<a title = "%s [lf.field.data]" knowl="lf.field.data" kwargs="label=%s">%s</a>' % (label, label, name)
def local_algebra_display_knowl(labels):
return '<a title = "{0} [lf.algebra.data]" knowl="lf.algebra.data" kwargs="labels={0}">{0}</a>' % (labels)
def eisensteinformlatex(pol, unram):
# pol=coeffs, unram =string
R = PolynomialRing(QQ, 'y')
Rx = PolynomialRing(R, 'x')
unram2 = R(unram.replace('t', 'y'))
pol = R(pol)
if unram2.degree() == 1 or unram2.degree() == pol.degree():
return latex(pol).replace('y', 'x')
unram = latex(Rx(unram.replace('t', 'x')))
l = []
while pol != 0:
qr = pol.quo_rem(unram2)
l.append(qr[1])
pol = qr[0]
newpol = latex(Rx(l))
newpol = newpol.replace('x', '(' + unram + ')')
newpol = newpol.replace('y', 'x')
return newpol
def plot_ramification_polygon(verts, p, polys=None, inds=None):
# print("VERTS", verts)
verts = [tuple(pt) for pt in verts]
if not verts:
# Unramified, so we won't be displaying the plot
return
# Extract the coefficients to be associated to x
ymax = verts[0][1]
xmax = verts[-1][0]
# How far we need to shift text depends on the scale
txshift = xmax / 80
tyshift = xmax / 48
#tick = xmax / 160
nextq = p
L = Graphics()
if ymax > 0:
asp_ratio = (xmax + 2*txshift) / (2 * (ymax + 2*tyshift)) # 2 comes from the fact that the actual image has width 500 and height 250.
else:
# Add in silly white dot
L += points([(0,1)], color="white")
asp_ratio = (xmax + 2*txshift) / (8 + 16*tyshift)
for i in range(xmax+1):
L += line([(-i, 0), (-i, ymax)], color=(0.85,0.85,0.85), thickness=0.5)
for j in range(ymax+1):
L += line([(0,j), (-xmax, j)], color=(0.85,0.85,0.85), thickness=0.5)
#L += line([(0,0), (0, ymax)], color="grey")
#L += line([(0,0), (-xmax, 0)], color="grey")
#for i in range(1, ymax + 1):
# L += line([(0, i), (-tick, i)], color="grey")
#for i in range(0, xmax + 1):
# L += line([(-i, 0), (-i, tick/asp_ratio)], color="grey")
xticks = set(P[0] for P in verts)
yticks = set(P[1] for P in verts)
if inds is not None:
xticks = xticks.union(p**i for i in range(len(inds)))
yticks = yticks.union(ind for ind in inds)
for x in xticks:
L += text(
f"${-x}$", (-x, -tyshift/asp_ratio),
color="black")
for y in yticks:
L += text(
f"${y}$", (txshift, y),
horizontal_alignment="left",
color="black")
if polys is not None:
R = ZZ["t"]["z"]
polys = [R(poly) for poly in reversed(polys)]
# print("POLYS", polys)
def restag(c, a, b):
return text(f"${latex(c)}$", (-a - txshift, b + tyshift/asp_ratio),
horizontal_alignment="left",
color="black")
L += restag(polys[0][0], 1, ymax)
for i in range(len(verts) - 1):
P = verts[i]
Q = verts[i+1]
slope = ZZ(P[1] - Q[1]) / ZZ(Q[0] - P[0]) # actually the negative of the slope
d = slope.denominator()
if slope != 0:
if polys is not None:
# Need to check that this is compatible with the residual polynomial normalization
while nextq <= Q[0]:
j = (nextq - P[0]) / d
if j in ZZ and polys[i][j]:
L += restag(polys[i][j], nextq, P[1] - (nextq - P[0]) * slope)
nextq *= p
L += text(
f"${slope}$", (-(P[0] + Q[0]) / 2 + txshift, (P[1] + Q[1]) / 2 - tyshift/(2*asp_ratio)),
horizontal_alignment="left",
color="blue")
#for x in range(P[0], Q[0] + 1):
# L += line(
# [(-x, Q[1]), (-x, P[1] - (x - P[0]) * slope)],
# color="grey",
# )
#for y in range(Q[1], P[1]):
# L += line(
# [(-P[0] + (y - P[1]) / slope, y), (-P[0], y)],
# color="grey",
# )
elif polys:
# For tame inertia, the coefficients can occur at locations other than powers of p
for j, c in enumerate(polys[i]):
if j and c:
L += restag(c, P[0] + j, P[1])
L += line([(-x,y) for (x,y) in verts], thickness=2)
L += polygon([(-x,y) for (x,y) in verts] + [(-xmax, ymax)], alpha=0.08)
if inds is not None:
# print("INDS", inds)
L += points([(-p**i, ind) for (i, ind) in enumerate(inds)], size=30, color="black", zorder=5)
L.axes(False)
L.set_aspect_ratio(asp_ratio)
return encode_plot(L, pad=0, pad_inches=0, bbox_inches="tight", figsize=(8,4), dpi=300)
@app.context_processor
def ctx_local_fields():
return {'local_field_data': local_field_data,
'local_algebra_data': local_algebra_data}
# Utilities for subfield display
def format_lfield(label, p):
if OLD_LF_RE.fullmatch(label):
data = db.lf_fields.lucky({"old_label": label}, ["n", "p", "rf", "old_label", "new_label"])
else:
data = db.lf_fields.lucky({"new_label": label}, ["n", "p", "rf", "old_label", "new_label"])
return lf_display_knowl(label, name=prettyname(data))
# Input is a list of pairs, coeffs of field as string and multiplicity
def format_subfields(sublist, multdata, p):
if not sublist:
return ''
subdata = zip(sublist, multdata)
return display_multiset(subdata, format_lfield, p)
# Encode string for rational into our special format
def ratproc(inp):
if '.' in inp:
inp = RR(inp)
qs = QQ(inp)
sstring = str(qs*1.)
sstring += '0'*14
if qs < 10:
sstring = '0'+sstring
sstring = sstring[0:12]
sstring += str(qs)
return sstring
def show_slopes(sl):
if str(sl) == "[]":
return "None"
return ('$' + sl + '$')
def show_slopes2(sl):
# uses empty brackets with a space instead of None
if str(sl) == "[]":
return r'[\ ]'
return (sl)
def show_slope_content(sl,t,u):
if sl is None or t is None or u is None:
return 'not computed'
sc = str(sl)
if t > 1:
sc += '_{%d}' % t
if u > 1:
sc += '^{%d}' % u
return latex_content(sc)
relative_columns = ["base", "n0", "e0", "f0", "c0", "label_absolute", "n_absolute", "e_absolute", "f_absolute", "c_absolute"]
@local_fields_page.route("/")
def index():
bread = get_bread()
info = to_dict(request.args, search_array=LFSearchArray(), stats=LFStats())
if any(col in info for col in relative_columns):
info["relative"] = 1
if len(request.args) != 0:
info["search_type"] = search_type = info.get("search_type", info.get("hst", ""))
if search_type in ['Families', 'FamilyCounts']:
info['search_array'] = FamiliesSearchArray(relative=("relative" in info))
if search_type in ['Counts', 'FamilyCounts']:
return local_field_count(info)
elif search_type in ['Families', 'RandomFamily']:
return families_search(info)
elif search_type in ['List', '', 'Random', 'Diagram']:
return local_field_search(info)
else:
flash_error("Invalid search type; if you did not enter it in the URL please report")
info["field_count"] = db.lf_fields.stats.column_counts(["n", "p"])
info["family_count"] = db.lf_families.count({"n0":1}, groupby=["n", "p"])
return render_template("lf-index.html", title="$p$-adic fields", titletag="p-adic fields", bread=bread, info=info, learnmore=learnmore_list())
@local_fields_page.route("/families/")
def family_redirect():
info = to_dict(request.args)
info["search_type"] = "Families"
if "relative" not in info:
# Check for the presence of any relative-only arguments
if any(x in info for x in relative_columns):
info["relative"] = 1
return redirect(url_for(".index", **info))
@local_fields_page.route("/<label>")
def by_label(label):
clean_label = clean_input(label)
if label != clean_label:
return redirect(url_for_label(label=clean_label), 301)
return render_field_webpage({'label': label})
def url_for_label(label):
if label == "random":
return url_for('.random_field')
return url_for(".by_label", label=label)
def url_for_family(label):
return url_for(".family_page", label=label)
def url_for_packet(packet):
return url_for(".index", packet=packet)
def local_field_jump(info):
if FAMILY_RE.fullmatch(info['jump']):
return redirect(url_for_family(info['jump']), 301)
else:
return redirect(url_for_label(info['jump']), 301)
def unpack_slopes(slopes, t, u):
return eval_rational_list(slopes), t, u
def format_eisen(eisstr):
Pt = PolynomialRing(QQ, 't')
Ptx = PolynomialRing(Pt, 'x')
return latex(Ptx(str(eisstr).replace('y','x')))
class LF_download(Downloader):
table = db.lf_fields
title = '$p$-adic fields'
inclusions = {
'field': (
["p", "coeffs"],
{
"magma": 'Prec := 100; // Default precision of 100\n base := pAdicField(out`p, Prec);\n field := LocalField(base, PolynomialRing(base)!(out`coeffs));',
"sage": 'Prec = 100 # Default precision of 100\n base = Qp(out["p"], Prec)\n unram = ZZx(out["unram"].replace("t","x"))\n unram_subfield.<t> = base.extension(unram, names="t") if unram.degree() > 1 else base\n eisen = sage_eval(out["eisen"], locals={"x":x, "t":t})\n field.<a> = unram_subfield.extension(eisen, names="a") if eisen.degree() > 1 else unram_subfield',
"gp": 'field = Polrev(mapget(out, "coeffs"));',
}
),
}
class LF_families_download(Downloader):
table = db.lf_families
title = '$p$-adic families'
def galcolresponse(n,t,cache):
if t is None:
return 'not computed'
return group_pretty_and_nTj(n, t, cache=cache)
def formatbracketcol(blist):
if blist is None or blist == '':
return 'not computed'
if blist == []:
return r'$[\ ]$'
return f'${blist}$'
def intcol(j):
if j == '':
return 'not computed'
return f'${j}$'
#label_col = LinkCol("new_label", "lf.field.label", "Label", url_for_label)
label_col = MultiProcessedCol("label", "lf.field_label", "Label", ["old_label", "new_label"], (lambda old_label, new_label: f'<a href="{url_for_label(new_label)}">{new_label}</a>' if new_label else f'<a href="{url_for_label(old_label)}">{old_label}</a>'), apply_download=(lambda old_label, new_label: (new_label if new_label else old_label)))
def poly_col(relative=False):
if relative:
def title(info): return "Polynomial" if info['family'].n0 == 1 else r"Polynomial $/ \Q_p$"
else:
title = "Polynomial"
return MultiProcessedCol("coeffs", "lf.defining_polynomial", title, ["coeffs", "unram"], eisensteinformlatex, mathmode=True, short_title="polynomial", apply_download=lambda coeffs, unram: coeffs)
p_col = MathCol("p", "lf.qp", "$p$", short_title="prime")
c_col = MathCol("c", "lf.discriminant_exponent", "$c$", short_title="discriminant exponent")
e_col = MathCol("e", "lf.ramification_index", "$e$", short_title="ramification index")
f_col = MathCol("f", "lf.residue_field_degree", "$f$", short_title="residue field degree")
def gal_col(relative=False):
if relative:
def title(info): return "Galois group" if info['family'].n0 == 1 else r"Galois group $/ \Q_p$"
else:
title = "Galois group"
return MultiProcessedCol("gal", "nf.galois_group", title,
["n", "gal", "cache"],
galcolresponse, short_title="Galois group",
apply_download=lambda n, t, cache: [n, t])
def aut_col(default):
return MathCol("aut", "lf.automorphism_group", r"$\#\Aut(K/\Q_p)$", short_title="auts", default=default)
def slopes_col(default=True, relative=False):
if relative:
def title(info): return "Artin slope content" if info['family'].n0 == 1 else r"Artin slope content $/ \Q_p$"
else:
title = "Artin slope content"
return MultiProcessedCol("slopes", "lf.slopes", title,
["slopes", "t", "u"],
show_slope_content, short_title="Artin slope content",
apply_download=unpack_slopes, default=default)
def hidden_col(default=True, relative=False):
if relative:
def title(info): return "Hidden Artin slopes" if info['family'].n0 == 1 else r"Hidden Artin slopes $/ \Q_p$"
else:
title = "Hidden Artin slopes"
return ProcessedCol("hidden", "lf.slopes",
title,
latex_content, short_title="hidden Artin slopes",
apply_download=False, default=default)
def swanslopes_col(default=False, relative=False):
if relative:
def title(info): return "Swan slope content" if info['family'].n0 == 1 else r"Swan slope content $/ \Q_p$"
else:
title = "Swan slope content"
return MultiProcessedCol("swanslopes", "lf.slopes", title,
["slopes", "t", "u", "c"],
(lambda slopes, t, u, c: show_slope_content(artin2swan(slopes), t, u)),
short_title="Swan slope content",
apply_download=(lambda slopes, t, u: unpack_slopes(artin2swan(slopes), t, u)),
default=default)
def hiddenswan_col(default=False, relative=False):
if relative:
def title(info): return "Hidden Swan slopes" if info['family'].n0 == 1 else r"Hidden Swan slopes $/ \Q_p$"
else:
title = "Hidden Swan slopes"
return MultiProcessedCol("hiddenswan", "lf.slopes",
title,
["hidden", "c"],
(lambda hidden, c: latex_content(hidden2swan(hidden))),
short_title="hidden Swan slopes",
apply_download=False,
default=default)
def insep_col(default=True, relative=False):
if relative:
def title(info): return "Ind. of Insep." if info['family'].n0 == 1 else r"Ind. of Insep. $/ \Q_p$"
else:
title = "Ind. of Insep."
return ProcessedCol("ind_of_insep", "lf.indices_of_inseparability", title, formatbracketcol, default=default, short_title="ind. of insep.")
def assoc_col(default=True, relative=False):
if relative:
def title(info): return "Assoc. Inertia" if info['family'].n0 == 1 else r"Assoc. Inertia $/ \Q_p$"
else:
title = "Assoc. Inertia"
return ProcessedCol("associated_inertia", "lf.associated_inertia", title, formatbracketcol, default=default)
def jump_col(default=True):
return ProcessedCol("jump_set", "lf.jump_set", "Jump Set", func=lambda js: f"${js}$" if js else "undefined", default=default, mathmode=False)
def respoly_col():
return ProcessedCol("residual_polynomials", "lf.residual_polynomials", "Resid. Poly", default=False, mathmode=True, func=lambda rp: ','.join(teXify_pol(f) for f in rp))
lf_columns = SearchColumns([
label_col,
MathCol("n", "lf.degree", "$n$", short_title="degree", default=False),
poly_col(),
p_col,
f_col,
e_col,
c_col,
gal_col(False),
ProcessedCol("u", "lf.unramified_degree", "$u$", intcol, short_title="unramified degree", default=False),
ProcessedCol("t", "lf.tame_degree", "$t$", intcol, short_title="tame degree", default=False),
RationalListCol("visible", "lf.slopes", "Visible Artin slopes",
show_slopes2, default=lambda info: info.get("visible"), short_title="visible Artin slopes"),
# throw in c as a trick to differentiate it from just visible
MultiProcessedCol("visibleswan", "lf.slopes", "Visible Swan slopes",
["visible","c"],
(lambda visible, c: latex_content(show_slopes2(artin2swan(visible)))),
mathmode=False, default=False,
short_title="visible Swan slopes",
apply_download=(lambda slopes: eval_rational_list(artin2swan(slopes)))),
slopes_col(),
swanslopes_col(),
hidden_col(default=False),
hiddenswan_col(),
aut_col(lambda info:info.get("aut")),
# Want apply_download for download conversion. Sage requires both 'unram' and 'eisen' in the download files to construct p-adic fields.
PolynomialCol("unram", "lf.unramified_subfield", "Unram. Ext.", default=lambda info:info.get("visible") or info.get("Submit") == "sage"),
ProcessedCol("eisen", "lf.eisenstein_polynomial", "Eisen. Poly.", default=lambda info:info.get("visible") or info.get("Submit") == "sage", mathmode=True, func=format_eisen),
insep_col(default=lambda info: info.get("ind_of_insep")),
assoc_col(default=lambda info: info.get("associated_inertia")),
respoly_col(),
jump_col(default=lambda info: info.get("jump_set"))],
db_cols=["aut", "c", "coeffs", "e", "f", "gal", "old_label", "new_label", "n", "p", "slopes", "t", "u", "visible", "hidden", "ind_of_insep", "associated_inertia", "jump_set", "unram", "eisen", "family", "residual_polynomials"])
family_columns = SearchColumns([
label_col,
MultiProcessedCol("packet_link", "lf.packet", "Packet size", ["packet", "packet_size"], (lambda packet, size: '' if size is None else f'<a href="{url_for_packet(packet)}">{size}</a>'), default=lambda info: info.get("one_per") == "packet", contingent=lambda info: info['family'].n0 == 1),
poly_col(relative=True),
gal_col(lambda info: "Galois group" if info['family'].n0 == 1 else r"Galois group $/ \Q_p$"),
MathCol("galsize", "nf.galois_group", lambda info: "Galois degree" if info['family'].n0 == 1 else r"Galois degree $/ \Q_p$", short_title="Galois degree"),
aut_col(True),
slopes_col(default=False, relative=True),
swanslopes_col(relative=True),
hidden_col(relative=True),
hiddenswan_col(relative=True),
insep_col(relative=True),
assoc_col(relative=True),
respoly_col(),
jump_col()],
db_cols=["old_label", "new_label", "packet", "packet_size", "coeffs", "unram", "n", "gal", "aut", "slopes", "t", "u", "c", "hidden", "ind_of_insep", "associated_inertia", "residual_polynomials", "jump_set"])
class PercentCol(MathCol):
def display(self, rec):
x = self.get(rec)
if x == 0:
return r"$0\%$"
elif x == 1:
return r"$100\%$"
return fr"${100*x:.2f}\%$"
def pretty_link(label, p, n, rf):
if OLD_LF_RE.fullmatch(label):
name = {"old_label": label}
else:
name = {"new_label": label}
name.update({"p": p, "n": n, "rf": rf})
name = prettyname(name)
return f'<a href="{url_for_label(label)}">{name}</a>'
families_columns = SearchColumns([
LinkCol("label", "lf.family_label", "Label", url_for_family),
MathCol("p", "lf.residue_field", "$p$", short_title="prime"),
MathCol("n", "lf.degree", "$n$", short_title="degree"),
MathCol("n0", "lf.degree", "$n_0$", short_title="base degree", default=False, contingent=lambda info: "relative" in info),
MathCol("n_absolute", "lf.degree", r"$n_{\mathrm{abs}}$", short_title="abs. degree", default=False, contingent=lambda info: "relative" in info),
MathCol("f", "lf.residue_field_degree", "$f$", short_title="res. field degree"),
MathCol("f0", "lf.residue_field_degree", "$f_0$", short_title="base res. field degree", default=False, contingent=lambda info: "relative" in info),
MathCol("f_absolute", "lf.residue_field_degree", r"$f_{\mathrm{abs}}$", short_title="abs. residue field degree", default=False, contingent=lambda info: "relative" in info),
MathCol("e", "lf.ramification_index", "$e$", short_title="ram. index"),
MathCol("e0", "lf.ramification_index", "$e_0$", short_title="base ram. index", default=False, contingent=lambda info: "relative" in info),
MathCol("e_absolute", "lf.ramification_index", r"$e_{\mathrm{abs}}$", short_title="abs. ram. index", default=False, contingent=lambda info: "relative" in info),
MathCol("c", "lf.discriminant_exponent", "$c$", short_title="disc. exponent"),
MathCol("c0", "lf.discriminant_exponent", "$c_0$", short_title="base disc. exponent", default=False, contingent=lambda info: "relative" in info),
MathCol("c_absolute", "lf.discriminant_exponent", r"$c_{\mathrm{abs}}$", short_title="abs. disc. exponent", default=False, contingent=lambda info: "relative" in info),
MultiProcessedCol("base_field", "lf.family_base", "Base",
["base", "p", "n0", "rf0"],
pretty_link,
apply_download=lambda base, p, n0, rf0: base,
contingent=lambda info: "relative" in info),
RationalListCol("visible", "lf.slopes", "Abs. Artin slopes",
show_slopes2, default=False, short_title="abs. Artin slopes"),
RationalListCol("slopes", "lf.slopes", "Swan slopes", short_title="Swan slopes"),
RationalListCol("means", "lf.means", "Means", delim=[r"\langle", r"\rangle"]),
RationalListCol("rams", "lf.rams", "Rams", delim="()"),
ProcessedCol("poly", "lf.family_polynomial", "Generic poly", lambda pol: teXify_pol(pol, greek_vars=True, subscript_vars=True), mathmode=True, default=False),
MathCol("ambiguity", "lf.family_ambiguity", "Ambiguity"),
MathCol("field_count", "lf.family_field_count", "Field count"),
MathCol("mass_relative", "lf.family_mass", "Mass", orig=["mass_relative_display"]),
MathCol("mass_absolute", "lf.family_mass", "Mass (absolute)", orig=["mass_absolute_display"], default=False),
MathCol("mass_stored", "lf.family_mass", "Mass stored", default=False),
PercentCol("mass_found", "lf.family_mass", "Mass found", default=False),
MathCol("wild_segments", "lf.wild_segments", "Wild segments", default=False),
MathCol("packet_count", "lf.packet", "Num. Packets", contingent=lambda info: "relative" not in info),
])
def lf_postprocess(res, info, query):
cache = knowl_cache(list({f"{rec['n']}T{rec['gal']}" for rec in res if rec.get('gal') is not None}))
for rec in res:
rec["cache"] = cache
if rec.get('gal') is not None:
gglabel = f"{rec['n']}T{rec['gal']}"
rec["galsize"] = cache[gglabel]["order"]
else:
rec["galsize"] = " $not computed$ " # undo mathmode
return res
def families_postprocess(res, info, query):
quads = list(set(rec["base"] for rec in res if rec["n0"] == 2))
if quads:
rflook = {rec["new_label"]: rec["rf"] for rec in db.lf_fields.search({"new_label":{"$in":quads}}, ["new_label", "rf"])}
for rec in res:
if rec["n0"] == 1:
rec["rf0"] = [1, 0]
elif rec["n0"] == 2:
rec["rf0"] = rflook[rec["base"]]
else:
rec["rf0"] = None
return res
slopes_re = re.compile(r"\[(\d+(/\d+)?)?(,\d+(/\d+)?)*\]")
rams_re = re.compile(r"\((\d+(/\d+)?)?(,\d+(/\d+)?)*\)")
means_re = re.compile(r"\{(\d+(/\d+)?)?(,\d+(/\d+)?)*\}") # clean_info changed "<>" to "{}" for html safety
@search_parser(default_field='herbrand', angle_to_curly=True)
def parse_herbrand(inp, query, qfield):
# We ignore qfield, since it is determined from the delimiters of the input
if slopes_re.fullmatch(inp):
query["slopes"] = inp.replace(",", ", ")
elif rams_re.fullmatch(inp):
query["rams"] = "[" + inp[1:-1].replace(",", ", ") + "]"
elif means_re.fullmatch(inp):
query["means"] = "[" + inp[1:-1].replace(",", ", ") + "]"
else:
print("INPINPINPINP", inp, len(inp))
raise ValueError("Improperly formatted Herbrand invariant")
def common_parse(info, query):
parse_ints(info,query,'p',name='Prime p')
parse_ints(info,query,'n',name='Degree')
parse_ints(info,query,'u',name='Unramified degree')
parse_ints(info,query,'t',name='Tame degree')
parse_galgrp(info,query,'gal',qfield=('galois_label','n'))
parse_ints(info,query,'aut',name='Automorphisms')
parse_ints(info,query,'c',name='Discriminant exponent c')
parse_ints(info,query,'e',name='Ramification index e')
parse_ints(info,query,'f',name='Residue field degree f')
parse_rats(info,query,'topslope',qfield='top_slope',name='Top Artin slope', process=ratproc)
parse_newton_polygon(info,query,"slopes", qfield="slopes_tmp", mode=info.get('slopes_quantifier'))
parse_newton_polygon(info,query,"visible", qfield="visible_tmp", mode=info.get('visible_quantifier'))
parse_newton_polygon(info,query,"ind_of_insep", qfield="ind_of_insep_tmp", mode=info.get('insep_quantifier'), reversed=True)
parse_bracketed_posints(info,query,"associated_inertia")
parse_bracketed_posints(info,query,"jump_set")
parse_inertia(info,query,qfield=('inertia_gap','inertia'))
parse_inertia(info,query,qfield=('wild_gap','wild_gap'), field='wild_gap')
parse_noop(info,query,'packet')
parse_noop(info,query,'family')
parse_noop(info,query,'hidden')
parse_padicsubfields(info,query,'subfield')
def count_fields(p, n=None, f=None, e=None, eopts=None):
# Implement a formula due to Monge for the number of fields with given n or e,f
if n is None and (f is None or e is None):
raise ValueError("Must specify n or (f and e)")
if f is None:
if e is None:
if eopts is None:
return sum(count_fields(p, e=e, f=n//e) for e in n.divisors())
return sum(count_fields(p, e=e, f=n//e) for e in n.divisors() if e in eopts)
elif n % e != 0:
return 0
f = n // e
elif e is None:
if n % f != 0:
return 0
e = n // f
def eps(i):
return sum(p**(-j) for j in range(1, i+1))
def ee(i):
return euler_phi(p**i)
def sig(n0, e, f, s):
nn = n0 * e * f
return 1 + sum(p**i * (p**(eps(i) * nn) - p**(eps(i-1) * nn)) for i in range(1,s+1))
def delta(m, s, i):
if s == i == 0:
return 1
if s > i == 0:
return (p**m - 1) * p**(m * (s-1))
if s > i > 0:
return (p - 1) * (p**m - 1) * p**(m * (s - 1) + i - 1)
if s == i > 0:
return (p - 1) * p**(m * s + s - 1)
return 0
def term(i, fp, ep):
ep_val = ep.valuation(p)
epp = e / (ee(i) * ep)
if not epp.is_integer():
return 0
epp_val, epp_unit = epp.val_unit(p)
fpp = f / fp
a = 1 if ((p**fp - 1) / epp_unit).is_integer() else 0
return a * euler_phi(epp_unit) * euler_phi(fpp) / ee(i) * sig(ee(i), ep, fp, ep_val) * delta(ee(i) * ep * fp, epp_val, i)
return 1/f * sum(term(i, fp, ep) for i in range(e.valuation(p)+1) for fp in f.divisors() for ep in e.divisors())
def fix_top_slope(s):
if isinstance(s, float):
return QQ(s)
elif isinstance(s, str):
return QQ(s[12:])
return s
def count_postprocess(res, info, query):
# We account for two possible ways of encoding top_slope
for key, val in list(res.items()):
res[key[0],fix_top_slope(key[1])] = res.pop(key)
# Fill in entries using field_count
if info["search_type"] == "Counts" and set(query).issubset("pne"):
groupby = info["groupby"]
if groupby == ["p", "n"]:
if "e" in info:
# We need to handle the possibility that there are constraints on e
eopts = integer_options(info["e"], upper_bound=47)
else:
eopts = None
def func(p, n): return count_fields(p, n=n, eopts=eopts)
elif groupby == ["p", "e"]:
n = db.lf_fields.distinct("n", query)
if len(n) != 1:
# There were no results...
return res
n = ZZ(n[0])
def func(p, e): return count_fields(p, n=n, e=e)
elif groupby == ["n", "e"]:
p = db.lf_fields.distinct("p", query)
if len(p) != 1:
# No results...
return res
p = ZZ(p[0])
def func(n, e): return count_fields(p, n=n, e=e)
else:
return res
for a in info["row_heads"]:
for b in info["col_heads"]:
if (a,b) not in res:
cnt = func(ZZ(a),ZZ(b))
if cnt:
info["nolink"].add((a,b))
res[a,b] = cnt
return res
@count_wrap(
template="lf-count-results.html",
table=db.lf_fields,
groupby=["p", "n"],
title="Local field count results",
err_title="Local field search input error",
postprocess=count_postprocess,
bread=lambda: get_bread([("Count results", " ")]),
)
def local_field_count(info, query):
if info["search_type"] == "Counts":
table = db.lf_fields
common_parse(info, query)
else:
common_family_parse(info, query)
table = db.lf_families
if "base" in query:
p = query["base"].split(".")[0]
if not p.isdigit():
raise ValueError(f"Invalid base {query['base']}")
p = int(p)
if "p" in query:
tmp = integer_options(info["p"], contained_in=table.distinct("p"))
if p not in tmp:
raise ValueError("Base prime not compatible with constraints on p")
info["p"] = str(p)
query["p"] = p
if "relative" not in info:
query["n0"] = 1
if "gal" in info and "n" not in info:
# parse_galgrp adds restrictions on n
if isinstance(query["n"], int):
info["n"] = str(query["n"])
else:
info["n"] = ",".join(query["n"]["$in"])
groupby = []
heads = []
maxval = {"p": 200, "n": 47, "e": 47}
for col in ["p", "n", "e", "c", "top_slope"]:
if col in "pne" and info["search_type"] == "Counts":
# Allow user to get virtual counts outside the specified range
tmp = integer_options(info.get(col, f"1-{maxval[col]}"), upper_bound=maxval[col])
if col == "p":
tmp = [p for p in tmp if ZZ(p).is_prime()]
elif col == "n" and "e" in info:
# Constrain degrees to b only multiples of some e
eopts = integer_options(info["e"], upper_bound=47)
if 1 not in eopts:
emuls = set()
for e in eopts:
emuls.update([e*j for j in range(1, 47//e + 1)])
tmp = sorted(set(tmp).intersection(emuls))
else:
tmp = table.distinct(col, query)
if len(tmp) > 1:
if col == "top_slope":
tmp = sorted(fix_top_slope(s) for s in tmp)
groupby.append(col)
heads.append(tmp)
if len(groupby) == 2:
break
else:
raise ValueError("To generate count table, you must not specify all of p, n, e, and c")
query["__groupby__"] = info["groupby"] = groupby
if info["search_type"] == "FamilyCounts":
query["__table__"] = table
query["__title__"] = "Family count results"
info["nolink"] = set()
urlgen_info = dict(info)
urlgen_info.pop("hst", None)
urlgen_info.pop("stats", None)
if info["search_type"] == "FamilyCounts":
urlgen_info["search_type"] = "Families"
def url_generator(a, b):
if (a,b) in info["nolink"]:
return
info_copy = dict(urlgen_info)
info_copy.pop("search_array", None)
if info["search_type"] == "Counts":
info_copy.pop("search_type", None)
info_copy.pop("nolink", None)
info_copy.pop("groupby", None)
info_copy[groupby[0]] = a
info_copy[groupby[1]] = b
return url_for(".index", **info_copy)
info["row_heads"], info["col_heads"] = heads
names = {"p": "Prime", "n": "Degree", "e": "Ramification index", "c": "Discriminant exponent", "top_slope": "Top Artin slope"}
info["row_label"], info["col_label"] = [names[col] for col in groupby]
info["url_func"] = url_generator
@search_wrap(table=db.lf_fields,
title='$p$-adic field search results',
titletag=lambda:'p-adic field search results',
err_title='Local field search input error',
columns=lf_columns,
per_page=50,
shortcuts={'jump': local_field_jump, 'download': LF_download()},
postprocess=lf_postprocess,
bread=lambda:get_bread([("Search results", ' ')]),
learnmore=learnmore_list,
url_for_label=url_for_label,
diagram_opts={
"title": "$p$-adic field diagram search",
"bread": lambda: get_bread([("Diagram search", " ")]),
"label_builder": lambda r: r["new_label"],
"x_axis_default": "f",
"y_axis_default": "c",
"color_default": "u",
})
def local_field_search(info,query):
common_parse(info, query)
def make_code_snippets(data):
"""
Create code snippets dictionary for p-adic field.
"""
# read in code.yaml from local_fields directory:
_curdir = os.path.dirname(os.path.abspath(__file__))
code = yaml.load(open(os.path.join(_curdir, "code.yaml")), Loader=yaml.FullLoader)
# Sage doesn't (yet) support arbitrary extensions of p-adic fields
# so must manually construct field using 'unram' and 'eisen' columns for Sage
sage_construct_field = ""
if data['e'] == 1 and data['f'] == 1:
# Trivial case
sage_construct_field = "K.<a> = Q"+str(data['p'])
elif data['e'] == 1:
# Unramified case
sage_construct_field = "K.<a> = Q"+str(data['p'])+".extension("+data['unram'].replace('t','x')+")"
elif data['f'] == 1:
# Totally ramified case
sage_construct_field = "K.<a> = Q"+str(data['p'])+".extension("+data['eisen']+")"
else:
# Mixed case (construct L as maximal unramified extension)
sage_construct_field = "L.<t> = Q"+str(data['p'])+".extension("+data['unram'].replace('t','x')+")\n"
sage_construct_field += "K.<a> = L.extension("+data['eisen']+")"
format_data = {
'p': data['p'],
'coeffs': str(data['coeffs']),
'sage_construct_field' : sage_construct_field
}
for prop in code:
if prop not in ['frontmatter', 'snippet_test']:
for lang in code[prop]:
code[prop][lang] = code[prop][lang].format(**format_data)
return code
def render_field_webpage(args):
data = None
info = {}
if 'label' in args:
label = clean_input(args['label'])
if NEW_LF_RE.fullmatch(label):
data = db.lf_fields.lucky({"new_label":label})
if data is None:
flash_error("Field %s was not found in the database.", label)
return redirect(url_for(".index"))
elif OLD_LF_RE.fullmatch(label):
data = db.lf_fields.lucky({"old_label": label})
if data is None:
flash_error("Field %s was not found in the database.", label)
return redirect(url_for(".index"))
new_label = data.get("new_label")
if new_label is not None:
return redirect(url_for_label(label=new_label), 301)
else:
flash_error("%s is not a valid label for a $p$-adic field.", label)
return redirect(url_for(".index"))
title = '$p$-adic field ' + prettyname(data)
titletag = 'p-adic field ' + prettyname(data)
polynomial = coeff_to_poly(data['coeffs'])
p = data['p']
Qp = r'\Q_{%d}' % p
e = data['e']
f = data['f']
n = data['n']
cc = data['c']
auttype = 'aut'
if data.get('galois_label') is not None:
gt = int(data['galois_label'].split('T')[1])
the_gal = WebGaloisGroup.from_nt(n,gt)
isgal = ' Galois' if the_gal.order() == n else ' not Galois'
abelian = ' and abelian' if the_gal.is_abelian() else ''
galphrase = 'This field is'+isgal+abelian+r' over $\Q_{%d}.$' % p
if the_gal.order() == n:
auttype = 'gal'
info['aut_gp_knowl'] = the_gal.aut_knowl()
# we don't know the Galois group, but maybe the Aut group is obvious
elif data['aut'] == 1:
info['aut_gp_knowl'] = abstract_group_display_knowl('1.1')
elif is_prime(data['aut']):
info['aut_gp_knowl'] = abstract_group_display_knowl(f"{data['aut']}.1")
prop2 = [
('Label', label),
('Base', r'\(%s\)' % Qp),