]> www.ginac.de Git - ginac.git/blob - ginac/utils.h
Move combinatorial helpers from power.cpp to utils.h.
[ginac.git] / ginac / utils.h
1 /** @file utils.h
2  *
3  *  Interface to several small and furry utilities needed within GiNaC but not
4  *  of any interest to the user of the library. */
5
6 /*
7  *  GiNaC Copyright (C) 1999-2017 Johannes Gutenberg University Mainz, Germany
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22  */
23
24 #ifndef GINAC_UTILS_H
25 #define GINAC_UTILS_H
26
27 #include "assertion.h"
28
29 #include <functional>
30 #include <cstdint> // for uintptr_t
31 #include <string>
32
33 namespace GiNaC {
34
35 /** Exception class thrown by functions to signal unimplemented functionality
36  *  so the expression may just be .hold() */
37 class dunno {};
38
39 // some compilers (e.g. cygwin) define a macro log2, causing confusion
40 #ifdef log2
41 #undef log2
42 #endif
43
44 unsigned log2(unsigned n);
45
46 /** Rotate bits of unsigned value by one bit to the left.
47   * This can be necessary if the user wants to define its own hashes. */
48 inline unsigned rotate_left(unsigned n)
49 {
50         return (n & 0x80000000U) ? (n << 1 | 0x00000001U) : (n << 1);
51 }
52
53 /** Compare two pointers (just to establish some sort of canonical order).
54  *  @return -1, 0, or 1 */
55 template <class T>
56 inline int compare_pointers(const T * a, const T * b)
57 {
58         // '<' is not defined for pointers that don't point to the same array,
59         // but std::less is.
60         if (std::less<const T *>()(a, b))
61                 return -1;
62         else if (std::less<const T *>()(b, a))
63                 return 1;
64         return 0;
65 }
66
67 /** Truncated multiplication with golden ratio, for computing hash values. */
68 inline unsigned golden_ratio_hash(uintptr_t n)
69 {
70         return n * UINT64_C(0x4f1bbcdd);
71 }
72
73 /* Compute the sign of a permutation of a container, with and without an
74    explicitly supplied comparison function. If the sign returned is 1 or -1,
75    the container is sorted after the operation. */
76 template <class It>
77 int permutation_sign(It first, It last)
78 {
79         using std::swap;
80         if (first == last)
81                 return 0;
82         --last;
83         if (first == last)
84                 return 0;
85         It flag = first;
86         int sign = 1;
87
88         do {
89                 It i = last, other = last;
90                 --other;
91                 bool swapped = false;
92                 while (i != first) {
93                         if (*i < *other) {
94                                 swap(*other, *i);
95                                 flag = other;
96                                 swapped = true;
97                                 sign = -sign;
98                         } else if (!(*other < *i))
99                                 return 0;
100                         --i;
101                         if (i != first)
102                                 --other;
103                 }
104                 if (!swapped)
105                         return sign;
106                 ++flag;
107                 if (flag == last)
108                         return sign;
109                 first = flag;
110                 i = first; other = first;
111                 ++other;
112                 swapped = false;
113                 while (i != last) {
114                         if (*other < *i) {
115                                 swap(*i, *other);
116                                 flag = other;
117                                 swapped = true;
118                                 sign = -sign;
119                         } else if (!(*i < *other))
120                                 return 0;
121                         ++i;
122                         if (i != last)
123                                 ++other;
124                 }
125                 if (!swapped)
126                         return sign;
127                 last = flag;
128                 --last;
129         } while (first != last);
130
131         return sign;
132 }
133
134 template <class It, class Cmp, class Swap>
135 int permutation_sign(It first, It last, Cmp comp, Swap swapit)
136 {
137         if (first == last)
138                 return 0;
139         --last;
140         if (first == last)
141                 return 0;
142         It flag = first;
143         int sign = 1;
144
145         do {
146                 It i = last, other = last;
147                 --other;
148                 bool swapped = false;
149                 while (i != first) {
150                         if (comp(*i, *other)) {
151                                 swapit(*other, *i);
152                                 flag = other;
153                                 swapped = true;
154                                 sign = -sign;
155                         } else if (!comp(*other, *i))
156                                 return 0;
157                         --i;
158                         if (i != first)
159                                 --other;
160                 }
161                 if (!swapped)
162                         return sign;
163                 ++flag;
164                 if (flag == last)
165                         return sign;
166                 first = flag;
167                 i = first; other = first;
168                 ++other;
169                 swapped = false;
170                 while (i != last) {
171                         if (comp(*other, *i)) {
172                                 swapit(*i, *other);
173                                 flag = other;
174                                 swapped = true;
175                                 sign = -sign;
176                         } else if (!comp(*i, *other))
177                                 return 0;
178                         ++i; 
179                         if (i != last)
180                                 ++other;
181                 }
182                 if (!swapped)
183                         return sign;
184                 last = flag;
185                 --last;
186         } while (first != last);
187
188         return sign;
189 }
190
191 /* Implementation of shaker sort, only compares adjacent elements. */
192 template <class It, class Cmp, class Swap>
193 void shaker_sort(It first, It last, Cmp comp, Swap swapit)
194 {
195         if (first == last)
196                 return;
197         --last;
198         if (first == last)
199                 return;
200         It flag = first;
201
202         do {
203                 It i = last, other = last;
204                 --other;
205                 bool swapped = false;
206                 while (i != first) {
207                         if (comp(*i, *other)) {
208                                 swapit(*other, *i);
209                                 flag = other;
210                                 swapped = true;
211                         }
212                         --i;
213                         if (i != first)
214                                 --other;
215                 }
216                 if (!swapped)
217                         return;
218                 ++flag;
219                 if (flag == last)
220                         return;
221                 first = flag;
222                 i = first; other = first;
223                 ++other;
224                 swapped = false;
225                 while (i != last) {
226                         if (comp(*other, *i)) {
227                                 swapit(*i, *other);
228                                 flag = other;
229                                 swapped = true;
230                         }
231                         ++i;
232                         if (i != last)
233                                 ++other;
234                 }
235                 if (!swapped)
236                         return;
237                 last = flag;
238                 --last;
239         } while (first != last);
240 }
241
242 /* In-place cyclic permutation of a container (no copying, only swapping). */
243 template <class It, class Swap>
244 void cyclic_permutation(It first, It last, It new_first, Swap swapit)
245 {
246         unsigned num = last - first;
247 again:
248         if (first == new_first || num < 2)
249                 return;
250
251         unsigned num1 = new_first - first, num2 = last - new_first;
252         if (num1 >= num2) {
253                 It a = first, b = new_first;
254                 while (b != last) {
255                         swapit(*a, *b);
256                         ++a; ++b;
257                 }
258                 if (num1 > num2) {
259                         first += num2;
260                         num = num1;
261                         goto again;
262                 }
263         } else {
264                 It a = new_first, b = last;
265                 do {
266                         --a; --b;
267                         swapit(*a, *b);
268                 } while (a != first);
269                 last -= num1;
270                 num = num2;
271                 goto again;
272         }
273 }
274
275 /** Generate all bounded combinatorial partitions of an integer n with exactly
276  *  m parts (including zero parts) in non-decreasing order.
277  */
278 class partition_generator {
279 private:
280         // Partitions n into m parts, not including zero parts.
281         // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
282         // FXT library)
283         struct mpartition2
284         {
285                 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
286                 std::vector<int> x;
287                 int n;   // n>0
288                 int m;   // 0<m<=n
289                 mpartition2(unsigned n_, unsigned m_)
290                   : x(m_+1), n(n_), m(m_)
291                 {
292                         for (int k=1; k<m; ++k)
293                                 x[k] = 1;
294                         x[m] = n - m + 1;
295                 }
296                 bool next_partition()
297                 {
298                         int u = x[m];  // last element
299                         int k = m;
300                         int s = u;
301                         while (--k) {
302                                 s += x[k];
303                                 if (x[k] + 2 <= u)
304                                         break;
305                         }
306                         if (k==0)
307                                 return false;  // current is last
308                         int f = x[k] + 1;
309                         while (k < m) {
310                                 x[k] = f;
311                                 s -= f;
312                                 ++k;
313                         }
314                         x[m] = s;
315                         return true;
316                 }
317         } mpgen;
318         int m;  // number of parts 0<m<=n
319         mutable std::vector<int> partition;  // current partition
320 public:
321         partition_generator(unsigned n_, unsigned m_)
322           : mpgen(n_, 1), m(m_), partition(m_)
323         { }
324         // returns current partition in non-decreasing order, padded with zeros
325         const std::vector<int>& current() const
326         {
327                 for (int i = 0; i < m - mpgen.m; ++i)
328                         partition[i] = 0;  // pad with zeros
329
330                 for (int i = m - mpgen.m; i < m; ++i)
331                         partition[i] = mpgen.x[i - m + mpgen.m + 1];
332
333                 return partition;
334         }
335         bool next()
336         {
337                 if (!mpgen.next_partition()) {
338                         if (mpgen.m == m || mpgen.m == mpgen.n)
339                                 return false;  // current is last
340                         // increment number of parts
341                         mpgen = mpartition2(mpgen.n, mpgen.m + 1);
342                 }
343                 return true;
344         }
345 };
346
347 /** Generate all compositions of a partition of an integer n, starting with the
348  *  compositions which has non-decreasing order.
349  */
350 class composition_generator {
351 private:
352         // Generates all distinct permutations of a multiset.
353         // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
354         // Multiset Permutations using a Constant Number of Variables by Prefix
355         // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
356         struct coolmulti {
357                 // element of singly linked list
358                 struct element {
359                         int value;
360                         element* next;
361                         element(int val, element* n)
362                           : value(val), next(n) {}
363                         ~element()
364                         {   // recurses down to the end of the singly linked list
365                                 delete next;
366                         }
367                 };
368                 element *head, *i, *after_i;
369                 // NB: Partition must be sorted in non-decreasing order.
370                 explicit coolmulti(const std::vector<int>& partition)
371                   : head(nullptr), i(nullptr), after_i(nullptr)
372                 {
373                         for (unsigned n = 0; n < partition.size(); ++n) {
374                                 head = new element(partition[n], head);
375                                 if (n <= 1)
376                                         i = head;
377                         }
378                         after_i = i->next;
379                 }
380                 ~coolmulti()
381                 {   // deletes singly linked list
382                         delete head;
383                 }
384                 void next_permutation()
385                 {
386                         element *before_k;
387                         if (after_i->next != nullptr && i->value >= after_i->next->value)
388                                 before_k = after_i;
389                         else
390                                 before_k = i;
391                         element *k = before_k->next;
392                         before_k->next = k->next;
393                         k->next = head;
394                         if (k->value < head->value)
395                                 i = k;
396                         after_i = i->next;
397                         head = k;
398                 }
399                 bool finished() const
400                 {
401                         return after_i->next == nullptr && after_i->value >= head->value;
402                 }
403         } cmgen;
404         bool atend;  // needed for simplifying iteration over permutations
405         bool trivial;  // likewise, true if all elements are equal
406         mutable std::vector<int> composition;  // current compositions
407 public:
408         explicit composition_generator(const std::vector<int>& partition)
409           : cmgen(partition), atend(false), trivial(true), composition(partition.size())
410         {
411                 for (unsigned i=1; i<partition.size(); ++i)
412                         trivial = trivial && (partition[0] == partition[i]);
413         }
414         const std::vector<int>& current() const
415         {
416                 coolmulti::element* it = cmgen.head;
417                 size_t i = 0;
418                 while (it != nullptr) {
419                         composition[i] = it->value;
420                         it = it->next;
421                         ++i;
422                 }
423                 return composition;
424         }
425         bool next()
426         {
427                 // This ugly contortion is needed because the original coolmulti
428                 // algorithm requires code duplication of the payload procedure,
429                 // one before the loop and one inside it.
430                 if (trivial || atend)
431                         return false;
432                 cmgen.next_permutation();
433                 atend = cmgen.finished();
434                 return true;
435         }
436 };
437
438 /** Compute the multinomial coefficient n!/(p1!*p2!*...*pk!) where
439  *  n = p1+p2+...+pk, i.e. p is a partition of n.
440  */
441 const numeric
442 multinomial_coefficient(const std::vector<int> & p);
443
444
445 // Collection of `construct on first use' wrappers for safely avoiding
446 // internal object replication without running into the `static
447 // initialization order fiasco'.  This chest of numbers helps speed up
448 // the library but should not be used outside it since it is
449 // potentially confusing.
450
451 class ex;
452
453 extern const numeric *_num_120_p;
454 extern const ex _ex_120;
455 extern const numeric *_num_60_p;
456 extern const ex _ex_60;
457 extern const numeric *_num_48_p;
458 extern const ex _ex_48;
459 extern const numeric *_num_30_p;
460 extern const ex _ex_30;
461 extern const numeric *_num_25_p;
462 extern const ex _ex_25;
463 extern const numeric *_num_24_p;
464 extern const ex _ex_24;
465 extern const numeric *_num_20_p;
466 extern const ex _ex_20;
467 extern const numeric *_num_18_p;
468 extern const ex _ex_18;
469 extern const numeric *_num_15_p;
470 extern const ex _ex_15;
471 extern const numeric *_num_12_p;
472 extern const ex _ex_12;
473 extern const numeric *_num_11_p;
474 extern const ex _ex_11;
475 extern const numeric *_num_10_p;
476 extern const ex _ex_10;
477 extern const numeric *_num_9_p;
478 extern const ex _ex_9;
479 extern const numeric *_num_8_p;
480 extern const ex _ex_8;
481 extern const numeric *_num_7_p;
482 extern const ex _ex_7;
483 extern const numeric *_num_6_p;
484 extern const ex _ex_6;
485 extern const numeric *_num_5_p;
486 extern const ex _ex_5;
487 extern const numeric *_num_4_p;
488 extern const ex _ex_4;
489 extern const numeric *_num_3_p;
490 extern const ex _ex_3;
491 extern const numeric *_num_2_p;
492 extern const ex _ex_2;
493 extern const numeric *_num_1_p;
494 extern const ex _ex_1;
495 extern const numeric *_num_1_2_p;
496 extern const ex _ex_1_2;
497 extern const numeric *_num_1_3_p;
498 extern const ex _ex_1_3;
499 extern const numeric *_num_1_4_p;
500 extern const ex _ex_1_4;
501 extern const numeric *_num0_p;
502 extern const basic *_num0_bp;
503 extern const ex _ex0;
504 extern const numeric *_num1_4_p;
505 extern const ex _ex1_4;
506 extern const numeric *_num1_3_p;
507 extern const ex _ex1_3;
508 extern const numeric *_num1_2_p;
509 extern const ex _ex1_2;
510 extern const numeric *_num1_p;
511 extern const ex _ex1;
512 extern const numeric *_num2_p;
513 extern const ex _ex2;
514 extern const numeric *_num3_p;
515 extern const ex _ex3;
516 extern const numeric *_num4_p;
517 extern const ex _ex4;
518 extern const numeric *_num5_p;
519 extern const ex _ex5;
520 extern const numeric *_num6_p;
521 extern const ex _ex6;
522 extern const numeric *_num7_p;
523 extern const ex _ex7;
524 extern const numeric *_num8_p;
525 extern const ex _ex8;
526 extern const numeric *_num9_p;
527 extern const ex _ex9;
528 extern const numeric *_num10_p;
529 extern const ex _ex10;
530 extern const numeric *_num11_p;
531 extern const ex _ex11;
532 extern const numeric *_num12_p;
533 extern const ex _ex12;
534 extern const numeric *_num15_p;
535 extern const ex _ex15;
536 extern const numeric *_num18_p;
537 extern const ex _ex18;
538 extern const numeric *_num20_p;
539 extern const ex _ex20;
540 extern const numeric *_num24_p;
541 extern const ex _ex24;
542 extern const numeric *_num25_p;
543 extern const ex _ex25;
544 extern const numeric *_num30_p;
545 extern const ex _ex30;
546 extern const numeric *_num48_p;
547 extern const ex _ex48;
548 extern const numeric *_num60_p;
549 extern const ex _ex60;
550 extern const numeric *_num120_p;
551 extern const ex _ex120;
552
553
554 // Helper macros for class implementations (mostly useful for trivial classes)
555
556 #define DEFAULT_CTOR(classname) \
557 classname::classname() { setflag(status_flags::evaluated | status_flags::expanded); }
558
559 #define DEFAULT_COMPARE(classname) \
560 int classname::compare_same_type(const basic & other) const \
561 { \
562         /* by default, the objects are always identical */ \
563         return 0; \
564 }
565
566 #define DEFAULT_PRINT(classname, text) \
567 void classname::do_print(const print_context & c, unsigned level) const \
568 { \
569         c.s << text; \
570 }
571
572 #define DEFAULT_PRINT_LATEX(classname, text, latex) \
573 DEFAULT_PRINT(classname, text) \
574 void classname::do_print_latex(const print_latex & c, unsigned level) const \
575 { \
576         c.s << latex; \
577 }
578
579 } // namespace GiNaC
580
581 #endif // ndef GINAC_UTILS_H