-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfeynson.cpp
More file actions
1749 lines (1652 loc) · 61.4 KB
/
feynson.cpp
File metadata and controls
1749 lines (1652 loc) · 61.4 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
static const char usagetext[] = R"(
Ss{NAME}
Nm{feynson} -- a tool for Feynman integral symmetries.
Ss{SYNOPSYS}
Nm{feynson} [Fl{options}] Cm{command} Ar{args} ...
Ss{DESCRIPTION}
Ss{COMMANDS}
Nm{feynson} Cm{symmetrize} [Fl{-d}] Ar{spec-file}
Print a list of momenta substitutions that make symmetries
between a list of integral families explicit.
These momenta substitutions will make the set of
denominators of two integral families exactly match (up
to a reordering) if the families are isomorphic, and
will make one a subset of the other if one family is
isomorphic to a subsector of another family.
The input specification file should be a list of three
elements:
1) a list of all integral families, with each family
being a list of propagators (e.g. Ql{(l1+l2)^2});
2) a list of all loop momenta;
3) a list of external invariant substitution rules, each
rule being a list of two elements: a scalar product
and its substitution (e.g. Ql[{q^2, 1}] or Ql[{p1*p2, s12}]).
For example: Ql[{ {{(q-l)^2, l^2}, {(q+l)^2, l^2}}, {l}, {} }].
Each family that can be mapped to (a subsector of) another
is guaranteed to be mapped to the first possible family,
prefering families that are larger or listed earlier.
If Fl{-d} flag is given, earlier families are prefered
irrespective of their size.
Note that if non-trivial invariant substitution rules
are supplied, it becomes possible that two families are
identical, but no loop momenta substitution exists to map
them onto each other. For example, a 1-loop propagator
with momenta Ql[p1] is equal to a 1-loop propagator with
Ql[p2], but only if Ql[p1^2 = p2^2], in which case no loop
momenta substitution can make the integrands identical.
For this reason, it is best to use Cm{symmetrize} with the
invariant substitution rules set to Ql[{}], and to fall back
to Cm{mapping-rules} otherwise.
Nm{feynson} Cm{mapping-rules} [Fl{-d}] Ar{spec-file}
Same as Cm{symmetrize}, but instead of printing the loop
momenta substitutions, produce explicit rules of mapping
between families: for each family that is symmetric to
another, print Ql[{fam, {n1, n2, ...}}], meaning that any
integral in this family with indices Ql[{i_1, i_2, ...}]
is equal to an integral in the family number Ql[fam] with
indices Ql[{i_n1, i_n2, ...}]. For unique families, print Ql[{}].
The families are numbered starting at 1. If a given family
is symmetric to a subfamily, some of the Ql{n} indices will
be Ql{0}: the convention is that Ql{i_0 = 0}.
Nm{feynson} Cm{zero-sectors} [Fl{-s}] Ar{spec-file}
Print a list of all zero sectors of a given integral
family.
The input specification file should be a list of four
elements:
1) a list of all propagator momenta (e.g. Ql{(l1-q)^2});
2) a list of cut flags, Ql{0} for normal propagators, Ql{1}
for cut propagators;
3) a list of all loop momenta (e.g. Ql{l1});
4) and a list of external invariant substitutions (e.g.
Ql[{q^2, 1}]).
For example: Ql[{ {(q-l)^2, l^2}, {0, 0}, {l}, {{q^2,1}} }].
The output will be a list of zero sectors, each denoted
by an integer s=2^{i_1-1} + ... + 2^{i_n-1}, where i_k
are the indices of denominators that belong to this
sector (counting from 1).
If the Fl{-s} ("short") flag is given, the output will
be shortened by only listing the topmost zero sectors:
all the remaining zero sectors are their subsectors.
Every sector that is missing a cut propagator of its
supersectors will be reported as zero.
Nm{feynson} Cm{ufx} Ar{spec-file}
Print Feynman parametrization (U, F, X) of an integral
defined by a set of propagators.
The input specification file should be a list of three
elements:
1) a list of all propagators, e.g. Ql{(l1-q)^2};
2) a list of all loop momenta, e.g. Ql{l1};
3) and a list of external invariant substitutions, e.g.
Ql[{q^2, 1}].
For example: Ql[{ {(q-l)^2, l^2}, {l}, {{q^2,1}} }].
The output will be a list of three items: the U polynomial,
the F polynomial, and the list of Feynman parameter
variables.
Nm{feynson} Cm{canonicalize-polynomials} Ar{spec-file}
Compute canonical permutations of a list of polynomials.
The input specification file should be a list of two
elements:
1) a list of all polynomial variables, e.g. Ql[{x1, x2, x3}];
2) a list of all polynomials.
For example: Ql[{ {x1, x2}, {x1+2*x2, x2+2*x1} }].
The output will be a list, where for each input polynomial
there will be a list of three elements:
1) a string hash, uniquely identifying the canonical
form of the polynomial;
2) the canonical permutation of the polynomial variables,
which is a list of indices, such that the replacement
of each Ql{variable[permutation[i]]} into Ql{variable[i]} puts
the corresponding polynomial into its canonical form;
3) the canonical form itself.
Ss{OPTIONS}
Fl{-j} Ar{jobs} Parallelize calculations using at most this many workers.
Fl{-d} Prioritize families in the definition order, irrespective of size.
Fl{-s} Shorten the output (in Cm{zero-sectors} and Cm{minimize-family}).
Fl{-q} Print a more quiet log.
Fl{-h} Show this help message.
Fl{-V} Print version information.
Ss{ARGUMENTS}
Ar{spec-file} Filename of the input file, with Ql{-} meaning the standard input.
Ss{ENVIRONMENT}
Ev{TMPDIR} Temporary files will be created here.
Ss{AUTHORS}
Vitaly Magerya <vitaly.magerya@tx97.net>
)";
#include <cln/real.h>
#include <ginac/ginac.h>
#include <ginac/parser.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <assert.h>
#include <atomic>
#include <chrono>
#include <fstream>
#include <sstream>
#include <queue>
#include <set>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <tuple>
#include <unistd.h>
// The fact that a random macro defined in sys/sysmacros.h somehow
// finds its way here to mess up my day is one of the reasons
// people should stay away from C++ altogether. "A minor device
// number"?
#undef minor
#undef major
using namespace GiNaC;
using namespace std;
// Nauty defines the "set" type, and we don't need this sort of
// a conflict.
#define set Nauty_set
#include <nauty/nausparse.h>
#undef set
#include "blake2b.c"
#include "ginacutils.cpp"
static bool COLORS = !!isatty(STDOUT_FILENO);
static bool VERBOSE = true;
static int JOBS = 1;
static int WORKER = -1;
typedef vector<symbol> symvector;
struct hash_t { uint8_t hash[32]; };
static inline bool
operator ==(const hash_t &a, const hash_t &b)
{
return memcmp((void*)&a.hash[0], (void*)&b.hash[0], sizeof(a.hash)) == 0;
}
static inline bool
operator <(const hash_t &a, const hash_t &b)
{
return memcmp((void*)&a.hash[0], (void*)&b.hash[0], sizeof(a.hash)) < 0;
}
/* FORMATTING
*
* This needs to go before logging, so that log_format would be
* able to see these definitions.
*/
static ostream&
operator <<(ostream &o, const set<unsigned> &v)
{
o << "set{";
bool first = true;
for (auto &&i : v) {
if (first) {
o << i;
first = false;
} else {
o << ", " << i;
}
}
o << "}";
return o;
}
static ostream&
operator <<(ostream &o, const hash_t &v)
{
for (size_t i = 0; i < sizeof(v.hash); i++) {
uint8_t dlo = v.hash[i] >> 4;
uint8_t dhi = v.hash[i] & 0x0f;
o << (char)(dhi < 10 ? '0' + dhi : 'a' - 10 + dhi);
o << (char)(dlo < 10 ? '0' + dlo : 'a' - 10 + dlo);
}
return o;
}
template<typename T> static ostream&
operator <<(ostream &o, const vector<T> &v)
{
o << "{";
for (size_t i = 0; i < v.size(); i++) {
if (i != 0) o << ", ";
o << v[i];
}
o << "}";
return o;
}
static ostream&
operator <<(ostream &o, const vector<uint8_t> &v)
{
o << "{";
for (size_t i = 0; i < v.size(); i++) {
if (i != 0) o << ", ";
o << (int)v[i];
}
o << "}";
return o;
}
static string
to_string(const ex& expr)
{
ostringstream s;
s << expr;
return s.str();
}
/* LOGGING
* ============================================================
*
* As with everything in C++, you can "optimize" this piece of
* code to e.g. use compile-only format string parsing, minimize
* number of created functions, and so on, but at the expense
* of kilolines of code, and your own sanity lost in the fight
* versus byzantine template rules. Please don't.
*/
static auto _log_starttime = chrono::steady_clock::now();
static auto _log_lasttime = chrono::steady_clock::now();
static int _log_depth = 0;
static const char*
log_adv(const char *fmt)
{
for (int i = 0; ; i++) {
if (fmt[i] == '{') {
cerr.write(fmt, i);
return fmt + i + 2;
}
if (fmt[i] == 0) {
cerr.write(fmt, i);
return fmt + i;
}
}
}
/* This function is used to print objects into the log. Override it
* for the data types you care about to modify their appearance.
*/
template<typename T> static inline void
log_format(ostream &o, const T &value)
{
o << value;
}
static void
log_print_start(const char *pre, const char *post)
{
auto t = chrono::steady_clock::now();
auto dt = chrono::duration_cast<chrono::duration<double>>(t - _log_starttime).count();
cerr << pre;
if ((JOBS > 1) && (WORKER >= 0)) cerr << "w" << WORKER + 1 << " ";
cerr << std::fixed << std::setprecision(4) << dt << "s +";
cerr << chrono::duration_cast<chrono::duration<double>>(t - _log_lasttime).count() << "s";
for (int i = 0; i < _log_depth; i++) {
cerr << " *";
}
cerr << post;
_log_lasttime = t;
}
template<typename T> static const char *
log_print_one(const char *fmt, const T &value)
{
fmt = log_adv(fmt);
log_format(cerr, value);
return fmt;
}
static void
log_print_end(const char *fmt)
{
cerr << fmt;
if (COLORS) cerr << "\033[0m";
cerr << endl;
}
struct _sequencehack {
template<typename ...Args>
_sequencehack(Args &&...) {}
};
template<typename ...Args> static void
log_fmt(const char *pre, const char *post, const char *fmt, const Args &...args)
{
log_print_start(pre, post);
(void) _sequencehack {
(fmt = log_print_one(fmt, args), 0)
...
};
log_print_end(fmt);
}
/* Log an debug message. These can be suppressed by setting
* VERBOSE to false.
*/
template<typename... Args> static inline void
logd(const char *fmt, const Args &...args)
{
if (unlikely(VERBOSE)) {
log_fmt(COLORS ? "\033[2;37m[dbg " : "[dbg ", "] ", fmt, args...);
}
}
/* Log an information message.
*/
template<typename... Args> static inline void
logi(const char *fmt, const Args &...args)
{
log_fmt(COLORS ? "\033[32m[inf " : "[inf ", COLORS ? "]\033[0m " : "] ", fmt, args...);
}
/* Log a warning message.
*/
template<typename... Args> static inline void
logw(const char *fmt, const Args &...args)
{
log_fmt(COLORS ? "\033[1;34m[wrn " : "[wrn ", "] ", fmt, args...);
}
/* Log an error message.
*/
template<typename... Args> static inline void
loge(const char *fmt, const Args &...args)
{
log_fmt(COLORS ? "\033[1;31m[err " : "[err ", "] ", fmt, args...);
}
template<typename F>
struct _scopeexithack {
_scopeexithack(F f) : f(f) {}
~_scopeexithack() { f(); }
F f;
};
/* Place this macro as the start of a function, and you'll get
* log entries every time this function is entered and exited.
*
* As a general rule, if you're adding logging statements to a
* function, add LOGME to its start as well.
*/
#define LOGME \
const auto &__log_func = __func__; \
logd("> {}()", __log_func); \
const auto __log_t0 = _log_lasttime; \
_log_depth++; \
auto __log_f = [&]{ \
_log_depth--; \
if (unlikely(VERBOSE)) { \
auto t = chrono::steady_clock::now(); \
auto dt = chrono::duration_cast<chrono::duration<double>>(t - __log_t0).count(); \
logd("< {}(+{}s)",__log_func, dt); \
} \
}; \
auto __log_s = _scopeexithack<decltype(__log_f)>(__log_f);
/* CONCURRENCY UTILS
* =================
*/
/* Allocate size bytes of memory identically visible across the
* forked workers.
*/
static void *
shared_alloc(size_t size)
{
// We could have used calloc() if FORK is false. Meh.
void *mem = mmap(NULL, size >= 1 ? size : 1, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (mem == MAP_FAILED) {
loge("Failed to mmap() {} bytes of shared memory: {}", size, strerror(errno));
exit(1);
}
return mem;
}
static void
shared_free(void *memory, size_t size)
{
if (munmap(memory, size >= 1 ? size : 1) != 0) {
logw("Failed to munmap() {} bytes of shared memory: {}", size, strerror(errno));
}
}
/* FORK-JOIN MULTIPROCESSING
* =========================
*
* Usage:
* FORK_BEGIN
* Worker code.
* Use WORKER variable (an int between 0 and JOBS-1) to
* determine which worker are you in.
* If FORK is false (or, equivalently, JOBS is 1), then no
* fork is done, and the worker code is executed in the
* main process.
* FORK_END
* Main process code (all the workes have joined at this point).
*
* Note: we must use fork-join instead of threads or OpenMP
* because GiNaC is not thread-safe.
*/
#define FORK (JOBS > 1)
#define FORK_BEGIN \
{ \
vector<pid_t> workerpids(JOBS); \
if (FORK) logd("Forking {} workers", JOBS); \
for (WORKER = 0; WORKER < JOBS; WORKER++) { \
if (!FORK || ((workerpids[WORKER] = fork()) == 0)) { \
{
#define FORK_END \
} \
if (FORK) exit(0); \
} \
} \
WORKER = -1; \
if (FORK) { \
logd("Waiting for workers"); \
int wst; \
for (pid_t wpid; (wpid = wait(&wst)) > 0;) { \
if (WIFEXITED(wst) && (WEXITSTATUS(wst) == 0)) { \
logd("Worker joined: {}", wpid); \
} else { \
loge("Worker failed: {}, quitting", wpid); \
for (int i = 0; i < JOBS; i++) { \
kill(workerpids[i], SIGTERM); \
}; \
exit(1); \
} \
} \
} \
}
/* TEMPORARY FILES
* ===============
*/
namespace tmpdir {
static char dirname[2048];
static void
create(const char *prefix)
{
const char *tmp = getenv("TMPDIR");
snprintf(dirname, sizeof(dirname), "%s/%s.%ld.XXXXXX",
tmp == NULL ? "/tmp" : tmp, prefix, (long)getpid());
if (mkdtemp(dirname) != dirname) {
loge("Failed to create temporary directory: {}", strerror(errno));
exit(1);
}
logd("Created temporary directory: {}", dirname);
}
static void
remove()
{
logd("Removing temporary directory: {}", dirname);
// There isn't a short way to run a command with a list
// of arguments without worying about quoting. Fork,
// exec, and then wait is the shortest...
if (fork() == 0) {
execl("/bin/rm", "/bin/rm", "-rf", dirname, NULL);
exit(1);
};
wait(NULL);
}
static string
filename(int suffix)
{
return string(dirname) + "/" + to_string(suffix);
}
}
/* BIT UTILS
* =========
*/
static unsigned
bitlength(unsigned x)
{
unsigned n = 0;
for (; x; x >>= 1) n++;
return n;
}
static unsigned
bitcount(uint64_t x)
{
unsigned n = 0;
for (; x; x >>= 1) n += x&1;
return n;
}
static int
bitposition(unsigned x, int bitn)
{
int i = 0;
for (int n = bitn + 1; x; x >>= 1, i++) {
n -= x&1;
if (n == 0) return i;
}
return -1;
}
static inline bool
is_subsector(uint64_t subsector, uint64_t sector)
{
return (sector | subsector) == sector;
}
/* MISC UTILS
* ==========
*/
static ex
readfile(const char *filename, parser &reader)
{
if (strcmp(filename, "-") == 0) {
return reader(cin);
} else {
ifstream i(filename);
if (!i) throw parse_error("the file was not found");
return reader(i);
}
}
static symvector
symbolsequence(const char *prefix, int n)
{
symvector x(n);
for (int i = 0; i < n; i++) {
ostringstream name;
name << prefix << i + 1;
x[i] = symbol(name.str());
}
return x;
}
static ex
normalize_productrules(ex productrules)
{
lst rules;
for (unsigned i = 0; i < productrules.nops(); i++) {
const ex &r = productrules.op(i);
rules.append(r.op(0) == r.op(1));
}
return rules;
}
static symvector
feynman_x(int ndens)
{
return symbolsequence("x", ndens);
}
static pair<ex, ex>
feynman_uf(const ex &denominators, const ex &loopmom, const ex &sprules, const symvector &X)
{
LOGME;
ex dens = denominators.expand().subs(sprules, subs_options::algebraic);
unsigned N = dens.nops();
unsigned L = loopmom.nops();
matrix A(L, L);
matrix B(L, 1);
ex C;
assert(denominators.nops() == X.size());
for (unsigned d = 0; d < N; d++) {
// Decompose D_i = a_ij l_i l_j + b_i l_i + c
ex D = dens.op(d).expand();
matrix a(L, L);
matrix b(L, 1);
bool has_a = false;
bool has_b = false;
for (unsigned i = 0; i < L; i++) {
// l_i^2
a(i, i) = D.coeff(loopmom.op(i), 2);
has_a = has_a || (!a(i, i).is_zero());
D -= a(i, i)*loopmom.op(i)*loopmom.op(i);
// l_i^1
ex ki = D.coeff(loopmom.op(i), 1);
for (unsigned j = i + 1; j < L; j++) {
ex k = ki.coeff(loopmom.op(j), 1);
a(i, j) = a(j, i) = k/2;
has_a = has_a || (!k.is_zero());
D -= k*loopmom.op(i)*loopmom.op(j);
}
b(i, 0) = D.coeff(loopmom.op(i), 1);
has_b = has_b || (!b(i, 0).is_zero());
D -= (b(i, 0)*loopmom.op(i)).expand();
}
A = A.add(a.mul_scalar(X[d]));
B = B.add(b.mul_scalar(X[d]/2));
C += X[d]*D;
if (!has_a && !has_b) {
loge("feynman_uf(): denominator #{} (={}) is free of the loop momenta", d+1, dens.op(d));
exit(1);
}
}
ex U = A.determinant().expand();
ex F = C*U;
for (unsigned i = 0; i < L; i++)
for (unsigned j = 0; j < L; j++) {
ex k = (B(i, 0)*B(j, 0)).expand().subs(sprules, subs_options::algebraic);
if (!k.is_zero()) F -= adjugate(A, i, j)*k;
}
return make_pair(U, F.expand());
}
/* Represent a polynomial in a list of variables as
* Sum_i (x1^k1i x2^k2i ... xN^kNi Ci), and return
* a map from variable exponents to coefficients,
* {k1i, ..., kNi} -> Ci.
*/
static map<vector<int>, ex>
bracket(const ex &expr, const symvector &X)
{
LOGME;
map<vector<int>, ex> result;
map<ex, int, ex_is_less> sym2id;
for (unsigned i = 0; i < X.size(); i++) {
sym2id[X[i]] = i;
}
term_iter(expr.expand(), [&](const ex &term) {
vector<int> stemidx(X.size());
exvector coef;
factor_iter(term, [&](const ex &factor, int power) {
auto it = sym2id.find(factor);
if (it != sym2id.end()) {
stemidx[it->second] = power;
} else {
if (power == 1) {
coef.push_back(factor);
} else {
coef.push_back(pow(factor, power));
}
}
});
result[stemidx] += mul(coef);
});
return result;
}
static vector<bool>
zero_sectors(const ex &G, const symvector &X, uint64_t cutmask)
{
LOGME;
// Lee criterium: k_i x_i dG/dx_i == G
symvector K = symbolsequence("k", X.size());
ex eqn = G;
for (unsigned i = 0; i < X.size(); i++) {
eqn -= K[i]*X[i]*G.diff(X[i]);
}
// Split eqn into {x1^p1 ... xn^pn} * { c0 + k1*c1 + ... + kn*cn },
// and save the c vectors.
vector<pair<uint64_t, exvector>> eqns;
for (auto &&kv : bracket(eqn, X)) {
uint64_t sector = 0;
for (unsigned i = 0; i < kv.first.size(); i++) {
if (kv.first[i] != 0) sector |= 1ul << i;
}
ex c0 = kv.second;
exvector c(K.size() + 1);
for (unsigned i = 0; i < K.size(); i++) {
c[i] = c0.coeff(K[i]);
c0 -= c[i]*K[i];
}
c[X.size()] = c0.expand();
eqns.push_back(make_pair(sector, c));
}
logd("Total equations: {}", eqns.size());
// Solve the equation for each sector;
uint64_t nsectors = 1UL << X.size();
logd("Total sectors: {}", nsectors);
uint8_t *zeros = (uint8_t*)shared_alloc(nsectors);
uint8_t *nonzeros = (uint8_t*)shared_alloc(nsectors);
zeros[0] = true;
matrix seceqns(0, K.size() + 1);
FORK_BEGIN;
// Any order of traversal will work; bottom up seems to be
// slightly faster.
for (uint64_t sector = nsectors/JOBS*WORKER; sector < nsectors; sector++) {
if (zeros[sector] || nonzeros[sector]) continue;
if (~sector & cutmask) {
// If sector has a 0 where cutmask has a 1.
zeros[sector] = true;
continue;
}
((matrix_hack*)&seceqns)->resize(0);
for (auto &&sc : eqns) {
if (is_subsector(sc.first, sector)) {
((matrix_hack*)&seceqns)->append_row(sc.second);
}
}
unsigned rank = seceqns.rank();
unsigned ndens = bitcount(sector);
if (rank <= ndens) {
for (uint64_t s = sector; s != 0; s = (s - 1) & sector) {
assert(is_subsector(s, sector));
zeros[s] = true;
}
} else {
for (uint64_t s = sector; s < nsectors; s = (s + 1) | sector) {
assert(is_subsector(sector, s));
nonzeros[s] = true;
}
}
}
FORK_END;
vector<bool> result(zeros, zeros + nsectors);
shared_free((void*)nonzeros, nsectors);
shared_free((void*)zeros, nsectors);
return result;
}
static vector<pair<vector<int>, int>>
subsector_bracket(const vector<pair<vector<int>, int>> &br, unsigned nx, unsigned mask)
{
assert((br.size() == 0) || (br[0].first.size() == nx));
int newnx = bitcount(mask);
vector<pair<vector<int>, int>> result;
for (auto &&stemcoef : br) {
vector<int> stem(newnx);
for (unsigned i = 0, j = 0; i < nx; i++) {
if (mask & (1u << i)) {
stem[j++] = stemcoef.first[i];
} else {
if (stemcoef.first[i] != 0) goto skip;
}
}
result.push_back(make_pair(stem, stemcoef.second));
skip:;
}
return result;
}
static vector<uint8_t>
canonical_variable_permutation(const vector<pair<vector<int>, int>> &polybr, unsigned nx)
{
assert((polybr.size() == 0) || (polybr[0].first.size() == nx));
// A list of stems and corresponding unique coefficient ids.
set<int> coefset;
for (auto &&stemcoef : polybr) {
coefset.insert(stemcoef.second);
}
int maxexponent = 1;
for (auto &&stemcoef : polybr) {
for (int p : stemcoef.first) {
maxexponent = max(maxexponent, p);
}
}
// We shall map the polynomial to a graph, with
// - a vertex x_i of color 0 for each x_i in X;
// - a vertex stem_j of color 1+uniqid[coef_j] for each
// term stem_j*coef_j in the bracketed polynomial;
// - an edge stem_k--x_i of color p for each x_i^p in stem_k.
// This construction ensures that all permutations of X
// that leave the polynomial unchanged correspond to graph
// relabelings, and vice versa.
// Note that edge colors are 1...n, because edge color 0
// corresponds to "no edge".
// Because nauty doesn't support edge colors directly, only
// vertex colors, we shall adjust by:
// - making multiple layers (copies) of vertices, each layer
// having a distinct set of vertex colors, with one line
// connecting all copies of the same vertex;
// - replicating an edge of color c in layer l if c&(1<<l).
int maxedgecolor = maxexponent;
unsigned nlayers = bitlength(maxedgecolor);
// Construct the graph.
SG_DECL(g);
g.nv = 0; g.nde = 0;
unsigned nterms = polybr.size();
SG_ALLOC(g, 1 + (nx + nterms)*nlayers, 32, "graph malloc");
#define BEGIN_VERTEX g.v[g.nv] = g.nde; g.d[g.nv] = 0;
#define ADD_EDGE(vertex) \
while (g.nde >= g.elen) {DYNREALLOC(int, g.e, g.elen, g.elen*2, "graph realloc");}; \
g.e[g.nde++] = (vertex); \
g.d[g.nv]++;
#define END_VERTEX g.nv++;
// Vertices go in this order:
// x1(1) ... xN(1) x1(2) ... xN(L) ... x1(L) ... xN(L)
// BR1(1) ... BR1(L) ...
#define VERTEX_Xil(i,l) nx*(l) + (i)
#define VERTEX_Bkl(k,l) nx*nlayers + nlayers*(k) + (l)
for (unsigned l = 0, lbit = 1; l < nlayers; l++, lbit <<= 1) {
for (unsigned i = 0; i < nx; i++) {
BEGIN_VERTEX;
if (l > 0) { ADD_EDGE(VERTEX_Xil(i, l - 1)); }
if (l < nlayers - 1) { ADD_EDGE(VERTEX_Xil(i, l + 1)); }
unsigned k = 0;
for (auto &&stemcoef : polybr) {
if (stemcoef.first[i] & lbit) {
ADD_EDGE(VERTEX_Bkl(k, l));
}
k++;
}
END_VERTEX;
}
}
unsigned k = 0;
for (auto &&stemcoef : polybr) {
for (unsigned l = 0, lbit = 1; l < nlayers; l++, lbit <<= 1) {
BEGIN_VERTEX;
if (l > 0) { ADD_EDGE(VERTEX_Bkl(k, l - 1)); }
if (l < nlayers - 1) { ADD_EDGE(VERTEX_Bkl(k, l + 1)); }
for (unsigned i = 0; i < nx; i++) {
if (stemcoef.first[i] & lbit) {
ADD_EDGE(VERTEX_Xil(i, l));
}
}
END_VERTEX;
}
k++;
}
int *lab = NULL; size_t lab_sz = 0;
int *ptn = NULL; size_t ptn_sz = 0;
int *orbits = NULL; size_t orbits_sz = 0;
DYNALLOC1(int, lab, lab_sz, g.nv, "malloc");
DYNALLOC1(int, ptn, ptn_sz, g.nv, "malloc");
DYNALLOC1(int, orbits, orbits_sz, g.nv, "malloc");
int partidx = 0;
#define BEGIN_PARTITION
#define ADD_VERTEX(vertex) lab[partidx] = (vertex); ptn[partidx] = 1; partidx++;
#define END_PARTITION ptn[partidx-1] = 0;
/* The partition has this order:
* x1(1) ... xn(1) | x1(2) ... x1(2) | ...
* BR1_c1(1) ... BRn_c1(1) | BR1_c2(1) ... BRn_c2(1) | ...
*/
for (unsigned l = 0; l < nlayers; l++) {
BEGIN_PARTITION; // layer #l vertices
for (unsigned i = 0; i < nx; i++) {
ADD_VERTEX(VERTEX_Xil(i, l));
}
END_PARTITION;
}
for (unsigned l = 0; l < nlayers; l++) {
// Walk coefficients in increasing order.
for (int coef : coefset) {
BEGIN_PARTITION; // layer #l, terms with coef #coef
unsigned k = 0;
for (auto &&stemcoef : polybr) {
if (stemcoef.second == coef) {
ADD_VERTEX(VERTEX_Bkl(k, l));
}
k++;
}
END_PARTITION;
}
}
assert(partidx == g.nv);
SG_DECL(cg);
DEFAULTOPTIONS_SPARSEGRAPH(options);
options.defaultptn = FALSE;
options.getcanon = TRUE;
statsblk stats;
sparsenauty(&g, lab, ptn, orbits, &options, &stats, &cg);
SG_FREE(cg);
SG_FREE(g);
vector<uint8_t> result(nx);
for (unsigned i = 0; i < nx; i++) {
result[i] = lab[i];
}
DYNFREE(lab, lab_sz);
DYNFREE(ptn, ptn_sz);
DYNFREE(orbits, orbits_sz);
return result;
}
static hash_t
canonical_hash(const vector<pair<vector<int>, int>> &polybr, unsigned nx, vector<uint8_t> perm)
{
assert((polybr.size() == 0) || (polybr[0].first.size() == nx));
vector<vector<int>> expr;
// { 1 0 2 } -> x1 * x3^2 /. x1->x2 x2->x3 x3->x1 -> x2 x1^2 -> { 2 1 0 }
for (unsigned i = 0; i < polybr.size(); i++) {
vector<int> term(nx + 1);
for (unsigned j = 0; j < nx; j++) {
term[j] = polybr[i].first[perm[j]];
}
term[nx] = polybr[i].second;
expr.push_back(term);
}
unsigned nterms = expr.size();
sort(expr.begin(), expr.end());
blake2b_state S;
blake2b_init(&S, sizeof(hash_t));
blake2b_update(&S, (void*)&nx, sizeof(nx));
blake2b_update(&S, (void*)&nterms, sizeof(nterms));
for (auto &&term : expr) {
blake2b_update(&S, (void*)&term[0], sizeof(term[0])*term.size());
}
hash_t result;
blake2b_final(&S, result.hash, sizeof(result.hash));
return result;
}
class NonLinear : public std::exception {};
static exvector
lincoefficients(const ex &expr, const symvector &vars)
{
exvector coefs;
coefs.reserve(vars.size() + 1);
ex restofexpr = expr;
for (unsigned i = 0; i < vars.size(); i++) {
if (restofexpr.degree(vars[i]) > 1) {
throw NonLinear();
}
ex c = restofexpr.coeff(vars[i]);
for (unsigned j = i + 1; j < vars.size(); j++) {
if (c.has(vars[j])) throw NonLinear();
}
coefs.push_back(c);
restofexpr = restofexpr - c*vars[i];
}
coefs.push_back(restofexpr);
return coefs;
}
static ex
find_momenta_map(const exvector &src, const exvector &dst, const ex &loopmom)
{
LOGME;
assert(src.size() == dst.size());
symvector newl = symbolsequence("$l", loopmom.nops());
exmap newloopmommap;
for (unsigned i = 0; i < loopmom.nops(); i++) {
newloopmommap[loopmom.op(i)] = newl[i];
}
vector<vector<exvector>> eqnsets;
exvector nonlinear_eqns;
for (unsigned i = 0; i < src.size(); i++) {
ex eq = src[i].subs(newloopmommap) - dst[i];
vector<exvector> eqns;
factor_iter(factor(eq), [&](const ex &factor, int power) {
(void)power;
if (is_a<numeric>(factor)) return;