Skip to content

Commit 5f9d955

Browse files
committed
Refactoring spectra_parser to class
1 parent 596a818 commit 5f9d955

File tree

2 files changed

+119
-110
lines changed

2 files changed

+119
-110
lines changed

pyspecchio/specchio_db_interface.py

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def upload_dataframe(self, dataframe, campaign, hierarchy_id):
112112
be uploaded."""
113113
self.set_spectra_file_info()
114114

115-
def read_test_data(self):
115+
def read_test_data(self, filename, filepath):
116116
"""Opens and read the test csv spectra and metadata files into a
117117
numpy array"""
118118
with open(filepath + filename, 'r') as csvfile:
@@ -157,25 +157,11 @@ def add_pico_metadata_for_spectra(self, smd, metadata, spectra_index):
157157
"""Adds the spectrometer-specific metadata to the spectra file"""
158158
# Add plot number metaparameter
159159
for metadata_key in self.PICO_METADATA:
160-
mp = metaparam.newInstance(self.specchio_client.getAttributesNameHash().get(self.MAP_PICO_METADATA_SPECCHIONAME[metadata_key]))
160+
mp = metaparam.newInstance(
161+
self.specchio_client.getAttributesNameHash().get(
162+
self.MAP_PICO_METADATA_SPECCHIONAME[metadata_key]))
161163
mp.setValue(str(metadata[spectra_index][metadata_key]))
162-
smd.addEntry(mp)
163-
164-
"""Old
165-
mp = metaparam.newInstance(self.specchio_client.getAttributesNameHash().get('Target ID'))
166-
mp.setValue(str(metadata[spectra_index]['Plot']))
167-
smd.addEntry(mp)
168-
169-
# Add Nitrate metaparameter
170-
mp = metaparam.newInstance(self.specchio_client.getAttributesNameHash().get('Nitrate Nitrogen'))
171-
mp.setValue(metadata[spectra_index]['Nitrate Nitrogen Mg/Kg'])
172-
smd.addEntry(mp)
173-
174-
# Add Phosphorous metaparameter
175-
mp = metaparam.newInstance(self.specchio_client.getAttributesNameHash().get('Phosphorus'))
176-
mp.setValue(metadata[spectra_index]['Phosphorus %'])
177-
smd.addEntry(mp)
178-
"""
164+
smd.addEntry(mp)
179165

180166
def add_ancillary_metadata_for_spectra(self, smd, ancil_metadata, spectra_index):
181167
"""Adds the 'other' anciliary metadata, e.g. LAI, Soils etc to the
@@ -185,18 +171,21 @@ def add_ancillary_metadata_for_spectra(self, smd, ancil_metadata, spectra_index)
185171
This metadata comes from the parser_pandas module file, which parses
186172
the excel files and returns them as pandas dataframes, by data type,
187173
with the rows in each dataframe referring to the plot."""
188-
189-
190-
174+
for ancildata_key in self.MAP_ANCIL_METADATA_SPECCHIONAME.keys():
175+
mp = metaparam.newInstance(
176+
self.specchio_client.getAttributesNameHash().get(
177+
self.MAP_ANCIL_METADATA_SPECCHIONAME[ancildata_key]))
178+
mp.setValue(str(ancil_metadata[spectra_index][ancildata_key]))
179+
smd.addEntry(mp)
191180

192-
193181
def specchio_upload_pico_spectra(self, spectra_filename, spectra_filepath):
194182
"""Upload the PICO type spectra.
195183
196184
Remember, the specs are:
197185
2 sets of Up and Down spectra (four in total)
198186
Each have their own set of metadata
199187
"""
188+
specp.set_spectra_file(spectra_filename, spectra_filepath)
200189
# Create a spectra file object
201190
spspectra_file_obj = sptypes.SpectralFile()
202191
self.set_spectra_file_info(spspectra_file_obj, spectra_filename, spectra_filepath)
@@ -230,6 +219,7 @@ def specchio_upload_pico_spectra(self, spectra_filename, spectra_filepath):
230219
#=-=-=-=-=-=
231220
smd = sptypes.Metadata()
232221
self.add_pico_metadata_for_spectra(smd, metadata)
222+
#self.add_ancillary_metadata_for_spectra(smd, metadata)
233223
spspectra_file_obj.addEavMetadata(smd)
234224

235225
# Convert the spectra list to a suitable
@@ -243,6 +233,8 @@ def specchio_upload_pico_spectra(self, spectra_filename, spectra_filepath):
243233
def specchio_uploader_test(self, filename, filepath, subhierarchy, use_dummy_spectra=False):
244234
"""Uploader for the test data.
245235
236+
DEPRECATED
237+
246238
The following code takes the spectral file object and fills the spectral data
247239
into a Java array and the Metadata into a metadata object. The spectral file
248240
object is then stored in the database under the campaign and hierarchy we
@@ -255,7 +247,7 @@ def specchio_uploader_test(self, filename, filepath, subhierarchy, use_dummy_spe
255247
self.set_spectra_file_info(spspectra_file, filepath, filename)
256248

257249
# read test data
258-
wavelengths, spectra, metadata = self.read_test_data()
250+
wavelengths, spectra, metadata = self.read_test_data(filename, filepath)
259251

260252
# Now we can set the number of spectra
261253
spspectra_file.setNumberOfSpectra(np.size(spectra,1))
@@ -306,10 +298,15 @@ def specchio_uploader_test(self, filename, filepath, subhierarchy, use_dummy_spe
306298

307299
db_interface = specchioDBinterface("Python test campaign")
308300

309-
filepath = '/home/centos/Downloads/'
310-
filename = 'spectra.csv'
311-
subhierarchy = 'Pasture'
312-
db_interface.specchio_uploader_test(filename, filepath, subhierarchy)
301+
#filepath = '/home/centos/Downloads/'
302+
#filename = 'spectra.csv'
303+
304+
spectra_testpath = "/home/centos/Downloads/DATA/Spectra_dir/"
305+
spectra_file_test = "QEP1USB1_b000000_s000002_light.pico"
306+
307+
subhierarchy = 'PlotScale'
308+
309+
db_interface.specchio_upload_pico_spectra(spectra_filename=spectra_file_test, spectra_filepath=spectra_testpath)
313310

314311

315312

pyspecchio/spectra_parser.py

Lines changed: 94 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
This file takes the .pico spectrometer files and parses them to a numpy
77
or pandas
88
9-
@author: centos
9+
@author: Declan Valters
1010
"""
1111

1212
import json
@@ -15,84 +15,89 @@
1515

1616
import unittest
1717

18-
path = "/home/centos/Downloads/DATA/Spectra_dir/"
19-
spectra_file_test = "QEP1USB1_b000000_s000002_light.pico"
20-
21-
def read_json():
22-
"""Simple JSON reader"""
23-
with open(path + spectra_file_test, "r") as f:
24-
data = json.load(f)
25-
return data
26-
27-
def pandas_read_json():
28-
"""pandas read json to dataframe"""
29-
with open(path + spectra_file_test, "r") as f:
30-
data = json.load(f)
31-
dataframe = pd.DataFrame(data)
32-
return dataframe
33-
34-
def pandas_read_json_spectra():
35-
"""Normalise the results to get the spectra"""
36-
with open(path + spectra_file_test, "r") as f:
37-
data = json.load(f)
38-
result = json_normalize(data["Spectra"])
39-
return result
40-
41-
def pandas_read_json_str():
42-
"""Normalise the results to get the spectra"""
43-
with open(path + spectra_file_test, "r") as f:
44-
data = json.load(f)
45-
return data
46-
47-
def get_only_spectra_pixels():
48-
"""Get just the spectra pixels"""
49-
with open(path + spectra_file_test, "r") as f:
50-
data = json.load(f)
51-
result = json_normalize(data["Spectra"])
52-
return result["Pixels"]
53-
54-
def valid_spectra(spectra_num):
55-
"""Checks the index provided is a valid range for the spectrometer data
56-
"""
57-
return spectra_num in range(0,4)
58-
59-
def get_spectra_metadata(spectra_number):
60-
"""Returns the dict represtning the metadata from the spectra file.
61-
for ONE of the up/down pairs.
18+
class SpectraFile(object):
19+
SPECTRAFILE = "None"
20+
SPECTRA_PATH = "None"
6221

63-
Note the file layout is like this:
64-
65-
Upwelling Spectra [0]
66-
Upwelling Spectra [1]
67-
Downwelling Spectra [2]
68-
Downwelling Spectra [3]
22+
def set_spectra_file(self, spectra_filename, spectra_filepath):
23+
self.SPECTRA_PATH = spectra_filepath
24+
self.SPECTRAFILE = spectra_filename
25+
26+
def read_json(self, path, spectra_file):
27+
"""Simple JSON reader"""
28+
with open(path + spectra_file, "r") as f:
29+
data = json.load(f)
30+
return data
6931

70-
So to get the first upwelling spetra, 0 is used."""
71-
if not valid_spectra(spectra_number):
72-
raise IndexError("Not a valid spectra number for this spectrometer: [0-3]")
73-
whole_file = read_json()
74-
# File format has spectra which contains a list of dicts:
75-
# Metadata [0] and Pixels [1]
76-
return whole_file['Spectra'][spectra_number]['Metadata']
77-
78-
def get_spectra_pixels(spectra_number):
79-
"""Returns the dict represtning the metadata from the spectra file.
80-
for ONE of the up/down pairs.
32+
def pandas_read_json(self, path, spectra_file):
33+
"""pandas read json to dataframe"""
34+
with open(path + spectra_file, "r") as f:
35+
data = json.load(f)
36+
dataframe = pd.DataFrame(data)
37+
return dataframe
8138

82-
Note the file layout is like this:
39+
def pandas_read_json_spectra(self, path, spectra_file):
40+
"""Normalise the results to get the spectra"""
41+
with open(path + spectra_file, "r") as f:
42+
data = json.load(f)
43+
result = json_normalize(data["Spectra"])
44+
return result
45+
46+
def pandas_read_json_str(self, path, spectra_file):
47+
"""Normalise the results to get the spectra"""
48+
with open(path + spectra_file, "r") as f:
49+
data = json.load(f)
50+
return data
51+
52+
def get_only_spectra_pixels(self, path, spectra_file):
53+
"""Get just the spectra pixels"""
54+
with open(path + spectra_file, "r") as f:
55+
data = json.load(f)
56+
result = json_normalize(data["Spectra"])
57+
return result["Pixels"]
58+
59+
def valid_spectra(self, spectra_num):
60+
"""Checks the index provided is a valid range for the spectrometer data
61+
"""
62+
return spectra_num in range(0,4)
63+
64+
def get_spectra_metadata(self, spectra_number):
65+
"""Returns the dict represtning the metadata from the spectra file.
66+
for ONE of the up/down pairs.
8367
84-
Upwelling Spectra [0] len = 1044
85-
Upwelling Spectra [1] len = 2048
86-
Downwelling Spectra [2] len = 1044
87-
Downwelling Spectra [3] len = 2048
68+
Note the file layout is like this:
69+
70+
Upwelling Spectra [0]
71+
Upwelling Spectra [1]
72+
Downwelling Spectra [2]
73+
Downwelling Spectra [3]
74+
75+
So to get the first upwelling spetra, 0 is used."""
76+
if not self.valid_spectra(spectra_number):
77+
raise IndexError("Not a valid spectra number for this spectrometer: [0-3]")
78+
whole_file = self.read_json()
79+
# File format has spectra which contains a list of dicts:
80+
# Metadata [0] and Pixels [1]
81+
return whole_file['Spectra'][spectra_number]['Metadata']
8882

89-
So to get the first upwelling spetra, 0 is used."""
90-
if not valid_spectra(spectra_number):
91-
raise IndexError("Not a valid spectra number for this spectrometer: [0-3]")
92-
whole_file = read_json()
93-
# File format has spectra which contains a list of dicts:
94-
# Metadata [0] and Pixels [1]
95-
return whole_file['Spectra'][spectra_number]['Pixels']
83+
def get_spectra_pixels(self, spectra_number, path, filename):
84+
"""Returns the dict represtning the metadata from the spectra file.
85+
for ONE of the up/down pairs.
86+
87+
Note the file layout is like this:
88+
89+
Upwelling Spectra [0] len = 1044
90+
Upwelling Spectra [1] len = 2048
91+
Downwelling Spectra [2] len = 1044
92+
Downwelling Spectra [3] len = 2048
93+
94+
So to get the first upwelling spetra, 0 is used."""
95+
if not self.valid_spectra(spectra_number):
96+
raise IndexError("Not a valid spectra number for this spectrometer: [0-3]")
97+
whole_file = self.read_json(path, filename)
98+
# File format has spectra which contains a list of dicts:
99+
# Metadata [0] and Pixels [1]
100+
return whole_file['Spectra'][spectra_number]['Pixels']
96101

97102

98103
class spectra_metadata():
@@ -103,21 +108,28 @@ def __init__(self):
103108
class TestSpectraParser(unittest.TestCase):
104109

105110
def test_valid_sepctra(self):
111+
sf = SpectraFile()
106112
for x in range(0,4):
107-
self.assertTrue(valid_spectra(x))
113+
self.assertTrue(sf.valid_spectra(x))
108114

109115
def test_invalid_spectra(self):
116+
sf = SpectraFile()
110117
for item in [1.5, "foobar", 7, -2]:
111-
self.assertFalse(valid_spectra(item))
118+
self.assertFalse(sf.valid_spectra(item))
112119

113120
if __name__ == "__main__":
114121
unittest.main()
115122

116-
data1 = read_json()
117-
df = pandas_read_json()
118-
df1 = pandas_read_json_str()
119-
df2 = pandas_read_json_spectra() # This is getting all four spectra pairs (UP/DOWN)
120-
pixels = get_only_spectra_pixels()
121-
metadata_upwell_zero = get_spectra_metadata(0)
123+
sf = SpectraFile()
124+
125+
path = '/home/centos/Downloads/'
126+
filename = 'spectra.csv'
127+
128+
data1 = sf.read_json(path, filename)
129+
df = sf.pandas_read_json(path, filename)
130+
df1 = sf.pandas_read_json_str(path, filename)
131+
df2 = sf.pandas_read_json_spectra(path, filename) # This is getting all four spectra pairs (UP/DOWN)
132+
pixels = sf.get_only_spectra_pixels(path, filename)
133+
metadata_upwell_zero = sf.get_spectra_metadata(0)
122134

123135

0 commit comments

Comments
 (0)