class Airconics_Viewgrid(QtWidgets.QWidget): """A simple grid containing both a 3d viewer and a range of performance metrics for the geometry contained in the widget Inputs ------ Topology - airconics.Toplogy (default None) The Topology to display in this widget: see attributes. If no Topology is specified. An empty Topology will be created Attributes ---------- Topology - airconics.Topology object The aircraft topology object which is mapped to this viewer. This is intended to not be deleted. Notes ----- """ select_clicked = QtCore.pyqtSignal() # Note: Some of these have a min target, some have max... misleading data_labels = ['Static Margin', 'Fuel Burn', 'Cost', 'Weight', 'Range', 'Payload'] colors = itertools.cycle(['b', 'r', 'g', 'm', 'y']) def __init__(self, Topology=None, *args): super(Airconics_Viewgrid, self).__init__() # Create a blank topology object if one has not been provided if Topology: self._Topology = Topology else: self._Topology = Topology() # Matplotlib colour character (different for each instance) self.color = next(self.colors) grid = QtGui.QGridLayout(self) self.setLayout(grid) viewer = qtViewer3d(*args) viewer.setMinimumSize(200, 200) self.viewer = viewer grid.setSpacing(10) grid.setMargin(10) # Add the viewer spanning 3/4 of the width of the widget grid.addWidget(viewer, 0, 0, 1, 1) self.InitDataCanvas() # Add the canvas to a new VBox layout with a title data_group = QtGui.QGroupBox("Estimated Performance Metrics") data_box = QtGui.QVBoxLayout(data_group) data_box.addWidget(self._data_canvas) data_group.setLayout(data_box) grid.addWidget(data_group, 0, 1) self.select_button = QtGui.QPushButton('Select', self) grid.addWidget(self.select_button, 1, 0, 1, 2) self.select_clicked.connect(self.Evolve) self._Topology.Display(self.viewer._display) @property def Topology(self): return self._Topology @Topology.setter def Topology(self, newTopology): self._Topology = newTopology self._Topology.Display(self.viewer._display) self.viewer._display.FitAll() # @QtCore.pyqtSlot() # def onSelectButtonClick(self): # Airconics_Viewgrid.select_clicked.emit() @QtCore.pyqtSlot() def Evolve(self): self.viewer._display.EraseAll() self.Topology.Display(self.viewer._display) Nvars = len(self.data_labels) # This initialises some data in the radar plot: remove this later! data = np.random.random(Nvars) self._ax.plot(self.radar_factory, data, color=self.color) self._ax.fill(self.radar_factory, data, facecolor=self.color, alpha=0.25) self._data_canvas.repaint() self._ax.redraw_in_frame() def InitDataCanvas(self): """Initialises a radar chart in self._data_canvas to be embedded in the parent viewer widget The radar chart contains the labels defined at the class level via self.data_labels. """ # Labels # labels = [] # outputs = [] # data_group = QtGui.QGroupBox("Estimated Performance Metrics") # data_gridlayout = QtGui.QVBoxLayout(data_group) # for i, lbl_string in enumerate(self.data_box_labels): # label = QtGui.QLabel(lbl_string) # labels.append(label) # # output = QtGui.QLineEdit("Nil") # # output.setReadOnly(True) # # outputs.append(output) # data_gridlayout.addWidget(label) # # data_gridlayout.addWidget(output, i, 1) # data_group.setLayout(data_gridlayout) Nvars = len(self.data_labels) # Nvars = len(self.data_labels) self.radar_factory = radar_factory(Nvars, frame='polygon') # This initialises some data in the radar plot: remove this later! data = np.random.random(Nvars) self._fig = plt.figure(facecolor="white") self._ax = self._fig.add_subplot(111, projection='radar') self._ax.set_rgrids([0.2, 0.4, 0.6, 0.8]) self._ax.set_rmin(0.) self._ax.set_rmax(1.) self._ax.plot(self.radar_factory, data, color=self.color) self._ax.fill(self.radar_factory, data, facecolor=self.color, alpha=0.25) self._ax.set_varlabels(self.data_labels) # plt.tight_layout() self._data_canvas = FigureCanvas(self._fig) self._data_canvas.setParent(self) self._data_canvas.setFocusPolicy(QtCore.Qt.StrongFocus) # self._data_canvas.setMinimumSize(200, 200) self._data_canvas.setMaximumSize(200, 200)
class PlotGenerator(QFrame): def __init__(self, plot_path, plot_config_path): QFrame.__init__(self) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.plot_figure = PlotFigure() self.canvas = FigureCanvas(self.plot_figure.getFigure()) self.canvas.setParent(self) self.canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) size = QSize(297*2, 210*2) # A4 aspectratio self.canvas.setMaximumSize(size) self.canvas.setMinimumSize(size) self.setMaximumSize(size) self.setMinimumSize(size) self.popup = Popup(self) self.plot_config_loader = PlotSettingsLoader() self.plot_settings = PlotSettings() self.plot_settings.setPlotPath(plot_path) self.plot_settings.setPlotConfigPath(plot_config_path) self.connect(self.popup, SIGNAL('updateProgress(int)'), self.updateProgress) self.plot_context_data_fetcher = PlotContextDataFetcher() self.plot_context_data_fetcher.initialize(self.plot_context_data_fetcher.getModel()) self.plot_data_fetcher = PlotDataFetcher() self.plot_data_fetcher.initialize(self.plot_data_fetcher.getModel()) def updateProgress(self, progress = 1): value = self.popup.progress_bar.value() self.popup.progress_bar.setValue(value + progress) def saveAll(self): self.popup.show() context_data = self.plot_context_data_fetcher.getFromModel() save_list = [] count = 0 for parameter in context_data.parameters: pt = parameter.type if pt == SummaryModel.TYPE or pt == KeywordModel.TYPE or pt == enums.obs_impl_type.FIELD_OBS: save_list.append(parameter) parameter.setUserData({'state' : enums.ert_state_enum.FORECAST}) if pt == KeywordModel.TYPE: choices = context_data.key_index_list[parameter.name] parameter.getUserData()['key_index_choices'] = choices count += len(choices) else: count += 1 self.popup.progress_bar.setMaximum(count) for parameter in save_list: if parameter.type == KeywordModel.TYPE: for choice in parameter.getUserData()['key_index_choices']: self.plot_data_fetcher.setParameter(parameter, context_data) parameter.getUserData()['key_index'] = choice # because setParameter overwrites this value self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) else: self.plot_data_fetcher.setParameter(parameter, context_data) self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) self.popup.ok_button.setEnabled(True) def save(self, plot_data): self.popup.show() self.popup.progress_bar.setMaximum(1) self.savePlot(plot_data) self.popup.ok_button.setEnabled(True) def savePlot(self, plot_data): generated_plot = self.generatePlot(plot_data) if generated_plot: self.savePlotToFile(plot_data.getSaveName()) self.popup.emit(SIGNAL('updateProgress(int)'), 1) def generatePlot(self, plot_data): name = plot_data.getSaveName() load_success = self.plot_config_loader.load(name, self.plot_settings) if load_success: self.plot_figure.drawPlot(plot_data, self.plot_settings) self.canvas.draw() return load_success def savePlotToFile(self, filename): """Save the plot visible in the figure.""" plot_path = self.plot_settings.getPlotPath() if not os.path.exists(plot_path): os.makedirs(plot_path) path = plot_path + "/" + filename self.plot_figure.getFigure().savefig(path + ".png", dpi=400, format="png") self.plot_figure.getFigure().savefig(path + ".pdf", dpi=400, format="pdf")
class PlotGenerator(QFrame): def __init__(self, plot_path, plot_config_path): QFrame.__init__(self) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.plot_figure = PlotFigure() self.canvas = FigureCanvas(self.plot_figure.getFigure()) self.canvas.setParent(self) self.canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) size = QSize(297*2, 210*2) # A4 aspectratio self.canvas.setMaximumSize(size) self.canvas.setMinimumSize(size) self.setMaximumSize(size) self.setMinimumSize(size) self.popup = Popup(self) self.plot_config_loader = PlotSettingsLoader() self.plot_settings = PlotSettings() self.plot_settings.setPlotPath(plot_path) self.plot_settings.setPlotConfigPath(plot_config_path) self.connect(self.popup, SIGNAL('updateProgress(int)'), self.updateProgress) self.plot_context_data_fetcher = PlotContextDataFetcher() self.plot_context_data_fetcher.initialize(self.plot_context_data_fetcher.getModel()) self.plot_data_fetcher = PlotDataFetcher() self.plot_data_fetcher.initialize(self.plot_data_fetcher.getModel()) def updateProgress(self, progress = 1): value = self.popup.progress_bar.value() self.popup.progress_bar.setValue(value + progress) def saveAll(self): self.popup.show() context_data = self.plot_context_data_fetcher.getFromModel() save_list = [] count = 0 for parameter in context_data.parameters: pt = parameter.type if pt == SummaryModel.TYPE or pt == KeywordModel.TYPE or pt == enums.obs_impl_type.FIELD_OBS: save_list.append(parameter) parameter.setUserData({'state' : enums.ert_state_enum.FORECAST}) if pt == KeywordModel.TYPE: choices = context_data.key_index_list[parameter.name] parameter.getUserData()['key_index_choices'] = choices count += len(choices) else: count += 1 self.popup.progress_bar.setMaximum(count) for parameter in save_list: if parameter.type == KeywordModel.TYPE: for choice in parameter.getUserData()['key_index_choices']: self.plot_data_fetcher.setParameter(parameter, context_data) parameter.getUserData()['key_index'] = choice # because setParameter overwrites this value self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) else: self.plot_data_fetcher.setParameter(parameter, context_data) self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) self.popup.ok_button.setEnabled(True) def save(self, plot_data): self.popup.show() self.popup.progress_bar.setMaximum(1) self.savePlot(plot_data) self.popup.ok_button.setEnabled(True) def savePlot(self, plot_data): generated_plot = self.generatePlot(plot_data) if generated_plot: self.savePlotToFile(plot_data.getSaveName()) self.popup.emit(SIGNAL('updateProgress(int)'), 1) def generatePlot(self, plot_data): name = plot_data.getSaveName() load_success = self.plot_config_loader.load(name, self.plot_settings) if load_success: self.plot_figure.drawPlot(plot_data, self.plot_settings) self.canvas.draw() return load_success def savePlotToFile(self, filename): """Save the plot visible in the figure.""" plot_path = self.plot_settings.getPlotPath() if not os.path.exists(plot_path): os.makedirs(plot_path) path = plot_path + "/" + filename self.plot_figure.getFigure().savefig(path + ".png", dpi=400, format="png") self.plot_figure.getFigure().savefig(path + ".pdf", dpi=400, format="pdf")
class Window(QtGui.QMainWindow): r""" A mainwindow object for the GUI display. Inherits from QMainWindow.""" def __init__(self): super(Window, self).__init__() self.interface() def interface(self): r""" Contains the main window interface generation functionality. Commented where needed.""" # Get the screen width and height and set the main window to that size screen = QtGui.QDesktopWidget().screenGeometry() self.setGeometry(0, 0, 800, screen.height()) self.setMaximumSize(QtCore.QSize(800, 2000)) # Set the window title and icon self.setWindowTitle("WAVE: Weather Analysis and Visualization Environment") self.setWindowIcon(QtGui.QIcon('./img/wave_64px.png')) # Import the stylesheet for this window and set it to the window stylesheet = "css/MainWindow.css" with open(stylesheet, "r") as ssh: self.setStyleSheet(ssh.read()) self.setAutoFillBackground(True) self.setBackgroundRole(QtGui.QPalette.Highlight) # Create actions for menus and toolbar exit_action = QtGui.QAction(QtGui.QIcon('./img/exit_64px.png'), 'Exit', self) exit_action.setShortcut('Ctrl+Q') exit_action.setStatusTip('Exit application') exit_action.triggered.connect(self.close) clear_action = QtGui.QAction(QtGui.QIcon('./img/clear_64px.png'), 'Clear the display', self) clear_action.setShortcut('Ctrl+C') clear_action.setStatusTip('Clear the display') clear_action.triggered.connect(self.clear_canvas) skewt_action = QtGui.QAction(QtGui.QIcon('./img/skewt_64px.png'), 'Open the skew-T dialog', self) skewt_action.setShortcut('Ctrl+S') skewt_action.setStatusTip('Open the skew-T dialog') skewt_action.triggered.connect(self.skewt_dialog) radar_action = QtGui.QAction(QtGui.QIcon('./img/radar_64px.png'), 'Radar', self) radar_action.setShortcut('Ctrl+R') radar_action.setStatusTip('Open Radar Dialog Box') radar_action.triggered.connect(self.radar_dialog) # Create the top menubar, setting native to false (for OS) and add actions to the menus menubar = self.menuBar() menubar.setNativeMenuBar(False) filemenu = menubar.addMenu('&File') editmenu = menubar.addMenu('&Edit') helpmenu = menubar.addMenu('&Help') filemenu.addAction(exit_action) # Create the toolbar, place it on the left of the GUI and add actions to toolbar left_tb = QtGui.QToolBar() self.addToolBar(QtCore.Qt.LeftToolBarArea, left_tb) left_tb.setMovable(False) left_tb.addAction(clear_action) left_tb.addAction(skewt_action) left_tb.addAction(radar_action) self.setIconSize(QtCore.QSize(30, 30)) # Create the toolbar, place it on the left of the GUI and add actions to toolbar right_tb = QtGui.QToolBar() self.addToolBar(QtCore.Qt.RightToolBarArea, right_tb) right_tb.setMovable(False) right_tb.addAction(clear_action) right_tb.addAction(skewt_action) right_tb.addAction(radar_action) # Create the status bar with a default display self.statusBar().showMessage('Ready') # Figure and canvas widgets that display the figure in the GUI self.figure = plt.figure(facecolor='#2B2B2B') self.canvas = FigureCanvas(self.figure) # Add subclassed matplotlib navbar to GUI # spacer widgets for left and right of buttons left_spacer = QtGui.QWidget() left_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) right_spacer = QtGui.QWidget() right_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.mpltb = QtGui.QToolBar() self.mpltb.addWidget(left_spacer) self.mpltb.addWidget(MplToolbar(self.canvas, self)) self.mpltb.addWidget(right_spacer) self.mpltb.setMovable(False) self.addToolBar(QtCore.Qt.TopToolBarArea, self.mpltb) # Set the figure as the central widget and show the GUI self.setCentralWidget(self.canvas) self.show() def skewt_dialog(self): r""" When the toolbar icon for the Skew-T dialog is clicked, this function is executed. Creates an instance of the SkewTDialog object which is the dialog box. If the submit button on the dialog is clicked, get the user inputted values and pass them into the sounding retrieval call (DataAccessor.get_sounding) to fetch the data. Finally, plot the returned data via self.plot. Args: None. Returns: None. Raises: None. """ dialog = SkewTDialog() if dialog.exec_(): source, lat, long = dialog.get_values() t, td, p, u, v, lat, long, time = DataAccessor.get_sounding(source, lat, long) self.plot(t, td, p, u, v, lat, long, time) def plot(self, t, td, p, u, v, lat, long, time): r"""Displays the Skew-T data on a matplotlib figure. Args: t (array-like): A list of temperature values. td (array-like): A list of dewpoint values. p (array-like): A list of pressure values. u (array-like): A list of u-wind component values. v (array-like): A list of v-wind component values. lat (string): A string containing the requested latitude value. long (string): A string containing the requested longitude value. time (string): A string containing the UTC time requested with seconds truncated. Returns: None. Raises: None. """ # Create a new figure. The dimensions here give a good aspect ratio self.skew = SkewT(self.figure, rotation=40) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot self.skew.plot(p, t, 'r') self.skew.plot(p, td, 'g') self.skew.plot_barbs(p, u, v, barbcolor='#FF0000', flagcolor='#FF0000') self.skew.ax.set_ylim(1000, 100) self.skew.ax.set_xlim(-40, 60) # Axis colors self.skew.ax.tick_params(axis='x', colors='#A3A3A4') self.skew.ax.tick_params(axis='y', colors='#A3A3A4') # Calculate LCL height and plot as black dot l = lcl(p[0], t[0], td[0]) lcl_temp = dry_lapse(concatenate((p[0], l)), t[0])[-1].to('degC') self.skew.plot(l, lcl_temp, 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = parcel_profile(p, t[0], td[0]).to('degC') self.skew.plot(p, prof, 'k', linewidth=2) # Color shade areas between profiles self.skew.ax.fill_betweenx(p, t, prof, where=t >= prof, facecolor='#5D8C53', alpha=0.7) self.skew.ax.fill_betweenx(p, t, prof, where=t < prof, facecolor='#CD6659', alpha=0.7) # Add the relevant special lines self.skew.plot_dry_adiabats() self.skew.plot_moist_adiabats() self.skew.plot_mixing_lines() # Set title deg = u'\N{DEGREE SIGN}' self.skew.ax.set_title('Sounding for ' + lat + deg + ', ' + long + deg + ' at ' + time + 'z', y=1.02, color='#A3A3A4') # Discards old graph, works poorly though # skew.ax.hold(False) # Figure and canvas widgets that display the figure in the GUI # set canvas size to display Skew-T appropriately self.canvas.setMaximumSize(QtCore.QSize(800, 2000)) # refresh canvas self.canvas.draw() def radar_dialog(self): r""" When the toolbar icon for the Skew-T dialog is clicked, this function is executed. Creates an instance of the SkewTDialog object which is the dialog box. If the submit button on the dialog is clicked, get the user inputted values and pass them into the sounding retrieval call (DataAccessor.get_sounding) to fetch the data. Finally, plot the returned data via self.plot. Args: None. Returns: None. Raises: None. """ radar_dialog = RadarDialog() if radar_dialog.exec_(): station, product = radar_dialog.get_radarvals() x, y, ref = DataAccessor.get_radar(station, product) self.plot_radar(x, y, ref) def plot_radar(self, x, y, ref): r"""Displays the Skew-T data on a matplotlib figure. Args: t (array-like): A list of temperature values. td (array-like): A list of dewpoint values. p (array-like): A list of pressure values. u (array-like): A list of u-wind component values. v (array-like): A list of v-wind component values. lat (string): A string containing the requested latitude value. long (string): A string containing the requested longitude value. time (string): A string containing the UTC time requested with seconds truncated. Returns: None. Raises: None. """ self.ax = self.figure.add_subplot(111) self.ax.pcolormesh(x, y, ref) self.ax.set_aspect('equal', 'datalim') self.ax.set_xlim(-460, 460) self.ax.set_ylim(-460, 460) self.ax.tick_params(axis='x', colors='#A3A3A4') self.ax.tick_params(axis='y', colors='#A3A3A4') # set canvas size to display Skew-T appropriately self.canvas.setMaximumSize(QtCore.QSize(800, 2000)) # refresh canvas self.canvas.draw() def clear_canvas(self): self.canvas.close() self.figure = plt.figure(facecolor='#2B2B2B') self.canvas = FigureCanvas(self.figure) self.setCentralWidget(self.canvas)
class Window(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.shot = None #opened shot self.folder_name = '' #folder to search for shots self.current_num = 0 #current diagram self.currently_selected = None #selected point plot self.selected_points = OrderedSet() #point to be added self.current_point = None #plot of current point self.overall_selected = None #points added to selected list #super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) self.canvas.setParent(parent) self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.canvas.setMinimumSize(500, 0) self.canvas.mpl_connect('pick_event', self.on_pick) self.canvas.mpl_connect('motion_notify_event', self.on_move) self.canvas.hide() # this is the Navigation widget # it takes the Canvas widget and a pa rent self.toolbar = NavigationToolbar(self.canvas, self) self.toolbar.hide() # Show files widget self.files = QtGui.QListWidget() self.files.itemDoubleClicked.connect(self.select_file) self.files.setMaximumSize(200, 100000) self.files.setMinimumSize(100, 0) self.files.hide() # Show selected points self.points = ThumbListWidget(self) #self.points.itemDoubleClicked.connect(self.unselect_point) self.points.itemClicked.connect(self.points_clicked) self.points.itemDoubleClicked.connect(self.points_doubleclicked) self.points.setMaximumSize(200, 100000) self.points.setMinimumSize(100, 0) self.points.hide() #Show diagram widget self.diagrams = QtGui.QListWidget() self.diagrams.itemClicked.connect(self.select_item) self.diagrams.setMaximumSize(250, 100000) self.diagrams.setMinimumSize(190, 0) self.diagrams.hide() #save result button self.save_button = QtGui.QPushButton('Add time point', self) self.save_button.clicked.connect(self.add_time) self.save_button.hide() #filter menu self.filters_button = QtGui.QPushButton('Manage filters', self) self.filters_button.clicked.connect(self.show_filters) self.filters_button.hide() self.filters = OrderedDict self.read_filters() #diagramms self.bottom_layout = QtGui.QGridLayout() self.diagrams_figure = plt.figure() self.diagrams_canvas = FigureCanvas(self.diagrams_figure) self.diagrams_canvas.setParent(parent) self.diagrams_canvas.setMinimumSize(250, 250) self.diagrams_canvas.setMaximumSize(500, 500) self.diagrams_toolbar = NavigationToolbar(self.diagrams_canvas, self) self.diagrams_toolbar.setMaximumWidth(250) self.diagrams_ax = self.diagrams_figure.add_subplot(111) self.diagrams_ax.set_ylim(ymin=0) self.diagrams_ax.set_xlim(xmin=0) self.diagrams_canvas.draw() self.enlargre_button = QtGui.QPushButton('Enlarge diagram', self) self.enlargre_button.clicked.connect(self.enlarge_diagram) self.bottom_layout.addWidget(self.diagrams_toolbar, 0, 2) self.bottom_layout.addWidget(self.diagrams_canvas, 1, 2, QtCore.Qt.AlignRight) self.bottom_layout.addWidget(self.enlargre_button, 0, 1) # set the layout self.layout = QtGui.QGridLayout() self.layout.addWidget(self.filters_button, 0, 1) self.layout.addWidget(self.toolbar, 0, 2) self.layout.addWidget(self.canvas, 1, 2) self.layout.addWidget(self.diagrams, 1, 1) self.layout.addWidget(self.files, 1, 0) self.layout.addWidget(self.points, 1, 3) self.layout.addWidget(self.save_button, 0, 3) self.layout.addLayout(self.bottom_layout, 2, 2) self.setLayout(self.layout) def enlarge_diagram(self): #меняет местами диаграммы pass def points_doubleclicked(self): if self.points._mouse_button == 1: num = self.points.currentRow() point = list(self.selected_points)[num] diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - point[0]).argmin() npoint = (xs[idx], ys[idx], self.current_num, self.shot.file[0]) for point in list(self.selected_points): if point[2] == self.current_point[2] and point[3] == self.current_point[3]: self.selected_points.remove(point) self.selected_points.add(npoint) self.refresh_points() def greenvald(self): #диаграмма хьюгилла #TODO - move to another file temp = {} names = self.shot.get_diagram_names() for x in self.selected_points: if x[3] not in temp: temp[x[3]] = {} tag = "" for name, value in self.filters.items(): if re.compile(value).match(names[x[2]]): tag = name break if tag: temp[x[3]][tag] = x[0], x[1], x[3] #X, Y, Shot points = [] for x in temp: if "Ip" in temp[x] and "neL" in temp[x] and "ITF" in temp[x]: a = 24 R = 36 k = 1.65 #print("wololo") Ip = temp[x]["Ip"][1]/1000 Itf = temp[x]["ITF"][1]/1000 neL = temp[x]["neL"][1] Bt = Itf*0.001*100*16*0.2/R print(Ip) print(Itf) print(neL) print(Bt) qcyl = 5*a*a*0.01*0.01*Bt*100*1000/(R*Ip) print(qcyl) #print(temp[x]) #print(Itf) #print(neL) rqcyl = 1/qcyl print(rqcyl) print("wololo") ne = neL*0.03/k BtrR = Bt*100/R print(ne) print(BtrR) neRrBt = ne/BtrR print(neRrBt) points.append(((neRrBt, rqcyl), temp[x]["Ip"][2])) return points def update_diagramms(self): points = self.greenvald() x = [tmp[0][0] for tmp in points] y = [tmp[0][1] for tmp in points] #self.diagrams_figure.clf() self.diagrams_ax.set_xlabel('neR/BT, 10^20/(T*m^2)') self.diagrams_ax.set_ylabel('1/qcyl') self.diagrams_ax.set_title("Greenwald") self.diagrams_ax.plot(x, y, 'bo', ms=5, alpha=0.8, markersize=5) self.diagrams_canvas.draw() print(points) def points_clicked(self):#один клик, правая кнопка - удалить точку, левая - подсветить if self.points._mouse_button == 1: num = self.points.currentRow() point = list(self.selected_points)[num] diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - point[0]).argmin() self.highlight.set_xdata([xs[idx]]) self.highlight.set_ydata([ys[idx]]) else: self.unselect_point(None) def read_filters(self): with open("filters.conf") as inp: lines = inp.readlines() n = int(lines[0]) mass = [] for i in range(n): mass.append((lines[2*i+1].strip(), lines[2*(i+1)].strip())) self.filters = OrderedDict(mass) def show_filters(self): self.f = FiltersPopup(self.filters) self.f.setGeometry(100, 100, 400, 200) self.f.exec_() self.filters = self.f.getValues() self.show_diagrams() def add_time(self): time, ok = QtGui.QInputDialog.getText(self, 'Time point', 'enter time point in seconds(e.g. 0.123):') if ok: if time.isdigit: diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - float(time)/1000).argmin() npoint = (xs[idx], ys[idx], self.current_num, self.shot.file[0]) for point in list(self.selected_points): if point[2] == self.current_point[2] and point[3] == self.current_point[3]: print("wololololololo") self.selected_points.remove(point) self.selected_points.add(npoint) self.refresh_points() def select_item(self, current): self.figure.clf() name = self.diagrams.currentItem().text() names = self.shot.get_diagram_names() if name in names: self.current_num = names.index(name) else: self.current_num = names.index("".join(name.split(':')[1:])[1:]) self.plot(self.shot.get_diagram(self.current_num)) def unselect_point(self, current): num = self.points.currentRow() self.selected_points.remove(list(self.selected_points)[num]) self.refresh_points() def select_file(self, current): self.figure.clf() self.show_shot(Shot(join(self.folder_name, self.files.currentItem().text()))) self.canvas.setFocus() def on_pick(self, event): print(self.selected_points) if self.current_point in self.selected_points: self.selected_points.remove(self.current_point) else: for point in list(self.selected_points): if point[2] == self.current_point[2] and point[3] == self.current_point[3]: print("wololo") self.selected_points.remove(point) self.selected_points.add(self.current_point) self.refresh_points() def refresh_points(self): self.update_diagramms() self.points.clear() self.points.addItems([str(x[0]) for x in self.selected_points]) self.overall_selected.set_xdata(self.active_points[0]) self.overall_selected.set_ydata(self.active_points[1]) def on_move(self, event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: ax = event.inaxes # the axes instance diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - event.xdata).argmin() self.currently_selected.set_xdata([diag.x[idx]]) self.currently_selected.set_ydata([diag.y[idx]]) self.current_point = (diag.x[idx], diag.y[idx], self.current_num, self.shot.file[0]) self.canvas.draw() @property def active_points(self): x = [x[0] for x in self.selected_points if x[2] == self.current_num and x[3] == self.shot.file[0]] y = [x[1] for x in self.selected_points if x[2] == self.current_num and x[3] == self.shot.file[0]] return x, y def plot(self, diagram=None): # create an axis ax = self.figure.add_subplot(111) # discards the old graph #pridicted max value ind = np.argmax(np.array(diagram.y)) # plot data if diagram: self.highlight, = ax.plot([diagram.x[ind]], [diagram.y[ind]], 'bo', ms=12, alpha=0.8, markersize=8) ax.plot(diagram.x, diagram.y, 'b-') self.currently_selected, = ax.plot([diagram.x[ind]], [diagram.y[ind]], 'yo', ms=12, alpha=0.6, markersize=6, picker=15) self.overall_selected, = ax.plot(self.active_points[0], self.active_points[1], 'ro', ms=12, alpha=0.9, markersize=4) ax.set_xlabel('t, sec') ax.set_ylabel(diagram.unit) ax.set_title(diagram.comment) self.figure.tight_layout() # refresh canvas self.canvas.draw() def show_diagrams(self): names = self.shot.get_diagram_names() self.diagrams.clear() res = set() for x in names: for name, reg in self.filters.items(): try: if re.compile(reg).match(x): res.add(str(name) + ': ' + str(x)) break except: pass #self.diagrams.addItems(list(names)) self.diagrams.addItems(list(res)) self.diagrams.show() def show_shot(self, shot): self.shot = shot self.show_diagrams() self.toolbar.show() self.canvas.show() self.files.show() self.points.show() self.save_button.show() self.filters_button.show() self.current_num = 0 self.plot(self.shot.get_diagram(0)) self.canvas.setFocus()