-
Notifications
You must be signed in to change notification settings - Fork 28
/
data.py
177 lines (136 loc) · 4.89 KB
/
data.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
from dataclasses import dataclass, field
from typing import Tuple
import autograd.numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from ..base.design import DesignSpace
@dataclass
class Data:
"""Class that contains data
:param data: data stored in a DataFrame
:param design: designspace
"""
design: DesignSpace
data: pd.DataFrame = field(init=False)
def __post_init__(self):
self.data = self.design.get_empty_dataframe()
def reset_data(self):
"""Reset the dataframe to an empty dataframe with the appropriate input and output columns"""
self.__post_init__()
def show(self):
"""Print the data to the console"""
print(self.data)
return
def add(self, data: pd.DataFrame, ignore_index: bool = False):
"""Add data
Parameters
----------
data
data to append
ignore_index, optional
whether to ignore the indices of the appended dataframe
"""
self.data = pd.concat([self.data, data], ignore_index=ignore_index)
# Apparently you need to cast the types again
# TODO: Breaks if values are NaN or infinite
self.data = self.data.astype(self.design._cast_types_dataframe(self.design.input_space, "input"))
self.data = self.data.astype(self.design._cast_types_dataframe(self.design.output_space, "output"))
def add_output(self, output: np.ndarray, label: str = "y"):
"""Add a numpy array to the output column of the dataframe
Parameters
----------
output
Output data
label, optional
label of the output column to add to
"""
self.data[("output", label)] = output
def add_numpy_arrays(self, input: np.ndarray, output: np.ndarray):
"""Append a numpy array to the datafram
Parameters
----------
input
2d numpy array added to input data
output
2d numpy array added to output data
"""
df = pd.DataFrame(np.hstack((input, output)), columns=self.data.columns)
self.add(df, ignore_index=True)
def remove_rows_bottom(self, number_of_rows: int):
"""Remove a number of rows from the end of the Dataframe
Parameters
----------
number_of_rows
number of rows to remove from the bottom
"""
if number_of_rows == 0:
return # Don't do anything if 0 rows need to be removed
self.data = self.data.iloc[:-number_of_rows]
def get_input_data(self) -> pd.DataFrame:
"""Get the input data
Returns
-------
DataFrame containing only the input data
"""
return self.data["input"]
def get_output_data(self) -> pd.DataFrame:
"""Get the output data
Returns
-------
DataFrame containing only the output data
"""
return self.data["output"]
def get_n_best_output_samples(self, nosamples: int) -> pd.DataFrame:
"""Returns the n lowest rows of the dataframe. Values are compared to the output columns
Parameters
----------
nosamples :
number of samples
Returns
-------
pd.DataFrame
Dataframe containing the n best samples
"""
return self.data.nsmallest(n=nosamples, columns=self.design.get_output_names())
def get_n_best_input_parameters_numpy(self, nosamples: int) -> np.ndarray:
"""Returns the input vector in numpoy array format of the n best samples
Parameters
----------
nosamples
number of samples
Returns
-------
numpy array containing the n best input parameters
"""
return self.get_n_best_output_samples(nosamples)["input"].to_numpy()
def get_number_of_datapoints(self) -> int:
"""Get the total number of datapoints
Returns
-------
total number of datapoints
"""
return len(self.data)
def plot(self, input_par1: str, input_par2: str = None) -> Tuple[plt.Figure, plt.Axes]:
"""Plot the data of two parameters in a figure
Parameters
----------
input_par1
name of first parameter (x-axis)
input_par2
name of second parameter (x-axis)
Returns
-------
Matplotlib figure and axes
"""
fig, ax = plt.figure(), plt.axes()
ax.scatter(self.data[("input", input_par1)], self.data[("input", input_par2)], s=3)
ax.set_xlabel(input_par1)
ax.set_ylabel(input_par2)
return fig, ax
def plot_pairs(self):
"""
Plot a matrix of 2D plots that visualize the spread of the samples for each dimension.
Requires seaborn to be installed.
"""
import seaborn as sb
sb.pairplot(data=self.get_input_data())