diff --git a/pyproject.toml b/pyproject.toml index cb04945..e89ca70 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ classifiers = [ ] dependencies = [ + "h5py>=3.0.0", "lmfit>=1.0.3", "matplotlib>=3.8.0", "numpy>=1.26.1,<2.0", diff --git a/src/mpes_tools/__init__.py b/src/mpes_tools/__init__.py index 96a0f00..a424587 100644 --- a/src/mpes_tools/__init__.py +++ b/src/mpes_tools/__init__.py @@ -1,7 +1,9 @@ """mpes-tools module easy access APIs.""" import importlib.metadata -from .Arpes_gui import MainWindow +from mpes_tools.guis.gui_4D import MpesTool4D +from mpes_tools.guis.gui_3D import MpesTool3D +from mpes_tools.guis.gui_fitting import MpesToolFitting __version__ = importlib.metadata.version("mpes-tools") -__all__ = ["MainWindow"] \ No newline at end of file +__all__ = ["MpesTool4D", "MpesTool3D", "MpesToolFitting"] \ No newline at end of file diff --git a/src/mpes_tools/graphs2.py b/src/mpes_tools/guis/graphs2.py similarity index 100% rename from src/mpes_tools/graphs2.py rename to src/mpes_tools/guis/graphs2.py diff --git a/src/mpes_tools/additional_window.py b/src/mpes_tools/guis/gui_3D.py similarity index 97% rename from src/mpes_tools/additional_window.py rename to src/mpes_tools/guis/gui_3D.py index 2712b93..17b0b9e 100644 --- a/src/mpes_tools/additional_window.py +++ b/src/mpes_tools/guis/gui_3D.py @@ -6,13 +6,14 @@ from matplotlib.patches import Circle from matplotlib.lines import Line2D -from mpes_tools.fi_panel6 import MainWindow +from mpes_tools.guis.gui_fitting import MpesToolFitting import xarray as xr -# %matplotlib qt +import matplotlib +matplotlib.use('qtagg') -class GraphWindow(QMainWindow): +class MpesTool3D(QMainWindow): def __init__(self,data_array: xr.DataArray,t,dt): global t_final super().__init__() @@ -172,7 +173,7 @@ def plot_graph(self,t,dt): def fit_panel(self,event): print('forfit',len(self.plot),'axis',len(self.axis)) - graph_window= MainWindow( self.data_o, self.axis,self.square_coords[0][1], self.square_coords[1][1],self.t,self.dt) + graph_window= MpesToolFitting( self.data_o, self.axis,self.square_coords[0][1], self.square_coords[1][1],self.t,self.dt) graph_window.show() self.graph_windows.append(graph_window) diff --git a/src/mpes_tools/Arpes_gui.py b/src/mpes_tools/guis/gui_4D.py similarity index 94% rename from src/mpes_tools/Arpes_gui.py rename to src/mpes_tools/guis/gui_4D.py index 881f664..13e5dd9 100644 --- a/src/mpes_tools/Arpes_gui.py +++ b/src/mpes_tools/guis/gui_4D.py @@ -3,14 +3,14 @@ from PyQt5.QtCore import Qt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.pyplot as plt -import numpy as np -import h5py -from mpes_tools.additional_window import GraphWindow +from mpes_tools.guis.gui_3D import MpesTool3D import xarray as xr -from mpes_tools.hdf5 import load_h5 +from mpes_tools.io.hdf5 import load_h5 +import matplotlib +matplotlib.use('qtagg') -class MainWindow(QMainWindow): +class MpesTool4D(QMainWindow): def __init__(self): super().__init__() @@ -159,7 +159,7 @@ def open_graph_kxkydt(self): E1=self.data_array[self.axes[2]][self.slider1[0].value()].item() E2=self.data_array[self.axes[2]][self.slider1[0].value()+self.slider2[0].value()+1].item() data_kxkydt = self.data_array.loc[{self.axes[2]:slice(E1,E2)}].mean(dim=(self.axes[2])) - graph_window=GraphWindow(data_kxkydt, self.slider3[0].value(), self.slider4[0].value()) + graph_window=MpesTool3D(data_kxkydt, self.slider3[0].value(), self.slider4[0].value()) # Show the graph window graph_window.show() self.graph_windows.append(graph_window) @@ -168,7 +168,7 @@ def open_graph_kxedt(self): ky1=self.data_array[self.axes[1]][self.slider1[1].value()].item() ky2=self.data_array[self.axes[1]][self.slider1[1].value()+self.slider2[1].value()+1].item() data_kxedt = self.data_array.loc[{self.axes[1]:slice(ky1,ky2)}].mean(dim=(self.axes[1])) - graph_window = GraphWindow(data_kxedt, self.slider3[1].value(), self.slider4[1].value()) + graph_window = MpesTool3D(data_kxedt, self.slider3[1].value(), self.slider4[1].value()) # Show the graph window graph_window.show() self.graph_windows.append(graph_window) @@ -177,7 +177,7 @@ def open_graph_kyedt(self): kx1=self.data_array[self.axes[0]][self.slider1[2].value()].item() kx2=self.data_array[self.axes[0]][self.slider1[2].value()+self.slider2[2].value()+1].item() data_kyedt = self.data_array.loc[{self.axes[0]:slice(kx1,kx2)}].mean(dim=(self.axes[0])) - graph_window = GraphWindow(data_kyedt, self.slider3[2].value(), self.slider4[2].value()) + graph_window = MpesTool3D(data_kyedt, self.slider3[2].value(), self.slider4[2].value()) # Show the graph window graph_window.show() self.graph_windows.append(graph_window) @@ -299,6 +299,6 @@ def slider_changed(self, value): if __name__ == "__main__": app = QApplication(sys.argv) - window = MainWindow() + window = MpesTool4D() window.show() sys.exit(app.exec_()) diff --git a/src/mpes_tools/fi_panel6.py b/src/mpes_tools/guis/gui_fitting.py similarity index 96% rename from src/mpes_tools/fi_panel6.py rename to src/mpes_tools/guis/gui_fitting.py index 277384e..09fdfe7 100644 --- a/src/mpes_tools/fi_panel6.py +++ b/src/mpes_tools/guis/gui_fitting.py @@ -8,13 +8,15 @@ import numpy as np from lmfit import CompositeModel, Model import inspect -from .movable_vertical_cursors_graph import MovableCursors -from .make_model import make_model -from .graphs2 import showgraphs +from mpes_tools.tools.movable_vertical_cursors_graph import MovableCursors +from mpes_tools.tools.make_model import make_model +from mpes_tools.guis.graphs2 import showgraphs +import matplotlib +matplotlib.use('qtagg') -class MainWindow(QMainWindow): +class MpesToolFitting(QMainWindow): def __init__(self,data,axis,c1,c2,t,dt): super().__init__() @@ -692,6 +694,6 @@ def zero(x): if __name__ == "__main__": app = QApplication(sys.argv) - window = MainWindow() + window = MpesToolFitting() window.show() sys.exit(app.exec_()) diff --git a/src/mpes_tools/hdf5.py b/src/mpes_tools/io/hdf5.py similarity index 100% rename from src/mpes_tools/hdf5.py rename to src/mpes_tools/io/hdf5.py diff --git a/src/mpes_tools/make_model.py b/src/mpes_tools/tools/make_model.py similarity index 100% rename from src/mpes_tools/make_model.py rename to src/mpes_tools/tools/make_model.py diff --git a/src/mpes_tools/movable_vertical_cursors_graph.py b/src/mpes_tools/tools/movable_vertical_cursors_graph.py similarity index 100% rename from src/mpes_tools/movable_vertical_cursors_graph.py rename to src/mpes_tools/tools/movable_vertical_cursors_graph.py diff --git a/tests/Arpes_gui.py b/tests/Arpes_gui.py deleted file mode 100644 index 0270868..0000000 --- a/tests/Arpes_gui.py +++ /dev/null @@ -1,392 +0,0 @@ -import sys -from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QAction, QFileDialog, QSlider, QGridLayout,QHBoxLayout, QSizePolicy,QLabel -from PyQt5.QtCore import Qt -from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas -import matplotlib.pyplot as plt -import numpy as np -import h5py -from matplotlib.widgets import CheckButtons, Button -from matplotlib.patches import Circle -from matplotlib.lines import Line2D -from additional_window import GraphWindow -from color_scale import update_color -import xarray as xr -from Drawwindow import DrawWindow -from h5toxarray import h5toxarray_loader -# from k_path_4d_4 import drawKpath - -class MainWindow(QMainWindow): - def __init__(self): - super().__init__() - - self.setWindowTitle("Main Window") - self.setGeometry(100, 100, 800, 600) - - # Create a central widget for the graph and slider - central_widget = QWidget() - self.setCentralWidget(central_widget) - - # Create a layout for the central widget - layout = QGridLayout() - central_widget.setLayout(layout) - - # Create four graphs and sliders - self.graphs = [] - self.slider1 = [] - self.slider2 = [] - self.slider3 = [] - self.slider4 = [] - self.sliders = [] - self.slider_labels = [] - - for i in range(2): - for j in range(2): - graph_window = QWidget() - graph_layout = QVBoxLayout() - graph_window.setLayout(graph_layout) - - # Create a figure and canvas for the graph - figure, axis = plt.subplots(figsize=(20, 20)) - canvas = FigureCanvas(figure) - graph_layout.addWidget(canvas) - - slider_layout= QHBoxLayout() - slider_layout_2= QHBoxLayout() - # Create a slider widget - slider1 = QSlider(Qt.Horizontal) - slider1.setRange(0, 100) - slider1.setValue(0) - slider1_label = QLabel("0") - # slider.valueChanged.connect(self.slider_changed) - # Set the size of the slider - - # default_size = slider1.sizeHint() - # print(f"Default size of the slider: {default_size.width()}x{default_size.height()}") - - slider2 = QSlider(Qt.Horizontal) - slider2.setRange(0, 10) - slider2.setValue(0) - slider2_label = QLabel("0") - - - - slider3 = QSlider(Qt.Horizontal) - slider3.setRange(0, 100) - slider3.setValue(0) - slider3_label = QLabel("0") - - slider4 = QSlider(Qt.Horizontal) - slider4.setRange(0, 10) - slider4.setValue(0) - slider4_label = QLabel("0") - - slider1.setFixedSize(200, 12) # Change the width and height as needed - slider2.setFixedSize(200, 12) # Change the width and height as needed - slider3.setFixedSize(200, 12) # Change the width and height as needed - slider4.setFixedSize(155, 10) # Change the width and height as needed - - slider_layout.addWidget(slider1) - slider_layout.addWidget(slider1_label) - slider_layout.addWidget(slider2) - slider_layout.addWidget(slider2_label) - - slider_layout_2.addWidget(slider3) - slider_layout_2.addWidget(slider3_label) - slider_layout_2.addWidget(slider4) - slider_layout_2.addWidget(slider4_label) - # slider2.valueChanged.connect(self.slider_changed) - - # Add the slider to the layout - graph_layout.addLayout(slider_layout) - graph_layout.addLayout(slider_layout_2) - # graph_layout.addWidget(slider3) - # graph_layout.addWidget(slider2) - - layout.addWidget(graph_window, i, j) - self.graphs.append(figure) - self.slider1.append(slider1) - self.slider2.append(slider2) - self.slider3.append(slider3) - self.slider4.append(slider4) - self.sliders.extend([slider1, slider2,slider3, slider4]) - self.slider_labels.extend([slider1_label, slider2_label,slider3_label, slider4_label]) - for slider in self.slider1: - slider.valueChanged.connect(self.slider_changed) - for slider in self.slider2: - slider.valueChanged.connect(self.slider_changed) - for slider in self.slider3: - slider.valueChanged.connect(self.slider_changed) - for slider in self.slider4: - slider.valueChanged.connect(self.slider_changed) - - self.xv = None - self.yv = None - self.ev = None - self.eh = None - self.ph= None - self.pxv=None - self.pyh=None - self.axis=[] - # print(self.sliders) - # Create a menu bar - menu_bar = self.menuBar() - - # Create a 'File' menu - file_menu = menu_bar.addMenu("File") - - # Create actions for opening a file and exiting - open_file_action = QAction("Open File", self) - open_file_action.triggered.connect(self.open_file) - file_menu.addAction(open_file_action) - - open_graphe_action = QAction("Energy", self) - open_graphe_action.triggered.connect(self.open_graph_energy) - open_graphy_action = QAction("kx_cut", self) - open_graphy_action.triggered.connect(self.open_graph_y_cut) - open_graphx_action = QAction("ky_cut", self) - open_graphx_action.triggered.connect(self.open_graph_x_cut) - - menu_bar = self.menuBar() - - # Create a 'Graph' menu - graph_menu = menu_bar.addMenu("Graph") - - # Add the actions to the menu - graph_menu.addAction(open_graphe_action) - graph_menu.addAction(open_graphx_action) - graph_menu.addAction(open_graphy_action) - - open_draw_action = QAction("k-path", self) - open_draw_action.triggered.connect(self.open_draw_k_path) - - draw_menu= menu_bar.addMenu("Draw path") - draw_menu.addAction(open_draw_action) - # file_menu.addAction(open_graph_action) - self.graph_windows = [] - self.ce=None - - def open_draw_k_path(self): - D=DrawWindow(self.data_array,self.slider1[0].value(),self.slider2[0].value() , self.slider1[1].value(), self.slider2[1].value()) - D.show() - self.graph_windows.append(D) - - def open_graph_energy(self): - print('energy') - self.dataet=np.zeros((len(self.axis[0]),len(self.axis[1]),len(self.axis[3]))) - self.axet=[self.axis[0],self.axis[1],self.axis[3]] - - for i in range(self.slider1[0].value(),self.slider1[0].value()+self.slider2[0].value()+1): - self.dataet += self.data_updated[:, :, i,:] - graph_window= GraphWindow(self.dataet,self.axet,self.slider3[0].value(),self.slider4[0].value()) - - graph_window.show() - self.graph_windows.append(graph_window) - def open_graph_x_cut(self): - self.dataxt=np.zeros((len(self.axis[0]),len(self.axis[2]),len(self.axis[3]))) - self.axxt=[self.axis[0],self.axis[2],self.axis[3]] - for i in range(self.slider1[1].value(),self.slider1[1].value()+self.slider2[1].value()+1): - self.dataxt += self.data_updated[:, i, :,:] - graph_window = GraphWindow(self.dataxt,self.axxt,self.slider3[1].value(),self.slider4[1].value()) - # Show the graph window - graph_window.show() - self.graph_windows.append(graph_window) - def open_graph_y_cut(self): - self.datayt=np.zeros((len(self.axis[1]),len(self.axis[2]),len(self.axis[3]))) - self.axyt=[self.axis[1],self.axis[2],self.axis[3]] - - for i in range(self.slider1[2].value(),self.slider1[2].value()+self.slider2[2].value()+1): - self.datayt += self.data_updated[i, :, :,:] - graph_window = GraphWindow(self.datayt,self.axyt,self.slider3[2].value(),self.slider4[2].value()) - # Show the graph window - graph_window.show() - self.graph_windows.append(graph_window) - def open_graph_xy_cut(self): - self.datapt=np.zeros((len(self.axis[0]),len(self.axis[1]),len(self.axis[3]))) - self.axpt=[self.axis[0],self.axis[1],self.axis[3]] - - for i in range(self.slider1[2].value(),self.slider1[2].value()+self.slider2[2].value()+1): - self.datayt += self.data_updated[i, :, :,:] - graph_window = GraphWindow(self.datayt,self.axyt,self.slider3[2].value(),self.slider4[2].value()) - # Show the graph window - graph_window.show() - self.graph_windows.append(graph_window) - def open_file(self): - # Open file dialog to select a .txt file - # file_path, _ = QFileDialog.getOpenFileName(self, "Open Text File", "", "Text Files (*.txt)") - file_path, _ = QFileDialog.getOpenFileName(self, "Open Text File", "", "Text Files (*.h5)") - print(file_path) - if file_path: - # Load data from the file - # x, y = self.load_data(file_path) - # self.axis,self.data_updated = self.load_data2(file_path) - # Convert to an xarray.DataArray with named dimensions - df = h5py.File(file_path, 'r') - loader= h5toxarray_loader(df) - self.data_array= loader.get_data_array() - self.data_updated= loader.get_original_array() - self.axis=[self.data_array['kx'].data,self.data_array['ky'].data,self.data_array['E'].data,self.data_array['dt'].data] - - # print(self.axis[2]) - self.slider1[0].setRange(0,len(self.data_array['E'].data)-1) - self.slider1[1].setRange(0,len(self.data_array['kx'].data)-1) - self.slider1[2].setRange(0,len(self.data_array['ky'].data)-1) - self.slider1[3].setRange(0,len(self.data_array['kx'].data)-1) - self.slider3[3].setRange(0,len(self.data_array['ky'].data)-1) - self.slider3[0].setRange(0,len(self.data_array['dt'].data)-1) - self.slider3[1].setRange(0,len(self.data_array['dt'].data)-1) - self.slider3[2].setRange(0,len(self.data_array['dt'].data)-1) - - - - # self.update_plot(self.slider1[0].value(),self.slider2[0].value() , self.slider1[1].value(), self.slider2[0].value(), self.slider1[2].value(), self.slider2[2].value(), self.slider3[0].value(), self.slider4[0].value(),self.slider3[1].value(), self.slider4[1].value(), self.slider3[2].value(), self.slider4[2].value(), self.slider1[3].value(), self.slider3[3].value(), self.slider2[3].value(), self.slider4[3].value()) - self.update_energy(self.slider1[0].value(),self.slider2[0].value() , self.slider1[1].value(), self.slider2[1].value()) - - # self.ce= update_color(self.im,self.graphs[0],self.graphs[0].gca()) - # self.ce.slider_plot.on_changed(self.ce.update) - - self.update_y(self.slider1[2].value(), self.slider2[2].value(), self.slider3[0].value(), self.slider4[0].value()) - - self.update_x(self.slider3[1].value(), self.slider4[1].value(), self.slider3[2].value(), self.slider4[2].value()) - - self.update_point(self.slider1[3].value(), self.slider3[3].value(), self.slider2[3].value(), self.slider4[3].value()) - - def update_energy(self,Energy,dE,te,dte): - E1=self.data_array['E'][Energy].item() - # print(Energy,E1) - E2=self.data_array['E'][Energy+dE].item() - te1=self.data_array['dt'][te].item() - te2=self.data_array['dt'][te+dte].item() - - self.graphs[0].clear() - ax=self.graphs[0].gca() - self.im=self.data_array.sel(E=slice(E1,E2), dt=slice(te1,te2)).mean(dim=("E", "dt")).T.plot(ax=ax) - # ax.set_title('Loaded Data') - ax.set_xlabel('kx') - ax.set_ylabel('ky') - ax.set_title(f'Energy: {E1:.2f}, dE: {E2-E1}') - # self.graphs[0].tight_layout() - self.graphs[0].canvas.draw() - self.ev = self.graphs[0].gca().axvline(x=self.axis[1][self.slider1[2].value()], color='r', linestyle='--') - self.eh = self.graphs[0].gca().axhline(y=self.axis[0][self.slider1[1].value()], color='r', linestyle='--') - self.pxv = self.graphs[0].gca().axvline(x=self.axis[1][self.slider1[3].value()], color='b', linestyle='--') - self.pyh = self.graphs[0].gca().axhline(y=self.axis[0][self.slider3[3].value()], color='b', linestyle='--') - # if self.ce is not None: - # self.ce.slider_plot.on_changed(self.ce.update) - - def update_y(self,ypos,dy,ty,dty): - - y1=self.data_array['ky'][ypos].item() - y2=self.data_array['ky'][ypos+dy].item() - ty1=self.data_array['dt'][ty].item() - ty2=self.data_array['dt'][ty+dty].item() - - self.graphs[1].clear() - ax=self.graphs[1].gca() - self.data_array.sel(ky=slice(y1,y2), dt=slice(ty1,ty2)).mean(dim=("ky", "dt")).plot(ax=ax) - # ax.set_title('Loaded Data') - - ax.set_xlabel('Energy (eV)') - ax.set_ylabel('kx (1/A)') - ax.set_title(f'ky_pos: {y1:.2f}, dky: {y2-y1}') - self.graphs[1].tight_layout() - self.graphs[1].canvas.draw() - self.yv = ax.axvline(x=self.axis[2][self.slider1[0].value()], color='r', linestyle='--') - - def update_x(self,xpos,dx,tx,dtx): - x1=self.data_array['kx'][xpos].item() - x2=self.data_array['kx'][xpos+dx].item() - tx1=self.data_array['dt'][tx].item() - tx2=self.data_array['dt'][tx+dtx].item() - - self.graphs[2].clear() - ax=self.graphs[2].gca() - self.data_array.sel(kx=slice(x1,x2), dt=slice(tx1,tx2)).mean(dim=("kx", "dt")).plot(ax=ax) - # ax.set_title('Loaded Data') - ax.set_xlabel('Energy (eV)') - ax.set_ylabel('ky (1/A)') - ax.set_title(f'kx_pos: {x1:.2f}, dkx: {x2-x1}') - self.graphs[2].tight_layout() - self.graphs[2].canvas.draw() - self.xv = ax.axvline(x=self.axis[2][self.slider1[0].value()], color='r', linestyle='--') - def update_point(self,xt,yt,dxt,dyt): - yt1=self.data_array['ky'][yt].item() - yt2=self.data_array['ky'][yt+dyt].item() - xt1=self.data_array['kx'][xt].item() - xt2=self.data_array['kx'][xt+dxt].item() - - self.graphs[3].clear() - ax=self.graphs[3].gca() - self.data_array.sel(kx=slice(xt1,xt2), ky=slice(yt1,yt2)).mean(dim=("kx", "ky")).plot(ax=ax) - # ax.set_title('Loaded Data') - ax.set_xlabel('time (fs)') - ax.set_ylabel('Energy (eV)') - ax.set_title(f'kx_pos: {xt1:.2f}, dkx: {xt2-xt1},ky_pos: {yt1:.2f}, dky: {yt2-yt1}') - self.graphs[3].tight_layout() - self.graphs[3].canvas.draw() - self.ph = ax.axhline(y=self.axis[2][self.slider1[0].value()], color='r', linestyle='--') - - - def load_data2(self, file_path): - # Load data from the text file - # r'C:\Users\admin-nisel131\Documents\\' - # 'Scan130_scan130_Amine_100x100x300x50_spacecharge4_gamma850_amp_3p3.h5', 'r') - df = h5py.File(file_path, 'r') - # print(df.keys()) - print(df['axes'].keys()) - - axis=[df['axes/ax0'][: ],df['axes/ax1'][: ],df['axes/ax2'][: ],df['axes/ax3'][: ]] - # print(df['binned/BinnedData'].keys()) - data=df['binned/BinnedData'] - - - return axis,data - - def slider_changed(self, value): - sender = self.sender() # Get the slider that emitted the signal - index = self.sliders.index(sender) # Find the index of the slider - # print(index) - - self.slider_labels[index].setText(str(value)) # Update the corresponding label text - - if index in range(0,4): - - self.update_energy(self.slider1[0].value(),self.slider2[0].value(),self.slider3[0].value(), self.slider4[0].value()) - # self.update_line() - if self.xv is not None: - self.xv.remove() - if self.yv is not None: - self.yv.remove() - if self.ph is not None: - self.ph.remove() - - self.xv = self.graphs[1].gca().axvline(x=self.axis[2][self.slider1[0].value()], color='r', linestyle='--') - self.yv = self.graphs[2].gca().axvline(x=self.axis[2][self.slider1[0].value()], color='r', linestyle='--') - self.ph = self.graphs[3].gca().axhline(y=self.axis[2][self.slider1[0].value()], color='r', linestyle='--') - elif index in range(4,8): - - if self.eh is not None: - self.eh.remove() - - self.eh = self.graphs[0].gca().axhline(y=self.axis[0][self.slider1[1].value()], color='r', linestyle='--') - - self.update_y(self.slider1[1].value(), self.slider2[1].value(),self.slider3[1].value(), self.slider4[1].value()) - print('here') - elif index in range (8,12): - if self.ev is not None: - self.ev.remove() - self.ev = self.graphs[0].gca().axvline(x=self.axis[1][self.slider1[2].value()], color='r', linestyle='--') - self.update_x(self.slider1[2].value(), self.slider2[2].value(),self.slider3[2].value(), self.slider4[2].value()) - else: - if self.pxv is not None: - self.pxv.remove() - if self.pyh is not None: - self.pyh.remove() - self.update_point(self.slider1[3].value(), self.slider3[3].value(), self.slider2[3].value(), self.slider4[3].value()) - self.pxv = self.graphs[0].gca().axvline(x=self.axis[1][self.slider1[3].value()], color='b', linestyle='--') - self.pyh = self.graphs[0].gca().axhline(y=self.axis[0][self.slider3[3].value()], color='b', linestyle='--') - -if __name__ == "__main__": - app = QApplication(sys.argv) - window = MainWindow() - window.show() - sys.exit(app.exec_()) diff --git a/tests/Drawwindow.py b/tests/Drawwindow.py deleted file mode 100644 index 77f70fe..0000000 --- a/tests/Drawwindow.py +++ /dev/null @@ -1,173 +0,0 @@ -import sys -import numpy as np -import matplotlib.pyplot as plt -from PyQt5.QtCore import Qt -from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas -from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QTextEdit, \ - QHBoxLayout, QSizePolicy,QSlider,QLabel -# from k_path_4d_4 import drawKpath - -class DrawWindow(QMainWindow): - def __init__(self,data,s1,s2,s3,s4): - super().__init__() - - # Set the title and size of the main window - self.setWindowTitle("PyQt5 Matplotlib Example") - self.setGeometry(100, 100, 800, 600) - self.data_array=data - print(data['E'][0]) - # Create the main layout - main_layout = QVBoxLayout() - - # Create a widget to hold the layout - widget = QWidget() - widget.setLayout(main_layout) - self.setCentralWidget(widget) - - # Create a horizontal layout for the top row - top_row_layout = QHBoxLayout() - - - # Create top left graph - self.figure1, self.axis1 = plt.subplots() - self.canvas1 = FigureCanvas(self.figure1) - top_row_layout.addWidget(self.canvas1) - - # Create bottom right graph - self.figure2, self.axis2 = plt.subplots() - self.canvas2 = FigureCanvas(self.figure2) - top_row_layout.addWidget(self.canvas2) - - layout = QVBoxLayout() - - slider_layout= QHBoxLayout() - self.slider1 = QSlider(Qt.Horizontal) - self.slider1.setRange(0, len(data['E'].data)) - self.slider1.setValue(s1) - self.slider1_label = QLabel("0") - - self.slider2 = QSlider(Qt.Horizontal) - self.slider2.setRange(0, 10) - self.slider2.setValue(s2) - self.slider2_label = QLabel("0") - - self.slider1.setFixedSize(200, 12) # Change the width and height as needed - self.slider2.setFixedSize(200, 12) # Change the width and height as needed - - slider_layout.addWidget(self.slider1) - slider_layout.addWidget(self.slider1_label) - slider_layout.addWidget(self.slider2) - slider_layout.addWidget(self.slider2_label) - # layout.addLayout(slider_layout) - slider_layout2= QHBoxLayout() - self.slider3 = QSlider(Qt.Horizontal) - self.slider3.setRange(0, 100) - self.slider3.setValue(s3) - self.slider3_label = QLabel("0") - - self.slider4 = QSlider(Qt.Horizontal) - self.slider4.setRange(0, 10) - self.slider4.setValue(s4) - self.slider4_label = QLabel("0") - - self.slider3.setFixedSize(200, 12) # Change the width and height as needed - self.slider4.setFixedSize(200, 12) # Change the width and height as needed - - slider_layout2.addWidget(self.slider3) - slider_layout2.addWidget(self.slider3_label) - slider_layout2.addWidget(self.slider4) - slider_layout2.addWidget(self.slider4_label) - - # layout.addLayout(slider_layout2) - - self.slider1.valueChanged.connect(self.slider1_changed) - self.slider2.valueChanged.connect(self.slider2_changed) - self.slider3.valueChanged.connect(self.slider3_changed) - self.slider4.valueChanged.connect(self.slider4_changed) - - - main_layout.addLayout(top_row_layout) - main_layout.addLayout(slider_layout) - main_layout.addLayout(slider_layout2) - - - # Set size policy for the graph widgets - self.canvas1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - self.canvas2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - - self.update_energy(s1, s2, s3, s4) - # self.d=drawKpath(data, axis, fig, ax, ax2, linewidth, slider, N) - - # Plot data - # self.plot_graphs() - # self.update_text_edit_boxes() - - def slider1_changed(self,value): - self.slider1_label.setText(str(value)) - print(value) - self.update_energy(self.slider1.value(),self.slider2.value() , self.slider3.value(), self.slider4.value()) - def slider2_changed(self,value): - self.slider2_label.setText(str(value)) - self.update_energy(self.slider1.value(),self.slider2.value() , self.slider3.value(), self.slider4.value()) - def slider3_changed(self,value): - self.slider3_label.setText(str(value)) - self.update_energy(self.slider1.value(),self.slider2.value() , self.slider3.value(), self.slider4.value()) - def slider4_changed(self,value): - self.slider4_label.setText(str(value)) - # self.plot_graph(self.slider1.value(),self.slider2.value()) - # print(self.slider1.value(),self.slider2.value()) - # self.update_show(self.slider1.value(),self.slider2.value()) - self.update_energy(self.slider1.value(),self.slider2.value() , self.slider3.value(), self.slider4.value()) - - def update_energy(self,Energy,dE,te,dte): - - # self.ce_state=True - E1=self.data_array['E'][Energy].item() - # print(Energy,E1) - E2=self.data_array['E'][Energy+dE].item() - te1=self.data_array['dt'][te].item() - te2=self.data_array['dt'][te+dte].item() - # print(E1,E2,te1) - self.figure1.clear() - ax = self.figure1.add_subplot(111) # Recreate the axis on the figure - self.im=self.data_array.sel(E=slice(E1,E2), dt=slice(te1,te2)).mean(dim=("E", "dt")).plot(ax=ax) - # ax.set_title('Loaded Data') - ax.set_xlabel('X') - ax.set_ylabel('Y') - # self.graphs[0].tight_layout() - self.figure1.canvas.draw() - # self.ev = self.graphs[0].gca().axvline(x=self.axis[0][self.slider1[1].value()], color='r', linestyle='--') - # self.eh = self.graphs[0].gca().axhline(y=self.axis[1][self.slider1[2].value()], color='r', linestyle='--') - - - def plot_graphs(self): - # Plot on the top left graph - x1 = np.linspace(0, 10, 100) - y1 = np.sin(x1) - self.axis1.plot(x1, y1) - self.axis1.set_title('Top Left Graph') - self.axis1.set_xlabel('X') - self.axis1.set_ylabel('Y') - - # Plot on the bottom right graph - x2 = np.linspace(0, 10, 100) - y2 = np.cos(x2) - self.axis2.plot(x2, y2) - self.axis2.set_title('Bottom Right Graph') - self.axis2.set_xlabel('X') - self.axis2.set_ylabel('Y') - - # Update the canvas - self.canvas1.draw() - self.canvas2.draw() - - # def update_text_edit_boxes(self): - # # self.text_edit_top_right.setPlaceholderText("Top Right Text Edit Box") - # self.text_edit_bottom_left.setPlaceholderText("Bottom Left Text Edit Box") - - -if __name__ == "__main__": - app = QApplication(sys.argv) - window = DrawWindow() - window.show() - sys.exit(app.exec_()) diff --git a/tests/additional_window.py b/tests/additional_window.py deleted file mode 100644 index c63c2a1..0000000 --- a/tests/additional_window.py +++ /dev/null @@ -1,473 +0,0 @@ -import sys -from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QCheckBox, QAction, QFileDialog, QSlider, QGridLayout,QHBoxLayout, QSizePolicy,QLabel -from PyQt5.QtCore import Qt -from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas -import matplotlib.pyplot as plt -import numpy as np -import h5py -from matplotlib.widgets import CheckButtons, Button -from matplotlib.patches import Circle -from matplotlib.lines import Line2D - - -from fit_panel6 import MainWindow - -# %matplotlib qt - -class GraphWindow(QMainWindow): - def __init__(self,data,axis,t,dt): - global t_final - super().__init__() - - self.setWindowTitle("Graph Window") - self.setGeometry(100, 100, 800, 600) - - # Create a central widget for the graph - central_widget = QWidget() - self.setCentralWidget(central_widget) - - layout = QVBoxLayout() - central_widget.setLayout(layout) - - self.fig, self.axs = plt.subplots(2,2,figsize=(20,16)) - self.canvas = FigureCanvas(self.fig) - - self.checkbox_e = QCheckBox("Integrate_energy") - self.checkbox_e.stateChanged.connect(self.checkbox_e_changed) - - self.checkbox_k = QCheckBox("Integrate_k") - self.checkbox_k.stateChanged.connect(self.checkbox_k_changed) - - self.checkbox_cursors = QCheckBox("energy_cursors") - self.checkbox_cursors.stateChanged.connect(self.checkbox_cursors_changed) - checkbox_layout= QHBoxLayout() - # Add the canvas to the layout - checkbox_layout.addWidget(self.checkbox_e) - checkbox_layout.addWidget(self.checkbox_k) - layout.addLayout(checkbox_layout) - layout.addWidget(self.canvas) - layout.addWidget(self.checkbox_cursors) - - slider_layout= QHBoxLayout() - self.slider1 = QSlider(Qt.Horizontal) - self.slider1.setRange(0, 100) - self.slider1.setValue(0) - self.slider1_label = QLabel("0") - - self.slider2 = QSlider(Qt.Horizontal) - self.slider2.setRange(0, 10) - self.slider2.setValue(0) - self.slider2_label = QLabel("0") - - self.slider1.setFixedSize(200, 12) # Change the width and height as needed - self.slider2.setFixedSize(200, 12) # Change the width and height as needed - - slider_layout.addWidget(self.slider1) - slider_layout.addWidget(self.slider1_label) - slider_layout.addWidget(self.slider2) - slider_layout.addWidget(self.slider2_label) - layout.addLayout(slider_layout) - # Create a layout for the central widget - self.active_cursor = None - self.cursorlinev1=1 - self.cursorlinev2=0 - # self.v1_pixel=None - # self.v2_pixel=None - self.Line1=None - self.Line2=None - self.square_artists = [] # To store the artists representing the dots - self.square_coords = [(0, 0), (0, 0)] # To store the coordinates of the dots - self.square_count = 0 # To keep track of the number of dots drawn - - - self.cid_press2= None - self.line_artists=[] - self.cid_press3 = None - self.cid_press4 = None - self.cid_press = None - - # Create a figure and canvas for the graph - - self.data_o=data - self.axis=axis - self.dt=dt - self.datae=np.zeros((len(self.axis[0]),len(self.axis[1]))) - # Plot data - self.plot_graph(t,dt) - self.ssshow(t,dt) - self.slider1.setRange(0,len(self.axis[2])-1) - self.plot=np.zeros_like(self.data[1,:]) - - self.slider1.valueChanged.connect(self.slider1_changed) - self.slider2.valueChanged.connect(self.slider2_changed) - t_final=self.axis[2].shape[0] - - - fit_panel_action = QAction('Fit_Panel',self) - fit_panel_action.triggered.connect(self.fit_panel) - - menu_bar = self.menuBar() - - # Create a 'Graph' menu - - graph_menu1 = menu_bar.addMenu("Fit Panel") - - graph_menu1.addAction(fit_panel_action) - - # Add the actions to the menu - - self.graph_windows=[] - self.t=t - - def slider1_changed(self,value): - self.slider1_label.setText(str(value)) - self.plot_graph(self.slider1.value(),self.slider2.value()) - # print(self.slider1.value(),self.slider2.value()) - self.update_show(self.slider1.value(),self.slider2.value()) - self.t=self.slider1.value() - # self.us() - # update_show(self.slider1.value(),self.slider2.value()) - def slider2_changed(self,value): - self.slider2_label.setText(str(value)) - self.plot_graph(self.slider1.value(),self.slider2.value()) - self.update_show(self.slider1.value(),self.slider2.value()) - self.dt=self.slider2.value() - # self.ssshow(self.slider1.value(),self.slider2.value()).update_show() - # self.us() - # update_show(self.slider1.value(),self.slider2.value()) - def checkbox_e_changed(self, state): - if state == Qt.Checked: - # print("Checkbox is checked") - self.integrate_E() - else: - # print("Checkbox is unchecked") - self.update_show(self.slider1.value(),self.slider2.value()) - def checkbox_k_changed(self, state): - if state == Qt.Checked: - # print("Checkbox is checked") - self.integrate_k() - else: - # print("Checkbox is unchecked") - self.update_show(self.slider1.value(),self.slider2.value()) - def checkbox_cursors_changed(self, state): - if state == Qt.Checked: - self.put_cursors() - # self.integrate_k() - else: - # print("Checkbox is unchecked") - self.remove_cursors() - def plot_graph(self,t,dt): - # Plot on the graph - x = [1, 2, 3, 4, 5] - y = [2, 3, 5, 7, 11] - self.data=np.zeros((len(self.axis[0]),len(self.axis[1]))) - # self.ax.plot(x, y) - for i in range (t,t+dt+1): - self.data+= self.data_o[:,:,i] - - self.axs[0,0].imshow(self.data, extent=[self.axis[1][0], self.axis[1][-1], self.axis[0][0], self.axis[0][-1]], origin='lower', cmap='viridis',aspect='auto') - self.axs[0,0].set_title('Sample Graph') - self.axs[0,0].set_xlabel('X') - self.axs[0,0].set_ylabel('Y') - self.fig.tight_layout() - self.canvas.draw() - - def fit_panel(self,event): - print('forfit',len(self.plot),'axis',len(self.axis)) - graph_window= MainWindow( self.data_o, self.axis,self.square_coords[0][1], self.square_coords[1][1],self.t,self.dt) - graph_window.show() - self.graph_windows.append(graph_window) - - def lz_fit(self, event): - two_lz_fit(self.data_o, self.axis, self.square_coords[0][1], self.square_coords[1][1], 0, t_final, self.v1_pixel, self.v2_pixel,self.dt,self.a).fit() - def fit(self, event): - fit_4d(self.data_o, self.axis, self.square_coords[0][1], self.square_coords[1][1], 0, t_final, self.v1_pixel, self.v2_pixel,self.dt).fit() - def fit_FD(self, event): - fit_FD(self.data_o, self.axis, self.square_coords[0][1], self.square_coords[1][1], 0, t_final, self.v1_pixel, self.v2_pixel,self.dt).fit() - def fit_FD_conv(self, event): - # print('ax0test=',self.ax[0]) - # print('ax1test=',self.ax[1]) - - fit_FD_lor_conv(self.data_o, self.axis, self.square_coords[0][1], self.square_coords[1][1], 0, t_final, self.v1_pixel, self.v2_pixel,self.dt).fit() - def fit_FD_conv_2(self, event): - - f=fit_FD_conv(self.data_o, self.axis, self.square_coords[0][1], self.square_coords[1][1], 0, t_final, self.v1_pixel, self.v2_pixel,self.dt) - f.show() - def ssshow(self,t,dt): - def test(self): - print('whatever test') - print('show is running') - c= self.data.shape[1]// 10 ** (len(str(self.data.shape[1])) - 1) - - def put_cursors(): - self.Line1=axe.axvline(x=self.cursorlinev1, color='red', linestyle='--',linewidth=2, label='Vertical Line',picker=10) - self.Line2=axe.axvline(x=self.cursorlinev2, color='red', linestyle='--',linewidth=2, label='Vertical Line',picker=10) - plt.draw() - self.fig.canvas.draw() - def remove_cursors(): - self.Line1.remove() - self.Line2.remove() - plt.draw() - self.fig.canvas.draw() - - - def integrate_E(): - self.plote=np.zeros_like(self.data[1,:]) - self.axs[1,0].clear() - plt.draw() - x_min = int(min(self.square_coords[1][1], self.square_coords[0][1])) - x_max = int(max(self.square_coords[1][1], self.square_coords[0][1])) + 1 - for i in range(x_min, x_max): - self.plote += self.data[i, :] - # if self.square_coords[1][1]self.square_coords[0][1]: - # for i in range(self.square_coords[0][1],self.square_coords[1][1]+1): - # self.plot+=self.data[i,:] - # else: - # self.plot+=self.data[self.square_coords[0][1],:] - - self.axs[1, 0].plot(self.axis[1][:],self.plote/abs(self.square_coords[0][1]-self.square_coords[1][1]),color='red') - - # save_data(self.axis[1], plot/abs(self.square_coords[0][1]-self.square_coords[1][1]),"EDC_time="+str(slider_t.val)+"_", [0.42,0.46],self.fig) - def integrate_k(): - self.plotk=np.zeros_like(self.data[:,1]) - self.axs[0,1].clear() - plt.draw() - x_min = int(min(self.square_coords[0][0], self.square_coords[1][0])) - x_max = int(max(self.square_coords[0][0], self.square_coords[1][0])) + 1 - for i in range(x_min, x_max): - self.plotk += self.data[:, i] - # if self.square_coords[0][0]0: - self.i-=1 - # self.mod= - # print('removal') - current_row_count = self.table_widget.rowCount() - print(current_row_count) - sig = inspect.signature(self.function_list[-1]) - params = sig.parameters - - for p in range(len(params)): - # print('p=',p) - # print('count=',current_row_count-1-p) - self.table_widget.removeRow(current_row_count-1-p) - - self.function_list.remove(self.function_list[-1]) - self.function_names_list.remove(self.function_names_list[-1]) - self.update_equation() - - def button_add_clicked(self): - # print(self.cursor_handler.cursors()) - def zero(x): - return 0 - - - self.i+=1 - self.function_list.append(self.function_selected) - self.function_names_list.append(self.list_widget.currentItem().text()) - - print('the list=',self.function_list,'iten',self.function_list[0]) - print('listlength=',len(self.function_list)) - j=0 - for p in self.function_list: - # j=0 - print('j==',j) - current_function=Model(p,prefix='f'+str(j)+'_') - j+=1 - - - current_row_count = self.table_widget.rowCount() - - self.table_widget.insertRow(current_row_count) - # self.table_widget.setVerticalHeaderLabels([self.list_widget.currentItem().text()]) - new_row_name = QTableWidgetItem(self.list_widget.currentItem().text()) - self.table_widget.setVerticalHeaderItem(current_row_count, new_row_name) - for col in range(4): - item = QTableWidgetItem('') - item.setFlags(Qt.ItemIsEnabled) # Make cell uneditable - self.table_widget.setItem(current_row_count, col, item) - item.setBackground(QBrush(QColor('grey'))) - c=current_row_count - # self.table_widget.insertRow(1) - # self.table_widget.insertRow(2) - for p in range(len(current_function.param_names)): - # c+=1 - # print(c+p+1) - self.table_widget.insertRow(c+p+1) - print(current_function.param_names[p]) - new_row_name = QTableWidgetItem(current_function.param_names[p]) - self.table_widget.setVerticalHeaderItem(c+p+1, new_row_name) - checkbox_widget = QWidget() - checkbox_layout = QHBoxLayout() - checkbox_layout.setAlignment(Qt.AlignCenter) - checkbox = QCheckBox() - # checkbox.stateChanged.connect(self.handle_checkbox_state_change) - checkbox.stateChanged.connect(lambda state, row=c + p + 1: self.handle_checkbox_state_change(state, row)) - checkbox_layout.addWidget(checkbox) - checkbox_widget.setLayout(checkbox_layout) - self.table_widget.setCellWidget(c+p+1, 3, checkbox_widget) - # self.table_widget.setVerticalHeaderLabels([Model(self.function_selected).param_names[p]]) - # print(self.Mod.param_names) - # params['A'].set(value=1.35, vary=True, expr='') - - self.update_equation() - # print(self.params) - - def update_equation(self): - self.equation='' - print('names',self.function_names_list) - for j,n in enumerate(self.function_names_list): - if len(self.function_names_list)==1: - self.equation= n - else: - if j==0: - self.equation= n - else: - self.equation+= '+' + n - if self.FD_state: - self.equation= '('+ self.equation+ ')* Fermi_Dirac' - self.text_equation.setPlainText(self.equation) - print('equation',self.equation) - - - def table_item_changed(self, item): - print(f"Table cell changed at ({item.row()}, {item.column()}): {item.text()}") - header_item = self.table_widget.verticalHeaderItem(item.row()) - # print(header_item.text()) - print('theeeeeeitem=',item.text()) - - def handle_checkbox_state_change(self,state,row): - if state == Qt.Checked: - print("Checkbox is checked") - print(row) - header_item = self.table_widget.verticalHeaderItem(row) - # self.params[header_item.text()].vary = False - - else: - print("Checkbox is unchecked") - header_item = self.table_widget.verticalHeaderItem(row) - # self.params[header_item.text()].vary = True - def fit(self): - - def zero(x): - return 0 - self.mod= Model(zero) - j=0 - for f in self.function_list: - self.mod+=Model(f,prefix='f'+str(j)+'_') - j+=1 - if self.FD_state == True: - self.mod= self.mod* Model(self.fermi_dirac) - if self.CV_state == True: - # self.mod=CompositeModel(self.mod, Model(self.gaussian_conv), self.convolve) - self.mod=CompositeModel(self.mod, Model(self.gaussian_conv), self.convolve) - # self.mod=CompositeModel(Model(self.jump), Model(gaussian), self.convolve) - - m1=make_model(self.mod, self.table_widget) - self.mod=m1.current_model() - # self.mod = CompositeModel(m1.current_model(), Model(gaussian), self.convolve) - self.params=m1.current_params() - # self.params=self.mod.make_params() - cursors= self.cursor_handler.cursors() - self.x_f=self.x[cursors[0]:cursors[1]] - self.y_f=self.y[cursors[0]:cursors[1]] - print(self.params) - # params['b'].set(value=0, vary=True, expr='') - # out = mod.fit(self.data[:,1], params, x=self.data[:,0],method='nelder') - out = self.mod.fit(self.y_f, self.params, x=self.x_f) - # dely = out.eval_uncertainty(sigma=3) - print(out.fit_report(min_correl=0.25)) - self.axis.plot(self.x_f,out.best_fit,color='red',label='fit') - # self.axis.plot(self.x_f,1e5*self.gaussian_conv(self.x_f,out.best_values['sigma'])) - def fit_all(self): - self.fit_results=[] - def zero(x): - return 0 - self.mod= Model(zero) - j=0 - for f in self.function_list: - self.mod+=Model(f,prefix='f'+str(j)+'_') - j+=1 - if self.FD_state == True: - self.mod= self.mod* Model(self.fermi_dirac) - if self.CV_state == True: - # self.mod=CompositeModel(self.mod, Model(self.gaussian_conv), self.convolve) - self.mod=CompositeModel(self.mod, Model(self.gaussian_conv), self.convolve) - m1=make_model(self.mod, self.table_widget) - self.mod=m1.current_model() - self.params=m1.current_params() - for pname, par in self.params.items(): - print('the paramsnames or',pname, par) - setattr(self, pname, np.zeros((len(self.axs[2])))) - # self.pname=np.zeros((len(self.axs[2]))) - cursors= self.cursor_handler.cursors() - for i in range(len(self.axs[2])-self.dt): - self.y=np.zeros((self.data_t.shape[0])) - for j in range (self.dt+1): - self.y+= self.data_t[:,i+j] - self.x_f=self.x[cursors[0]:cursors[1]] - self.y_f=self.y[cursors[0]:cursors[1]] - # print(self.params) - # params['b'].set(value=0, vary=True, expr='') - # out = mod.fit(self.data[:,1], params, x=self.data[:,0],method='nelder') - self.axis.clear() - out = self.mod.fit(self.y_f, self.params, x=self.x_f) - # dely = out.eval_uncertainty(sigma=3) - # print(out.fit_report(min_correl=0.25)) - self.axis.plot(self.x,self.y, 'bo', label='Data') - self.axis.plot(self.x_f,out.best_fit,color='red',label='fit') - for pname, par in self.params.items(): - array=getattr(self, pname) - array[i]=out.best_values[pname] - setattr(self, pname,array) - if self.dt>0: - self.axs[2]=self.axs[2][:-self.dt] - for pname, par in self.params.items(): - self.fit_results.append(getattr(self, pname)[:-self.dt]) - else: - for pname, par in self.params.items(): - self.fit_results.append(getattr(self, pname)) - print('fit_results',len(self.fit_results)) - print('thelengthis=',self.fit_results[0].shape) - - - sg=showgraphs(self.axs[2], self.fit_results) - sg.show() - self.graph_windows.append(sg) - # pname='T' - # print(getattr(self, pname)) - # out.best_values['A1'] - # self.axis.clear() - -if __name__ == "__main__": - app = QApplication(sys.argv) - window = MainWindow() - window.show() - sys.exit(app.exec_()) diff --git a/tests/graphs2.py b/tests/graphs2.py deleted file mode 100644 index 7b50216..0000000 --- a/tests/graphs2.py +++ /dev/null @@ -1,80 +0,0 @@ -import sys -import numpy as np -from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QGridLayout -from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas -import matplotlib.pyplot as plt - -class showgraphs(QMainWindow): - def __init__(self, x, y_arrays): - super().__init__() - self.setWindowTitle("Multiple Array Plots") - self.setGeometry(100, 100, 800, 600) - - # Store x and y data - self.x = x - self.y_arrays = y_arrays - self.num_plots = len(y_arrays) - - # Create a central widget and layout - central_widget = QWidget(self) - self.setCentralWidget(central_widget) - layout = QGridLayout(central_widget) - - # Create and add buttons and plots for each y array in a 3x3 layout - for i, y in enumerate(y_arrays): - # Create a button to show the plot in a new window - button = QPushButton(f"Show Plot {i+1}") - button.setFixedSize(80, 30) # Set a fixed size for the button - button.clicked.connect(lambda checked, y=y, index=i+1: self.show_plot(y, index)) - - # Calculate grid position - row = (i // 3) * 2 # Each function will take 2 rows: one for the plot, one for the button - col = i % 3 - - # Add the plot canvas to the grid - layout.addWidget(self.create_plot_widget(y, f"Plot {i+1}"), row, col) # Plot in a 3x3 grid - layout.addWidget(button, row + 1, col) # Button directly below the corresponding plot - - def create_plot_widget(self, y, title): - """Creates a plot widget for displaying a function.""" - figure, ax = plt.subplots() - ax.plot(self.x, y) - ax.set_title(title) - ax.grid(True) - ax.set_xlabel('x') - ax.set_ylabel('y') - - # Create a FigureCanvas to embed in the Qt layout - canvas = FigureCanvas(figure) - return canvas # Return the canvas so it can be used in the layout - - def show_plot(self, y, index): - """Show the plot in a new window.""" - figure, ax = plt.subplots() - ax.plot(self.x, y) - ax.set_title(f"Plot {index}") - ax.grid(True) - ax.set_xlabel('x') - ax.set_ylabel('y') - plt.show() # Show the figure in a new window - -if __name__ == "__main__": - app = QApplication(sys.argv) - - # # Example data: Define x and multiple y arrays - # x = np.linspace(-10, 10, 400) - # y_arrays = [ - # np.sin(x), - # np.cos(x), - # np.tan(x), - # np.exp(x / 10), - # x**2, - # x**3, - # np.abs(x), - # np.log(x + 11), # Shift to avoid log(0) - # np.sqrt(x + 11) # Shift to avoid sqrt of negative - # ] - - main_window = showgraphs() - main_window.show() - sys.exit(app.exec_()) diff --git a/tests/h5toxarray.py b/tests/h5toxarray.py deleted file mode 100644 index ff6065f..0000000 --- a/tests/h5toxarray.py +++ /dev/null @@ -1,55 +0,0 @@ -import h5py -import numpy as np -import xarray as xr - - -class h5toxarray_loader(): - def __init__(self, df): - - if len(list(df['binned'].keys()))>1: - first_key = sorted(df['binned'].keys(), key=lambda x: int(x[1:]))[0] - data_shape = df['binned/' + first_key][:].shape - self.M = np.empty((data_shape[0], data_shape[1], data_shape[2], len(df['binned']))) - axis=[] - for idx, v in enumerate(sorted(df['binned'].keys(), key=lambda x: int(x[1:]))): - self.M[:, :, :, idx] = df['binned/' + v][:] - else: - self.M= df['binned/' + list(df['binned'].keys())[0]][:] - - - # Define the desired order lists - desired_orders = [ - ['ax0', 'ax1', 'ax2', 'ax3'], - ['kx', 'ky', 'E', 'delay'], - ['kx', 'ky', 'E', 'ADC'] - ] - - axes_list = [] - - matched_order = None - for i, order in enumerate(desired_orders): - # Check if all keys in the current order exist in df['axes'] - if all(f'axes/{axis}' in df for axis in order): - # If match is found, generate axes_list based on this order - axes_list = [df[f'axes/{axis}'] for axis in order] - matched_order = i + 1 # Store which list worked (1-based index) - break # Stop once the first matching list is found - - if matched_order: - print(f"Matched desired list {matched_order}: {desired_orders[matched_order - 1]}") - else: - print("No matching desired list found.") - - # print("Axes list:", axes_list) - # print(M[12,50,4,20]) - self.data_array = xr.DataArray( - self.M, - coords={"kx": axes_list[0], "ky": axes_list[1], "E": axes_list[2], "dt": axes_list[3]}, - dims=["kx", "ky", "E","dt"] - ) - def get_data_array(self): - return self.data_array - def get_original_array(self): - return self.M -# df =h5py.File(r'C:\Users\admin-nisel131\Documents\Scan130_scan130_Amine_100x100x300x50_spacecharge4_gamma850_amp_3p3.h5', 'r') -# test=h5toxarray_loader(df) diff --git a/tests/k_path_4d_4.py b/tests/k_path_4d_4.py deleted file mode 100644 index 13876c7..0000000 --- a/tests/k_path_4d_4.py +++ /dev/null @@ -1,422 +0,0 @@ -import numpy as np -import h5py -import matplotlib -import matplotlib.pyplot as plt -import numpy as np -from matplotlib.widgets import CheckButtons, Button -from scipy.ndimage import rotate -import h5py -# import mplcursors -from matplotlib.widgets import Slider, Cursor, SpanSelector -from matplotlib.gridspec import GridSpec -from matplotlib.lines import Line2D -from matplotlib.patches import Circle -from AdditionalInterface import AdditionalInterface -from AxisInteractor import AxisInteractor -from LinePixelGetter import LinePixelGetter -from update_plot_cut_4d import update_plot_cut -import json -import csv -from datetime import datetime - -class drawKpath: - # print(True) - def __init__(self, data,axis,fig, ax,ax2,linewidth,slider,N): - self.active_cursor=None - self.dots_count=0 - self.ax=ax - self.fig=fig - self.dot1_x=0 - self.do1_y=0 - self.dot2_x=0 - self.do2_y=0 - self.cid_press=None - self.linewidth=1 - self.line_artist=None - self.cb_line=None - self.button_update=None - self.dot1=None - self.dot2=None - self.method_running = False - self.pixels_along_line=[] - self.number=N - self.og_number=N - self.dots_list=[] - self.line_artist_list=[None]*N - self.pixels_along_path=[None]*N - # self.number=N - self.is_drawn= False - self.is_loaded= False - self.new=False - self.add_pressed=False - self.lw=linewidth - self.ax2=ax2 - self.data=data[:,:,:,slider] - self.axis=axis - self.pixels=[] - self.slider=slider - self.data2=data - self.slider_ax7 = plt.axes([0.55, 0.14, 0.02, 0.3]) - self.slider_dcut= Slider(self.slider_ax7, 'dcut_kpath', 0, 15, valinit=1, valstep=1, orientation='vertical') - # def update_plot_cut(self): - # update_plot_cut.update_plot_cut(self.data2[:,:,:,self.slider],self.ax2,self.pixels,self.lw) - def isdrawn(self): - return self.is_drawn - - - def get_pixels(self): - if self.pixels is not None: - return self.pixels - def get_pixels_along_line(self): - if self.pixels_along_line is not None: - return self.pixels_along_line - - def get_status(self): - if self.cb_line is not None: - return self.cb_line.get_status()[0] - else: - return False - - def draw(self): - # print('beginning') - def add_path(event): - self.add_pressed= True - - for i in range (self.number): - self.line_artist_list.append(None) - self.pixels_along_path.append(None) - # self.dots_list - print('line list=', len(self.line_artist_list)) - self.number=self.number+self.og_number - self.is_drawn=False - self.dots_count=0 - self.cid_press = self.fig.canvas.mpl_connect('button_press_event', drawdots) - - def drawline(dot1,dot2,pos): - self.pixels=[] - if self.dots_count ==0 and self.line_artist_list[len(self.dots_list)-2] is not None : - if not self.loaded: - self.line_artist_list[len(self.dots_list)-2].remove() # Remove the previous line if exists - print('test,code') - # if self.dots_count==2: - # line = Line2D([self.dots_list[len(self.dots_list)].center[0], self.dots_list[len(self.dots_list)-1].center[0]], [self.dots_list[len(self.dots_list)].center[1], self.dots_list[len(self.dots_list)-1].center[1]], linewidth=self.linewidth, color='red') - if self.dots_count==2 : - line = Line2D([dot1.center[0], dot2.center[0]], [dot1.center[1], dot2.center[1]], linewidth=self.linewidth, color='red') - - self.ax.add_line(line) - # print('movement',len(self.line_artist_list)) - print('currentline=',self.line_artist_list[pos]) - if self.line_artist_list[pos] is not None: - # print(pos,self.line_artist_list[pos].get_data()) - self.line_artist_list[pos].remove() - # if self.line_artist is not None: - # self.line_artist.remove() # Remove the previous line if exists - - self.line_artist = line - # self.line_artist_list.append(line) - self.line_artist_list[pos]=line - # print(pos,self.line_artist_list[pos].get_data()) - # x1=self.line_artist_list[pos].get_data()[0][1] - # y1=self.line_artist_list[pos].get_data()[1][1] - # x2= self.line_artist_list[pos].get_data()[0][0] - # y2=self.line_artist_list[pos].get_data()[1][0] - x1_pixel=int((self.line_artist_list[pos].get_data()[0][1] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - y1_pixel=int((self.line_artist_list[pos].get_data()[1][1] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - x2_pixel=int((self.line_artist_list[pos].get_data()[0][0] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - y2_pixel=int((self.line_artist_list[pos].get_data()[1][0] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - - self.pixels_along_path[pos] = LinePixelGetter.get_pixels_along_line(x1_pixel, y1_pixel, x2_pixel, y2_pixel, self.linewidth) - # print(x1_pixel,y1_pixel) - # self.pixels_along_path[pos]=LinePixelGetter.get_pixels_along_line(self.line_artist_list[pos].get_data()[0][1], self.line_artist_list[pos].get_data()[1][1], self.line_artist_list[pos].get_data()[0][0], self.line_artist_list[pos].get_data()[1][0], self.linewidth) - # for i in self.pixels_along_path: - for i in range (0,self.number): - if self.pixels_along_path[i] is not None: - self.pixels+=self.pixels_along_path[i] - - def drawdots(event): - # if self.add_pressed: - - - if self.cb_line.get_status()[0] and len(self.dots_list) < self.number and (self.new or not self.is_drawn): - x = event.xdata # Round the x-coordinate to the nearest integer - y = event.ydata # Round the y-coordinate to the nearest integer - print('you hereeee') - print(self.number) - # print('line list=', len(self.line_artist_list)) - if self.dots_count==0: - self.dot= Circle((x, y), radius=0.1, color='yellow', picker=20) - self.ax.add_patch(self.dot) - # self.dot_coords[self.dots_count] = (x, y) - self.dots_list.append(self.dot) - self.dots_count += 1 - self.fig.canvas.draw() - else: - self.dot= Circle((x, y), radius=0.1, color='yellow', picker=20) - self.ax.add_patch(self.dot) - # self.dot_coords[self.dots_count] = (x, y) - self.dots_count += 1 - self.dots_list.append(self.dot) - print('dots list=',len(self.dots_list)) - drawline(self.dots_list[len(self.dots_list)-1],self.dots_list[len(self.dots_list)-2],len(self.dots_list)-2) - self.dots_count -= 1 - update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels,self.slider_dcut.val) - - self.fig.canvas.draw() - if len(self.dots_list)== self.number: - self.is_drawn=True - # print(self.is_drawn) - def on_checkbox_change(label): - if self.cb_line.get_status()[0]: - if self.is_loaded: - for i in range(len(self.dots_list)): - self.ax.add_patch(self.dots_list[i]) - plt.draw() - for i in range(len(self.line_artist_list)): - if self.line_artist_list[i] is not None: - self.ax.add_line(self.line_artist_list[i]) - plt.draw() - elif self.is_drawn: - for i in range(len(self.dots_list)): - self.ax.add_patch(self.dots_list[i]) - plt.draw() - for i in range(len(self.line_artist_list)): - if self.line_artist_list[i] is not None: - self.ax.add_line(self.line_artist_list[i]) - plt.draw() - - else: - self.cid_press = self.fig.canvas.mpl_connect('button_press_event', drawdots) - - else: - # Disconnect the click event - self.is_loaded= False - self.fig.canvas.mpl_disconnect(self.cid_press) - for i in range(len(self.dots_list)): - self.dots_list[i].remove() - plt.draw() - for i in range(len(self.line_artist_list)): - if self.line_artist_list[i] is not None: - self.line_artist_list[i].remove() - plt.draw() - def new(event): - - for i in range(len(self.dots_list)): - print(i) - self.dots_list[i].remove() - plt.draw() - for i in range(len(self.line_artist_list)): - print(i) - if self.line_artist_list[i] is not None: - self.line_artist_list[i].remove() - plt.draw() - self.new=True - self.is_drawn= False - self.is_loaded= False - self.dots_list=[] - self.line_artist_list=[None]*self.number - self.pixels_along_path=[None]*self.number - self.dots_count=0 - self.cid_press = self.fig.canvas.mpl_connect('button_press_event', drawdots) - def on_pick(event): - for i in range(len(self.dots_list)): - if event.artist == self.dots_list[i]: - self.active_cursor = self.dots_list[i] - def on_motion(event): - # global dot1,dot2 - if self.active_cursor is not None and event.inaxes == self.ax: - # Initialize a list of dictionaries to store dot information - dot_info_list = [{"dot": dot, "center": dot.center} for dot in self.dots_list] - self.dots_count=2 - - # Iterate through the list to find the selected dot - selected_dot_index = None - for i, dot_info in enumerate(dot_info_list): - dot = dot_info["dot"] - contains, _ = dot.contains(event) - if contains: - selected_dot_index = i - break # Exit the loop when a matching dot is found - - if selected_dot_index is not None: - selected_dot_info = dot_info_list[selected_dot_index] - selected_dot = selected_dot_info["dot"] - # print(f"Selected dot index: {selected_dot_index}") - # print(f"Selected dot center: {selected_dot_info['center']}") - selected_dot.center = (event.xdata, event.ydata) - plt.draw() - i=selected_dot_index - if i==len(self.dots_list)-1: - # self.line_artist_list[i-1].remove() - drawline(self.dots_list[i],self.dots_list[i-1],i-1) - update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels,self.slider_dcut.val) - elif i==0: - drawline(self.dots_list[i+1],self.dots_list[i],i) - update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels,self.slider_dcut.val) - else: - # self.line_artist_list[i-1].remove() - # self.line_artist_list[i].remove() - drawline(self.dots_list[i+1],self.dots_list[i],i) - update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels,self.slider_dcut.val) - drawline(self.dots_list[i],self.dots_list[i-1],i-1) - update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels,self.slider_dcut.val) - plt.draw() - - - def on_release(event): - self.active_cursor = None - def get_status(): - return self.cb_line.get_status()[0] - def dots_coord(): - return [self.dot1.center, self.dot2.center] - - def update_dcut(val): - self.linewidth=self.slider_dcut.val - self.pixels=[] - for position, line in enumerate(self.line_artist_list): - if line is not None: - line.set_linewidth(self.linewidth+1) - x1_pixel=int((line.get_data()[0][1] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - y1_pixel=int((line.get_data()[1][1] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - x2_pixel=int((line.get_data()[0][0] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - y2_pixel=int((line.get_data()[1][0] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - # print(x1_pixel,y1_pixel,x2_pixel,y2_pixel) - self.pixels_along_path[position] = LinePixelGetter.get_pixels_along_line(x1_pixel, y1_pixel, x2_pixel, y2_pixel, self.linewidth) - self.pixels+=self.pixels_along_path[position] - - print('before before line') - # for pos in range(0,self.number): - # print('before line') - # if self.line_artist_list[pos] is not None: - # x1_pixel=int((self.line_artist_list[pos].get_data()[0][1] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - # y1_pixel=int((self.line_artist_list[pos].get_data()[1][1] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - # x2_pixel=int((self.line_artist_list[pos].get_data()[0][0] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - # y2_pixel=int((self.line_artist_list[pos].get_data()[1][0] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - # print(x1_pixel,y1_pixel,x2_pixel,y2_pixel) - # self.pixels_along_path[pos] = LinePixelGetter.get_pixels_along_line(x1_pixel, y1_pixel, x2_pixel, y2_pixel, self.linewidth) - # self.pixels+=self.pixels_along_path[pos] - - # self.pixels_along_line = LinePixelGetter.get_pixels_along_line(self.dot1_x_pixel, self.dot1_y_pixel, self.dot2_x_pixel, self.dot2_y_pixel, self.linewidth) - # update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels_along_line,self.slider_dcut.val) - update_plot_cut.update_plot_cut(self.data,self.ax2,self.pixels,self.slider_dcut.val) - def draw_load(): - if self.is_loaded: - for i in range(len(self.dots_list)): - self.ax.add_patch(self.dots_list[i]) - plt.draw() - for i in range(len(self.line_artist_list)): - if self.line_artist_list[i] is not None: - self.ax.add_line(self.line_artist_list[i]) - plt.draw() - def save_path(event): - def c_to_string(circle): - return f"{circle.center[0]}, {circle.center[1]}, {circle.radius}" - def l_to_string(line): - x_data, y_data = line.get_data() - linewidth = line.get_linewidth() - return f"{x_data[0]}, {y_data[0]}, {x_data[1]},{y_data[1]},{linewidth}" - # self.positions= np.array([[0]*4]*len(self.line_artist_list)) - # for position, line in enumerate(self.line_artist_list): - # if line is not None: - # line.set_linewidth(self.linewidth+1) - # x1_pixel=int((line.get_data()[0][1] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - # y1_pixel=int((line.get_data()[1][1] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - # x2_pixel=int((line.get_data()[0][0] - self.axis[0][0]) / (self.axis[0][-1] - self.axis[0][0]) * (self.axis[0].shape[0] - 1) + 0.5) - # y2_pixel=int((line.get_data()[1][0] - self.axis[1][0]) / (self.axis[1][-1] - self.axis[1][0]) * (self.axis[1].shape[0] - 1) + 0.5) - # self.positions[position][0] - output_directory = "C:/Users/admin-nisel131/Documents/CVS_TR_flatband_fig/" - current_time = datetime.now() - current_time_str = current_time.strftime("%Y-%m-%d_%H%M%S") - file_name = "k_path" - output_path = f"{output_directory}/{file_name}_{current_time_str}.txt" - with open(output_path, "w",newline="") as file: - file.write(f"{self.number}" + "\n") - for circle in self.dots_list: - file.write(c_to_string(circle) + "\n") - for line in self.line_artist_list: - if line is not None: - file.write(l_to_string(line) + "\n") - def load_path(event): - self.fig.canvas.mpl_disconnect(self.cid_press) - circle_list=[] - line_list=[] - file_path1="C:/Users/admin-nisel131/Documents/CVS_TR_flatband_fig/" - # file="k_path_2023-10-06_153243.txt" - # file= "k_path_2023-10-10_221437.txt" - # file= "k_path_2024-04-03_125248.txt" - file= "k_path_2024-04-03_140548.txt" - - - file_path=file_path1+file - with open(file_path, "r") as file: - lines=file.readlines() - # print(lines) - # for line_number, line in enumerate(file, start=1): - for line_number, line in enumerate(lines, start =1): - # if line_number==2: - # a,b,c= map(float, line.strip().split(', ')) - # print(a,b,c) - # print(map(float, line.strip().split(', '))) - # print('linenumber=',line_number) - # Split the line into individual values - # if line_number==1: - # print('firstline',line_number) - # number=7 - # first_line = file.readline().strip() # Read and strip whitespace - # print(line) - # first_line = file.readline() - - # number= int(first_line) - # print(number) - # print(first_line) - # print() - if line_number==1: - number= int(line) - # print(number) - elif line_number>=2 and line_number<=number+1: - x, y, radius = map(float, line.strip().split(', ')) - # print(x,y,radius) - circle = Circle((x, y), radius=radius, color='yellow', picker=20) - circle_list.append(circle) - self.dots_list=circle_list - else: - x0,y0,x1,y1,lw=map(float, line.strip().split(',')) - line1=Line2D([x0,x1], [y0, y1], linewidth=lw, color='red') - line_list.append(line1) - self.line_artist_list=line_list - self.is_loaded= True - self.dots_count=2 - # draw_load() - # print(len(self.line_artist_list),len(self.dots_list)) - - # print(x0,y0,x1,y1,lw) - # on_checkbox_change('K path') - - - self.slider_dcut.on_changed(update_dcut) - self.fig.canvas.mpl_connect('pick_event', on_pick) - self.fig.canvas.mpl_connect('motion_notify_event', on_motion) - self.fig.canvas.mpl_connect('button_release_event', on_release) - - rax_line = self.fig.add_axes([0.45, 0.02, 0.06, 0.03]) # [left, bottom, width, height] - self.cb_line = CheckButtons(rax_line, ['K path'], [False]) - self.cb_line.on_clicked(on_checkbox_change) - - rax_button = self.fig.add_axes([0.52, 0.02, 0.06, 0.03]) - self.button_update = Button(rax_button, 'new k') - self.button_update.on_clicked(new) - - savepath_button = self.fig.add_axes([0.52, 0.06, 0.06, 0.03]) - self.button_save = Button(savepath_button, 'save k-path') - self.button_save.on_clicked(save_path) - - loadpath_button = self.fig.add_axes([0.45, 0.06, 0.06, 0.03]) - self.button_load = Button(loadpath_button, 'load k-path') - self.button_load.on_clicked(load_path) - - addpath_button = self.fig.add_axes([0.37, 0.06, 0.06, 0.03]) - self.button_add = Button(addpath_button, 'add k-path') - self.button_add.on_clicked(add_path) - - plt.show() - self.fig.canvas.draw() - \ No newline at end of file diff --git a/tests/make_model.py b/tests/make_model.py deleted file mode 100644 index 940b1e2..0000000 --- a/tests/make_model.py +++ /dev/null @@ -1,70 +0,0 @@ -import sys -from PyQt5.QtGui import QBrush, QColor -from PyQt5.QtWidgets import QTextEdit, QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QSlider, QLabel, QAction, QCheckBox, QPushButton, QListWidget, QTableWidget, QTableWidgetItem, QTableWidget, QCheckBox, QSplitter -from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import QTableWidgetItem, QHBoxLayout, QCheckBox, QWidget -from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas -import matplotlib.pyplot as plt - - - -class make_model: - # from matplotlib.widgets import CheckButtons, Button - # %matplotlib qt - - def __init__(self,mod,table_widget): - - self.mod=mod - self.params=mod.make_params() - print('otherpalce',self.params) - print('thefuuuuTable',table_widget) - print('count',table_widget.rowCount()) - for row in range(table_widget.rowCount()): - item = table_widget.item(row, 1) - checkbox_widget = table_widget.cellWidget(row, 3) - print('tableitenm=',item) - if item is not None and item.text().strip(): - header_item = table_widget.verticalHeaderItem(item.row()) - checkbox=checkbox_widget.findChild(QCheckBox) - print(header_item.text(),item.text()) - if header_item.text()== "Fermi level": - self.params['mu'].set(value=float(item.text())) - if table_widget.item(row, 0) is not None: - self.params['mu'].set(min=float(table_widget.item(row, 0).text())) - if table_widget.item(row, 2) is not None: - self.params['mu'].set(max=float(table_widget.item(row, 2).text())) - if checkbox.isChecked(): - self.params['mu'].vary = False - - elif header_item.text()== "Temperature": - self.params['T'].set(value=float(item.text())) - if table_widget.item(row, 0) is not None: - self.params['T'].set(min=float(table_widget.item(row, 0).text())) - if table_widget.item(row, 2) is not None: - self.params['T'].set(max=float(table_widget.item(row, 2).text())) - if checkbox.isChecked(): - self.params['T'].vary = False - elif header_item.text()== "sigma": - self.params['sigma'].set(value=float(item.text())) - self.params['sigma'].set(min=0) - if table_widget.item(row, 0) is not None: - self.params['sigma'].set(min=float(table_widget.item(row, 0).text())) - if table_widget.item(row, 2) is not None: - self.params['sigma'].set(max=float(table_widget.item(row, 2).text())) - if checkbox.isChecked(): - self.params['sigma'].vary = False - else: - self.params[header_item.text()].set(value=float(item.text())) - if table_widget.item(row, 0) is not None: - self.params[header_item.text()].set(min=float(table_widget.item(row, 0).text())) - if table_widget.item(row, 2) is not None: - self.params[header_item.text()].set(max=float(table_widget.item(row, 2).text())) - if checkbox.isChecked(): - self.params[header_item.text()].vary = False - - - def current_model(self): - return self.mod - def current_params(self): - return self.params - \ No newline at end of file diff --git a/tests/movable_vertical_cursors_graph.py b/tests/movable_vertical_cursors_graph.py deleted file mode 100644 index 580f4a8..0000000 --- a/tests/movable_vertical_cursors_graph.py +++ /dev/null @@ -1,77 +0,0 @@ -# movable_cursors.py - -import numpy as np -import matplotlib.pyplot as plt - -class MovableCursors: - def __init__(self, ax): - self.ax = ax - line = self.ax.lines[0] - self.active_cursor=None - - self.axis = line.get_xdata() - - self.cursorlinev1=self.axis[int(len(self.axis)/4)] - self.cursorlinev2=self.axis[int(3*len(self.axis)/4)] - # Create initial cursors (at the middle of the plot) - # self.v1_cursor = self.ax.axvline(x=5, color='r', linestyle='--', label='Cursor X') - # self.v2_cursor = self.ax.axhline(y=0, color='g', linestyle='--', label='Cursor Y') - - self.Line1=self.ax.axvline(x=self.cursorlinev1, color='red', linestyle='--',linewidth=2, label='Vertical Line',picker=10) - self.Line2=self.ax.axvline(x=self.cursorlinev2, color='red', linestyle='--',linewidth=2, label='Vertical Line',picker=10) - - # Connect mouse events for the canvas of the axes - self.ax.figure.canvas.mpl_connect('pick_event', self.on_pick) - self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) - self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release) - - def on_pick(self,event): - - if event.artist == self.Line1: - self.active_cursor =self.Line1 - elif event.artist == self.Line2: - self.active_cursor =self.Line2 - # self.active_cursor=None - def on_motion(self,event): - - if self.active_cursor is not None and event.inaxes == self.ax: - if self.active_cursor == self.Line1: - self.Line1.set_xdata([event.xdata, event.xdata]) - self.cursorlinev1= event.xdata - elif self.active_cursor == self.Line2: - self.Line2.set_xdata([event.xdata, event.xdata]) - self.cursorlinev2= event.xdata - # print(dot1.center) - # print(self.cursorlinev1,self.cursorlinev2) - self.ax.figure.canvas.draw() - plt.draw() - def find_nearest_index(array, value): - idx = (np.abs(array - value)).argmin() - return idx - self.v1_pixel=find_nearest_index(self.axis, self.cursorlinev1) - self.v2_pixel=find_nearest_index(self.axis, self.cursorlinev2) - - # self.v1_pixel=int((self.cursorlinev1 - self.axis[0]) / (self.axis[-1] - self.axis[0]) * (self.axis.shape[0] - 1) + 0.5) - # self.v2_pixel=int((self.cursorlinev2 - self.axis[0]) / (self.axis[-1] - self.axis[0]) * (self.axis.shape[0] - 1) + 0.5) - print(self.v1_pixel,self.v2_pixel) - - # print(self.v1_pixel,self.v2_pixel) - def on_release(self,event): - # global self.active_cursor - self.active_cursor = None - def remove(self): - self.cursorlinev1= self.Line1.get_xdata()[0] - self.cursorlinev2= self.Line2.get_xdata()[0] - self.Line1.remove() - self.Line2.remove() - # plt.draw() - self.ax.figure.canvas.draw() - - def redraw(self): - # print(self.cursorlinev1,self.cursorlinev2) - self.Line1=self.ax.axvline(x=self.cursorlinev1, color='red', linestyle='--',linewidth=2, label='Vertical Line',picker=10) - self.Line2=self.ax.axvline(x=self.cursorlinev2, color='red', linestyle='--',linewidth=2, label='Vertical Line',picker=10) - # plt.draw() - self.ax.figure.canvas.draw() - def cursors(self): - return [self.v1_pixel,self.v2_pixel] \ No newline at end of file