-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.m
More file actions
1896 lines (1686 loc) · 70.7 KB
/
Copy pathutils.m
File metadata and controls
1896 lines (1686 loc) · 70.7 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
(* # Mathematica utility belt (`utils.m`)
*
* ## Contents
* [[table of contents]]
*
* ## Misc
*)
(* Check if `a <= b` in the sense of `OrderedQ`. *)
LessOrEqualQ[a_, b_] := OrderedQ[{a, b}]
(* Check if `a < b` in the sense of `OrderedQ`. *)
LessQ[a_, b_] := Not[OrderedQ[{b, a}]]
(* Flatten, join, and convert the arguments to a string. *)
MkString[args__] := args // List // Flatten // Map[ToString] // StringJoin
(* Convert the arguments into a string, and that into an expression. *)
MkExpression[args__] := MkString[args] // ToExpression
(* Convert the items into a string, and write it into a given file object. *)
WrString[f_, items__] := {items} // Flatten // Map[BinaryWrite[f, # // ToString]&]
(* Convert the items into a string and write it into the file. *)
MkFile[filename_, items__] :=
Module[{fd},
(* The BinaryFormat is needed for the BinaryWrite in WrString. *)
fd = OpenWrite[MkString[filename], BinaryFormat->True];
If[fd === $Failed,
Error["MkFile: failed to open ", filename, " for writing"]];
WrString[fd, {items}];
Close[fd];
]
(* Set a key's value in an association if the key is not already
* assigned.
*)
SetDefault[assoc_, key_, value_] :=
If[Not[KeyExistsQ[assoc, key]], assoc[key] = value; Null]
SetAttributes[SetDefault, {HoldFirst}];
(* Persist results of some slow computation in a file: if a
* given filename exists, return its content (via [[SafeGet]]),
* otherwise recompute the expression, save its value to the
* file, and return it.
*)
Cached[filename_, ex_] :=
Module[{value},
If[FileExistsQ[filename],
Print["Loading ", filename];
SafeGet[filename]
,
Print["Overwriting ", filename];
value = ex;
SafePut[value, filename];
value
]
]
Attributes[Cached] = {HoldRest};
(* Convert the items into a string and write it into the file, unless
* that file already exists and has presisely the same content already.
*
* This is an upgrade over [[MkFile]] that helps to preserve file
* timestamps, which is useful if e.g. `make` is used somewhere
* down the line.
*)
MaybeMkFile[filename_, items__] :=
Module[{fd, oldtext, newtext},
oldtext = Quiet[ReadString[filename], {OpenRead::noopen}];
If[oldtext === $Failed,
MkFile[filename, items];
,
newtext = MkString[items];
If[newtext =!= oldtext,
MkFile[filename, newtext];
];
]
]
(* Highlight a matching pattern in red. Useful during development
* inside the GUI. *)
Highlight[pat_] := ReplaceAll[e : pat :> Style[e, Red, Bold]]
Highlight[pat_, style__] := ReplaceAll[e : pat :> Style[e, style]]
(* Just like `MapIndexed`, but the index is `i` rather than
* `{i}`. Does not support `levelspec` for this reason; level
* 1 is always assumed.
*)
MapIndexed1[f_, expr_] := MapIndexed[f[#1, #2//First]&, expr]
MapIndexed1[f_] := MapIndexed1[f, #]&
(* Print a list, each element on its own line with an index. *)
PrintIndexed[ex_List] := (ex // MapIndexed[Print[#2//First, ") ", #1]&]; ex)
PrintIndexed[ex_] := (Print["?) ", ex]; ex)
(* Return a list of {index, value} pairs. *)
Enumerate[ex_List] := MapIndexed[{#2//First, #1}&, ex]
(* Find all unique occurrences of pat in ex. *)
CaseUnion[ex_List, pat_] := ex // Map[CaseUnion[pat]] // Apply[Join] // Union;
CaseUnion[ex_, pat_] := Cases[ex, pat, {0, Infinity}] // Union
CaseUnion[pat_] := CaseUnion[#, pat]&
(* A safe way to apply replacement rules to a list of items: map a
* list, replacing each item (non-recursively) with given rules;
* fail if one of the items matches no replacement pattern.
*
* Note: the third form is deprecated, as it is inconsistent
* with the plain `Replace[]`.
*)
MapReplace[{rules__}] := Map[Replace[{rules,
x_ :> Error["Failed to replace: ", x, ", with rules: ", {rules}[[;;,1]]]}]]
MapReplace[rule_] := Map[Replace[{rule,
x_ :> Error["Failed to replace: ", x, ", with rule: ", rule[[1]]]}]]
MapReplace[rules__] := Map[Replace[{rules,
x_ :> Error["Failed to replace: ", x, ", with rules: ", {rules}[[;;,1]]]}]]
(* Same as `Replace`, but fail if no replacement was made. *)
ReallyReplace[{rules__}] := Replace[{rules, x_ :> Error["Failed to replace: ", x]}]
ReallyReplace[rule_] := Replace[{rule, x_ :> Error["Failed to replace: ", x]}]
ReallyReplace[ex_, rule_] := ex // ReallyReplace[rule]
(* Apply a function to key-value pairs of an Association, returning
* the same Association with mapped values. *)
MapKV[f_, a_Association] := a // Normal // Map[Apply[(#1 -> f[#1, #2])&]] // Association
MapKV[f_] := MapKV[f, #]&
(* Get the first and the only element in a list, fail if the
* list is not a single element list. *)
Only[{el_}] := el
Only[l_] := Error["Only: a list of exactly one element expected, got: ", l]
(* Get the second element in a list, fail if the list doesn't
* have at least 2 elements.
*)
Second[{_, el_, ___}] := el
Second[l_] := Error["Second: a list of at least 2 elements expected, got: ", l]
(* Get the third element in a list, fail if the list doesn't
* have at least 2 elements.
*)
Third[{_, _, el_, ___}] := el
Third[l_] := Error["Third: a list of at least 3 elements expected, got: ", l]
(* Replace each unique object matching `oldpattern` in `ex` to one
* of the objects from `newlist` (which is assumed to contain
* enough new objects). *)
RenameUniques[ex_, oldpattern_, newlist_List] :=
Module[{old, i},
old = CaseUnion[ex, oldpattern];
If[Length[old] > Length[newlist], Error["RenameUniques: too few new names given; trying to rename: ", old]];
ex /. Table[old[[i]] -> newlist[[i]], {i, Length[old]}]
]
RenameUniques[oldpattern_, newlist_List] := RenameUniques[#, oldpattern, newlist]&
(* Same as `Select[items, f]`, but return the indices of the
* selected items. *)
SelectIndices[items_, f_] := MapIndexed[If[f[#1], #2//First, Nothing]&, items]
SelectIndices[f_] := SelectIndices[#, f]&
(* Return the first index of the given list where `f[element]` is true. *)
ElementIndex[l_List, f_, default_] := FirstPosition[l, _?f, {default}, {1}, Heads->False] // First
(* Return the first index of the given list where `element` is located. *)
IndexOf[l_List, element_, default_] := FirstPosition[l, element, {default}, {1}, Heads->False] // First
(* Apply `f` to every term of a series. *)
MapSeries[f_, 0] := f[0]
MapSeries[f_, Verbatim[SeriesData][x_, x0_, l_List, n1_, n2_, d_]] := SeriesData[x, x0, Map[f, l], n1, n2, d]
MapSeries[f_] := MapSeries[f, #]&
MapSeries[f_, l_List] := Map[MapSeries[f], l]
(* Return the lowest power of a series expression. *)
SeriesLowestPower[l_List] := Map[SeriesLowestPower, l]
SeriesLowestPower[Verbatim[SeriesData][x_, x0_, l_List, n1_, n2_, d_]] := n1/d
(* Return the highest power of a series expression. *)
SeriesHighestPower[l_List] := Map[SeriesHighestPower, l]
SeriesHighestPower[Verbatim[SeriesData][x_, x0_, l_List, n1_, n2_, d_]] := (n2 - 1)/d
(* Return the number of terms in a series expression. *)
SeriesTermCount[Verbatim[SeriesData][x_, x0_, l_List, n1_, n2_, d_]] := n2 - n1
SeriesTermCount[l_List] := Map[SeriesTermCount, l]
(* Truncate the series to the leading term only. *)
SeriesLeadingTerm[s_SeriesData] := If[s[[3]] === {}, s, s + O[s[[1]]]*s[[1]]^s[[4]]]
(* Get the coefficient of a term in a series with a particular
* order of the expansion. *)
SeriesOrderCoefficient[Verbatim[SeriesData][x_, x0_, l_List, n1_, n2_, d_], o_] :=
Which[
o < n1/d, 0,
o >= n2/d, $Failed,
o - n1/d >= Length[l], 0,
True, l[[o - n1/d + 1]]]
SeriesOrderCoefficient[l_List, o_] := Map[SeriesOrderCoefficient[#, o]&, l]
SeriesOrderCoefficient[o_] := SeriesOrderCoefficient[#, o]&
(* Return the list of terms in an expression. Zero is considered
* to have no terms. *)
Terms[ex_Plus] := List @@ ex
Terms[0] := {}
Terms[ex_] := {ex}
(* Return the number of terms in an expression. *)
TermCount[ex_Plus] := Length[ex]
TermCount[0] := 0
TermCount[ex_] := 1
(* Apply a given function to each term in an expression. *)
MapTerms[f_, ex_Plus] := Map[f, ex]
MapTerms[f_, ex_List] := Map[MapTerms[f], ex]
MapTerms[f_, ex_] := f[ex]
MapTerms[f_] := MapTerms[f, #]&
(* Return the list of factors of an expression. *)
Factors[ex_Times] := List @@ ex
Factors[ex_] := {ex}
(* Apply a given function to each factor of an expression. *)
MapFactors[f_, ex_Times] := Map[f, ex]
MapFactors[f_, ex_List] := Map[MapFactors[f], ex]
MapFactors[f_, ex_] := f[ex]
MapFactors[f_] := MapFactors[f, #]&
(* Expand inside each factor of an expression, and take out the
* overall monomial prefactors. Faster than the full Factor.
*)
FactorMonomials[ex_List] := Map[FactorMonomials, ex]
FactorMonomials[ex_Times] := Map[FactorMonomials, ex]
FactorMonomials[ex_^n_] := FactorMonomials[ex]^n
FactorMonomials[ex_] :=
Module[{gcd, terms},
terms = ex // Expand // Terms;
If[Length[terms] === 0,
0
,
gcd = terms[[1]];
terms[[2 ;;]] // Map[(gcd = PolynomialGCD[#, gcd];) &];
terms // Map[#/gcd &] // Apply[Plus] // #*gcd &
]
]
(* Return True if an expression is a zero matrix, or a zero
* SparseMatrix. Return False otherwise. *)
ZeroMatrixQ[mx_SparseArray] := Length[mx["NonzeroPositions"]] === 0
ZeroMatrixQ[mx_List] := mx // Flatten // Union // # === {0}&
ZeroMatrixQ[_] := False
(* Return True if a rational expression is probably zero, and
* False if it is definitely not zero.
*)
ProbablyZeroQ[ex_] :=
Module[{vars, map},
vars = ex // CaseUnion[_Symbol];
Quiet[
AllTrue[Range[10], (
map = vars // Map[# -> RandomInteger[{10, 10000}]&] // Association;
Check[Together[ex /. map] === 0, True, {Power::infy, Infinity::indet}]
)&]
,
{Power::infy, Infinity::indet}]
]
(* Read and parse a file, return the expression inside. Automatically
* handle `.gz`, `.bz2`, and `.mx` files. Fail if no such file exists,
* or if there is an error reading it. *)
SafeGet[filename_String] :=
Module[{result},
result = If[Not[FileExistsQ[filename]],
$Failed,
Which[
StringMatchQ[filename, ___~~".gz"],
RunThrough["zcat -q '" <> filename <> "' 2>/dev/null", 0] // Replace[Null -> $Failed],
StringMatchQ[filename, ___~~".bz2"],
RunThrough["bzcat -q '" <> filename <> "' 2>/dev/null", 0] // Replace[Null -> $Failed],
StringMatchQ[filename, ___~~".mx"],
Quiet[Import[filename], {Import::nffil}],
StringMatchQ[filename, ___],
Get[filename]
]
];
If[MatchQ[result, $Failed],
Error["Failed to get: ", filename];
];
result
]
(* Save an expression to a file. Automatically handle `.mx` files. *)
SafePut[expr_, filename_String] := (
Which[
StringMatchQ[filename, ___~~".m"],
Export[filename, expr],
StringMatchQ[filename, ___~~".mx"],
Export[filename, expr],
StringMatchQ[filename, ___],
Put[expr, filename]
];
If[Not[FileExistsQ[filename]],
Error["Failed to create: ", filename];
];
);
(* Print the error message and stop the computation. Exit with
* an error code if running in a script; raise an exception when
* in GUI. *)
Error[msg__] := If[Length[Cases[$CommandLine, "-script"]] > 0,
Print["ERROR: ", msg]; Exit[1];
,
Print[Style["ERROR: ", Red, Bold], msg]; Throw[$Failed];
]
(* Fail the computation unless a condition is met. Useful for
* assetions and unit tests. *)
FailUnless[tests___] :=
Module[{test, idx, result},
Do[
test = Extract[Hold[tests], {idx}, HoldForm];
If[test === HoldForm[Null], Continue[]];
result = ReleaseHold[test];
If[result =!= True,
If[MatchQ[Extract[test, {1,0}, HoldForm], HoldForm[_Symbol]],
Print["!!! Test: ", Extract[test, {1,0}, HoldForm], " => ", result];
Print["!!! 1: ", Extract[test, {1,1}, HoldForm]];
Print["!!! == ", Extract[test, {1,1}]];
Print["!!! 2: ", Extract[test, {1,2}, HoldForm]];
Print["!!! == ", Extract[test, {1,2}]];
,
Print["!!! Test: ", test];
Print["!!! => ", result];
];
Error["Test failed!"];
];
,
{idx, Length[Hold[tests]]}
];
];
SetAttributes[FailUnless, {HoldAll}]
(* Format a real number in the scientific notation, e.g. 1.23e-4,
* with a fixed total width (if it can be achieved).
*)
FormatScientific[x:(_Integer|_Real), width_Integer] :=
Module[{sign, man, exp, zeros},
{man, exp} = MantissaExponent[x//N, 10];
sign = If[man >= 0, "", "-"];
{man, exp} = If[man === 0.0, {0.0, 0}, {Abs[man]*10, exp - 1}];
exp = "e" <> ToString[exp];
man = ToString[NumberForm[man, Max[1, width - StringLength[sign] - StringLength[exp] - 1]]];
zeros = width - StringLength[sign] - StringLength[man] - StringLength[exp];
If[zeros > 0, sign <> man <> StringRepeat["0", zeros] <> exp, sign <> man <> exp]
]
FormatScientific[width_Integer] := FormatScientific[#, width]&
FormatScientific[Complex[re_, im_], width_Integer] :=
FormatScientific[re, width] <> " " <> FormatScientific[im, width] <> "j"
(* Format a real number with fixed number of digits after the
* decimal point.
*)
FormatFixed[x:(_Integer|_Real), digits_Integer] :=
IntegerDigits[x*10^digits//Round] //
If[1 + digits - Length[#] > 0, Join[Table[0, 1 + digits - Length[#]], #], #]& //
MkString[If[x < 0, "-", ""], #[[;;-digits-1]], ".", #[[-digits;;]]]&
FormatFixed[x:(_Integer|_Real), 0] :=
IntegerDigits[x//Round] //
If[1 - Length[#] > 0, Join[Table[0, 1 - Length[#]], #], #]& //
MkString[If[x < 0, "-", ""], #]&
FormatFixed[digits_Integer] := FormatFixed[#, digits]&
FormatFixed[Complex[re_, im_], digits_Integer] :=
FormatFixed[re, width] <> " " <> FormatFixed[im, width] <> "j"
(* Convert a string in scientific notation (e.g. `1.23e4`) to a
* number. *)
StringToNumber[s_String] := Internal`StringToDouble[s]
(* Format a quantity in a human-readable format using the given
* units. The units are specified as a list of string names and
* numeric values.
*)
FormatAmount[units_List] := FormatAmount[#, units]&
FormatAmount[amount_, units_List] :=
Module[{i, a},
For[i = 1, i < Length[units] - 1 && amount > units[[i+1,2]]*0.95, i++, True];
a = amount / units[[i, 2]] // N;
MkString[NumberForm[a, {Infinity, 3}], units[[i,1]]]
]
(* Format bytes in human-readable format.
*)
FormatBytes[amount_] := FormatAmount[amount, {
{"B", 1}, {"kB", 2^10}, {"MB", 2^20}, {"GB", 2^30}, {"TB", 2^40},
{"PB", 2^50}, {"EB", 2^60}, {"ZB", 2^70}, {"YB", 2^80}
}]
(* Format seconds in human-readable format.
*)
FormatSeconds[amount_] := FormatAmount[amount, {
{"s", 1}, {"m", 60}, {"h", 3600}, {"d", 24*3600}, {"w", 7*24*3600},
{"y", 365*24*3600}
}]
(* Convert a structured expression to a string, and make it
* pretty.
*)
Pretty[ex_] := MkString[Pretty[ex, "", ""]]
Pretty[ex:{(_Integer|_Symbol) ...}, indent1_, indent2_] := {
indent1, "{",
ex //
MapIndexed1[Pretty[#1, "", indent2 <> " "]&] //
Riffle[#, ", "]&,
"}"
}
Pretty[ex_List, indent1_, indent2_] := {
indent1, "{",
ex //
MapIndexed1[Pretty[#1, If[#2 === 1, "", indent2 <> " "], indent2 <> " "]&] //
Riffle[#, ",\n"]&,
"}"
}
Pretty[ex_Association, indent1_, indent2_] := {
indent1, "<|",
ex //
Normal //
MapIndexed1[Pretty[#1, If[#2 === 1, "", indent2 <> " "], indent2 <> " "]&] //
Riffle[#, ",\n"]&,
"|>"
}
Pretty[a_ -> b:Except[_List|_Association], indent1_, indent2_] := {
Pretty[a, indent1, indent2],
" -> ",
Pretty[b, "", indent2 <> " "]
}
Pretty[a_ -> b_, indent1_, indent2_] := {
Pretty[a, indent1, indent2],
" ->\n",
Pretty[b, indent2 <> " ", indent2 <> " "]
}
Pretty[ex_, indent1_, indent2_] := { indent1, ex // InputForm }
(* Put a given expression into a file, use [[Pretty]] to format it.
*)
PrettyPut[expr_, filename_String] := MkFile[filename, expr // Pretty]
(* Extract the list of leaf elements, map them with the given
* function, and put them back in. Note that `mapfn` must return
* a list of the same size as its input. *)
LeafApply[mapfn_, ex_] :=
Module[{skeleton, items},
LeafApply$SkeletonizeCounter = 0;
{skeleton, items} = Reap[LeafApply$Skeletonize[ex]];
items = First[items, {}] // mapfn;
If[NotMatchQ[items, _List], Error["LeafApply: map did not return a list"]];
skeleton /. LeafApply$SkeletonizePlace[i_] :> items[[i]]
]
LeafApply[mapfn_] := LeafApply[mapfn, #]&
SetAttributes[LeafApply$Skeletonize, {Listable}];
LeafApply$SkeletonizeCounter = 0;
LeafApply$Skeletonize[s_SeriesData] := MapAt[LeafApply$Skeletonize, s, {3}]
LeafApply$Skeletonize[ex_] := (Sow[ex]; LeafApply$SkeletonizeCounter++; LeafApply$SkeletonizePlace[LeafApply$SkeletonizeCounter])
(* Find all parts of `ex` that match `pat`, apply `mapfn` to the list
* of such parts, put its result back into the expression. Note
* that `mapfn` must return a list of the same size as its input.
*)
SubexpressionApply[mapfn_, ex_, pat_] :=
Module[{counter, elements, exX, p, X},
counter = 0;
elements = <||>;
exX = ex /. p:pat :> (counter++; elements[counter] = p; X[counter]);
{keys, elements} = elements // Normal // {#[[;;,1]], #[[;;,2]]}&;
elements = elements // mapfn;
If[NotMatchQ[elements, _List], Error["SubexpressionApply: map did not return a list"]];
elements = MapThread[Rule, {keys, elements}] // Association;
exX /. X -> elements
]
SubexpressionApply[mapfn_, ex_, pat_:>fn_] :=
Module[{counter, elements, exX, p, X},
counter = 0;
elements = <||>;
exX = ex /. p:pat :> (counter++; elements[counter] = fn; X[counter]);
{keys, elements} = elements // Normal // {#[[;;,1]], #[[;;,2]]}&;
elements = elements // mapfn;
If[NotMatchQ[elements, _List], Error["SubexpressionApply: map did not return a list"]];
elements = MapThread[Rule, {keys, elements}] // Association;
exX /. X -> elements
]
(* Apply a list-to-list mapping function MapFun to a list, but
* do so by figuring out the set of unique items, applying the
* mapping function to them, and then reshuffling the result so
* it would look like it was applied to the whole list. Useful if
* the mapping function is slow and there is a lot of duplicated
* items. *)
UniqueApply[MapFun_, items_List] :=
Module[{WRAP, uniqItemList, uniqItemIndex, itemIndexList, mappedUniqItems, item, idx},
uniqItemList = {};
uniqItemIndex = <||>;
itemIndexList = {};
Do[
(* We need to wrap items so that Flatten would work on uniqItemList. *)
item = WRAP[item];
idx = Lookup[uniqItemIndex, item, None];
If[idx === None,
uniqItemList = {uniqItemList, item};
uniqItemIndex[item] = idx = Length[uniqItemIndex] + 1;
];
itemIndexList = {itemIndexList, idx};
,
{item, items}];
mappedUniqItems = uniqItemList // Flatten // #[[;;,1]]& // MapFun;
If[NotMatchQ[mappedUniqItems, _List], Error["UniqApply: MapFun did not return a list"]];
mappedUniqItems[[itemIndexList // Flatten]]
]
UniqueApply[MapFun_] := UniqueApply[MapFun, #]&
(*
Among a list of sets, find such a sublist such that all other
sets are subsets of these ones. Return the list, and a list of
indices indicating which set belongs to which superset.
Example:
{{3},{1,2,3},{2,3,1},{2},{1,4,3},{4}}//UniqueSupersetMapping
> { {{1,2,3}, {1,4,3}}, {1,1,1,1,2,2} }
*)
UniqueSupersetMapping[sets_List, subsetq_:SubsetQ] :=
Module[{supersets, idx, IdxOf},
supersets = {};
IdxOf[set_] := IdxOf[set] = (
idx = ElementIndex[supersets, subsetq[#, set]&, None];
If[idx === None,
supersets = Append[supersets, set // Sort];
Length[supersets]
,
idx
]
);
sets // SortBy[Length] // Reverse // MapWithProgress[IdxOf];
{supersets, sets // Map[IdxOf] }
]
(* What an awfully named function. Ugh. Don’t use it.
*)
SelectFactors[ex_, pat_] :=
Module[{f},
f = ex // Factors;
{
f // Cases[pat] // Apply[Times],
f // DeleteCases[pat] // Apply[Times]
}
]
SelectFactors[pat_] := SelectFactors[#,pat]&
(* Another badly named function. Consider not using.
*)
SplitFactors[ex_, pat_] :=
Module[{f},
f = ex // Factor // Factors;
{
f // Select[FreeQ[#, pat] &] // Apply[Times],
f // Select[Not[FreeQ[#, pat]] &] // Apply[Times]
}
]
SplitFactors[pat_] := SplitFactors[#,pat]&
(* Apply `Cases[]` to factors of an expression.
*)
FactorCases[ex_, pat_] := ex // Factors // Cases[pat] // Apply[Times]
FactorCases[pat_] := FactorCases[#, pat]&
(* Apply `DeleteCases[]` to factors of an expression.
*)
FactorDeleteCases[ex_, pat_] := ex // Factors // DeleteCases[pat] // Apply[Times]
FactorDeleteCases[pat_] := FactorDeleteCases[#, pat]&
(* Split a matrix into partial fraction.
*)
MxApart[mx_, x_] :=
Module[{mxa, xxlist, xx},
mxa = Apart[mx, x] // Expand[#, x]& // Map[Terms, #, {2}]& // Map[SplitFactors[#, x]&, #, {3}]&;
xxlist = mxa[[;; , ;; , ;; , 2]] // Flatten // Union;
Table[List[
xx,
Map[(Cases[#, {k_, xx} :> k] // Apply[Plus]) &, mxa, {2}]
], {xx, xxlist}]
]
(* For an expression linear in a list of variables, return the
* matrix of coefficients. Fail if the expression is not linear.
*)
CoefficientMatrix[vars_List] := CoefficientMatrix[#, vars]&
CoefficientMatrix[ex_List, vars_List] :=
Module[{mxl},
mxl = CoefficientArrays[ex, vars];
Which[
Length[mxl] === 0,
Table[0, Length[ex], Length[vars]],
Length[mxl] === 1,
FailUnless[ZeroMatrixQ[mxl[[1]]]];
Table[0, Length[ex], Length[vars]],
Length[mxl] === 2,
FailUnless[ZeroMatrixQ[mxl[[1]]]];
mxl[[2]] // Normal,
True,
Error["CoefficientMatrix: quadratic terms in the expression?"];
]
]
(* Check if there is a linear combination of the given polynomials
* in the given variables that is a zero.
*)
PolynomialsLinearlyDependentQ[polynomials_List, vars_List] :=
Module[{coefrules, monomial2index, coefarray},
coefrules = polynomials // Map[CoefficientRules[#, vars] &] // DeleteCases[{}];
monomial2index = coefrules[[;; , ;; , 1]] // Apply[Join] // Union // PositionIndex;
coefarray = coefrules // MapAt[monomial2index, #, {;; , ;; , 1}] & // MapIndexed[MapAt[Prepend[#2 // First], #1, {;; , 1}] &] // Apply[Join] // SparseArray;
MatrixRank[coefarray] < Length[coefarray]
]
(* Return the sign of the leading term of a polynomial. Which
* term is considered "leading" is up to Mathematica term ordering.
*)
LeadingSign[ex_List] := Map[LeadingSign, ex]
LeadingSign[ex_ /; (FactorTermsList[ex] // First // Negative)] := -1
LeadingSign[ex_] := 1
(* Return the polynomial with the leading sign changed to positive.
*)
DropLeadingSign[ex_List] := Map[DropLeadingSign, ex]
DropLeadingSign[ex_^n_] := DropLeadingSign[ex]^n
DropLeadingSign[ex_ /; (FactorTermsList[ex] // First // Negative)] := -ex
DropLeadingSign[ex_] := ex
(* Expand the expression, and bracket out all parts of terms
* that have pat in them. Apply coeff to each bracket, and stemf
* to each prefactor. *)
Bracket[ex_List, pat_, coeff_, stemf_] := Map[Bracket[#, pat, coeff, stemf] &, ex]
Bracket[ex_Rule, pat_, coeff_, stemf_] := Map[Bracket[#, pat, coeff, stemf] &, ex]
Bracket[ex_SeriesData, pat_, coeff_, stemf_] := MapAt[Bracket[#, pat, coeff, stemf] &, ex, 3]
Bracket[ex_, pat_] := Bracket[ex, pat, #&, #&]
Bracket[ex_, pat_, coeff_] := Bracket[ex, pat, coeff, #&]
Bracket[ex_, vars_List, coeff_, stemf_] := Bracket[ex, Alternatives @@ vars, coeff, stemf]
Bracket[ex_, pat_, coeff_, stemf_] :=
ex // Expand[#, pat]& // Terms // Map[Factors /* (Times @@@ {Cases[#, pat^_.], DeleteCases[#, pat^_.]} &)] //
GroupBy[First] // Normal //
Map[stemf[#[[1]]] coeff[Plus @@ #[[2, ;; , 2]]] &] // Apply[Plus]
(* Similar to [[Bracket]] but returns an association of
* {stem->coefficient} pairs. *)
BracketAssociation[ex_, pat_] :=
ex //
Expand[#, pat]& //
Terms //
Map[Factors /* (Times @@@ {Cases[#, pat^_.], DeleteCases[#, pat^_.]} &)] //
GroupBy[First] //
Map[(Plus @@ #[[;;,2]])&] //
Association
BracketAssociation[pat_] := BracketAssociation[#, pat]&
(* Print the time it takes to evaluate its argument, and return
* the result of the evaluation. Useful for ad-hoc profiling.
*)
TM[ex_] := AbsoluteTiming[ex] // (Print[HoldForm[ex], ": ", #[[1]]//FormatSeconds]; #[[2]]) &
SetAttributes[TM, HoldFirst]
(* Print an expression and return it. Useful for debugging. *)
PR[ex_] := (Print[ex]; ex)
(* Copy an expression to the clipboard, and return it. *)
ClipCopy[ex_] := (
Put[ex, "/tmp/clipboard.txt"];
Run["xclip -i -selection clipboard /tmp/clipboard.txt"];
ex
);
(* A shortcut for `Not[FreeQ[...]]`. *)
NotFreeQ[ex_, pat_, level_] := Not[FreeQ[ex, pat, level]]
NotFreeQ[ex_, pat_] := Not[FreeQ[ex, pat]]
NotFreeQ[pat_] := FreeQ[pat] /* Not
(* A shortcut for `Not[MatchQ[...]]`. *)
NotMatchQ[ex_, pat_] := Not[MatchQ[ex, pat]]
NotMatchQ[pat_] := MatchQ[pat] /* Not
(* Evaluate a given expression many times, for at least a second,
* and return the average evaluation time. *)
TimeIt[ex_] :=
Module[{t, niter = 2},
t = AbsoluteTiming[Do[ex, niter]] // First;
While[t < 0.9,
niter = Max[niter*2, 1.1*niter/Max[t, 0.01] // Ceiling];
t = AbsoluteTiming[Do[ex, niter]] // First;
];
t/niter
]
SetAttributes[TimeIt, HoldFirst];
(* Return a random name of a fresh file of the form prefix.XXXXsuffix.
* Make sure no file with this name exists.
*)
MkTemp[prefix_, suffix_] :=
Module[{i, fn, alphabet},
alphabet = Characters["abcdefghijklmnopqrstuvwxyz0123456789"];
While[True,
i = RandomSample[alphabet, 8];
fn = FileNameJoin[{$TemporaryDirectory, MkString[prefix, ".", Environment["USER"], ".", $ProcessID, ".", i, suffix]}];
If[Not[FileExistsQ[fn]], Return[fn]];
]
]
(* Create a new temporary directory, with the name of the form
* prefix.XXXXsuffix.
*)
MkTempDirectory[prefix_, suffix_] :=
Module[{dirname},
dirname = MkTemp[prefix, suffix];
EnsureDirectory[dirname];
dirname
]
(* Make sure a directory exists. Create it if it doesn’t. *)
EnsureDirectory[dirs__] :=
Module[{dir},
Do[Quiet[CreateDirectory[dir], {CreateDirectory::filex, CreateDirectory::eexist}];, {dir, {dirs}}];
]
(* Make sure a directory doesn’t exist. Remove it if it does. *)
EnsureNoDirectory[dirs__] :=
Module[{dir},
Do[Quiet[DeleteDirectory[dir, DeleteContents->True], {DeleteDirectory::nodir}];, {dir, {dirs}}];
]
(* Make sure a directory exists and has no files inside. *)
EnsureCleanDirectory[dirs__] := (
EnsureNoDirectory[dirs];
EnsureDirectory[dirs];
);
(* Make sure a file doesn’t exist. Remove it if it does. *)
EnsureNoFile[files__] :=
Module[{file},
Do[Quiet[DeleteFile[file], {DeleteFile::fdnfnd}];, {file, {files}}];
]
(* Add a given directory to the "PATH" environment variable, if
* it is not already there. *)
EnsureIsInPATH[directory_String] :=
Module[{PATH},
PATH = Environment["PATH"] // StringSplit[#, ":"]& // #[[;;-1]]&;
If[Not[MemberQ[PATH, directory]],
SetEnvironment["PATH" -> (Join[PATH, {directory}] // StringRiffle[#, ":"]&)]
];
]
(* Run a command, fail if the exist status is not zero. *)
SafeRun[code__] :=
Module[{retCode},
retCode = Run[MkString[code]];
If[retCode =!= 0,
Error["SafeRun: command failed with code ", retCode];
];
];
(* Evaluate a given text fragment as Mathematica script in a fresh
* kernel. Return the value of the `RESULT` variable at the end
* of the program. Fail if the program aborted before the end.
*
* This is useful because some libraries require a clean Mathematica
* environment, and explode if mixed with any other code.
*)
RunMathProgram[code___] :=
Module[{tmpfile, resfile, math, retCode, result},
tmpfile = MkTemp["math", ".m"];
resfile = tmpfile <> ".result.m";
MkFile[tmpfile, "RESULT = Null;\n\n", code, "\n\nPut[RESULT, \"", resfile, "\"];\n"];
(*MkString[code]//PR;*)
Run["cat " <> tmpfile];
math = Environment["MATH"] /. $Failed -> "math";
retCode = Run[math <> " -script " <> tmpfile];
If[retCode =!= 0,
Error["RunMathProgram: mathematica failed with code ", retCode];
];
result = Get[resfile];
If[result === $Failed,
Error["RunMathProgram: the script did not finish"];
];
DeleteFile[{tmpfile, resfile}];
result
]
(* Apply a function to a list of items (same as `Map`), but also
* print current progress information and estimated completion time
*)
MapWithProgress[f_, items_Association] := items // Values // MapWithProgress[f] // MapThread[Rule, {items // Keys, #}]& // Association
MapWithProgress[f_, items_List] :=
Module[{result, t0, tx, t, ndone = 0, ntodo = Length[items], bcounts, bfrac},
t0 = tx = SessionTime[];
bcounts = items//Map[ByteCount];
result = Map[(
result = f[#];
ndone++;
t = SessionTime[];
If[t - tx > 1,
bfrac = Plus@@bcounts[[;;ndone]]/Plus@@bcounts//N;
Print["\r\033[KMap: ", ndone, "/", ntodo, " at ", t-t0//FormatSeconds,
", bytes: ", NumberForm[100 bfrac, {Infinity, 1}]//ToString,
"%, eta ", (t-t0)*(1/bfrac-1)//FormatSeconds];
tx = t;
];
result
)&, items];
Print["Map: done ", ntodo, " items in ", t-t0//FormatSeconds];
result
]
MapWithProgress[f_] := MapWithProgress[f, #] &
(* Parallel `Map` with progress indicator.
*)
PMap[f_, data_] :=
Module[{tmpfile, todo, result, r, nitems, nstarted, nended, i},
{nitems, nstarted, nended} = {Length[data], 0, 0};
$PARALLELDATA = data;
SetSharedVariable[nstarted, nended];
Status["PMap: distributing data, ", ByteCount[$PARALLELDATA]//FormatBytes];
DistributeDefinitions[$PARALLELDATA];
ClearAll[$PARALLELDATA];
Status["PMap: distributing definitions..."];
DistributeDefinitions[Status, nitems, f];
Status["PMap: mapping..."];
todo = Table[ParallelSubmit[{i},
nstarted++;
r = f[$PARALLELDATA[[i]]];
nended++;
Status["PMap: ", nended, "/", nstarted, "/", nitems];
r
], {i, Length[data]}];
result = WaitAll[todo];
ParallelEvaluate[ClearAll[$PARALLELDATA]];
UnsetShared[nstarted, nended];
Status["PMap: done, ", result//ByteCount//FormatBytes];
result
]
$LastStatusTime = AbsoluteTime[];
SetSharedVariable[$LastStatusTime];
Status[msg___] := Module[{t = AbsoluteTime[]}, If[t - $LastStatusTime > 1, $LastStatusTime = t; Print[MkString[msg]]]]
(* ## B Maps
*
* B maps are a way to apply many substitution rules for `B[...]`
* objects, as efficiently as Mathematica allows for. They are
* implemented as a set of substitution rules attached to a symbol,
* but can be loaded/saved to the usual format of a list of rules
* (i.e. `{B[...] -> ..., ...}`).
*)
(* Load substitution rules from a file and add them to a B map
* identified by a given name (symbol). The file should be in
* Mathematica format: a list of `B[...] -> ...` rules. Duplicate
* rules are allowed; conflicting rules will be detected. *)
BMapLoad[name_Symbol, filename_String] := BMapLoad[name, SafeGet[filename]]
(* Add substitution rules to a B map. Check for conflicting
* rules. *)
BMapLoad[name_Symbol, map_List] :=
Module[{args, rule, k, v, k0, v0, ndups},
ndups = 0;
Do[
If[Not[MatchQ[rule, _B -> _]],
Print["! Not a B rule: ", rule];
Throw[BMapLoad]];
{k0, v0} = List @@ rule;
k = name @@ k0;
v = v0 /. B -> name;
If[B @@ k === k0,
Evaluate[k] = v;
,
If[k =!= v,
Print["! Bad duplicate map for: ", k0];
Print["! Old value: ", k /. name -> B];
Print["! New value: ", v0];
Print["! = ", v /. name -> B];
Throw[BMapLoad];
,
ndups++;
];
];
,
{rule, map}
];
Print["Loaded ", Length[map], " rules (", ndups, " duplicates)"];
]
(* Set one key in a B map. Check for conflicting rules. *)
BMapSet[name_Symbol, key_B, value_] :=
Module[{k, v},
k = name @@ key;
v = value /. B -> name;
If[B @@ k === key,
Evaluate[k] = v;
,
If[k =!= v,
Print["! Bad duplicate map for: ", key];
Print["! Old value: ", k /. name -> B];
Print["! New value: ", value];
Print["! = ", v /. name -> B];
Throw[BMapAdd];
];
];
];
(* Save a B map to a file, as a list of substitution rules. *)
BMapSave[name_Symbol, filename_String] :=
Put[DownValues[Evaluate[name]] /. name -> B /. (Verbatim[HoldPattern][pat_] :> val_) :> (pat -> val) // Sort, filename]
(* Clear a B map. *)
BMapClear[name_Symbol] := Clear[Evaluate[name]]
(* Apply a B map to an expression. *)
BMapApply[name_Symbol, ex_] := ex /. B -> name /. name -> B
BMapApply[name_Symbol] := BMapApply[name, #] &
(* Append one or several B maps to a given one. *)
BMapAppendTo[result_Symbol, rest__] :=
Module[{names = List[rest], keys, name, values},
keys = Prepend[names, result] // Map[(DownValues[#] // Map[First] // ReplaceAll[# -> B] // Map[ReleaseHold])&] // Apply[Join] // Union;
values = keys /. B -> result /. result -> First[names];
Do[values = values /. names[[i-1]] -> names[[i]], {i, 2, Length[names]}];
values = values /. Last[names] -> result;
Clear[Evaluate[result]];
DownValues[Evaluate[result]] = MapThread[RuleDelayed, {keys // Map[HoldPattern] // ReplaceAll[B -> result], values}];
]
(* Add one key-value pair to a B map. *)
BMapAppendOne[name_Symbol, key_B, value_] :=
Module[{keys, values},
keys = BMapKeys[name] // Append[#, key]&;
values = keys /. B -> name /. name -> B /. key -> value;
Clear[Evaluate[name]];
DownValues[Evaluate[name]] = MapThread[RuleDelayed, {keys // Map[HoldPattern], values}] // ReplaceAll[B -> name];
];
(* Map all values of a B map. *)
BMapMapValues[name_Symbol, fn_] :=
Module[{keys, values},
keys = BMapKeys[name];
values = keys // BMapApply[name] // Map[fn];
Clear[Evaluate[name]];
DownValues[Evaluate[name]] = MapThread[RuleDelayed, {keys // Map[HoldPattern], values}] // ReplaceAll[B -> name];
];
(* Map all values of a B map. *)
BMapMapItems[name_Symbol, fn_] :=
Module[{keys, values, kv},
keys = BMapKeys[name];
values = keys // BMapApply[name];
kv = MapThread[fn, {keys, values}];
Clear[Evaluate[name]];
DownValues[Evaluate[name]] = Map[RuleDelayed @@ {HoldPattern[Evaluate[#[[1]]]], #[[2]]}&, kv] // ReplaceAll[B -> name];
];
(* List all the unique `B[...]` expressions on the right-hand
* side of the B map. *)
BMapMasters[name_Symbol] := DownValues[Evaluate[name]] /. name -> B // Map[#[[2]]&] // Cases[#, _B, -1]& // Union
(* Get the number of items in a B map. *)
BMapLength[name_Symbol] := DownValues[Evaluate[name]] // Length
(* Get the list of a B map keys. *)
BMapKeys[name_Symbol] := DownValues[Evaluate[name]] // Map[First] // ReplaceAll[name -> B] // Map[ReleaseHold]
(* Get the B map as a list of rules. *)
BMapRules[name_Symbol] := DownValues[Evaluate[name]] /. name -> B /. {RuleDelayed -> Rule, Verbatim[HoldPattern][x_] :> x}
(*
* ## Maple
*)
(* Set `$MapleBinary` variable or `MAPLE` environment variable
* before using this. By default `maple` is used. *)
If[Not[MatchQ[$MapleBinary, _String]],
$MapleBinary = Environment["MAPLE"] /. $Failed -> "maple"];
(* Set `$MapleDebug` to `True` to see Maple input/output. *)
If[Not[MatchQ[$MapleDebug, True|False]],
$MapleDebug = False];
(* Run a Maple script defined by a (possibly nested) list of
* expressions. Export the 'result' variable from Maple after
* the script is over, and return its value.
*
* Note that sometimes when something goes wrong, 'mserver'
* process lingers on, even after the maple session is over. Those
* need to be killed manually, for example by 'pkill mserver'.
*)
MapleRun[script_List] :=