-
Notifications
You must be signed in to change notification settings - Fork 0
/
speclib.py
120 lines (94 loc) · 3.49 KB
/
speclib.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
# -*- coding:utf-8 -*-
'''
# File: speclib.py
# Project: /Users/li/work_github/pkgspc
# Created Date: 2022/12/01
# Author: ssdxj
# -----
# Last Modified: 2022/12/23 23:27:57
# Modified By: ssdxj ([email protected]) at mac.local
# -----
# HISTORY:
# Date By Comments
# ------------ ----- -------------------------------------------------
'''
import pandas as pd
import numpy.typing as npt
import numpy as np
import re
class Speclib:
def __init__(self, fpath) -> None:
self._fpath = fpath
self._wavelength, self._wavelength_name, self._reflectance, self._meta = self._load_csv(
fpath)
@property
def wavelength(self) -> npt.ArrayLike:
return self._wavelength
@property
def wavelength_name(self) -> npt.ArrayLike:
return self._wavelength_name
@property
def reflectance(self) -> pd.DataFrame:
return self._reflectance
@property
def meta(self) -> pd.DataFrame:
return self._meta
@staticmethod
def _load_csv(fpath) -> tuple[npt.ArrayLike, npt.ArrayLike, pd.DataFrame, pd.DataFrame]:
"""Parse csv spectra data
Args:
fpath (str): csv file path in wide table format.
Returns:
tuple[npt.ArrayLike, npt.ArrayLike, npt.DataFrame, pd.DataFrame]: Wavelength array (1d), Wavelength name array (1d), reflectance dataframe, meta dataframe.
"""
df = pd.read_csv(fpath)
all_colnames = df.columns.values.tolist()
reflectance_columns = Speclib._extract_number_colnames(
all_colnames, False)
meta_colnames = Speclib._extract_number_colnames(all_colnames, True)
df_reflectance = df.loc[:, reflectance_columns]
df_meta = df.loc[:, meta_colnames]
wl = [float(x) for x in reflectance_columns]
return wl, reflectance_columns, df_reflectance, df_meta
@staticmethod
def _extract_number_colnames(colnames: npt.ArrayLike, reverse: bool = False) -> npt.ArrayLike:
"""Extract spectra or meta columns names from wide spectra table by RE.
Args:
colnames (npt.ArrayLike): Table column names.
reverse (bool, optional): False for spectra column names, while True for meta column names. Defaults to False.
Returns:
npt.ArrayLike: List of columns.
"""
if not reverse:
out = [x for x in colnames if re.match('^[0-9]+(\.[0-9]+)*', x)]
else:
out = [x for x in colnames if not re.match(
'^[0-9]+(\.[0-9]+)*', x)]
return out
def plot(self, index: list = None):
if index is None:
df = self.reflectance
alpha = 1/3
else:
df = self.reflectance.iloc[index, :]
alpha = 1
df.reset_index(inplace=True)
df = df.melt(id_vars="index", value_vars=self.wavelength_name)
# df.index = df.index.astype('category')
df.variable = [float(x) for x in df.variable]
p = ggplot(df, aes('variable', 'value', group='index'))
if index is None:
p += geom_line(alpha=1/3)
else:
p += geom_line(aes(color='factor(index)'), alpha=1)
p += labs(x='Wavelength(nm)', y='Reflectance')
p += theme_bw()
p += theme(
legend_title=element_blank(),
legend_position='top'
)
return p
# ----------------------------------- main ----------------------------------- #
fpath = "spc.csv"
spc = Speclib(fpath)
spc.plot(index=[1, 10, 20])