This repository has been archived by the owner on Sep 7, 2023. It is now read-only.
forked from mjfitzpatrick/specserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
specClient.py
2516 lines (2017 loc) · 82.6 KB
/
specClient.py
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
#!/usr/bin/env python
#
# SPECCLIENT -- Client methods for the Spectroscopic Data Service
#
__authors__ = 'Mike Fitzpatrick <[email protected]>'
__version__ = 'v1.2.0'
'''
Client methods for the Spectroscopic Data Service.
Spectro Client Interface
------------------------
client = getClient (context='<context>', profile='<profile>')
status = isAlive (svc_url=DEF_SERVICE_URL, timeout=2)
set_svc_url (svc_url)
svc_url = get_svc_url ()
set_context (context)
ctx = get_context ()
ctxs = list_contexts (context, fmt='text')
ctxs = list_contexts (context=None, fmt='text')
set_profile (profile)
prof = get_profile ()
profs = list_profiles (profile, fmt='text')
profs = list_profiles (profile=None, fmt='text')
catalogs = catalogs (context='default', profile='default')
QUERY INTERFACE:
id_list = query (<region> | <coord, size> | <ra, dec, size>,
constraint=<sql_where_clause>,
context=None, profile=None, **kw)
ACCESS INTERFACE:
list = getSpec (id_list, fmt='numpy',
out=None, align=False, cutout=None,
context=None, profile=None, **kw)
PLOT INTERFACE:
plot (spec, context=None, profile=None, out=None, **kw)
status = prospect (spec, context=context, profile=profile, **kw)
image = preview (id, context=context, profile=profile, **kw)
image = plotGrid (id_list, nx, ny, page=<N>,
context=context, profile=profile, **kw)
image = stackedImage (id_list, fmt='png|numpy',
align=False, yflip=False,
context=context, profile=profile, **kw)
UTILITY METHODS:
df = to_pandas (npy_data)
spec1d = to_Spectrum1D (npy_data)
tab = to_Table (npy_data)
Import via
.. code-block:: python
from dl import specClient
'''
import os
import sys
import socket
import json
import numpy as np
import pandas as pd
from io import BytesIO
from PIL import Image
# Turn off some annoying astropy warnings
import warnings
from astropy.utils.exceptions import AstropyWarning
warnings.simplefilter('ignore', AstropyWarning)
import logging
logging.disable(logging.WARNING)
logging.getLogger("specutils").setLevel(logging.CRITICAL)
from specutils import Spectrum1D
from specutils import SpectrumCollection
from astropy import units as u
#from astropy.nddata import StdDevUncertainty
from astropy.nddata import InverseVariance
from astropy.table import Table
from matplotlib import pyplot as plt # visualization libs
try:
import pycurl_requests as requests # faster 'requests' lib
except ImportError:
import requests
import pycurl # low-level interface
from urllib.parse import quote_plus # URL encoding
# Data Lab imports.
#from dl import queryClient
from dl import storeClient
from dl.Util import def_token
from dl.Util import multimethod
from dl.helpers.utils import convert
# Python version check.
is_py3 = sys.version_info.major == 3
# The URL of the service to access. This may be changed by passing a new
# URL into the set_svc_url() method before beginning.
DEF_SERVICE_ROOT = "https://datalab.noirlab.edu"
# Allow the service URL for dev/test systems to override the default.
THIS_HOST = socket.gethostname()
if THIS_HOST[:5] == 'dldev':
DEF_SERVICE_ROOT = "https://dldev.datalab.noirlab.edu"
elif THIS_HOST[:6] == 'dltest':
DEF_SERVICE_ROOT = "https://dltest.datalab.noirlab.edu"
elif THIS_HOST[:5] == 'gp12':
DEF_SERVICE_ROOT = "http://gp06.datalab.noirlab.edu:6998"
# Allow the service URL for dev/test systems to override the default.
sock = socket.socket(type=socket.SOCK_DGRAM) # host IP address
sock.connect(('8.8.8.8', 1)) # Example IP address, see RFC 5737
THIS_IP, _ = sock.getsockname()
DEF_SERVICE_URL = DEF_SERVICE_ROOT + "/spec"
SM_SERVICE_URL = DEF_SERVICE_ROOT + "/storage"
QM_SERVICE_URL = DEF_SERVICE_ROOT + "/query"
# Use cURL for requests when possible.
USE_CURL = True
# The requested service "profile". A profile refers to the specific
# machines and services used by the service.
DEF_SERVICE_PROFILE = "default"
# The requested dataset "context". A context refers to the specific dataset
# being served. This determines what is allowed within certain methods.
DEF_SERVICE_CONTEXT = "default"
# Use a /tmp/AM_DEBUG file as a way to turn on debugging in the client code.
DEBUG = os.path.isfile('/tmp/SPEC_DEBUG')
VERBOSE = os.path.isfile('/tmp/SPEC_VERBOSE')
# ######################################################################
#
# Spectroscopic Data Client Interface
#
# This API provides convenience methods that allow an application to
# import the Client class without having to explicitly instantiate a
# class object. The parameter descriptions and example usage is given
# in the comments for the class methods. Module methods have their
# docstrings patched below.
#
# ######################################################################
# ###################################
# Spectroscopic Data error class
# ###################################
class dlSpecError(Exception):
'''A throwable error class.
'''
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
# ###################################
# Py2/Py3 Compatability Utilities
# ###################################
def spcToString(s):
'''spcToString -- Force a return value to be type 'string' for all
Python versions.
'''
if is_py3:
if isinstance(s, bytes):
strval = str(s.decode())
elif isinstance(s, str):
strval = s
else:
if isinstance(s, bytes) or isinstance(s, unicode):
strval = str(s)
else:
strval = s
return strval
# -----------------------------
# Utility Methods
# -----------------------------
# --------------------------------------------------------------------
# SET_SVC_URL -- Set the ServiceURL to call.
#
def set_svc_url(svc_url):
return sp_client.set_svc_url(svc_url.strip('/'))
# --------------------------------------------------------------------
# GET_SVC_URL -- Get the ServiceURL to call.
#
def get_svc_url():
return sp_client.get_svc_url()
# --------------------------------------------------------------------
# SET_PROFILE -- Set the service profile to use.
#
def set_profile(profile):
return sp_client.set_profile(profile)
# --------------------------------------------------------------------
# GET_PROFILE -- Get the service profile to use.
#
def get_profile():
return sp_client.get_profile()
# --------------------------------------------------------------------
# SET_CONTEXT -- Set the dataset context to use.
#
def set_context(context):
return sp_client.set_context(context)
# --------------------------------------------------------------------
# GET_CONTEXT -- Get the dataset context to use.
#
def get_context():
return sp_client.get_context()
# --------------------------------------------------------------------
# ISALIVE -- Ping the service to see if it responds.
#
def isAlive(svc_url=DEF_SERVICE_URL, timeout=5):
return sp_client.isAlive(svc_url=svc_url, timeout=timeout)
# --------------------------------------------------------------------
# LIST_PROFILES -- List the available service profiles.
#
@multimethod('spc', 1, False)
def list_profiles(profile, fmt='text'):
return sp_client._list_profiles(profile=profile, fmt=fmt)
@multimethod('spc', 0, False)
def list_profiles(profile=None, fmt='text'):
'''Retrieve the profiles supported by the spectro data service.
Usage:
list_profiles ([profile], fmt='text')
MultiMethod Usage:
------------------
specClient.list_profiles (profile)
specClient.list_profiles ()
Parameters
----------
profile: str
A specific profile configuration to list. If None, a list of
available profiles is returned.
format: str
Result format: One of 'text' or 'json'
Returns
-------
profiles: list/dict
A list of the names of the supported profiles or a dictionary of
the specific profile
Example
-------
.. code-block:: python
profiles = specClient.list_profiles(profile)
profiles = specClient.list_profiles()
'''
return sp_client._list_profiles(profile=profile, fmt=fmt)
# --------------------------------------------------------------------
# LIST_CONTEXTS -- List the available dataset contexts.
#
@multimethod('spc',1,False)
def list_contexts(context, fmt='text'):
return sp_client._list_contexts(context=context, fmt=fmt)
@multimethod('spc',0,False)
def list_contexts(context=None, fmt='text'):
'''Retrieve the contexts supported by the spectro data service.
Usage:
list_contexts ([context], fmt='text')
MultiMethod Usage:
------------------
specClient.list_contexts (context)
specClient.list_contexts ()
Parameters
----------
contexts: str
A specific contexts configuration to list. If None, a list of
available contexts is returned.
format: str
Result format: One of 'text' or 'json'
Returns
-------
contexts: list/dict
A list of the names of the supported contexts or a dictionary of
the specific contexts
Example
-------
.. code-block:: python
contexts = specClient.list_contexts(context)
contexts = specClient.list_contexts()
'''
return sp_client._list_contexts(context=context, fmt=fmt)
# --------------------------------------------------------------------
# CATALOGS -- List available catalogs for a given dataset context
#
def catalogs(context='default', profile='default', fmt='text'):
'''List available catalogs for a given dataset context
'''
return sp_client.catalogs(context=context, profile=profile, fmt=fmt)
# --------------------------------------------------------------------
# TO_SPECTRUM1D -- Utility method to convert a Numpy array to Spectrum1D
#
def to_Spectrum1D(npy_data):
'''Utility method to convert a Numpy array to Spectrum1D
'''
return sp_client.to_Spectrum1D(npy_data)
# --------------------------------------------------------------------
# TO_PANDAS -- Utility method to convert a Numpy array to a Pandas DataFrame
#
def to_pandas(npy_data):
'''Utility method to convert a Numpy array to a Pandas DataFrame
'''
return sp_client.to_pandas(npy_data)
# --------------------------------------------------------------------
# TO_TABLE -- Utility method to convert a Numpy array to an Astropy Table
#
def to_Table(npy_data):
'''Utility method to convert a Numpy array to an Astropy Table object.
'''
return sp_client.to_Table(npy_data)
#######################################
# Spectroscopic Data Client Methods
#######################################
# --------------------------------------------------------------------
# QUERY -- Query for spectra by position.
#
@multimethod('spc',3,False)
def query(ra, dec, size, constraint=None, out=None,
context=None, profile=None, **kw):
return sp_client._query(ra=ra, dec=dec, size=size,
pos=None,
region=None,
constraint=constraint,
out=out,
context=context, profile=profile, **kw)
@multimethod('spc',2,False)
def query(pos, size, constraint=None, out=None,
context=None, profile=None, **kw):
return sp_client._query(ra=None, dec=None, size=size,
pos=pos,
region=None,
constraint=constraint,
out=out,
context=context, profile=profile, **kw)
@multimethod('spc',1,False)
def query(region, constraint=None, out=None,
context=None, profile=None, **kw):
return sp_client._query(ra=None, dec=None, size=None,
pos=None,
region=region,
constraint=constraint,
out=out,
context=context, profile=profile, **kw)
@multimethod('spc',0,False)
def query(constraint=None, out=None, context=None, profile=None, **kw):
'''Query for a list of spectrum IDs that can then be retrieved from
the service.
Usage:
id_list = query(ra, dec, size, constraint=None, out=None,
context=None, profile=None, **kw)
id_list = query(pos, size, constraint=None, out=None,
context=None, profile=None, **kw)
id_list = query(region, constraint=None, out=None,
context=None, profile=None, **kw)
id_list = query(constraint=None, out=None,
context=None, profile=None, **kw)
Parameters
----------
ra: float
RA search center specified in degrees.
dec: float
Dec of search center specified in degrees.
size: float
Size of search center specified in degrees.
pos: Astropy Coord object
Coordinate of search center specified as an Astropy Coord object.
region: float
Array of polygon vertices (in degrees) defining a search region.
constraint: str
A valid SQL syntax that can be used as a WHERE constraint in the
search query.
out: str
Output filename to create. If None or an empty string the query
results are returned directly to the client. Otherwise, results
are writeen to the named file with one identifier per line. A
Data Lab 'vos://' prefix will save results to the named virtual
storage file.
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
For context='sdss_dr16' | 'default':
fields:
specobjid # or 'bestobjid', etc
tuple # a plate/mjd/fiber tuple
Service will always return array of 'specobjid'
value, the p/m/f tuple is extracted from the
bitmask value by the client.
catalog:
<schema>.<table> # alternative catalog to query e.g. a
# VAC from earlier DR (must support an
# ra/dec search and return a specobjid-
# like value)
For all contexts:
verbose = False
Print verbose messages during retrieval
debug = False
Print debug messages during retrieval
Returns
-------
result: array
An array of spectrum IDs appropriate for the dataset context.
Example
-------
1) Query by position:
.. code-block:: python
id_list = spec.query (0.125, 12.123, 0.1)
'''
return sp_client._query(ra=None, dec=None, size=None,
pos=None,
region=None,
constraint=constraint,
out=out,
context=context, profile=profile, **kw)
# --------------------------------------------------------------------
# GETSPEC -- Retrieve spectra for a list of objects.
#
def getSpec(id_list, fmt='numpy', out=None, align=False, cutout=None,
context=None, profile=None, **kw):
'''Get spectra for a list of object IDs.
Usage:
getSpec(id_list, fmt='numpy', out=None, align=False, cutout=None,
context=None, profile=None, **kw)
Parameters
----------
id_list: list object
List of object identifiers.
fmt: str
Return format of spectra
out:
Output file or return to caller if None
align:
Align spectra to common wavelength grid with zero-padding
cutout:
Wavelength cutout range (as "<start>-<end>")
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
values = None
Spectrum vectors to return.
token = None
Data Lab auth token.
id_col = None
Name of ID column in input table.
verbose = False
Print verbose messages during retrieval
debug = False
Print debug messages during retrieval
Returns
-------
result: object or array of objects or 'OK' string
Example
-------
1) Retrieve spectra individually:
.. code-block:: python
id_list = spec.query (0.125, 12.123, 0.1)
for id in id_list:
spec = spec.getSpec (id)
.... do something
2) Retrieve spectra in bulk:
.. code-block:: python
spec = spec.getSpec (id_list, fmt='numpy')
.... 'spec' is an array of NumPy objects that may be
different sizes
'''
return sp_client.getSpec(id_list=id_list, fmt=fmt, out=out,
align=align, cutout=cutout,
context=context, profile=profile, **kw)
# --------------------------------------------------------------------
# PLOT -- Utility to batch plot a single spectrum, display plot directly.
#
def plot(spec, context=None, profile=None, out=None, **kw):
'''Utility to batch plot a single spectrum.
Usage:
spec.plot(id, context=None, profile=None, **kw)
Parameters
----------
spec: object ID or data array
Spectrum to be plotted. If 'spec' is a numpy array or a
Spectrum1D object the data are plotted directly, otherwise
the value is assumed to be an object ID that will be retrieved
from the service.
out: str
Output filename. If specified, plot saved as PNG.
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
rest_frame - Whether or not to plot the spectra in the
rest-frame (def: True)
z - Redshift value
xlim - Set the xrange of the plot
ylim - Set the yrange of the plot
values - A comma-delimited string of which values to plot,
a combination of 'flux,model,sky,ivar'
mark_lines - Which lines to mark. No lines marked if None or
an empty string, otherwise one of 'em|abs|all|both'
grid - Plot grid lines (def: True)
dark - Dark-mode plot colors (def: True)
em_lines - List of emission lines to plot. If not given,
all the lines in the default list will be plotted.
abs_lines - Lines of absorption lines to plot. If not given,
all the lines in the default list will be plotted.
spec_args - Plotting kwargs for the spectrum
model_args - Plotting kwargs for the model
ivar_args - Plotting kwargs for the ivar
sky_args - Plotting kwargs for the sky
Returns
-------
Nothing
Example
-------
1) Plot a single spectrum, save to a virtual storage file
.. code-block:: python
spec.plot (specID, context='sdss_dr16', out='vos://spec.png')
'''
return sp_client.plot(spec, context=context, profile=profile,
out=None, **kw)
# --------------------------------------------------------------------
# PROSPECT -- Utility wrapper to launch the interactive PROSPECT tool.
#
def prospect(spec, context=None, profile=None, **kw):
'''Utility wrapper to launch the interactive PROSPECT tool.
Usage:
stat = prospect(spec, context=None, profile=None, **kw)
Parameters
----------
spec: object ID or data array
Spectrum to be plotted. If 'spec' is a numpy array or a
Spectrum1D object the data are plotted directly, otherwise
the value is assumed to be an object ID that will be retrieved
from the service.
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
TBD
Returns
-------
result: str
Status 'OK' string or error message.
Example
-------
1) Plot ....
.. code-block:: python
stat = spec.prospect (specID)
'''
pass
# --------------------------------------------------------------------
# PREVIEW -- Get a preview plot of a spectrum
#
def preview(spec, context=None, profile=None, **kw):
'''Get a preview plot of a spectrum
Usage:
spec.preview(spec, context=None, profile=None, **kw):
Parameters
----------
id_list: list object
List of object identifiers.
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
N/A
Returns
-------
image: A PNG image object
Example
-------
1) Display a preview plot a given spectrum:
.. code-block:: python
from IPython.display import display, Image
display(Image(spec.preview(id),
format='png', width=400, height=100, unconfined=True))
'''
pass
return sp_client.preview(spec, context=context, profile=profile, **kw)
# --------------------------------------------------------------------
# PLOTGRID -- Get a grid of preview plots of a spectrum list.
#
def plotGrid(id_list, nx, ny, page=0, context=None, profile=None, **kw):
'''Get a grid of preview plots of a spectrum list.
Usage:
image = plotGrid(id_list, nx, ny, page=0,
context=None, profile=None, **kw):
Parameters
----------
id_list: list object
List of object identifiers.
nx: int
Number of plots in the X dimension
ny: int
Number of plots in the Y dimension
page: int
Dataset context.
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
verbose = False
Print verbose messages during retrieval
debug = False
Print debug messages during retrieval
Returns
-------
image: A PNG image object
Example
-------
1) Display a 5x5 grid of preview plots for a list:
.. code-block:: python
npages = np.round((len(id_list) / 25) + (25 / len(id_list))
for pg in range(npages):
data = spec.getGridPlot(id_list, 5, 5, page=pg)
display(Image(data, format='png',
width=400, height=100, unconfined=True))
'''
return sp_client.plotGrid(id_list, nx, ny, page=page,
context=context, profile=profile, **kw)
# --------------------------------------------------------------------
# STACKEDIMAGE -- Get a stacked image of a list of spectra.
#
def stackedImage(id_list, align=False, yflip=False,
context=None, profile=None, **kw):
'''Get ...
Usage:
Parameters
----------
id_list: list object
List of spectrum identifiers.
context: str
Dataset context.
profile: str
Data service profile.
**kw: dict
Optional keyword arguments. Supported keywords currently include:
verbose = False
Print verbose messages during retrieval
debug = False
Print debug messages during retrieval
Returns
-------
result: ....
Example
-------
1) Query ....
.. code-block:: python
id_list = spec.query (0.125, 12.123, 0.1)
'''
pass
return sp_client.stackedImage(id_list, align=align, yflip=yflip,
context=context, profile=profile, **kw)
#######################################
# Spectroscopic Data Client Class
#######################################
class specClient(object):
'''
SPECCLIENT -- Client-side methods to access the Data Lab
Spectroscopic Data Service.
'''
def __init__(self, context='default', profile='default'):
'''Initialize the specClient class.
'''
self.svc_url = DEF_SERVICE_URL # service URL
self.qm_svc_url = QM_SERVICE_URL # Query Manager service URL
self.sm_svc_url = SM_SERVICE_URL # Storage Manager service URL
self.auth_token = def_token(None) # default auth token (not used)
self.svc_profile = profile # service profile
self.svc_context = context # dataset context
self.hostip = THIS_IP
self.hostname = THIS_HOST
self.debug = DEBUG # interface debug flag
self.verbose = VERBOSE # interface verbose flag
# Get the server-side config for the context. Note this must also
# be updated whenever we do a set_svc_url() or set_context().
self.context = self._list_contexts(context)
# Standard Data Lab service methods.
#
def set_svc_url(self, svc_url):
'''Set the URL of the Spectroscopic Data Service to be used.
Parameters
----------
svc_url: str
Spectroscopic Data service base URL to call.
Returns
-------
Nothing
Example
-------
.. code-block:: python
from dl import specClient
specClient.set_svc_url("http://localhost:7001/")
'''
self.svc_url = spcToString(svc_url.strip('/'))
self.context = self._list_contexts(context=self.svc_context)
def get_svc_url(self):
'''Return the currently-used Spectroscopic Data Service URL.
Parameters
----------
None
Returns
-------
service_url: str
The currently-used Spectroscopic Data Service URL.
Example
-------
.. code-block:: python
from dl import specClient
service_url = specClient.get_svc_url()
'''
return spcToString(self.svc_url)
def set_profile(self, profile):
'''Set the requested service profile.
Parameters
----------
profile: str
Requested service profile string.
Returns
-------
Nothing
Example
-------
.. code-block:: python
from dl import specClient
profile = specClient.client.set_profile("dev")
'''
url = self.svc_url + '/validate?what=profile&value=%s' % profile
if spcToString(self.curl_get(url)) == 'OK':
self.svc_profile = spcToString(profile)
return 'OK'
else:
raise Exception('Invalid profile "%s"' % profile)
return 'OK'
def get_profile(self):
'''Get the requested service profile.
Parameters
----------
None
Returns
-------
profile: str
The currently requested service profile.
Example
-------
.. code-block:: python
from dl import specClient
profile = specClient.client.get_profile()
'''
return spcToString(self.svc_profile)
def set_context(self, context):
'''Set the requested dataset context.
Parameters
----------
context: str
Requested dataset context string.
Returns
-------
Nothing
Example
-------
.. code-block:: python
from dl import specClient
context = specClient.client.set_context("dev")
'''
url = self.svc_url + '/validate?what=context&value=%s' % context
if spcToString(self.curl_get(url)) == 'OK':