-
Notifications
You must be signed in to change notification settings - Fork 0
/
factmsieve.py
executable file
·2266 lines (1909 loc) · 73.5 KB
/
factmsieve.py
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
#!/usr/bin/python
# factmsieve.py - A Python driver for GGNFS and MSIEVE
#
# Copyright (c) 2010, Brian Gladman
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with
# or without modification, are permitted provided that the
# following conditions are met:
#
# Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# Redistributions in binary form must reproduce the
# above copyright notice, this list of conditions and
# the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# The names of its contributors may not be used to
# endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# This code is a conversion of the script factmsieve.pl
# which is Copyright 2004, Chris Monico. His contribution
# is acknowledged, as are those of all who contributed to
# the original Perl script.
#
# I also acknowledge the invaluable help I have had from
# Jeff Gilchrist in testing amd debugging this driver.
# Without his support during its development, it would
# never have reached a working state.
#
# The support of Wingware, who kindly donated their first
# class Python development environment, is acknowledged.
# Minor adjustments by Daniel Suteu (2019) to make it work
# on Arch Linux with the `ggnfs-svn` AUR package installed.
# Experimental porting to Python 3 by Daniel Suteu (2020).
from __future__ import print_function
from __future__ import division
import os, sys, random, re, functools, string, socket, signal
import time, subprocess, gzip, glob, math, tempfile, datetime
import atexit, threading, collections, multiprocessing, platform
VERSION = '0.86'
# Set binary directory paths
GGNFS_PATH = '/usr/bin'
MSIEVE_PATH = '/usr/bin'
# Set the number of CPU cores and threads
NUM_CORES = 1
THREADS_PER_CORE = 1
USE_CUDA = False
GPU_NUM = 0
MSIEVE_POLY_TIME_LIMIT = 0
MIN_NFS_BITS = 264
# msieve polynomial search leading coefficients limits
# search from POLY_MIN_LC + 1 to POLY_MAX_LC inclusive
POLY_MIN_LC = 0
POLY_MAX_LC = 4000
# Set global flags to control operation
CHECK_BINARIES = True
CHECK_POLY = True
CLEANUP = False
DOCLASSICAL = False
NO_DEF_NM_PARAM = False
PROMPTS = False
SAVEPAIRS = True
USE_KLEINJUNG_FRANKE_PS = False
USE_MSIEVE_POLY = True
VERBOSE = True
# End of configuration options
# number of msieve poly search threads to launch
MS_THREADS = NUM_CORES * THREADS_PER_CORE
# number of siever threads to launch
SV_THREADS = NUM_CORES * THREADS_PER_CORE
# number of linear algebra threads to launch
LA_THREADS = NUM_CORES * THREADS_PER_CORE
# ggnfs and msieve executable flie names
MSIEVE = 'msieve'
MAKEFB = 'makefb'
PROCRELS = 'procrels'
POL51M0 = 'pol51m0b'
POL51OPT = 'pol51opt'
POLYSELECT = 'polyselect'
PLOT = 'autogplot.sh'
# default parameter files
DEFAULT_PAR_FILE = 'def-par.txt'
DEFAULT_POLSEL_PAR_FILE = 'def-nm-params.txt'
# temporary files
PARAMFILE = '.params'
RELSBIN = 'rels.bin'
if sys.platform.startswith('win'):
EXE_SUFFIX = '.exe'
else:
EXE_SUFFIX = ''
NICE_PATH = ''
# static global variables
PNUM = 0
LARGEP = 3
LARGEPRIMES = '-' + str(LARGEP) + 'p'
nonPrefDegAdjust = 12
polySelTimeMultiplier = 1.0
# poly5 parameters
pol5_p = { 'max_pst_time':0, 'search_a5step':0, 'npr':0, 'normmax':0.0,
'normmax1':0.0, 'normmax2':0.0, 'murphymax':0.0 }
# poly select parameters
pols_p = { 'degree':0, 'maxs1':0, 'maxskew':0, 'goodscore':0.0,
'examinefrac':0.0, 'j0':0, 'j1':0, 'estepsize':0, 'maxtime':0 }
# lattice sieve parameters
lats_p = { 'rlim':0, 'alim':0, 'lpbr':0, 'lpba':0, 'mfbr':0, 'mfba':0,
'rlambda':0.0, 'alambda':0.0, 'qintsize':0, 'lss':1,
'siever': 'gnfs-lasieve4I10e', 'minrels':0, 'currels':0 }
# classical sieve parameters
clas_p = { 'a0':0, 'a1':0, 'b0':0, 'b1':0, 'cl_a':0, 'cl_b':0 }
# polynomial parameters
poly_p = { 'n':0, 'degree':0, 'm':0, 'skew':0.0, 'coeff':dict() }
# factorisation parameters
fact_p = { 'n':0, 'dec_digits':0, 'type':'', 'knowndiv':0, 'snfs_difficulty':0,
'digs':0, 'qstart':0, 'qstep':0, 'q0':0, 'dd':0, 'primes':list(),
'comps':list(), 'divisors':list(),
'q_dq':collections.deque([(0,0,0)] * SV_THREADS) }
# Utillity Routines
# print an error message and exit
def die(x, rv = -1):
print(x)
sys.exit(rv)
def sig_exit(x, y):
die('Signal caught. Terminating...')
# obtain a float or an int from a string
def get_nbr(s):
try:
return float(s)
except ValueError:
try:
return int(s)
except ValueError:
pass
return None
# delete a file (unlink equivalent)
def delete_file(fn):
if os.path.exists(fn):
try:
os.unlink(fn)
except WindowsError:
pass
# GREP on a list of text lines
def grep_l(pat, lines):
r = []
c = re.compile(pat)
for l in lines:
if c.search(l):
r += [re.sub('\r|\n', ' ', l)]
return r
# GREP on a named file
def grep_f(pat, file_path):
r = []
c = re.compile(pat)
try:
with open(file_path, 'r') as in_file:
for l in in_file:
if c.search(l):
r += [re.sub('\r|\n', ' ', l)]
return r
except IOError:
die("can't find file " + file_path)
# concatenate file 'app' to file 'to'
def cat_f(app, to):
try:
with open(to, 'ab') as out_file:
try:
with open(app, 'rb') as in_file:
if VERBOSE:
print('appending {0:s} to {1:s}'.format(app, to))
buf = in_file.read(8192)
while buf:
out_file.write(buf)
buf = in_file.read(8192)
except IOError:
die("can't find file " + app)
except IOError:
die("can't find file " + to)
# compress file 'fr' to file 'to'
def gzip_f(fr, to):
try:
with open(fr, 'rb') as in_file:
if VERBOSE:
print('compressing {0:s} to {1:s}'.format(fr, to))
out_file = gzip.open(to, 'ab')
out_file.writelines(in_file)
out_file.close()
except IOError:
die("can't find file " + fr)
# remove comment lines
def chomp_comment(s):
return re.sub('#.*', '', s).strip()
# produce date/time string for log
def date_time_string() :
dt = datetime.datetime.today()
return dt.strftime('%a %b %d %H:%M:%S %Y ')
# write string to log(s):
def write_string_to_log(s):
with open(CWD + LOGNAME, 'a') as out_f:
print(date_time_string() + s, file = out_f)
def output(s, console = True, log = True):
if console:
print(s)
if log:
write_string_to_log(s)
# find processor speed
def proc_speed():
if os.sys.platform.startswith('win'):
if sys.version_info[0] == 2:
from _winreg import OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE
else:
from winreg import OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE
h = OpenKey(HKEY_LOCAL_MACHINE,
'HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0')
mhz = float(QueryValueEx(h, '~MHz')[0])
else:
tmp = grep_f('cpu MHz\s+:\s+', '/proc/cpuinfo')
m = re.search('\s*cpu MHz\s+:\s+([0-9]+)', tmp[0])
mhz = float(m.group(1)) if m else 0.0
return 1e-3 * mhz
# check that an executable file exists
def check_binary(exe):
if CHECK_BINARIES:
pth = MSIEVE_PATH if exe == MSIEVE else GGNFS_PATH
pth = os.path.join(pth, exe + EXE_SUFFIX)
if not os.path.exists(pth):
print('-> Could not find the program: {0:s}.'.format(exe))
print('-> Did you set the paths properly in this script?')
print('-> They are currently set to:')
print('-> GGNFS_BIN_PATH = {0:s}'.format(GGNFS_PATH))
print('-> MSIEVE_BIN_PATH = {0:s}'.format(MSIEVE_PATH))
sys.exit(-1)
# run an executable file
def run_exe(exe, args, inp = '', in_file = None, out_file = None,
log = True, display = VERBOSE, wait = True):
al = {} if VERBOSE else {'creationflags' : 0x08000000 }
if sys.platform.startswith('win'):
# priority_high = 0x00000080
# priority_normal = 0x00000020
# priority_idle = 0x00000040
al['creationflags'] = al.get('creationflags', 0) | 0x00000040
#else:
#al['preexec_fn'] = NICE_PATH
if in_file and os.path.exists(in_file):
al['stdin'] = open(in_file, 'r')
if out_file:
if out_file == subprocess.PIPE:
md = '> PIPE'
al['stdout'] = subprocess.PIPE
elif os.path.exists(out_file):
md = '>> ' + out_file
al['stdout'] = open(out_file, 'a')
else:
md = '> ' + out_file
al['stdout'] = open(out_file, 'w')
cs = '-> {0:s} {1:s}'.format(exe, args)
if in_file:
cs += '< {0:s}'.format(in_file)
if out_file:
cs += md
output(cs, console = display, log = log)
ex = os.path.join((GGNFS_PATH if exe != MSIEVE
else MSIEVE_PATH), exe + EXE_SUFFIX)
p = subprocess.Popen([ex] + args.split(' '), **al)
if not wait:
return p
if out_file == subprocess.PIPE:
if sys.version_info[0] == 3:
res = p.communicate(input=inp.encode())[0].decode()
else:
res = p.communicate(input=inp)[0]
if res:
res = re.split('(?:\r|\n)*', res)
ret = p.poll()
return (ret, res)
else:
return p.wait()
def run_msieve(ap, extn='', parallel=False):
rel = os.path.abspath(CWD)
dp = os.path.join(rel, DATNAME + extn)
lp = os.path.join(rel, LOGNAME + extn)
ip = os.path.join(rel, ININAME + extn)
fp = os.path.join(rel, FBNAME + extn)
args = ('-s {0:s} -l {1:s} -i {2:s} -nf {3:s} '
.format(dp, lp, ip, fp))
if parallel:
op = os.path.join(rel, OUTNAME + extn)
ret = run_exe(MSIEVE, args + ap, out_file=op, wait=False)
else:
ret = run_exe(MSIEVE, args + ap)
os.chdir(CWD)
return ret
# generate a list of primes
def prime_list(n):
sieve = [False, False] + [True] * (n - 1)
for i in range(2, int(n ** 0.5) + 1):
if sieve[i]:
m = n // i - i
sieve[i * i : n + 1 : i] = [False] * (m + 1)
return [i for i in range(n + 1) if sieve[i]]
# greatest common divisor
def gcd(x, y):
if x == 0:
return y
elif y == 0:
return x
else:
return gcd(y % x, x)
# Miller Rabin 'probable prime' test
#
# returns 'False' if 'n' is definitely composite
# returns 'True' if 'n' is prime or probably prime
#
# 'r' is the number of trials performed
def miller_rabin(n, r = 10):
t = n - 1
s = 0
while not t & 1:
t >>= 1
s += 1
for i in range(r):
a = random.randint(2, n - 1)
x = pow(a, t, n)
if x != 1 and x != n - 1:
for j in range(s - 1):
x = (x * x) % n
if x == 1:
return False
if x == n - 1:
break
else:
return False
return True
# determine if n is probably prime - return
# 0 if n is 0, 1 or composite
# 1 if n is probably prime
# 2 if n is definitely prime
def probable_prime_p(nn, r):
n = abs(nn)
if n <= 2:
return 2 if n == 2 else 0
# trial division
for p in prime_list(1000):
if not n % p:
return 2 if n == p else 0
if p * p > n:
return 2
# Fermat test
if pow(random.randint(2, n - 1), n - 1, n) != 1:
return 0
# Miller-Rabin test
return 1 if miller_rabin(n, r) else 0
# count the number of lines in a file
def linecount(file_path):
count = 0
if not os.path.exists(file_path):
die('can\'t open {0:s}'.format(file_path))
with open(file_path, 'r') as in_file:
for l in in_file:
count += 1
return count
# Read the log file to see if we've found all the prime
# divisors of N yet.
def get_primes(fact_p):
with open(LOGNAME, 'r') as in_f:
for l in in_f:
m1 = re.search('r\d+=(\d+)\s+', l.rstrip())
if m1:
val = int(m1.group(1))
if len(val) > 1 and len(val) < len(fact_p['ndivfree']):
# Is this a prime divisor or composite?
m2 = re.search('\(pp(\d+)\)', l)
if m2:
# If this is a prime we don't already have, add it.
found = False
for p in fact_p['primes']:
if val == p:
found = True
if not found:
fact_p['primes'].append(val)
else:
fact_p['comps'].append(val)
# Now, try to figure out if we have all the prime factors:
x = itertools.reduce(lambda x,y : x * y, fact_p['primes'], 1)
if x == fact_p['ndivfree'] or probab_prime_p(fact_p['ndivfree'] // x, 10):
if x != fact_p['ndivfree']:
fact_p['primes'].append(fact_p['ndivfree'] // x)
for p in fact_p['primes']:
cs = '-> p: {0:s} (pp{1:d})'.format(val, len(val))
output(cs)
return True
# Here, we could try to recover other factors by division,
# but until we have a primality test available, this would
# be pointless since we couldn't really know if we're done.
return False
# The parameter degree, if nonzero, will let this function adjust
# parameters for SNFS factorizations with a predetermined polynomial
# of degree that is not the optimal degree.
nonPrefDegAdjust = 12
def load_default_parameters(nfs_type, digits, degree,
fact_p, pols_p, lats_p, clas_p):
if nfs_type == 'gnfs':
lats_p['lss'] = 0
pth = "/usr/share/ggnfs-svn/def-par.txt"
if not os.path.exists(pth):
die('Could not find default parameter file {0:s}!'
.format(pth))
with open(pth, 'r') as in_f:
par_digits = 0
par_degree = 0
how_close = 1000
for l in in_f:
l = chomp_comment(l.strip()).strip()
if l:
tu = l.split(',')
t = tu[0]
if t == nfs_type:
o = 2
cand_digits = int(tu[1])
cand_degree = int(tu[o + 0])
s1 = abs(cand_digits - digits)
s2 = abs(cand_digits - nonPrefDegAdjust - digits) + nonPrefDegAdjust
# try to properly handle crossover from degree 4 to degree 5
if (s1 if nfs_type == 'gnfs' or not degree or degree == cand_degree
or par_degree == cand_degree - 1 else s2) < how_close:
how_close = (s2 if nfs_type != 'gnfs' and degree
and cand_degree != degree else s1)
par_digits = cand_digits
par_degree = cand_degree
pols_p['maxs1'] = int(tu[o + 1])
pols_p['maxskew'] = int(tu[o + 2])
pols_p['goodscore'] = float(tu[o + 3])
pols_p['examinefrac'] = float(tu[o + 4])
pols_p['j0'] = int(tu[o + 5])
pols_p['j1'] = int(tu[o + 6])
pols_p['estepsize'] = int(tu[o + 7])
pols_p['maxtime'] = int(tu[o + 8])
lats_p['rlim'] = int(tu[o + 9])
lats_p['alim'] = int(tu[o + 10])
lats_p['lpbr'] = int(tu[o + 11])
lats_p['lpba'] = int(tu[o + 12])
lats_p['mfbr'] = int(tu[o + 13])
lats_p['mfba'] = int(tu[o + 14])
lats_p['rlambda'] = float(tu[o + 15])
lats_p['alambda'] = float(tu[o + 16])
lats_p['qintsize'] = int(tu[o + 17])
clas_p['cl_a'] = int(tu[o + 18])
clas_p['cl_b'] = int(tu[o + 19])
fact_p['qstep'] = lats_p['qintsize']
fact_p['digs'] = digits / 0.72 if nfs_type == 'gnfs' else digits
# 0.72 is inspired by T.Womack's crossover 28/29 for GNFS-144 among other consideration
if fact_p['digs'] >= 160:
# the table parameters are easily splined; the table may be not needed at all --SB.
lats_p['rlim'] = lats_p['alim'] = int(0.07 * 10 ** (fact_p['digs'] / 60.0) + 0.5) * 100000
lats_p['lpbr'] = lats_p['lpba'] = int(21 + fact_p['digs'] / 25.0)
lats_p['mfbr'] = lats_p['mfba'] = 2 * lats_p['lpbr'] - (1 if fact_p['digs'] < 190 else 0)
lats_p['rlambda'] = lats_p['alambda'] = 2.5 if fact_p['digs'] < 200 else 2.6
lats_p['qintsize'] = fact_p['qstep'] = 100000
clas_p['cl_a'] = 4000000
clas_p['cl_b'] = 400
par_digits = digits
pols_p['degree'] = par_degree
print('-> Selected default factorization parameters for {0:d} digit level.'.
format(par_digits))
if nfs_type == 'gnfs':
r = (95, 110, 140, 158, 185, 999)
else:
if degree and par_degree != degree:
digits += nonPrefDegAdjust
r = (120, 150, 195, 240, 275, 999)
i = 1
for v in r:
if digits < v:
break
i += 1
else:
die('You are joking?')
lats_p['siever'] = 'gnfs-lasieve4I1' + str(i) + 'e'
output('-> Selected lattice siever: {0:s}'.format(lats_p['siever']))
# These are default parameters for polynomial selection using the
# Kleinjung/Franke tool.
# arg0 = number of digits in N.
def load_pol5_parameters(digits, pol5_p):
par_digits = 0
if NO_DEF_NM_PARAM or digits < 100:
pol5_p['search_a5step'] = 1
pol5_p['npr'] = int(digits / 13.0 - 4.5)
pol5_p['npr'] = pol5_p['npr'] if pol5_p['npr'] > 4 else 4
pol5_p['normmax'] = 10 ** (0.163 * digits - 1.4794)
pol5_p['normmax1'] = 10 ** (0.1522 * digits - 1.6969)
pol5_p['normmax2'] = 10 ** (0.142 * digits - 2.6429)
pol5_p['murphymax'] = 10 ** (-0.0569 * digits - 2.8452)
pol5_p['max_pst_time'] = int(0.000004 / pol5_p['murphymax'])
output('-> Selected polsel parameters for {0:d} digit level.'.format(digits))
return
pth = "/usr/share/ggnfs-svn/def-nm-params.txt"
if not os.path.exists(pth):
die('Could not find default parameter file {0:s}!'
.format(pth))
with open(pth, 'r') as in_f:
how_close = 1000
for l in in_f:
l = chomp_comment(l.strip()).strip()
if l:
tu = l.split(',')
d = int(tu[0])
if abs(d - digits) < how_close:
o = 1
how_close = abs(d - digits)
par_digits = d
pol5_p['max_pst_time'] = 60 * int(tu[o + 0])
pol5_p['search_a5step'] = int(tu[o + 1])
pol5_p['npr'] = int(tu[o + 2])
pol5_p['normmax'] = float(tu[o + 3])
pol5_p['normmax1'] = float(tu[o + 4])
pol5_p['normmax2'] = float(tu[o + 5])
pol5_p['murphymax'] = float(tu[o + 6])
output('-> Selected default polsel parameters for {0:d} digit level.'
.format(par_digits))
# The dictionary entries in this routine map each coefficient as a string
# to the coefficient value as floating point values. The (name, value)
# pairs on the BEGIN_POLY line are also entered into the dictionary for
# each polynomial
pname = ''
def terminate_pol5(x, y):
die('Terminated on {0:s} by SIGINT'.format(pname))
def run_pol5(fact_p, pol5_p, lats_p, clas_p):
global pname
check_binary(POL51M0)
check_binary(POL51OPT)
projectname = NAME + '.polsel'
host = socket.gethostname()
pname = projectname + host + '.' + str(os.getpid())
with open(pname + '.data', 'w') as out_f:
print('N ' + str(fact_p['n']), file = out_f)
pol5_term_flag = False
old_handler = signal.signal(signal.SIGINT, terminate_pol5)
load_pol5_parameters(fact_p['dec_digits'], pol5_p)
pol5_p['max_pst_time'] *= polySelTimeMultiplier
hmult = 1e3
load_default_parameters('gnfs', fact_p['dec_digits'], 5,
fact_p, pols_p, lats_p, clas_p)
bestpolyinf = dict()
bestpolyinf['Murphy_E'] = 0
start_time = time.time()
nerr = 0
h_lo = 0
while not pol5_term_flag and nerr < 2:
h_hi = h_lo + pol5_p['search_a5step']
output('-> Searching leading coefficients from {0:g} to {1:g}'
.format(h_lo * hmult + 1, h_hi * hmult))
args = ('-b {0:s} -v -v -p {1:d} -n {2:g} -a {3:g} -A {4:g}'
.format(pname, pol5_p['npr'], pol5_p['normmax'], h_lo, h_hi))
if not run_exe(POL51M0, args, out_file = pname + '.log'):
# lambda-comp related errors can be skipped and some polys are
# then found ull5-comp related are probably fatal, but let the
# elapsed time.time() take care of them
nerr = 0
suc = grep_f('success', pname + '.log')
changed = False
if suc:
args = ('-b {0:s} -v -v -n {1:g} -N {2:g} -e {3:g}'
.format(pname, pol5_p['normmax1'], pol5_p['normmax2'], pol5_p['murphymax']))
ret = run_exe(POL51OPT, args, out_file = pname + '.log')
if ret:
die('Abnormal return value {0:d}. Terminating...'.format(ret))
cat_f(pname + '.51.m', projectname + '.51.m.all')
with open(pname + '.cand', 'r') as in_f:
polyinf = dict()
for l in in_f:
l = l.rstrip()
if re.match('BEGIN POLY', l):
l = re.sub('BEGIN POLY', '', l)
l = re.sub('^ #', '', l)
tu = l.split()
for i in range(0, len(tu), 2):
polyinf[tu[i]] = float(tu[i + 1])
elif re.match('END POLY', l):
if polyinf['Murphy_E'] > bestpolyinf['Murphy_E']:
bestpolyinf = polyinf.copy()
changed = True
polyinf = dict()
else:
tu = l.split()
polyinf[re.sub('^X', 'c', tu[0])] = int(tu[1])
if changed:
for key in sorted(bestpolyinf):
print(key, ':', bestpolyinf[key])
with open(NAME + '.poly', 'w') as out_f:
print('name: {0:s}'.format(NAME), file = out_f)
print('n: {0:d}'.format(fact_p['n']), file = out_f)
for key in reversed(sorted(bestpolyinf)):
if re.match('c\d+', key) or re.match('Y\d+', key):
print('{0:s}: {1:d}'
.format(key, bestpolyinf[key]), file = out_f)
elif re.match('skewness', key):
print('skew: {0:<10.2f}'
.format(bestpolyinf[key]), file = out_f)
elif key == 'M':
print(key, bestpolyinf[key])
print('# {0:s} {1:d}'
.format(key, bestpolyinf[key]), file = out_f)
else:
print('# {0:s} {1:g}'
.format(key, bestpolyinf[key]), file = out_f)
print('type: {0:s}'.format('gnfs'), file = out_f)
print('rlim: {0:d}'.format(lats_p['rlim']), file = out_f)
print('alim: {0:d}'.format(lats_p['alim']), file = out_f)
print('lpbr: {0:d}'.format(lats_p['lpbr']), file = out_f)
print('lpba: {0:d}'.format(lats_p['lpba']), file = out_f)
print('mfbr: {0:d}'.format(lats_p['mfbr']), file = out_f)
print('mfba: {0:d}'.format(lats_p['mfba']), file = out_f)
print('rlambda: {0:g}'.format(lats_p['rlambda']), file = out_f)
print('alambda: {0:g}'.format(lats_p['alambda']), file = out_f)
print('qintsize: {0:d}'.format(lats_p['qintsize']), file = out_f)
cat_f(pname +'.cand', projectname + '.cand.all')
delete_file(pname + '.cand')
print('-> =====================================================')
output('-> Best score so far: {0:g} (good_score={1:g})'
.format(bestpolyinf['Murphy_E'], pol5_p['murphymax']))
print('-> =====================================================')
delete_file(pname + '.log')
delete_file(pname + '.51.m')
if time.time() > start_time + pol5_p['max_pst_time']:
pol5_term_flag = True
h_lo = h_hi
delete_file(pname + '.data')
signal.signal(signal.SIGINT, old_handler)
# We will start with a higher leading coefficient divisor. When it
# appears that we are searching in an interesting range, it will
# be backed down so that the resulting range can be searched with
# a finer resolution. This means that from time to time, the same
# poly will be found several times as we hone in on a region.
def run_poly_select(fact_p, pols_p, lats_p, clas_p):
check_binary(POLYSELECT)
lcd_choices = (2, 4, 4, 12, 12, 24, 24, 48, 48, 144, 144, 720, 5040)
lcd_level = 4 + (fact_p['dec_digits'] - 70) // 10
if lcd_level < 0:
lcd_level = 0
if lcd_level > 12:
lcd_level = 12
output('-> Starting search with leading coefficient divisor {0:d}'
.format(lcd_choices[lcd_level]))
load_default_parameters('gnfs', fact_p['dec_digits'], 0,
fact_p, pols_p, lats_p, clas_p)
pols_p['maxtime'] *= polySelTimeMultiplier
best_score = 0.0
start_time = time.time()
done = False
best_lc = 1
last_lc = 0
multiplier = 0.75
e_lo = 1
while not done:
e_hi = e_lo + pols_p['estepsize']
lcd = lcd_choices[lcd_level]
with open(NAME + '.polsel', 'w') as out_f:
print('name: {0:s}'.format(NAME), file = out_f)
print('n: {0:d}'.format(fact_p['n']), file = out_f)
print('deg: {0:d}'.format(pols_p['degree']), file = out_f)
print('bf: {0:s}.best.poly'.format(NAME), file = out_f)
print('maxs1: {0:d}'.format(pols_p['maxs1']), file = out_f)
print('maxskew: {0:d}'.format(pols_p['maxskew']), file = out_f)
print('enum: {0:d}'.format(lcd), file = out_f)
print('e0: {0:d}'.format(e_lo), file = out_f)
print('e1: {0:d}'.format(e_hi), file = out_f)
print('cutoff: {0:g}'.format(0.75 * pols_p['goodscore']), file = out_f)
print('examinefrac: {0:g}'.format(pols_p['examinefrac']), file = out_f)
print('j0: {0:d}'.format(pols_p['j0']), file = out_f)
print('j1: {0:d}'.format(pols_p['j1']), file = out_f)
args = '-if {0:s}.polsel'.format(NAME)
ret = run_exe(POLYSELECT, args)
if ret:
die('Return value res. Terminating...'.format(ret))
# Find the score of the best polynomial: E(F1,F2) =
inp = True
try:
tmp = grep_f('E\(F1,F2\) =', NAME + '.best.poly')
except IOError:
inp = False
if inp:
score = tmp[0]
score = float(re.sub('.*E\(F1,F2\) =', '', tmp[0]))
tmp = grep_f('^c' + str(pols_p['degree']), NAME + '.best.poly')
m = re.search('^c' + str(pols_p['degree']) + ':\s([\+\-]*\d*)', tmp[0])
lc = int(m.group(1))
else:
score = 0.0
if (score > multiplier * pols_p['goodscore'] and lc != best_lc
and lc != last_lc ):
multipler = 1.1 * multiplier if multiplier < 0.9 / 1.1 else multiplier
last_lc = lc
new_lcd_level = lcd_level - 1 if lcd > 0 else 0
e_lo = e_lo * lcd_choices[lcd_level] // lcd_choices[new_lcd_level] - pols_p['estepsize']
if lcd_level != new_lcd_level:
print('-> Leading coefficient divisor dropped from {0:d} to {1:d}.'
.format(lcd_choices[lcd_level], lcd_choices[new_lcd_level]))
lcd_level = new_lcd_level
if score > best_score and lc != best_lc:
best_score = score
best_lc = lc
last_best_time = time.time()
os.rename(NAME + '.best.poly', NAME + '.thebest.poly')
# We should now fill in the missing parameters with the default
# loaded in from table. Do this now, so that the user has the
# option to kill the script and still have a viable poly file.
with open(NAME + '.thebest.poly', 'r') as in_f:
with open(NAME + '.poly', 'w') as out_f:
for l in in_f:
l = l.rstrip()
if l.find('rlim:') != -1:
l = 'rlim: {0:d}'.format(lats_p['rlim'])
elif l.find('alim:') != -1:
l = 'alim: {0:d}'.format(lats_p['alim'])
elif l.find('lpbr:') != -1:
l = 'lpbr: {0:d}'.format(lats_p['lpbr'])
elif l.find('lpba:') != -1:
l = 'lpba: {0:d}'.format(lats_p['lpba'])
elif l.find('mfbr:') != -1:
l = 'mfbr: {0:d}'.format(lats_p['mfbr'])
elif l.find('mfba:') != -1:
l = 'mfba: {0:d}'.format(lats_p['mfba'])
elif l.find('rlambda:') != -1:
l = 'rlambda: {0:g}'.format(lats_p['rlambda'])
elif l.find('alambda:') != -1:
l = 'alambda: {0:g}'.format(lats_p['alambda'])
elif l.find('qintsize:') != -1:
l = 'qintsize: {0:d}'.format(lats_p['qintsize'])
if l:
print(l, file = out_f)
print('type: gnfs', file = out_f)
delete_file(NAME + '.thebest.poly')
delete_file(NAME + '.best.poly')
print('-> =====================================================')
output('-> Best score so far: {0:g} (good_score={1:g}) '
.format(best_score, pols_p['goodscore']))
print('-> =====================================================')
# We will allow another 5 minutes just in case there happens to
# be a really good poly nearby (or the 'good_score' value was too low)
if best_score > 1.4 * pols_p['goodscore']:
done = (time.time() > last_best_time + 300)
done |= (time.time() > start_time + pols_p['maxtime'])
e_lo = e_hi
output('-> Using poly with score={0:f}'.format(best_score))
delete_file(NAME + '.polsel')
def msieve_mpqs(fact_p):
with open(ININAME, 'w') as out_f:
out_f.write('{0:d}'.format(fact_p['n']))
ret = run_msieve('-v')
if ret:
die('Msieve Error: return value {0:d}... terminating...'.format(ret))
return True
procs = []
def terminate_threads(sig=signal.SIGINT, frame=None):
global procs
try:
for p in procs:
if p.poll() == None:
p.terminate()
for p in procs:
if p.poll() == None:
p.wait()
except:
pass
def fb_to_poly():
with open(NAME + '.poly', 'w') as out_f:
with open(NAME + '.fb', 'r') as in_f:
for l in in_f:
m = re.match('N\s+(\d+)', l)
if m:
print('n: {0:s}'.format(m.group(1)), file = out_f)
m = re.match('SKEW\s+(\d*\.\d*)', l)
if m:
skew = float(m.group(1))
m = re.match('R(\d+)\s+([+-]?\d+)', l)
if m:
print('Y{0:s}: {1:s}'.format(m.group(1),
m.group(2)), file = out_f)
m = re.match('A(\d+)\s+([+-]?\d+)', l)
if m:
print('c{0:s}: {1:s}'.format(m.group(1),
m.group(2)), file = out_f)
try:
print('skew: {0:<10.2f}'.format(skew), file = out_f)
print('type: gnfs', file = out_f)
except:
die('{0:s}.fb is not in the correct format'.format(NAME))
def find_best(fn, bestscore, poly):
try:
in_f = open(fn, 'r')
except IOError:
die("can't read " + fn)
# first input line (followed by polynomial lines) format:
# norm 1.498232e-10 alpha -5.818790 e 9.344e-10 rroots 3
# 1 2 3 4 5 6 7 8
for l in in_f:
word = l.split()
if word[1] == 'norm':
better = False
if float(word[6]) > bestscore:
bestscore = float(word[6])
output("Best score so far: {0:s}".format(l.strip()))
better = True
poly = []
if better:
poly += [l]
in_f.close()
return (bestscore, poly)