-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathutil.py
More file actions
174 lines (151 loc) · 5.84 KB
/
Copy pathutil.py
File metadata and controls
174 lines (151 loc) · 5.84 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
# -*- coding: utf-8 -*-
"""
Miscellaneous mathics.core utility functions.
"""
import re
import sys
from itertools import chain
from pathlib import PureWindowsPath
from platform import python_implementation
from typing import Optional
from mathics.core.atoms import MachineReal, NumericArray
from mathics.core.symbols import Symbol
IS_PYPY = python_implementation() == "PyPy"
def canonic_filename(path: str) -> str:
"""
Canonicalize path. On Microsoft Windows, use PureWidnowsPath() to
turn backslash "\" to "/". On other platforms we currently, do
nothing, but we might in the future canonicalize the filename
further, e.g. via os.path.normpath().
"""
if sys.platform.startswith("win"):
# win32 or win64..
# PureWindowsPath.as_posix() strips trailing "/" .
dir_suffix = "/" if path.endswith("/") else ""
path = PureWindowsPath(path).as_posix() + dir_suffix
# Should we use "os.path.normpath() here?
return path
# FIXME: These functions are used pattern.py
def permutations(items):
if not items:
yield []
# already_taken = set()
# first yield identical permutation without recursion
yield items
for index in range(len(items)):
item = items[index]
# if item not in already_taken:
for sub in permutations(items[:index] + items[index + 1 :]):
yield [item] + list(sub)
# already_taken.add(item)
def strip_string_quotes(s: str) -> str:
"""
Remove leading and trailing string quotes if they exist.
Note: we need this too often probably a bad design decision in String.
"""
return s[1:-1] if len(s) >= 2 and s[0] == s[-1] == '"' else s
def subsets(items, min: int, max: Optional[int], included=None, less_first=False):
if max is None:
max = len(items)
lengths = list(range(min, max + 1))
if not less_first:
lengths = list(reversed(lengths))
if lengths and lengths[0] == 0:
lengths = lengths[1:] + [0]
def decide(chosen, not_chosen, rest, count):
if count < 0 or len(rest) < count:
return
if count == 0:
yield chosen, list(chain(not_chosen, rest))
elif len(rest) == count:
if included is None or all(item in included for item in rest):
yield list(chain(chosen, rest)), not_chosen
elif rest:
item = rest[0]
if included is None or item in included:
for set in decide(chosen + [item], not_chosen, rest[1:], count - 1):
yield set
for set in decide(chosen, not_chosen + [item], rest[1:], count):
yield set
for length in lengths:
for chosen, not_chosen in decide([], [], items, length):
yield chosen, ([], not_chosen)
def subranges(
items, min_count, max, *, flexible_start=False, included=None, less_first=False
):
"""
generator that yields possible divisions of items as
([items_inside],([previos_items],[remaining_items]))
with items_inside of variable lengths.
If flexible_start, then [previos_items] also has a variable size.
"""
# TODO: take into account included
if max is None:
max = len(items)
max = min(max, len(items))
if flexible_start:
starts = list(range(len(items) - max + 1))
else:
starts = (0,)
for start in starts:
lengths = list(range(min_count, max + 1))
if not less_first:
lengths = reversed(lengths)
lengths = list(lengths)
if lengths == [0, 1]:
lengths = [1, 0]
for length in lengths:
yield (
items[start : start + length],
(items[:start], items[start + length :]),
)
def print_expression_tree(
expr, indent="", marker=lambda expr: "", file=None, approximate=False
):
"""
Print a Mathics Expression as an indented tree.
Caller may supply a marker function that computes a marker
to be displayed in the tree for the given node.
The approximate flag causes numbers to be printed with fewer digits
and the number of bits of precision (i.e. Real32 vs Real64) to be
omitted from printing for numpy arrays, to faciliate comparisons
across systems.
"""
if file is None:
file = sys.stdout
if isinstance(expr, (tuple, list)):
for e in expr:
print_expression_tree(e, indent, marker, file, approximate)
elif isinstance(expr, Symbol):
print(f"{indent}{marker(expr)}{expr}", file=file)
elif not hasattr(expr, "elements"):
if isinstance(expr, MachineReal) and approximate:
# fewer digits
value = str(round(expr.value * 1e6) / 1e6)
elif isinstance(expr, NumericArray) and approximate:
# Real32/64->Real*, Integer32/64->Integer*
value = re.sub("[0-9]+,", "*,", str(expr))
else:
value = str(expr)
print(f"{indent}{marker(expr)}{expr.get_head()} {value}", file=file)
if isinstance(expr, NumericArray):
# numpy provides an abbreviated version of the array
# it is inherently approximated (i.e. limited precision) in its own way
na_str = str(expr.value)
i = indent + " "
na_str = i + na_str.replace("\n", "\n" + i)
print(na_str, file=file)
else:
print(f"{indent}{marker(expr)}{expr.head}", file=file)
for elt in expr.elements:
print_expression_tree(
elt, indent + " ", marker=marker, file=file, approximate=approximate
)
def print_sympy_tree(expr, indent=""):
"""Print a SymPy Expression as an indented tree"""
if expr.args:
print(f"{indent}{expr.func.__name__}")
for i, arg in enumerate(expr.args):
print_sympy_tree(arg, indent + " ")
else:
print(f"{indent}{expr.func.__name__}({str(expr)})")