sparclclient 1.2.1__py2.py3-none-any.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.
sparcl/utils.py ADDED
@@ -0,0 +1,209 @@
1
+ # Python library
2
+ import datetime
3
+ import time
4
+ import socket
5
+ import itertools
6
+ import json
7
+ import subprocess
8
+ # External packages
9
+ # none
10
+ # LOCAL packages
11
+ # none
12
+
13
+
14
+ # data = {
15
+ # "a": "aval",
16
+ # "b": {
17
+ # "b1": {
18
+ # "b2b": "b2bval",
19
+ # "b2a": {
20
+ # "b3a": "b3aval",
21
+ # "b3b": "b3bval"
22
+ # }
23
+ # }
24
+ # }
25
+ # }
26
+ #
27
+ # data1 = AttrDict(data)
28
+ # print(data1.b.b1.b2a.b3b) # -> b3bval
29
+ class _AttrDict(dict):
30
+ """Dictionary subclass whose entries can be accessed by attributes
31
+ (as well as normally).
32
+ """
33
+
34
+ def __init__(self, *args, **kwargs):
35
+ def from_nested_dict(data):
36
+ """Construct nested AttrDicts from nested dictionaries."""
37
+ if not isinstance(data, dict):
38
+ return data
39
+ else:
40
+ return _AttrDict(
41
+ {key: from_nested_dict(data[key]) for key in data}
42
+ )
43
+
44
+ super(_AttrDict, self).__init__(*args, **kwargs)
45
+ self.__dict__ = self
46
+
47
+ for key in self.keys():
48
+ self[key] = from_nested_dict(self[key])
49
+
50
+
51
+ def tic():
52
+ """Start tracking elapsed time. Works in conjunction with toc().
53
+
54
+ Args:
55
+ None.
56
+ Returns:
57
+ Elapsed time.
58
+ """
59
+ tic.start = time.perf_counter()
60
+
61
+
62
+ def toc():
63
+ """Return elapsed time since previous tic().
64
+
65
+ Args:
66
+ None.
67
+ Returns:
68
+ Elapsed time since previous tic().
69
+ """
70
+ elapsed_seconds = time.perf_counter() - tic.start
71
+ return elapsed_seconds # fractional
72
+
73
+
74
+ def here_now():
75
+ """Used to track info for benchmark. Probably OBE?
76
+
77
+ Args:
78
+ None.
79
+ Returns:
80
+ Time, date, and hostname.
81
+ """
82
+ hostname = socket.gethostname()
83
+ now = str(datetime.datetime.now())
84
+ return (hostname, now)
85
+
86
+
87
+ def objform(obj):
88
+ """Nested structure of python object. Avoid spewing big lists.
89
+ See also: https://code.activestate.com/recipes/577504/
90
+
91
+ Args:
92
+ obj: Python object.
93
+ Returns:
94
+ Length if list, objforms of dict contents if dict, type if
95
+ anything else.
96
+ Example:
97
+ >>> res = client.sample_records(1)[0]
98
+ >>> objform(res)
99
+ <class 'sparcl.client.AttrDict'>
100
+ """
101
+ # dict((k,len(v)) for (k,v) in qs[0]['spzline'].items())
102
+ if obj is None:
103
+ return None
104
+ elif type(obj) is list:
105
+ if len(obj) > 999:
106
+ return f"CNT={len(obj)}"
107
+ elif len(obj) < 9:
108
+ return [objform(x) for x in obj]
109
+ else:
110
+ return [objform(x) for x in obj[:10]] + ["..."]
111
+ elif type(obj) is dict:
112
+ return dict((k, objform(v)) for (k, v) in obj.items())
113
+ else:
114
+ return str(type(obj))
115
+
116
+
117
+ def dict2tree(obj, name=None, prefix=""):
118
+ """Return abstracted nested tree. Terminals contain TYPE.
119
+ As a special case, a list is given as a dict that represents a
120
+ compound type. E.G. {'<list(3835)[0]>': float} means a list of
121
+ 3835 elements where the first element is of type 'float'. NB:
122
+ Only the type of the first element in a list is given. If the
123
+ list has hetergeneous types, that fact is invisible in the
124
+ structure!!
125
+ """
126
+ nextpfx = "" if name is None else (prefix + name + ".")
127
+ showname = prefix if name is None else (prefix + name)
128
+ if isinstance(obj, dict):
129
+ children = dict()
130
+ for k, v in obj.items():
131
+ if isinstance(v, dict) or isinstance(v, list):
132
+ val = dict2tree(v, name=k, prefix=nextpfx)
133
+ else:
134
+ #!val = {k: type(v).__name__}
135
+ val = {nextpfx + k: type(v).__name__}
136
+ children.update(val)
137
+ tree = children if name is None else {showname: children}
138
+ elif isinstance(obj, list):
139
+ children = f"<list({len(obj)})[0]>:{type(obj[0]).__name__}"
140
+ tree = {showname: children}
141
+ else:
142
+ tree = {showname: type(obj).__name__}
143
+ return tree
144
+
145
+
146
+ def invLUT(lut):
147
+ """Given dict[k]=v, Return dict[v]=k"""
148
+ return {v: k for k, v in lut.items()}
149
+
150
+
151
+ def count_values(recs):
152
+ """Count number of non-None values in a list of dictionaries.
153
+ A key that exists with a value of None is treated the same as a
154
+ key that does not exist at all. i.e. It does not add to the count.
155
+
156
+ Args:
157
+ recs (:obj:`list`): ('records') List of dictionaries.
158
+
159
+ Returns:
160
+ A dictionary. Keys are the full list of keys available in any
161
+ of the recs. Values are the count of occurances of non-None values
162
+ for that key.
163
+
164
+ >>> count_values([dict(a=None, b=3), dict(a=1, b=2), dict(a=None, b=2)])
165
+ {'a': 1, 'b': 3}
166
+ """
167
+ allkeys = set(list(itertools.chain(*recs)))
168
+ return {k: sum(x.get(k) is not None for x in recs) for k in allkeys}
169
+
170
+
171
+ # In case I want to give CURL equivalents for client methods.
172
+ #
173
+ # Retrieve may return results as a pickle file since it usually contains
174
+ # spectra vectors. To handle pickle results, write curl output to out.pkl
175
+ # and do something like:
176
+ # with open('out.pkl', 'rb') as f: res = pickle.load(f)
177
+ def curl_retrieve_str(ids, server, svc="spectras", qstr=None):
178
+ #! ids = ['00000dd7-b1ff-48ed-b162-46d9d65f829c', 'BADID']
179
+ #!svc = 'spectras' if use_async else 'retrieve'
180
+ #! qstr = urlencode(uparams)
181
+ # server = "https://sparc1.datalab.noirlab.edu"
182
+ qqstr = "" if qstr is None else f"?{qstr}"
183
+ url = f"{server}/sparc/{svc}/{qqstr}"
184
+ curlpost1 = "curl -X 'POST' -H 'Content-Type: application/json' "
185
+ curlpost2 = f"-d '{json.dumps(ids)}' '{url}'"
186
+ curlpost3 = " | python3 -m json.tool"
187
+ return curlpost1 + curlpost2 + curlpost3
188
+
189
+
190
+ # see: curl_retrieve_str
191
+ def curl_find_str(sspec, server, qstr=None):
192
+ qqstr = "" if qstr is None else f"?{qstr}"
193
+ url = f"{server}/sparc/find/{qqstr}"
194
+ curlpost1 = "curl -X 'POST' -H 'Content-Type: application/json' "
195
+ curlpost2 = f"-d '{json.dumps(sspec)}' '{url}'"
196
+ curlpost3 = " | python3 -m json.tool"
197
+ return curlpost1 + curlpost2 + curlpost3
198
+
199
+ def githash(verbose=False):
200
+ try:
201
+ # "/usr/bin/git"
202
+ ret = subprocess.run(["git", "rev-parse", "HEAD"],\
203
+ capture_output=True)
204
+ commit_hash = ret.stdout.decode().strip()
205
+ except Exception as err:
206
+ if verbose:
207
+ print(err)
208
+ commit_hash = "<NA>"
209
+ return commit_hash
@@ -0,0 +1,31 @@
1
+ Copyright 2022 Association of Universities for Research in
2
+ Astronomy. Original code written by S. Pothier and A. Jacques.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are
6
+ met:
7
+
8
+ Redistributions of source code must retain the above copyright &
9
+ attribution notice, this list of conditions, and the following
10
+ disclaimer.
11
+
12
+ Redistributions in binary form must reproduce the above copyright &
13
+ attribution notice, this list of conditions, and the following
14
+ disclaimer in the documentation and/or other materials provided with
15
+ the distribution.
16
+
17
+ Neither the name of the copyright holder nor the names of its
18
+ contributors may be used to endorse or promote products derived from
19
+ this software without specific prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.1
2
+ Name: sparclclient
3
+ Version: 1.2.1
4
+ Summary: A client for getting spectra and meta-data from NOIRLab.
5
+ Author-email: "S. Pothier" <datalab-spectro@noirlab.edu>
6
+ Description-Content-Type: text/markdown
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Project-URL: Bug Tracker, https://github.com/pypa/sparclclient/issues
9
+ Project-URL: Documentation, https://sparclclient.readthedocs.io/en/latest/
10
+ Project-URL: Homepage, https://github.com/pypa/sparclclient
11
+
12
+ # sparclclient
13
+ Python Client for SPARCL (SPectra Analysis and Retrievable Catalog Lab)
14
+
@@ -0,0 +1,19 @@
1
+ sparcl/Results.py,sha256=YFh7HmiAfjxQv1y55OHhXsJbpKBh7mn92zPJZ56gJxw,8477
2
+ sparcl/__init__.py,sha256=SluDg17Gz9p8om9iydlLFewwIGJdYiR9VC2R-cXXdXU,934
3
+ sparcl/client.py,sha256=Y8nNwdusP6ZnqE_fvWL1Nfjxlot0SHKHjQdw0hdCl2A,32324
4
+ sparcl/conf.py,sha256=GFNDelaiVIAkjNjvFlG7HAlPpU39nqZmTPohQGmOcgI,928
5
+ sparcl/exceptions.py,sha256=QfK3aTl1HTQmbhUCRfW9eo-rzEA1yUawKGtv_ca4nvY,3801
6
+ sparcl/fields.py,sha256=Oef3KNmWqsqi8BPXuQA7EazLtwgfkqprbrPxev8sCio,5126
7
+ sparcl/gather_2d.py,sha256=mTM9YhsGf2CMOQ-CE4-JcAs1PhA0mVKlciy9dKnp67o,8685
8
+ sparcl/resample_spectra.py,sha256=Z_Lkoq4LapaIQp7tqZ88LayRLE8o9c832Icc0jSr5ok,1282
9
+ sparcl/sparc.ini,sha256=q_wjo9DLnCYRxWFMl0CtMYp4DD1AXfEcK6BP6cmncwo,329
10
+ sparcl/type_conversion.py,sha256=QmXNX9j_7QHnBu83f2ZBfREoql9wuo98ZbhQtSjRRWc,12965
11
+ sparcl/unsupported.py,sha256=bfkkZa-PuqwN-Bqo3vCIrLupbWMDTCiTHPMNfXnqmMc,1848
12
+ sparcl/utils.py,sha256=1u1e9mjOqdJTaywTQah1cnLIEuHEVj2lUJVOx8WpX3I,6287
13
+ sparcl/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ sparcl/benchmarks/benchmarks.py,sha256=OmlSdnAPLmcvGXsr-HzGyfAAcnoqlO0JQ4EIA7JGhZc,9424
15
+ sparcl/notebooks/sparcl-examples.ipynb,sha256=jdGaSw5KzYHXfPCthwjm0v2QFBcBeMf7-dvfGXwjZTA,257613
16
+ sparclclient-1.2.1.dist-info/LICENSE,sha256=y10EluGMCzGs9X4oYCYyix3l6u-lawB_vlGR8qe442Q,1576
17
+ sparclclient-1.2.1.dist-info/WHEEL,sha256=Sgu64hAMa6g5FdzHxXv9Xdse9yxpGGMeagVtPMWpJQY,99
18
+ sparclclient-1.2.1.dist-info/METADATA,sha256=1GUhe_YELEavKXmfpXS1BbT7HvXV_TedlSyoGT2eGHc,564
19
+ sparclclient-1.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any