cosmic-popsynth 3.4.15__cp39-cp39-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cosmic/filter.py ADDED
@@ -0,0 +1,214 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (C) Duncan Macleod (2017-2020)
3
+ #
4
+ # This file is part of GWpy.
5
+ #
6
+ # GWpy is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # GWpy is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with GWpy. If not, see <http://www.gnu.org/licenses/>.
18
+
19
+ """Utilies for filtering a `Table` using column slice definitions
20
+ """
21
+
22
+ import operator
23
+ import token
24
+ import re
25
+ from tokenize import generate_tokens
26
+ from collections import OrderedDict
27
+
28
+ from six import string_types
29
+ from six.moves import StringIO
30
+
31
+ __author__ = "Duncan Macleod <duncan.macleod@ligo.org>"
32
+
33
+ OPERATORS = OrderedDict(
34
+ [
35
+ ("<", operator.lt),
36
+ ("<=", operator.le),
37
+ ("=", operator.eq),
38
+ ("==", operator.eq),
39
+ (">=", operator.ge),
40
+ (">", operator.gt),
41
+ ("!=", operator.ne),
42
+ ]
43
+ )
44
+
45
+ OPERATORS_INV = OrderedDict(
46
+ [
47
+ ("<=", operator.ge),
48
+ ("<", operator.gt),
49
+ (">", operator.lt),
50
+ (">=", operator.le),
51
+ ]
52
+ )
53
+
54
+ QUOTE_REGEX = re.compile(r"^[\s\"\']+|[\s\"\']+$")
55
+ DELIM_REGEX = re.compile(r"(and|&+)", re.I)
56
+
57
+
58
+ # -- filter parsing -----------------------------------------------------------
59
+
60
+
61
+ def _float_or_str(value):
62
+ """Internal method to attempt `float(value)` handling a `ValueError`"""
63
+ # remove any surrounding quotes
64
+ value = QUOTE_REGEX.sub("", value)
65
+ try: # attempt `float()` conversion
66
+ return float(value)
67
+ except ValueError: # just return the input
68
+ return value
69
+
70
+
71
+ def parse_operator(mathstr):
72
+ """Parse a `str` as a function from the `operator` module
73
+
74
+ Parameters
75
+ ----------
76
+ mathstr : `str`
77
+ a `str` representing a mathematical operator
78
+
79
+ Returns
80
+ -------
81
+ op : `func`
82
+ a callable `operator` module function
83
+
84
+ Raises
85
+ ------
86
+ KeyError
87
+ if input `str` cannot be mapped to an `operator` function
88
+
89
+ Examples
90
+ --------
91
+ >>> parse_operator('>')
92
+ <built-in function gt>
93
+ """
94
+ try:
95
+ return OPERATORS[mathstr]
96
+ except KeyError as exc:
97
+ exc.args = ("Unrecognised operator %r" % mathstr,)
98
+ raise
99
+
100
+
101
+ def parse_column_filter(definition):
102
+ """Parse a `str` of the form 'column>50'
103
+
104
+ Parameters
105
+ ----------
106
+ definition : `str`
107
+ a column filter definition of the form ``<name><operator><threshold>``
108
+ or ``<threshold><operator><name><operator><threshold>``, e.g.
109
+ ``frequency >= 10``, or ``50 < snr < 100``
110
+
111
+ Returns
112
+ -------
113
+ filters : `list` of `tuple`
114
+ a `list` of filter 3-`tuple`s, where each `tuple` contains the
115
+ following elements:
116
+
117
+ - ``column`` (`str`) - the name of the column on which to operate
118
+ - ``operator`` (`callable`) - the operator to call when evaluating
119
+ the filter
120
+ - ``operand`` (`anything`) - the argument to the operator function
121
+
122
+ Raises
123
+ ------
124
+ ValueError
125
+ if the filter definition cannot be parsed
126
+
127
+ KeyError
128
+ if any parsed operator string cannnot be mapped to a function from
129
+ the `operator` module
130
+
131
+ Notes
132
+ -----
133
+ Strings that contain non-alphanumeric characters (e.g. hyphen `-`) should
134
+ be quoted inside the filter definition, to prevent such characters
135
+ being interpreted as operators, e.g. ``channel = X1:TEST`` should always
136
+ be passed as ``channel = "X1:TEST"``.
137
+
138
+ Examples
139
+ --------
140
+ >>> parse_column_filter("frequency>10")
141
+ [('frequency', <function operator.gt>, 10.)]
142
+ >>> parse_column_filter("50 < snr < 100")
143
+ [('snr', <function operator.gt>, 50.), ('snr', <function operator.lt>, 100.)]
144
+ >>> parse_column_filter("channel = "H1:TEST")
145
+ [('channel', <function operator.eq>, 'H1:TEST')]
146
+ """ # noqa
147
+ # parse definition into parts (skipping null tokens)
148
+ parts = list(generate_tokens(StringIO(definition.strip()).readline))
149
+ while parts[-1][0] in (token.ENDMARKER, token.NEWLINE):
150
+ parts = parts[:-1]
151
+
152
+ # parse simple definition: e.g: snr > 5
153
+ if len(parts) == 3:
154
+ a, b, c = parts # pylint: disable=invalid-name
155
+ if a[0] in [token.NAME, token.STRING]: # string comparison
156
+ name = QUOTE_REGEX.sub("", a[1])
157
+ oprtr = OPERATORS[b[1]]
158
+ value = _float_or_str(c[1])
159
+ return [(name, oprtr, value)]
160
+ elif b[0] in [token.NAME, token.STRING]:
161
+ name = QUOTE_REGEX.sub("", b[1])
162
+ oprtr = OPERATORS_INV[b[1]]
163
+ value = _float_or_str(a[1])
164
+ return [(name, oprtr, value)]
165
+
166
+ # parse between definition: e.g: 5 < snr < 10
167
+ elif len(parts) == 5:
168
+ a, b, c, d, e = list(zip(*parts))[1] # pylint: disable=invalid-name
169
+ name = QUOTE_REGEX.sub("", c)
170
+ return [
171
+ (name, OPERATORS_INV[b], _float_or_str(a)),
172
+ (name, OPERATORS[d], _float_or_str(e)),
173
+ ]
174
+
175
+ raise ValueError("Cannot parse filter definition from %r" % definition)
176
+
177
+
178
+ def parse_column_filters(*definitions):
179
+ """Parse multiple compound column filter definitions
180
+
181
+ Examples
182
+ --------
183
+ >>> parse_column_filters('snr > 10', 'frequency < 1000')
184
+ [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)]
185
+ >>> parse_column_filters('snr > 10 && frequency < 1000')
186
+ [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)]
187
+ """ # noqa: E501
188
+ fltrs = []
189
+ for def_ in _flatten(definitions):
190
+ if is_filter_tuple(def_):
191
+ fltrs.append(def_)
192
+ else:
193
+ for splitdef in DELIM_REGEX.split(def_)[::2]:
194
+ fltrs.extend(parse_column_filter(splitdef))
195
+ return fltrs
196
+
197
+
198
+ def _flatten(container):
199
+ """Flatten arbitrary nested list of filters into a 1-D list"""
200
+ if isinstance(container, string_types):
201
+ container = [container]
202
+ for elem in container:
203
+ if isinstance(elem, string_types) or is_filter_tuple(elem):
204
+ yield elem
205
+ else:
206
+ for elem2 in _flatten(elem):
207
+ yield elem2
208
+
209
+
210
+ def is_filter_tuple(tup):
211
+ """Return whether a `tuple` matches the format for a column filter"""
212
+ return isinstance(tup, (tuple, list)) and (
213
+ len(tup) == 3 and isinstance(tup[0], string_types) and callable(tup[1])
214
+ )
@@ -0,0 +1,15 @@
1
+ import subprocess
2
+
3
+ def get_commit_hash():
4
+ # Run git command to get the latest commit hash
5
+ result = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
6
+ commit_hash = result.stdout.decode('utf-8').strip()
7
+ return commit_hash
8
+
9
+ def write_commit_hash_to_file(commit_hash):
10
+ with open('./src/cosmic/_commit_hash.py', 'w') as f:
11
+ f.write(f'COMMIT_HASH = "{commit_hash}"\n')
12
+
13
+ if __name__ == "__main__":
14
+ commit_hash = get_commit_hash()
15
+ write_commit_hash_to_file(commit_hash)