-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
217 lines (189 loc) · 9.41 KB
/
main.py
File metadata and controls
217 lines (189 loc) · 9.41 KB
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
import wx
import wx.lib.scrolledpanel as scrolled
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use("WXAgg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
class FilterRow(wx.Panel):
def __init__(self, parent, columns, datasets, remove_callback):
super().__init__(parent)
self.remove_callback = remove_callback
self.datasets = datasets
s = wx.BoxSizer(wx.HORIZONTAL)
self.col = wx.ComboBox(self, choices=columns, style=wx.CB_READONLY)
self.op = wx.ComboBox(self, choices=["==", "!=", "<", ">", "<=", ">=", "contains"], style=wx.CB_READONLY)
self.val = wx.ComboBox(self, style=wx.CB_DROPDOWN)
rem = wx.Button(self, label="X", size=(25, 25))
s.Add(self.col, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2)
s.Add(self.op, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2)
s.Add(self.val, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2)
s.Add(rem, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2)
self.SetSizer(s)
self.col.Bind(wx.EVT_COMBOBOX, self.update_unique_values)
rem.Bind(wx.EVT_BUTTON, self.on_remove)
def update_unique_values(self, event):
column_name = self.col.GetValue()
unique_vals = set()
for df in self.datasets.values():
if column_name in df.columns:
unique_vals.update(df[column_name].dropna().unique().astype(str))
self.val.Set(sorted(list(unique_vals))[:1000]) # Limite para evitar lag
def on_remove(self, event):
self.remove_callback(self)
self.Destroy()
def get_expression(self):
c, o, v = self.col.GetValue(), self.op.GetValue(), self.val.GetValue()
if not c or not o or v == "": return None
col_esc = f"`{c}`"
if o == "contains": return f"{col_esc}.astype(str).str.contains('{v}')"
try:
float(v)
return f"{col_esc}{o}{v}"
except: return f"{col_esc}{o}'{v}'"
class App(wx.Frame):
def __init__(self):
super().__init__(None, title="Scientific Data Analyzer", size=(1400, 900))
self.datasets = {}
panel = wx.Panel(self)
self.main_sizer = wx.BoxSizer(wx.HORIZONTAL)
# --- SIDEBAR ---
sidebar = wx.Panel(panel)
sidebar.SetMinSize((380, -1))
side_sizer = wx.BoxSizer(wx.VERTICAL)
load_btn = wx.Button(sidebar, label="LOAD CSV")
load_btn.Bind(wx.EVT_BUTTON, self.on_load_csv)
self.meta_text = wx.TextCtrl(sidebar, style=wx.TE_MULTILINE|wx.TE_READONLY, size=(-1, 120))
self.nb = wx.Notebook(sidebar)
# 1D: Ahora es un plano XY (Líneas/Puntos)
self.tab1d = self.create_dim_tab(self.nb, ["X Axis", "Y Axis", "Color (Optional)"])
# 2D: Ahora es Heatmap (X, Y, Intensidad)
self.tab_heat = self.create_dim_tab(self.nb, ["X (Grid)", "Y (Grid)", "Intensity (Z)"])
# 3D: Volumétrico
self.tab3d = self.create_dim_tab(self.nb, ["X", "Y", "Z", "Color"])
self.nb.AddPage(self.tab1d, "1D (Plot XY)")
self.nb.AddPage(self.tab_heat, "2D (Heatmap)")
self.nb.AddPage(self.tab3d, "3D (Scatter)")
self.plot_btn = wx.Button(sidebar, label="GENERATE VISUALIZATION")
self.plot_btn.SetBackgroundColour(wx.Colour(180, 220, 255))
self.plot_btn.Bind(wx.EVT_BUTTON, self.on_plot_request)
side_sizer.Add(load_btn, 0, wx.EXPAND|wx.ALL, 5)
side_sizer.Add(self.meta_text, 0, wx.EXPAND|wx.ALL, 5)
side_sizer.Add(self.nb, 1, wx.EXPAND|wx.ALL, 5)
side_sizer.Add(self.plot_btn, 0, wx.EXPAND|wx.ALL, 10)
sidebar.SetSizer(side_sizer)
# --- CANVAS ---
self.fig = plt.Figure()
self.canvas = Canvas(panel, -1, self.fig)
self.main_sizer.Add(sidebar, 0, wx.EXPAND)
self.main_sizer.Add(self.canvas, 1, wx.EXPAND)
panel.SetSizer(self.main_sizer)
self.Show()
def create_dim_tab(self, parent, axes_list):
tab = wx.Panel(parent)
sizer = wx.BoxSizer(wx.VERTICAL)
tab.file_list = wx.CheckListBox(tab, size=(-1, 80))
sizer.Add(wx.StaticText(tab, label="Files (Overlays):"), 0, wx.TOP|wx.LEFT, 5)
sizer.Add(tab.file_list, 0, wx.EXPAND|wx.ALL, 5)
tab.controls = {}
grid = wx.FlexGridSizer(len(axes_list), 2, 5, 5)
grid.AddGrowableCol(1, 1)
for ax in axes_list:
grid.Add(wx.StaticText(tab, label=f"{ax}:"), 0, wx.ALIGN_CENTER_VERTICAL)
cb = wx.ComboBox(tab, style=wx.CB_READONLY)
grid.Add(cb, 1, wx.EXPAND)
tab.controls[ax] = cb
sizer.Add(grid, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(wx.StaticLine(tab), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
add_f_btn = wx.Button(tab, label="+ Add Filter")
tab.filter_panel = scrolled.ScrolledPanel(tab, size=(-1, 180))
tab.filter_sizer = wx.BoxSizer(wx.VERTICAL)
tab.filter_panel.SetSizer(tab.filter_sizer)
tab.filter_panel.SetupScrolling()
tab.filters = []
sizer.Add(add_f_btn, 0, wx.EXPAND|wx.ALL, 2)
sizer.Add(tab.filter_panel, 1, wx.EXPAND|wx.ALL, 5)
tab.SetSizer(sizer)
add_f_btn.Bind(wx.EVT_BUTTON, lambda e: self.add_filter_row(tab))
return tab
def add_filter_row(self, tab):
all_cols = sorted(list(set([c for df in self.datasets.values() for c in df.columns])))
row = FilterRow(tab.filter_panel, all_cols, self.datasets, lambda r: self.remove_filter_row(tab, r))
tab.filter_sizer.Add(row, 0, wx.EXPAND)
tab.filters.append(row)
tab.filter_panel.Layout()
tab.filter_panel.SetupScrolling()
def remove_filter_row(self, tab, row):
if row in tab.filters: tab.filters.remove(row)
tab.filter_panel.Layout()
def on_load_csv(self, event):
dlg = wx.FileDialog(self, "Open CSV", "", "", "CSV files (*.csv)|*.csv", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
name = path.split('\\')[-1]
df = pd.read_csv(path)
self.datasets[name] = df
summary = f"File: {name}\nRows: {df.shape[0]}\nCols: {df.shape[1]}\n" + "-"*20 + "\n"
for col in df.columns:
summary += f"[{col}]: {df[col].dtype}\n"
self.meta_text.SetValue(summary)
all_cols = sorted(list(set([c for d in self.datasets.values() for c in d.columns])))
for tab in [self.tab1d, self.tab_heat, self.tab3d]:
if name not in tab.file_list.GetItems(): tab.file_list.Append(name)
for cb in tab.controls.values(): cb.Set(all_cols)
def apply_filters(self, tab, df):
queries = [f.get_expression() for f in tab.filters if f.get_expression() and f.col.GetValue() in df.columns]
if not queries: return df
try: return df.query(" and ".join(queries))
except: return df
def on_plot_request(self, event):
idx = self.nb.GetSelection()
tab = [self.tab1d, self.tab_heat, self.tab3d][idx]
selected = [tab.file_list.GetString(i) for i in tab.file_list.GetCheckedItems()]
if not selected: return
self.fig.clf()
if idx == 0: self.draw_1d(tab, selected)
elif idx == 1: self.draw_heatmap(tab, selected)
elif idx == 2: self.draw_3d(tab, selected)
self.canvas.draw()
def draw_1d(self, tab, names):
x_col = tab.controls["X Axis"].GetValue()
y_col = tab.controls["Y Axis"].GetValue()
c_col = tab.controls["Color (Optional)"].GetValue()
if not x_col or not y_col: return
ax = self.fig.add_subplot(111)
for name in names:
df = self.apply_filters(tab, self.datasets[name]).sort_values(by=x_col)
if x_col in df.columns and y_col in df.columns:
ax.plot(df[x_col], df[df.columns[df.columns.get_loc(y_col)]], label=name, marker='o', markersize=2)
ax.set_xlabel(x_col); ax.set_ylabel(y_col); ax.legend()
def draw_heatmap(self, tab, names):
x_col = tab.controls["X (Grid)"].GetValue()
y_col = tab.controls["Y (Grid)"].GetValue()
z_col = tab.controls["Intensity (Z)"].GetValue()
if not x_col or not y_col or not z_col: return
ax = self.fig.add_subplot(111)
for name in names:
df = self.apply_filters(tab, self.datasets[name])
# Pivot para crear matriz de heatmap
try:
pivot = df.pivot_table(index=y_col, columns=x_col, values=z_col, aggfunc='mean')
im = ax.imshow(pivot, origin='lower', extent=[df[x_col].min(), df[x_col].max(), df[y_col].min(), df[y_col].max()], aspect='auto', cmap='viridis')
self.fig.colorbar(im, ax=ax, label=z_col)
except: pass
ax.set_xlabel(x_col); ax.set_ylabel(y_col)
def draw_3d(self, tab, names):
x, y, z = tab.controls["X"].GetValue(), tab.controls["Y"].GetValue(), tab.controls["Z"].GetValue()
c_col = tab.controls["Color"].GetValue()
if not x or not y or not z: return
ax = self.fig.add_subplot(111, projection='3d')
for name in names:
df = self.apply_filters(tab, self.datasets[name])
c = df[c_col] if c_col in df.columns else None
ax.scatter(df[x], df[y], df[z], c=c, label=name, s=10, alpha=0.7)
ax.set_xlabel(x); ax.set_ylabel(y); ax.set_zlabel(z); ax.legend()
if __name__ == "__main__":
app = wx.App(False)
App()
app.MainLoop()