def onData(self): """ Executed when selected item data is modified. """ if not self.skip: self.skip = True plt = Plot.getPlot() if not plt: self.updateUI() return # Ensure that selected serie exist if self.item >= len(Plot.series()): self.updateUI() return # Set label serie = Plot.series()[self.item] if(self.form.isLabel.isChecked()): serie.name = None self.form.label.setEnabled(False) else: serie.name = self.form.label.text() self.form.label.setEnabled(True) # Set line style and marker style = self.form.style.currentIndex() linestyles = Line2D.lineStyles.keys() serie.line.set_linestyle(linestyles[style]) marker = self.form.marker.currentIndex() markers = Line2D.markers.keys() serie.line.set_marker(markers[marker]) # Set line width and marker size serie.line.set_linewidth(self.form.width.value()) serie.line.set_markersize(self.form.size.value()) plt.update() # Regenerate series labels self.setList() self.skip = False
def onData(self, value): """ Executed when selected item data is modified. """ plt = Plot.getPlot() if not plt: self.updateUI() return if not self.skip: self.skip = True name = self.names[self.item] obj = self.objs[self.item] x = self.form.x.value() y = self.form.y.value() s = self.form.s.value() # x/y labels only have one position control if name.find('x label') >= 0: self.form.y.setValue(x) elif name.find('y label') >= 0: self.form.x.setValue(y) # title and labels only have one size control if name.find('title') >= 0 or name.find('label') >= 0: obj.set_position((x,y)) obj.set_size(s) # legend have all controls else: Plot.legend(plt.legend, (x,y), s) plt.update() self.skip = False
def onColor(self): """ Executed when color pallete is requested. """ plt = Plot.getPlot() if not plt: self.updateUI() return mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.color = self.widget(QtGui.QPushButton, "color") # Ensure that selected serie exist if self.item >= len(Plot.series()): self.updateUI() return # Show widget to select color col = QtGui.QColorDialog.getColor() # Send color to widget and serie if col.isValid(): serie = plt.series[self.item] form.color.setStyleSheet( "background-color: rgb({}, {}, {});".format(col.red(), col.green(), col.blue())) serie.line.set_color((col.redF(), col.greenF(), col.blueF())) plt.update()
def onOffset(self, value): """Executed when axes offsets have been modified.""" # Ensure that we can work plt = Plot.getPlot() if not plt: self.updateUI() return # Get again all the subwidgets (to avoid PySide Pitfalls) mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.all = self.widget(QtGui.QCheckBox, "allAxes") form.xOffset = self.widget(QtGui.QSpinBox, "xOffset") form.yOffset = self.widget(QtGui.QSpinBox, "yOffset") axesList = [plt.axes] if form.all.isChecked(): axesList = plt.axesList # Set new offset for axes in axesList: # For some reason, modify spines offset erase axes labels, so we # need store it in order to regenerate later x = axes.get_xlabel() y = axes.get_ylabel() for loc, spine in axes.spines.iteritems(): if loc in ['bottom', 'top']: spine.set_position(('outward', form.xOffset.value())) if loc in ['left', 'right']: spine.set_position(('outward', form.yOffset.value())) # Now we can restore axes labels Plot.xlabel(unicode(x)) Plot.ylabel(unicode(y)) plt.update()
def onOffset(self, value): """ Executed when axes offsets have been modified. """ # Get apply environment plt = Plot.getPlot() if not plt: self.updateUI() return axesList = [plt.axes] if self.form.all.isChecked(): axesList = plt.axesList # Set new offset for axes in axesList: # For some reason, modify spines offset erase axes labels, so we # need store it in order to regenerate later x = axes.get_xlabel() y = axes.get_ylabel() for loc, spine in axes.spines.iteritems(): if loc in ['bottom', 'top']: spine.set_position(('outward',self.form.xOffset.value())) if loc in ['left', 'right']: spine.set_position(('outward',self.form.yOffset.value())) # Now we can restore axes labels Plot.xlabel(unicode(x)) Plot.ylabel(unicode(y)) plt.update()
def trainData3(folder, gradDecent): datas, labels = LR.loadDataSet(folder, "data3.txt"); datasMap = []; degree = 6; m = np.shape(datas)[0]; for k in range(m): tmp = [1]; for i in range(degree): for j in range(i + 2): tmp.append(pow(datas[k][0], i + 1 - j) * pow(datas[k][1], j)); datasMap.append(tmp); datas = np.mat(datasMap); alpha = 1; lamb = 1; # itemNum = 100; # batch itemNum = 500; thetas = gradDecent(datas, labels, alpha, lamb, itemNum); print "thetas: ", thetas; thetas = np.mat(thetas); m = np.shape(datas)[0]; error = 0; for i in range(m): pred = LR.classfy(thetas, np.mat(datas[i])); if pred != labels[i]: error = error + 1; errorRate = float(error) * 100 / m; print "The error rate of the test is %f percents" % errorRate thetas = np.array(thetas)[0]; Plot.plot(folder, "data3.txt", thetas);
def stocGradDecent(X, Y, alpha, lamb, iterNum): X = np.mat(X); Ymat = np.mat(Y); m, n = np.shape(X); thetas = np.zeros((1, n)); costs = []; for i in range(iterNum): dataIndex = range(m); for j in range(m): alpha = 4 / (1.0 + j + i) + 0.01; randIndex = int(np.random.uniform(0, len(dataIndex))); thetas_re = [0]; thetas_re.extend(thetas[0][1:]); thetas_re = np.mat(thetas_re); grads = (X[randIndex,:] * np.sum(sigmoid(X[randIndex,:] * thetas.T) - Y[randIndex])) + lamb * thetas_re; thetas = thetas - alpha * grads del(dataIndex[randIndex]) thetas_re = [0]; thetas_re.extend(thetas[0][1:]); thetas_re = np.mat(thetas_re); cost = (-1.0 / m) * np.sum(Ymat * np.log(sigmoid(X * thetas.T)) + (1 - Ymat) * np.log(1 - sigmoid(X * thetas.T))) + (lamb / (2 * m)) * np.sum(thetas_re * thetas_re.T); costs.append([i+1, cost]); print "Iterater time: %d, cost: %f" % ((i+1), cost); Plot.plotCost(costs); return np.array(thetas)[0];
def onData(self, value): """ Executed when selected item data is modified. """ plt = Plot.getPlot() if not plt: self.updateUI() return mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.items = self.widget(QtGui.QListWidget, "items") form.x = self.widget(QtGui.QDoubleSpinBox, "x") form.y = self.widget(QtGui.QDoubleSpinBox, "y") form.s = self.widget(QtGui.QDoubleSpinBox, "size") if not self.skip: self.skip = True name = self.names[self.item] obj = self.objs[self.item] x = form.x.value() y = form.y.value() s = form.s.value() # x/y labels only have one position control if name.find('x label') >= 0: form.y.setValue(x) elif name.find('y label') >= 0: form.x.setValue(y) # title and labels only have one size control if name.find('title') >= 0 or name.find('label') >= 0: obj.set_position((x, y)) obj.set_size(s) # legend have all controls else: Plot.legend(plt.legend, (x, y), s) plt.update() self.skip = False
def setupUi(self): mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.axId = form.findChild(QtGui.QSpinBox, "axesIndex") form.title = form.findChild(QtGui.QLineEdit, "title") form.titleSize = form.findChild(QtGui.QSpinBox, "titleSize") form.xLabel = form.findChild(QtGui.QLineEdit, "titleX") form.xSize = form.findChild(QtGui.QSpinBox, "xSize") form.yLabel = form.findChild(QtGui.QLineEdit, "titleY") form.ySize = form.findChild(QtGui.QSpinBox, "ySize") self.form = form self.retranslateUi() # Look for active axes if can axId = 0 plt = Plot.getPlot() if plt: while plt.axes != plt.axesList[axId]: axId = axId + 1 form.axId.setValue(axId) self.updateUI() QtCore.QObject.connect(form.axId, QtCore.SIGNAL('valueChanged(int)'),self.onAxesId) QtCore.QObject.connect(form.title, QtCore.SIGNAL("editingFinished()"),self.onLabels) QtCore.QObject.connect(form.xLabel, QtCore.SIGNAL("editingFinished()"),self.onLabels) QtCore.QObject.connect(form.yLabel, QtCore.SIGNAL("editingFinished()"),self.onLabels) QtCore.QObject.connect(form.titleSize,QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes) QtCore.QObject.connect(form.xSize, QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes) QtCore.QObject.connect(form.ySize, QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes) QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) return False
def onNew(self): """ Executed when new axes must be created. """ plt = Plot.getPlot() if not plt: self.updateUI() return Plot.addNewAxes() self.form.axId.setValue(len(plt.axesList)-1) plt.update()
def Activated(self): import Plot from plotUtils import Translator plt = Plot.getPlot() if not plt: msg = Translator.translate("Legend must be activated on top of a plot document.") FreeCAD.Console.PrintError(msg+"\n") return flag = plt.isLegend() Plot.legend(not flag)
def Activated(self): import Plot plt = Plot.getPlot() if not plt: msg = QtGui.QApplication.translate("plot_console", "Grid must be activated on top of a plot document", None,QtGui.QApplication.UnicodeUTF8) FreeCAD.Console.PrintError(msg+"\n") return flag = plt.isGrid() Plot.grid(not flag)
def plot(self, roll, gz): """ Plot the GZ curve. Position arguments: roll -- List of roll angles (in degrees). gz -- List of GZ values (in meters). """ try: import Plot plt = Plot.figure('GZ') except ImportError: msg = QtGui.QApplication.translate( "ship_console", "Plot module is disabled, so I cannot perform the plot", None) FreeCAD.Console.PrintWarning(msg + '\n') return True gz_plot = Plot.plot(roll, gz, 'GZ curve') gz_plot.line.set_linestyle('-') gz_plot.line.set_linewidth(1.0) gz_plot.line.set_color((0.0, 0.0, 0.0)) ax = Plot.axes() Plot.xlabel(r'$\phi \; [\mathrm{deg}]$') Plot.ylabel(r'$GZ \; [\mathrm{m}]$') ax.xaxis.label.set_fontsize(20) ax.yaxis.label.set_fontsize(20) Plot.grid(True) plt.update() return False
def accept(self): plt = Plot.getPlot() if not plt: msg = Translator.translate("Plot document must be selected in order to save it.") App.Console.PrintError(msg+"\n") return False path = unicode(self.form.path.text()) size = (self.form.sizeX.value(), self.form.sizeY.value()) dpi = self.form.dpi.value() Plot.save(path, size, dpi) return True
def test_procedure(self, list_n_context_choice, context_selectors, n_repetitions=20, results_file="results-test.json", seed=None): (nSample, nFeature) = np.shape(self.dataset) #cast single object to list if type(context_selectors) is not dict: context_selectors = {"default": context_selectors} if type(list_n_context_choice) is not list: list_n_context_choice = [list_n_context_choice] #initialize statistics collection results_by_algorithm = {} for n_context_choice in list_n_context_choice: results_by_algorithm[n_context_choice] = {} for name in context_selectors.keys(): results_by_algorithm[n_context_choice][name] = [] pool = multiprocessing.Pool(len(context_selectors)) for repetition in range(n_repetitions): # experiments for n_context_choice in list_n_context_choice: print((repetition + 1), "repetition with", n_context_choice, "contexts") # set up rng for the current run self.__prepare_holdout(nSample, seed) for selector in context_selectors.values(): selector.train_method.set_seed(seed) # parallel execution self.n_context_choice = n_context_choice results = pool.map(self._test_selector, context_selectors.items()) # result gathering order = np.argsort([r[1] for r in results]) for i in range(len(results)): # performance visualization selector_name, actual_mae = results[order[i]] if i == 0: dif = 0 else: dif = results[order[i-1]][1] - actual_mae print(selector_name, actual_mae, "(", dif, ")") results_by_algorithm[n_context_choice][selector_name].append(actual_mae) # save current results with open(results_file, 'w') as f: f.write(json.dumps(results_by_algorithm)) # setup RNG for the next iteration if seed is not None: seed += 17 Plot.plot(results_by_algorithm)
def accept(self): plt = Plot.getPlot() if not plt: msg = QtGui.QApplication.translate("plot_console", "Plot document must be selected in order to save it", None,QtGui.QApplication.UnicodeUTF8) App.Console.PrintError(msg+"\n") return False path = unicode(self.form.path.text()) size = (self.form.sizeX.value(), self.form.sizeY.value()) dpi = self.form.dpi.value() Plot.save(path, size, dpi) return True
def performance_test(ml,clf,result,features,**args): plt.draw_roc(ml.y_test,result,ml.tag) if args['mla_selection'] == 'rf' and\ (args['estimators'] is True or\ args['classes'] is True or\ args['feature_importance'] is True): print("\n=== Diagnostic(s) of Trained RandomForest ===") MLA.DiagnosingTrainedForest(clf,features,**args) else: pass
def setupUi(self): mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.axId = form.findChild(QtGui.QSpinBox, "axesIndex") form.new = form.findChild(QtGui.QPushButton, "newAxesButton") form.remove = form.findChild(QtGui.QPushButton, "delAxesButton") form.all = form.findChild(QtGui.QCheckBox, "allAxes") form.xMin = form.findChild(QtGui.QSlider, "posXMin") form.xMax = form.findChild(QtGui.QSlider, "posXMax") form.yMin = form.findChild(QtGui.QSlider, "posYMin") form.yMax = form.findChild(QtGui.QSlider, "posYMax") form.xAlign = form.findChild(QtGui.QComboBox, "xAlign") form.yAlign = form.findChild(QtGui.QComboBox, "yAlign") form.xOffset = form.findChild(QtGui.QSpinBox, "xOffset") form.yOffset = form.findChild(QtGui.QSpinBox, "yOffset") form.xAuto = form.findChild(QtGui.QCheckBox, "xAuto") form.yAuto = form.findChild(QtGui.QCheckBox, "yAuto") form.xSMin = form.findChild(QtGui.QLineEdit, "xMin") form.xSMax = form.findChild(QtGui.QLineEdit, "xMax") form.ySMin = form.findChild(QtGui.QLineEdit, "yMin") form.ySMax = form.findChild(QtGui.QLineEdit, "yMax") self.form = form self.retranslateUi() # Look for active axes if can axId = 0 plt = Plot.getPlot() if plt: while plt.axes != plt.axesList[axId]: axId = axId + 1 form.axId.setValue(axId) self.updateUI() QtCore.QObject.connect(form.axId, QtCore.SIGNAL('valueChanged(int)'),self.onAxesId) QtCore.QObject.connect(form.new, QtCore.SIGNAL("pressed()"),self.onNew) QtCore.QObject.connect(form.remove, QtCore.SIGNAL("pressed()"),self.onRemove) QtCore.QObject.connect(form.xMin, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.QObject.connect(form.xMax, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.QObject.connect(form.yMin, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.QObject.connect(form.yMax, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.QObject.connect(form.xAlign, QtCore.SIGNAL("currentIndexChanged(int)"),self.onAlign) QtCore.QObject.connect(form.yAlign, QtCore.SIGNAL("currentIndexChanged(int)"),self.onAlign) QtCore.QObject.connect(form.xOffset,QtCore.SIGNAL("valueChanged(int)"),self.onOffset) QtCore.QObject.connect(form.yOffset,QtCore.SIGNAL("valueChanged(int)"),self.onOffset) QtCore.QObject.connect(form.xAuto, QtCore.SIGNAL("stateChanged(int)"),self.onScales) QtCore.QObject.connect(form.yAuto, QtCore.SIGNAL("stateChanged(int)"),self.onScales) QtCore.QObject.connect(form.xSMin, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.QObject.connect(form.xSMax, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.QObject.connect(form.ySMin, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.QObject.connect(form.ySMax, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) return False
def create(self, title, function, xlength, xname, xunit, xscale, yname, yunit, yscale, numxpoints): # Initialize import Plot self.title = title self.function = function # This is assumed to be always a SegmentFunction self.xlength = xlength self.xname = xname self.xunit = xunit self.xscale = xscale self.yname = yname self.yunit = yunit self.yscale = yscale self.numxpoints = numxpoints # Create a plot window self.win = Plot.figure(title) # Get the plot object from the window self.thePlot = Plot.getPlot() # Format the plot object Plot.xlabel("$%s$ [%s]" % (xname, xunit)) Plot.ylabel("$%s$ [%s]" % (yname, yunit)) Plot.grid(True) # Calculate points (self.xpoints, self.ypoints) = self.function.evaluate(self.xlength, self.numxpoints) # Create plot self.plot()
def onRemove(self): """Executed when the data serie must be removed.""" plt = Plot.getPlot() if not plt: self.updateUI() return # Ensure that selected serie exist if self.item >= len(Plot.series()): self.updateUI() return # Remove serie Plot.removeSerie(self.item) self.setList() self.updateUI() plt.update()
def onNew(self): """Executed when new axes must be created.""" # Ensure that we can work plt = Plot.getPlot() if not plt: self.updateUI() return # Get again all the subwidgets (to avoid PySide Pitfalls) mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.axId = self.widget(QtGui.QSpinBox, "axesIndex") Plot.addNewAxes() form.axId.setValue(len(plt.axesList) - 1) plt.update()
def updateUI(self): """ Setup UI controls values if possible """ plt = Plot.getPlot() self.form.axId.setEnabled(bool(plt)) self.form.title.setEnabled(bool(plt)) self.form.titleSize.setEnabled(bool(plt)) self.form.xLabel.setEnabled(bool(plt)) self.form.xSize.setEnabled(bool(plt)) self.form.yLabel.setEnabled(bool(plt)) self.form.ySize.setEnabled(bool(plt)) if not plt: return # Ensure that active axes is correct index = min(self.form.axId.value(), len(plt.axesList)-1) self.form.axId.setValue(index) # Store data before starting changing it. ax = plt.axes t = ax.get_title() x = ax.get_xlabel() y = ax.get_ylabel() tt = ax.title.get_fontsize() xx = ax.xaxis.label.get_fontsize() yy = ax.yaxis.label.get_fontsize() # Set labels self.form.title.setText(t) self.form.xLabel.setText(x) self.form.yLabel.setText(y) # Set font sizes self.form.titleSize.setValue(tt) self.form.xSize.setValue(xx) self.form.ySize.setValue(yy)
def setupUi(self): mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.items = form.findChild(QtGui.QListWidget, "items") form.label = form.findChild(QtGui.QLineEdit, "label") form.isLabel = form.findChild(QtGui.QCheckBox, "isLabel") form.style = form.findChild(QtGui.QComboBox, "lineStyle") form.marker = form.findChild(QtGui.QComboBox, "markers") form.width = form.findChild(QtGui.QDoubleSpinBox, "lineWidth") form.size = form.findChild(QtGui.QSpinBox, "markerSize") form.color = form.findChild(QtGui.QPushButton, "color") form.remove = form.findChild(QtGui.QPushButton, "remove") self.form = form self.retranslateUi() self.fillStyles() self.updateUI() QtCore.QObject.connect(form.items, QtCore.SIGNAL("currentRowChanged(int)"),self.onItem) QtCore.QObject.connect(form.label, QtCore.SIGNAL("editingFinished()"),self.onData) QtCore.QObject.connect(form.isLabel,QtCore.SIGNAL("stateChanged(int)"),self.onData) QtCore.QObject.connect(form.style, QtCore.SIGNAL("currentIndexChanged(int)"),self.onData) QtCore.QObject.connect(form.marker, QtCore.SIGNAL("currentIndexChanged(int)"),self.onData) QtCore.QObject.connect(form.width, QtCore.SIGNAL("valueChanged(double)"),self.onData) QtCore.QObject.connect(form.size, QtCore.SIGNAL("valueChanged(int)"),self.onData) QtCore.QObject.connect(form.color, QtCore.SIGNAL("pressed()"),self.onColor) QtCore.QObject.connect(form.remove, QtCore.SIGNAL("pressed()"),self.onRemove) QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) return False
def onMdiArea(self, subWin): """ Executed when window is selected on mdi area. @param subWin Selected window. """ plt = Plot.getPlot() if plt != subWin: self.updateUI()
def onRemove(self): """Executed when axes must be deleted.""" # Ensure taht we can work plt = Plot.getPlot() if not plt: self.updateUI() return # Get again all the subwidgets (to avoid PySide Pitfalls) mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.axId = self.widget(QtGui.QSpinBox, "axesIndex") # Don't remove first axes if not form.axId.value(): msg = QtGui.QApplication.translate( "plot_console", "Axes 0 can not be deleted", None) App.Console.PrintError(msg + "\n") return # Remove axes ax = plt.axes ax.set_axis_off() plt.axesList.pop(form.axId.value()) # Ensure that active axes is correct index = min(form.axId.value(), len(plt.axesList) - 1) form.axId.setValue(index) plt.update()
def setupUi(self): mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.items = self.widget(QtGui.QListWidget, "items") form.x = self.widget(QtGui.QDoubleSpinBox, "x") form.y = self.widget(QtGui.QDoubleSpinBox, "y") form.s = self.widget(QtGui.QDoubleSpinBox, "size") self.form = form self.retranslateUi() self.updateUI() QtCore.QObject.connect( form.items, QtCore.SIGNAL("currentRowChanged(int)"), self.onItem) QtCore.QObject.connect( form.x, QtCore.SIGNAL("valueChanged(double)"), self.onData) QtCore.QObject.connect( form.y, QtCore.SIGNAL("valueChanged(double)"), self.onData) QtCore.QObject.connect( form.s, QtCore.SIGNAL("valueChanged(double)"), self.onData) QtCore.QObject.connect( Plot.getMdiArea(), QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"), self.onMdiArea) return False
def onDims(self, value): """Executed when axes dims have been modified.""" # Ensure that we can work plt = Plot.getPlot() if not plt: self.updateUI() return # Get again all the subwidgets (to avoid PySide Pitfalls) mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.all = self.widget(QtGui.QCheckBox, "allAxes") form.xMin = self.widget(QtGui.QSlider, "posXMin") form.xMax = self.widget(QtGui.QSlider, "posXMax") form.yMin = self.widget(QtGui.QSlider, "posYMin") form.yMax = self.widget(QtGui.QSlider, "posYMax") axesList = [plt.axes] if form.all.isChecked(): axesList = plt.axesList # Set new dimensions xmin = form.xMin.value() / 100.0 xmax = form.xMax.value() / 100.0 ymin = form.yMin.value() / 100.0 ymax = form.yMax.value() / 100.0 for axes in axesList: axes.set_position([xmin, ymin, xmax - xmin, ymax - ymin]) plt.update()
def onMdiArea(self, subWin): """Executed when a new window is selected on the mdi area. Keyword arguments: subWin -- Selected window. """ plt = Plot.getPlot() if plt != subWin: self.updateUI()
def batchGradDecent(X, Y, alpha, lamb, iterNum): X = np.mat(X); Y = np.mat(Y); m, n = np.shape(X); thetas = np.zeros((1, n)); costs = []; for i in range(iterNum): thetas_re = [0]; thetas_re.extend(np.array(thetas)[0][1:]); thetas_re = np.mat(thetas_re); cost = (-1.0 / m) * np.sum(Y * np.log(sigmoid(X * thetas.T)) + (1 - Y) * np.log(1 - sigmoid(X * thetas.T))) + (lamb / (2 * m)) * np.sum(thetas_re * thetas_re.T); grads = (1.0 / m) * (X.T * (sigmoid(X * thetas.T) - Y.T)) + (lamb / m) * thetas_re.T; thetas = thetas - alpha * grads.T costs.append([i+1, cost]); print "Iterater time: %d, cost: %f" % ((i+1), cost); Plot.plotCost(costs); return np.array(thetas)[0];
def onColor(self): """ Executed when color pallete is requested. """ plt = Plot.getPlot() if not plt: self.updateUI() return # Ensure that selected serie exist if self.item >= len(Plot.series()): self.updateUI() return # Show widget to select color col = QtGui.QColorDialog.getColor() # Send color to widget and serie if col.isValid(): serie = plt.series[self.item] self.form.color.setStyleSheet("background-color: rgb(%d, %d, %d);" % (col.red(), col.green(), col.blue())) serie.line.set_color((col.redF(), col.greenF(), col.blueF())) plt.update()
def accept(self): if not self.ship: return False # Get general data disp = self.computeDisplacement() draft = self.computeDraft(disp[0], self.form.trim.value()) trim = self.form.trim.value() # Get roll angles roll0 = self.form.roll0.value() roll1 = self.form.roll1.value() nRoll = self.form.nRoll.value() dRoll = (roll1 - roll0) / (nRoll - 1) roll = [] GZ = [] msg = Translator.translate("Computing GZ...\n") App.Console.PrintMessage(msg) for i in range(0, nRoll): App.Console.PrintMessage("\t%d/%d\n" % (i + 1, nRoll)) roll.append(i * dRoll) GZ.append(self.computeGZ(draft[0], trim, roll[-1])) Plot(roll, GZ, disp[0] / 1000.0, draft[0], trim) return True
def __init__(self, backend='matplotlib'): self.reset() if backend == 'gnuplot': import Gnuplot self.g = Gnuplot.Gnuplot() self.g('set style data lines') self.g.title("Simulation residuals") self.g.xlabel("Iteration") self.g.ylabel("Residual") self.g("set grid") self.g("set logscale y") self.g("set yrange [0.95:1.05]") self.g("set xrange [0:1]") elif backend == 'matplotlib': if withinFreeCAD: self.fig = Plot.figure(FreeCAD.ActiveDocument.Name + "Residuals") self.Timer = QtCore.QTimer() self.Timer.timeout.connect(self.refresh) self.Timer.start(1000) self.updated = False else: self.fig = plt.figure() self.axis = self.fig.add_subplot(1, 1, 1) self.axis.set_title("Simulation residuals") self.axis.set_xlabel("Iteration") self.axis.set_ylabel("Residual") self.axis.grid(True) self.axis.set_yscale('log') self.axis.set_ylim(1e-4, 1e2) # or autoscale? #xaxis data is not needed for steady case for var in self.residuals: self.axis.plot(self.residuals[var], label=var) plt.legend() #todo: setup animation hook else: print('plot backend {} is not supported'.format(backend)) self.backend = backend
def onAxesId(self, value): """Executed when axes index is modified.""" if not self.skip: self.skip = True # No active plot case plt = Plot.getPlot() if not plt: self.updateUI() self.skip = False return # Get again all the subwidgets (to avoid PySide Pitfalls) mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.axId = self.widget(QtGui.QSpinBox, "axesIndex") form.axId.setMaximum(len(plt.axesList)) if form.axId.value() >= len(plt.axesList): form.axId.setValue(len(plt.axesList) - 1) # Send new control to Plot instance plt.setActiveAxes(form.axId.value()) self.updateUI() self.skip = False
def doAnalysis(runners, jobName): #1. What are the mean, median, mode, and range of the race results for all racers by gender? analysis_Log.info( Analysis.AttributeStats(runners, "time_secs_net", jobName)) analysis_Log.info(Analysis.AttributeStats(runners, "int_age", jobName)) Plot.plotScatter(jobName, runners, "int_age", "time_secs_net") Plot.plotScatter(jobName, runners, "int_age", "time_secs_gun") #2. Analyze the difference between gun and net time race results. analysis_Log.info( "%s time_secs_net difference from time_secs_gun: %f" % (jobName, Analysis.getDifference(runners, Analysis.getMean, "time_secs_net", Analysis.getMean, "time_secs_gun"))) #4. Compare the race results of each division. Plot.plotBinData(jobName, runners, "int_age", "time_secs_net", divisions)
def updateUI(self): """ Setup UI controls values if possible """ mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.path = self.widget(QtGui.QLineEdit, "path") form.pathButton = self.widget(QtGui.QPushButton, "pathButton") form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX") form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY") form.dpi = self.widget(QtGui.QSpinBox, "dpi") plt = Plot.getPlot() form.path.setEnabled(bool(plt)) form.pathButton.setEnabled(bool(plt)) form.sizeX.setEnabled(bool(plt)) form.sizeY.setEnabled(bool(plt)) form.dpi.setEnabled(bool(plt)) if not plt: return fig = plt.fig size = fig.get_size_inches() dpi = fig.get_dpi() form.sizeX.setValue(size[0]) form.sizeY.setValue(size[1]) form.dpi.setValue(dpi)
def __init__(self,escalonador,arquivo,modelo): #carrega cenario self.cenario = Cenario() self.arquivo = arquivo self.escalonador = escalonador self.modelo = modelo self.quantum = self.escalonador.getQuantum() self.preemptivo = self.escalonador.getPreemp() self.colecao = Colecoes() self.tempoSimulacao = 0.0 #----------INDICADORES-----------# self.throughput = 0 self.turnaround = 0.0 self.esperaTotal = 0.0 #________________________________# self.filaDeProntos = Fila() self.plot = Plot()
def onAlign(self, value): """ Executed when axes align have been modified. """ # Get apply environment plt = Plot.getPlot() if not plt: self.updateUI() return axesList = [plt.axes] if self.form.all.isChecked(): axesList = plt.axesList # Set new alignement for axes in axesList: if self.form.xAlign.currentIndex() == 0: axes.xaxis.tick_bottom() axes.spines['bottom'].set_color((0.0, 0.0, 0.0)) axes.spines['top'].set_color('none') axes.xaxis.set_ticks_position('bottom') axes.xaxis.set_label_position('bottom') else: axes.xaxis.tick_top() axes.spines['top'].set_color((0.0, 0.0, 0.0)) axes.spines['bottom'].set_color('none') axes.xaxis.set_ticks_position('top') axes.xaxis.set_label_position('top') if self.form.yAlign.currentIndex() == 0: axes.yaxis.tick_left() axes.spines['left'].set_color((0.0, 0.0, 0.0)) axes.spines['right'].set_color('none') axes.yaxis.set_ticks_position('left') axes.yaxis.set_label_position('left') else: axes.yaxis.tick_right() axes.spines['right'].set_color((0.0, 0.0, 0.0)) axes.spines['left'].set_color('none') axes.yaxis.set_ticks_position('right') axes.yaxis.set_label_position('right') plt.update()
def setupUi(self): mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.items = form.findChild(QtGui.QListWidget, "items") form.x = form.findChild(QtGui.QDoubleSpinBox, "x") form.y = form.findChild(QtGui.QDoubleSpinBox, "y") form.s = form.findChild(QtGui.QDoubleSpinBox, "size") self.form = form self.retranslateUi() self.updateUI() QtCore.QObject.connect(form.items, QtCore.SIGNAL("currentRowChanged(int)"), self.onItem) QtCore.QObject.connect(form.x, QtCore.SIGNAL("valueChanged(double)"), self.onData) QtCore.QObject.connect(form.y, QtCore.SIGNAL("valueChanged(double)"), self.onData) QtCore.QObject.connect(form.s, QtCore.SIGNAL("valueChanged(double)"), self.onData) QtCore.QObject.connect( Plot.getMdiArea(), QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"), self.onMdiArea) return False
def __init__(self, controller, parent=None): tk.LabelFrame.__init__(self, parent, text="Info:") self.controller = controller self.name = Line(self, "Name:") self.name.pack(side=tk.TOP, expand=1, fill=tk.X) self.ref = Line(self, "Reference:") self.ref.pack(side=tk.TOP, expand=1, fill=tk.X) self.frames = Line(self, "Frames:") self.frames.pack(side=tk.TOP, expand=1, fill=tk.X) self.atoms = Line(self, "Atoms:") self.atoms.pack(side=tk.TOP, expand=1, fill=tk.X) self.armsd = Line(self, "avg RMSD:") self.armsd.pack(side=tk.TOP, expand=1, fill=tk.X) #self.text.bind('<Button-2>',self.controller.onPopUp) #self.text.bind('<Button-3>',self.controller.onPopUp) self.figure = Plot.Figure(self) self.makePopUp() if not self.name: print "hgskdgjkshdjkaJKSDjkah" self.update(None)
def run(self): dsConf = self.ds print(dsConf.get('testPath') + ' dataset ') pathModels = dsConf.get('pathModels') pathPlot = dsConf.get('pathPlot') pathDataset = dsConf.get('pathDataset') configuration = self.config numEsecutions = int(configuration.get('NUM_EXECUTIONS')) pathDatasetNumeric = dsConf.get('pathDatasetNumeric') pathDatasetEncoded = dsConf.get('pathDatasetEncoded') pathDatasetCluster = dsConf.get('pathDatasetCluster') testPath = dsConf.get('testPath') n_classes = int(configuration.get('N_CLASSES')) VALIDATION_SPLIT = float(configuration.get('VALIDATION_SPLIT')) N_CLASSES = int(configuration.get('N_CLASSES')) pd.set_option('display.expand_frame_repr', False) # Preprocessing phase from original to numerical dataset PREPROCESSING1 = int(configuration.get('PREPROCESSING1')) ds = Datasets(dsConf) if (PREPROCESSING1 == 1): tic_preprocessing1 = time.time() prp.toNumeric(ds) toc_preprocessing1 = time.time() time_preprocessing1 = toc_preprocessing1 - tic_preprocessing1 self.file.write("Time Preprocessing: %s" % (time_preprocessing1)) train_df = pd.read_csv(pathDatasetNumeric + 'Train_standard.csv') test_df = pd.read_csv(pathDatasetNumeric + 'Test_standard' + testPath + '.csv') self._clsTrain = ds.getClassification(train_df) print(self._clsTrain) train_X, train_Y = prp.getXY(train_df, self._clsTrain) test_X, test_Y = prp.getXY(test_df, self._clsTrain) AUTOENCODER_PREP = int(configuration.get('AUTOENCODER_PREPROCESSING')) LOAD_AUTOENCODER = int(configuration.get('LOAD_AUTOENCODER')) if (AUTOENCODER_PREP == 1): tic_preprocessingAutoencoder = time.time() if (LOAD_AUTOENCODER == 0): autoencoder, best_time, encoder = ah.hypersearch( train_X, train_Y, test_X, test_Y, pathModels + 'autoencoder.h5') self.file.write("Time Training Autoencoder: %s" % best_time) else: print('Load autoencoder') autoencoder = load_model(pathModels + 'autoencoder.h5') autoencoder.summary() encoder = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer('encod2').output) encoder.summary() ''' Encoded dataset creation''' encoded_train = pd.DataFrame(encoder.predict(train_X)) encoded_train = encoded_train.add_prefix('feature_') encoded_train["classification"] = train_Y print(encoded_train.shape) print(encoded_train.head()) encoded_train.to_csv(pathDatasetEncoded + 'train_encoded.csv', index=False) encoded_test = pd.DataFrame(encoder.predict(test_X)) encoded_test = encoded_test.add_prefix('feature_') encoded_test["classification"] = test_Y print(encoded_test.shape) print(encoded_test.head()) encoded_test.to_csv(pathDatasetEncoded + 'test_encoded' + testPath + '.csv', index=False) toc_preprocessingAutoencoder = time.time() self.file.write( "Time Creations Encoded Dataset: %s" % (toc_preprocessingAutoencoder - tic_preprocessingAutoencoder)) ORD = int(configuration.get('ORD_DATASET')) if (ORD == 1): encoded_train, encoded_test = eo.ord( pathDatasetEncoded + 'train_encoded', pathDatasetEncoded + 'test_encoded' + testPath) else: encoded_train = pd.read_csv(pathDatasetEncoded + 'train_encoded_ord.csv') encoded_test = pd.read_csv(pathDatasetEncoded + 'test_encoded' + testPath + '_ord.csv') image_construction = int(configuration.get('IMAGE')) if (image_construction == 1): train_df = encoded_train test_df = encoded_test # divido il train in esempi normali e di attacco, utili per il K-Means trainNormal = train_df[train_df['classification'] == 1] trainAttack = train_df[train_df['classification'] == 0] train_X, train_Y = prp.getXY(train_df, self._clsTrain) test_X, test_Y = prp.getXY(test_df, self._clsTrain) distTrain, distTest = self.distance(train_X, test_X, trainNormal, trainAttack, self.nearest) train_X = np.array(distTrain) test_X = np.array(distTest) if self.TRAIN == 1: saveNpArray( train_X, train_Y, pathDatasetCluster + str(self.num_cluster) + "Train") if self.TEST == 1: saveNpArray( test_X, test_Y, pathDatasetCluster + str(self.num_cluster) + testPath) else: print('Load Image dataset') train_X = np.load(pathDatasetCluster + str(self.num_cluster) + "TrainX" + '.npy') train_Y = np.load(pathDatasetCluster + str(self.num_cluster) + "TrainY" + '.npy') test_X = np.load(pathDatasetCluster + str(self.num_cluster) + testPath + "X" + '.npy') test_Y = np.load(pathDatasetCluster + str(self.num_cluster) + testPath + "Y" + '.npy') # convert class vectors to binary class matrices y_train = np_utils.to_categorical(train_Y, int(n_classes)) y_test = np_utils.to_categorical(test_Y, int(n_classes)) print(train_X.shape) print(test_X.shape) load_cnn = int(configuration.get('LOAD_CNN')) if K.image_data_format() == 'channels_first': x_train = train_X.reshape(train_X.shape[0], 1, train_X.shape[1], train_X.shape[2]) x_test = test_X.reshape(test_X.shape[0], 1, train_X.shape[1], train_X.shape[2]) input_shape = (1, train_X.shape[1], train_X.shape[2]) else: x_train = train_X.reshape(train_X.shape[0], train_X.shape[1], train_X.shape[2], 1) x_test = test_X.reshape(test_X.shape[0], train_X.shape[1], train_X.shape[2], 1) input_shape = (train_X.shape[1], train_X.shape[2], 1) XTraining, XValidation, YTraining, YValidation = train_test_split( x_train, y_train, stratify=y_train, test_size=0.2) if (load_cnn == 0): callbacks_list = [ callbacks.EarlyStopping(monitor='loss', min_delta=0.0001, patience=10, restore_best_weights=True), ] tic = time.time() p = ds.getParameters() model = Models.CNN(p, input_shape, n_classes) history = model.fit( x_train, y_train, batch_size=p['batch_size'], epochs=p['epochs'], callbacks=callbacks_list, verbose=2, #validation_split=VALIDATION_SPLIT, validation_data=(XValidation, YValidation), use_multiprocessing=True, workers=64) Plot.printPlotAccuracy(history, 'cnn', dsConf.get('pathPlot')) Plot.printPlotLoss(history, 'cnn', dsConf.get('pathPlot')) modelName = str(self.num_cluster) + '_' + testPath + 'cnn.h5' model.save(pathModels + modelName) toc = time.time() self.file.write("Time Fitting CNN : " + str(toc - tic)) self.file.write('\n') else: print('Load CNN') modelName = str(self.num_cluster) + '_' + testPath + 'cnn.h5' model = load_model(pathModels + modelName) model.summary() tic_prediction_classifier = time.time() print('Softmax on test set') # create pandas for results columns = [ 'Clusters', 'TP', 'FN', 'FP', 'TN', 'OA', 'AA', 'P', 'R', 'F1', 'FAR(FPR)', 'TPR' ] columnsTemp = [ 'TP', 'FN', 'FP', 'TN', 'OA', 'AA', 'P', 'R', 'F1', 'FAR(FPR)', 'TPR' ] results = pd.DataFrame(columns=columns) predictions = model.predict(x_test, verbose=1) y_pred = np.argmax(predictions, axis=1) cm = confusion_matrix(test_Y, y_pred) r = getResult(cm, n_classes) r.insert(0, self.num_cluster) dfResults = pd.DataFrame([r], columns=columns) print(dfResults) results = results.append(dfResults, ignore_index=True) toc_prediction_classifier = time.time() time_prediction_classifier = ( toc_prediction_classifier - tic_prediction_classifier) / numEsecutions self.file.write("Time for predictions: %s " % (time_prediction_classifier)) model.summary() results.to_csv(testPath + '_results.csv', index=False) self.file.close()
def get_plot(points, nickname): plot = plt.Plot(points, nickname) t = threading.Thread(target=plot.construction_graphic) t.start() t.join() return True
def build_autoencoder_model(batch_size, input_shape, kernel_size, latent_dim, layer_filters, x_train, x_test, img_rows, img_cols, channels): # 1. Build encoder model input_images = Input(shape=input_shape, name='encoder_input') x = input_images for filters in layer_filters: x = Conv2D(filters=filters, kernel_size=kernel_size, strides=2, activation='relu', padding='same')(x) shape = K.int_shape(x) x = Flatten()(x) latent = Dense(latent_dim, name='latent_vector')(x) # 2. Instantiate Encoder Model encoder = Model(input_images, latent, name='encoder') encoder.summary() # 3. Build decoder Model latent_inputs = Input(shape=(latent_dim, ), name='decoder_input') x = Dense(shape[1] * shape[2] * shape[3])(latent_inputs) x = Reshape((shape[1], shape[2], shape[3]))(x) for filters in layer_filters[::-1]: x = Conv2DTranspose(filters=filters, kernel_size=kernel_size, strides=2, activation='relu', padding='same')(x) output_images = Conv2DTranspose(filters=channels, kernel_size=kernel_size, padding='same', activation='sigmoid', name='decoder_output')(x) # 4. Instantiate decoder Model decoder = Model(latent_inputs, output_images, name='decoder') decoder.summary() # 5. Instantiate Autoencoder Model # Reshape Images # normalize output train and test color images x_train_gray = plot.convert_rgb_to_gray(x_train) x_test_gray = plot.convert_rgb_to_gray(x_test) plot.display_images_grayscale(x_test_gray, x_train.shape[1], x_train.shape[2], 'saved_images') # Normalize input for colored train and test set x_train = x_train.astype('float32') / 255 x_test = x_test.astype('float32') / 255 # normalize input train and test grayscale images x_train_gray = x_train_gray.astype('float32') / 255 x_test_gray = x_test_gray.astype('float32') / 255 # reshape images to row x col x channel for CNN output/validation x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, channels) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, channels) # reshape images to row x col x channel for CNN input x_train_gray = x_train_gray.reshape(x_train_gray.shape[0], img_rows, img_cols, 1) x_test_gray = x_test_gray.reshape(x_test_gray.shape[0], img_rows, img_cols, 1) autoencoder = Model(input_images, decoder(encoder(input_images)), name='autoencoder') autoencoder.summary() # 6. Train Autoencoder Model autoencoder.compile(loss='mse', optimizer='adam') autoencoder.fit(x_train_gray, x_train, validation_data=(x_test_gray, x_test), epochs=30, batch_size=batch_size) x_decoded = autoencoder.predict(x_test_gray) # 7. Plot Predicted Image Colors plot.display_colorized_predicted_images(x_decoded, x_train.shape[1], x_train.shape[2], x_train.shape[3], 'saved_images')
"Metadata in the format MEGAN exports it in (tab separated, samples in rows, data in columns)" ) args = parser.parse_args() #Convert if args.qiime: Convert.QIIMEConvert(args.qiime[0], args.qiime[1], args.qiime[2], args.qiime[3], args.qiime[4], args.out) if args.mothur: Convert.mothurConvert(args.mothur[0], args.out) if args.megan: print("Conversion") Convert.MEGANConvert(args.megan[0], args.megan[1], args.megan[2], args.megan[3], args.megan[4], args.out) #Correlate for i in args.coefficients: c = i.lower() print("Correlation on " + c) Correlate.correlate(args.out, c, args.pval, 0.0) print("Metadata for " + c) Metadata.correlate(args.out, args.metadata, c, args.pval, 0.0) print("Networking") Networking.writeNetworks(args.out) #Filter print("Filtering") Filter.filterAll(args.out, args.cutoffs) #Plot print("Plotting!") Plot.network(args.out) print("DONE!")
import sys import math filename = sys.argv[1] algorithmChoice = int(sys.argv[2]) runs = 1 totalRuns = 1 try: #Handles having just 2 arguments totalRuns = int(sys.argv[3]) except IndexError: print "Number of runs was not specified. Setting totalRuns to default.(1)" averageCrops = 0 #will run totalRuns times while runs <= totalRuns: p = Plot() #create plot robot = Robot() #create robot walls = [] walls.append([]) walls = p.RetrievePlot(filename, walls) runs += 1 if algorithmChoice == 1 or algorithmChoice == 5: #These algorithms are similar. They run the same code but altered slightly. highestPercentLocation = (0, 0) highestPercent = 0 bestCrop = (0, 0) if algorithmChoice == 5: #Algorithm 5 finds the best coordinate for crops that have highest probability of growing the most bestCrop = (0, 0) bestTime = 999 for crop in p.cropCoordinates: #algorithm for calculating the location percent = p.plotDictionary[crop][0] avg = math.ceil(1 / percent)
def plotStability(self): """ Perform stability hydrostatics. @return True if error happens. """ try: import Plot plt = Plot.figure('Stability') except ImportError: return True # Generate the sets of axes Plot.grid(True) for i in range(0, 3): ax = Plot.addNewAxes() # Y axis can be placed at right ax.yaxis.tick_right() ax.spines['right'].set_color((0.0, 0.0, 0.0)) ax.spines['left'].set_color('none') ax.yaxis.set_ticks_position('right') ax.yaxis.set_label_position('right') # And X axis can be placed at bottom for loc, spine in ax.spines.iteritems(): if loc in ['bottom', 'top']: spine.set_position(('outward', (i + 1) * 35)) Plot.grid(True) disp = [] draft = [] farea = [] kbt = [] bmt = [] for i in range(len(self.points)): disp.append(self.points[i].disp) draft.append(self.points[i].draft) farea.append(self.points[i].farea) kbt.append(self.points[i].KBt) bmt.append(self.points[i].BMt) axes = Plot.axesList() for ax in axes: ax.set_position([0.1, 0.2, 0.8, 0.75]) plt.axes = axes[0] serie = Plot.plot(draft, disp, r'$T$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.0, 0.0, 0.0)) Plot.xlabel(r'$T \; \left[ \mathrm{m} \right]$') Plot.ylabel(r'$\bigtriangleup \; \left[ \mathrm{tons} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[1] serie = Plot.plot(farea, disp, r'Floating area') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((1.0, 0.0, 0.0)) Plot.xlabel(r'$Floating \; area \; \left[ \mathrm{m}^2 \right]$') Plot.ylabel(r'$\bigtriangleup \; \left[ \mathrm{tons} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[2] serie = Plot.plot(kbt, disp, r'$KB_T$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.0, 0.0, 1.0)) Plot.xlabel(r'$KB_T \; \left[ \mathrm{m} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[3] serie = Plot.plot(bmt, disp, r'$BM_T$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.2, 0.8, 0.2)) Plot.xlabel(r'$BM_T \; \left[ \mathrm{m} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) Plot.legend(True) plt.update() return False
weights += learning_rate * x * (1 if t == 1 else -1) count += 1 if count >= num_steps: return weights def generate_boundary(weights, xts): x1s = [x1 for (o, x1, x2), t in xts] # find x1-range x1_range = 1.5 * (max(x1s) - min(x1s)) # ` ` ` x1s = [(n - 50) * x1_range / 100.0 for n in range(100)] x2s = [(-weights[0] - weights[1] * x1) / weights[2] for x1 in x1s] return x1s, x2s for i, j in zip('123', [0, 1, 2]): xts = get_xts('D' + i + '_train.csv') weights = compute_weights(xts) print(weights) x1s, x2s = generate_boundary(weights, xts) classes = {0: [], 1: []} for x, t in xts: classes[t].append(x) Plot.plot_scatter(classes[0], 0, label='class 0') Plot.plot_scatter(classes[1], 1, label='class 1') Plot.plot_line(x1s, x2s, label='decision boundary') Plot.save_plot('x1', 'x2', 'Logistic Decision Boundary for D' + i, 'perceptron_' + i + '.png') Errors = [x for x, t in xts if t != predict(x, weights)] print('E', len(Errors))
elif timecode_mode is False and len(args) in range(2, 8): if Path(args[-1]).is_file() is not True: sys.exit(f"File {args[-1]} does not exists") date = args[-1].split("/")[-2] timecode = args[-1].split("/")[-1].split("-")[-2] for f in args: file_exist = Path(f).is_file() if file_exist is not True: sys.exit(f"File {f} does not exists") for node in suffix: if f.split("-")[-1] == node: files[node + "_file"] = f if verbose_mode is True: print("Info: Loading file {}.".format(f)) else: sys.exit("Invalid arguments. Expected usage:\n" + str(args[0]) + " rtr_file atk_file cc_file lc_file cs_file ls_file\nor\n" + str(args[0]) + " timecode 2021-05-20 1516\n") PlotNetTrace = Plot(date, timecode, files["rtr_file"], files["atk_file"], files["cc_file"], files["lc_file"], files["cs_file"], files["ls_file"], files["rtrvm_file"], rewrite_mode) if special_mode is True: PlotNetTrace.special_plot() else: PlotNetTrace.visualize()
file = "Data/GSE42308.txt" samples = Core.ParseFile(file).get_samples() # samples2 = Core.ParseBatch("Data/").get_all_samples() probes = annotations.get_probes(annotations.get_all_probe_ids()) print(len(probes)) probe2 = Annotation.get_probes_from_feature(probes, Annotation.Feature(Annotation.CpG_location.ISLAND)) print(len(probe2)) probe3 = Annotation.get_probes_from_feature(probe2, Annotation.Feature("BRCA1")) print(len(probe3)) brcaprobes = annotations.get_probes(annotations.get_probes_id_from_gene("BRCA1")) #groups= [groups[0], groups[3]] Plot.BoxPlot(probes, samples) # probe_list = annotations.get_probes_from_gene("TP53") # probe_list2 =annotations.get_probes_id_from_loc(Annotation.Location.BODY) # probe_list3 =annotations.get_probes_id_from_cpg(Annotation.CpG_location.NSHORE) # print(probe_list3) # sort data # probe_list = annotations.sort_coord_probe(probe_list) # Core.write_data("data.txt", groups, probe_list) Plot.Heatmap(samples, brcaprobes, "brca1.png")
def __init__(self): # Initialise PyGame environment for graphics and sound. pygame.init() pygame.mixer.init() pygame.font.init() self.ThisSurface = pygame.display.set_mode( (0, 0), pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) # Hide mouse pointer, using a touch screen for click events. # pygame.mouse.set_visible(False) # Get the dimensions of the surface to draw the visual object onto. (self.DisplayXLen, self.DisplayYLen) = pygame.Surface.get_size(self.ThisSurface) if DEBUG == "ON": print("DISPLAY: " + str(self.DisplayXLen) + " x " + str(self.DisplayYLen)) self.SurfaceXLen = pygame.display.Info().current_w self.SurfaceYLen = pygame.display.Info().current_h # Scale gagit sizes to a preportion of the display surface. self.GadgitWidth = int(self.SurfaceXLen / 3) self.GadgitHeight = int( (self.SurfaceYLen - Visual.BUTTON_HEIGHT) / 1.4) self.ButtonWidth = int(self.SurfaceXLen / 12) # Define the buttons to be displayed on the background. self.Buttons = { "METERS": Button.Button(self.ThisSurface, "METERS", Visual.PRESS_LATCH, 2 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Meters.png"), "FRAME": Button.Button(self.ThisSurface, "FRAME", Visual.PRESS_LATCH, 3 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Frame.png"), "FREEZE": Button.Button(self.ThisSurface, "FREEZE", Visual.PRESS_LATCH, 4 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/FreezeFrame.png"), "PLOTS": Button.Button(self.ThisSurface, "PLOTS", Visual.PRESS_LATCH, 5 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Plots.png"), "TROUBLE": Button.Button(self.ThisSurface, "TROUBLE", Visual.PRESS_LATCH, 6 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Trouble.png"), "VEHICLE": Button.Button(self.ThisSurface, "VEHICLE", Visual.PRESS_LATCH, 7 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Vehicle.png"), "ELM327": Button.Button(self.ThisSurface, "ELM327", Visual.PRESS_LATCH, 8 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/OBDII.png"), "BUSY": Button.Button(self.ThisSurface, "BUSY", Visual.PRESS_DOWN, self.DisplayXLen - 2 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Busy.png"), "EXIT": Button.Button(self.ThisSurface, "EXIT", Visual.PRESS_DOWN, self.DisplayXLen - self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Exit.png"), "MIL": Button.Button(self.ThisSurface, "MIL", Visual.PRESS_DOWN, 0, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/MIL_Off.png", DownText="IMAGE:ICONS/MIL_On.png"), "SAVE": Button.Button(self.ThisSurface, "SAVE", Visual.PRESS_DOWN, self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Save.png"), "PRINT": Button.Button(self.ThisSurface, "PRINT", Visual.PRESS_DOWN, 2 * self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Print.png"), "DATE": Button.Button(self.ThisSurface, "DATE", Visual.PRESS_NONE, 4 * self.ButtonWidth, Visual.BUTTON_HEIGHT, 2 * self.ButtonWidth, Visual.BUTTON_HEIGHT, "DATE"), "TIME": Button.Button(self.ThisSurface, "TIME", Visual.PRESS_NONE, 6 * self.ButtonWidth, Visual.BUTTON_HEIGHT, 2 * self.ButtonWidth, Visual.BUTTON_HEIGHT, "TIME"), } # Define the meters tab area for the display. self.Meters["LOCK"] = Button.Button(self.ThisSurface, "LOCK", Visual.PRESS_TOGGLE, 0, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Lock_Off.png", DownText="IMAGE:ICONS/Lock_On.png") self.Meters["ADD"] = Button.Button(self.ThisSurface, "ADD", Visual.PRESS_DOWN, self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Add.png") self.Meters["GO_STOP"] = Button.Button(self.ThisSurface, "GO_STOP", Visual.PRESS_TOGGLE, self.DisplayXLen - 3 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Go.png", DownText="IMAGE:ICONS/Stop.png") # Define the frame data tab area for the display. self.FrameData["INFO"] = Button.Button( self.ThisSurface, "INFO", Visual.PRESS_NONE, 0, 2 * Visual.BUTTON_HEIGHT, self.DisplayXLen, self.DisplayYLen - 2 * Visual.BUTTON_HEIGHT, "", Visual.ALIGN_TEXT_LEFT) self.FrameData["RELOAD"] = Button.Button( self.ThisSurface, "RELOAD", Visual.PRESS_DOWN, self.DisplayXLen - self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Reload.png") # Define the freeze frame data tab area for the display. self.FreezeFrameData["INFO"] = Button.Button( self.ThisSurface, "INFO", Visual.PRESS_NONE, 0, 2 * Visual.BUTTON_HEIGHT, self.DisplayXLen, self.DisplayYLen - 2 * Visual.BUTTON_HEIGHT, "", Visual.ALIGN_TEXT_LEFT) self.FreezeFrameData["RELOAD_FREEZE"] = Button.Button( self.ThisSurface, "RELOAD_FREEZE", Visual.PRESS_DOWN, self.DisplayXLen - self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Reload.png") # Define the plot tab area for the display. self.Plots["PLOT"] = Plot.Plot( self.ThisSurface, "PLOT", Visual.PRESS_NONE, 0, 2 * Visual.BUTTON_HEIGHT, self.DisplayXLen, self.DisplayYLen - 2 * Visual.BUTTON_HEIGHT, "") self.Plots["GO_STOP"] = Button.Button(self.ThisSurface, "GO_STOP", Visual.PRESS_TOGGLE, self.DisplayXLen - 3 * self.ButtonWidth, 0, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Go.png", DownText="IMAGE:ICONS/Stop.png") self.Plots["PLOT_1"] = Button.Button( self.ThisSurface, "PLOT_1", Visual.PRESS_DOWN, self.DisplayXLen - 4 * self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "[1]") self.Plots["PLOT_2"] = Button.Button( self.ThisSurface, "PLOT_2", Visual.PRESS_DOWN, self.DisplayXLen - 3 * self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "[2]") self.Plots["PLOT_3"] = Button.Button( self.ThisSurface, "PLOT_3", Visual.PRESS_DOWN, self.DisplayXLen - 2 * self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "[3]") self.Plots["RESET"] = Button.Button( self.ThisSurface, "RESET", Visual.PRESS_DOWN, self.DisplayXLen - self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Reset.png") # Define the trouble tab area for the display. self.TroubleInfo["INFO"] = Button.Button( self.ThisSurface, "INFO", Visual.PRESS_NONE, 0, 2 * Visual.BUTTON_HEIGHT, self.DisplayXLen, self.DisplayYLen - 2 * Visual.BUTTON_HEIGHT, "", Visual.ALIGN_TEXT_LEFT) self.TroubleInfo["REFRESH"] = Button.Button( self.ThisSurface, "REFRESH", Visual.PRESS_DOWN, 9 * self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Refresh.png") self.TroubleInfo["CLEAR"] = Button.Button( self.ThisSurface, "CLEAR", Visual.PRESS_DOWN, self.DisplayXLen - self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Clear.png") # Define the vehicle tab area for the display. self.VehicleInfo["INFO"] = Button.Button( self.ThisSurface, "INFO", Visual.PRESS_NONE, 0, 2 * Visual.BUTTON_HEIGHT, self.DisplayXLen, self.DisplayYLen - 2 * Visual.BUTTON_HEIGHT, "", Visual.ALIGN_TEXT_LEFT) # Define the ELM327 tab area for the display. self.ELM327Info["INFO"] = Button.Button( self.ThisSurface, "INFO", Visual.PRESS_NONE, 0, 2 * Visual.BUTTON_HEIGHT, self.DisplayXLen, self.DisplayYLen - 2 * Visual.BUTTON_HEIGHT, "", Visual.ALIGN_TEXT_LEFT) self.ELM327Info["CONFIG"] = Button.Button( self.ThisSurface, "CONFIG", Visual.PRESS_DOWN, 9 * self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Config.png") self.ELM327Info["CONNECT"] = Button.Button( self.ThisSurface, "CONNECT", Visual.PRESS_DOWN, self.DisplayXLen - self.ButtonWidth, Visual.BUTTON_HEIGHT, self.ButtonWidth, Visual.BUTTON_HEIGHT, "IMAGE:ICONS/Connect.png") # Currently selected tab, default meters. self.CurrentTab = self.ELM327Info self.Buttons["ELM327"].SetDown(True) self.Buttons["BUSY"].SetVisible(False)
def __init__(self, simMap, robots): self.simMap = simMap self.robots = robots self.plot = Plot()
from Test import Test import Table import Plot N = 1000 t = Test(N) isb = t.InsertionSortBest() ism = t.InsertionSortRandom() isw = t.InsertionSortWorst() msb = t.MergeSortBest() msm = t.MergeSortRandom() msw = t.MergeSortWorst() Plot.GraphicPlot(N, isb, ism, isw, msb, msm, msw) Table.ExperimentalDataTable(isb, ism, isw, msb, msm, msw)
#! /usr/bin/env python3 import Plot # we need this to draw somenthing!! import math # need the sin() for the function below def sinc(x: float) -> float: ''' Sine cardinal function ''' if x == 0: return 1 return math.sin(10 * x) / (10 * x) if __name__ == '__main__': ''' Write whaterver function you like, may also be a lambda like: ''' line = lambda x: 2 * x + 1 ''' ...or the cardinal sine above... ''' ''' ...feed it to the plot object ''' plot = Plot.Plot(sinc) ''' enjoy math !! ''' plot.plot()
def updateUI(self): """ Setup UI controls values if possible """ plt = Plot.getPlot() self.form.items.setEnabled(bool(plt)) self.form.label.setEnabled(bool(plt)) self.form.isLabel.setEnabled(bool(plt)) self.form.style.setEnabled(bool(plt)) self.form.marker.setEnabled(bool(plt)) self.form.width.setEnabled(bool(plt)) self.form.size.setEnabled(bool(plt)) self.form.color.setEnabled(bool(plt)) self.form.remove.setEnabled(bool(plt)) if not plt: self.plt = plt self.form.items.clear() return self.skip = True # Refill list if self.plt != plt or len(Plot.series()) != self.form.items.count(): self.plt = plt self.setList() # Ensure that have series if not len(Plot.series()): self.form.label.setEnabled(False) self.form.isLabel.setEnabled(False) self.form.style.setEnabled(False) self.form.marker.setEnabled(False) self.form.width.setEnabled(False) self.form.size.setEnabled(False) self.form.color.setEnabled(False) self.form.remove.setEnabled(False) return # Set label serie = Plot.series()[self.item] if serie.name == None: self.form.isLabel.setChecked(True) self.form.label.setEnabled(False) self.form.label.setText("") else: self.form.isLabel.setChecked(False) self.form.label.setText(serie.name) # Set line style and marker self.form.style.setCurrentIndex(0) linestyles = Line2D.lineStyles.keys() for i in range(0,len(linestyles)): style = linestyles[i] if style == serie.line.get_linestyle(): self.form.style.setCurrentIndex(i) self.form.marker.setCurrentIndex(0) markers = Line2D.markers.keys() for i in range(0,len(markers)): marker = markers[i] if marker == serie.line.get_marker(): self.form.marker.setCurrentIndex(i) # Set line width and marker size self.form.width.setValue(serie.line.get_linewidth()) self.form.size.setValue(serie.line.get_markersize()) # Set color color = Colors.colorConverter.to_rgb(serie.line.get_color()) self.form.color.setStyleSheet("background-color: rgb(%d, %d, %d);" % (int(color[0]*255), int(color[1]*255), int(color[2]*255))) self.skip = False
def __ascan(self,tMot,tPos,events_per_point,dets): if type(tMot) is not tuple: tMot = (tMot,) ostr = "#%s" % self.status() ostr = ostr.replace("\n","\n#") ostr = ostr[:-1] if ( self.__monitor is not None ): ostr += "#readings (except for monitor) are normalized\n" ## take care of the motor first initial_pos = [] for m in tMot: initial_pos.append( m.wm() ) for i in range(len(tMot)): print "%s initial position is %.4g" % (tMot[i].name,initial_pos[i]) sys.stdout.flush() self.__scanstr= ostr controls = [] for m in tMot: controls.append( (m.name,m.wm()) ) self.configure(events_per_point,controls=controls) scanstartdate = datetime.now() if (len(dets) != 0): plotid=self.__prepare_plot(dets) self.plot=Plot.Plot2D(plotid) self.plot.set_xlabel(tMot[0].name) self.plot.set_ylabel(dets[0].name) for m in tMot: self.__scanstr+= "#** Scanning motor: %s (pvname: %s)\n" % (m.name,m.pvname) self.__scanstr+= "# number of points: %d\n" % len(tPos) self.__scanstr+= "# number of shots per point: %d\n" % events_per_point for i in range(len(tMot)): if len(tMot)>1: self.__scanstr+="# step size for motor %s: %.4e\n" % (tMot[i].name,tPos[1][i]-tPos[0][i]) else: self.__scanstr+="# step size for motor %s: %.4e\n" % (tMot[0].name,tPos[1]-tPos[0]) line1,line2 = self.__prepare_dets_title(dets) self.__scanstr += "#++%5s" % ("") for m in tMot: self.__scanstr += "%12s" % (m.name) self.__scanstr += "%s\n" % (line1) self.__scanstr += "# point|" for m in tMot: self.__scanstr += "%12s" % ("position") self.__scanstr += "%s\n" % (line2) print self.__scanstr, for cycle in range(len(tPos)): t0cycle=time.time() pos = tPos[cycle]; if ( (type(pos) is not tuple) and (type(pos) is not list) ): pos=(pos,) for i in range(len(pos)): tMot[i].move_silent(pos[i]) for i in range(len(pos)): tMot[i].wait() sys.stdout.flush() if (self.settling_time != 0): sleep(self.settling_time) if (config.TIMEIT>0): print "time needed for moving and settling %.3f" % (time.time()-t0move) self.__start_av(dets) sleep(0.05); # to make sure readback is uptodate (20ms) controls = [] for m in tMot: controls.append( (m.name,m.wm()) ) self.calibcycle( events_per_point, controls=controls ) ret = self.__stop_av(dets) ostr = "%7d" % (cycle+1) # for i in range(len(pos)): ostr+="|%11.4e" % pos[i] for m in tMot: ostr+="|% 11.5e" % (m.wm()) ostr += "%s" % (ret[0]) print ostr self.__scanstr+="%s\n" % ostr t0plots=time.time() if ( len(dets) != 0 ): self.__x.append(pos[0]) if ( cycle>1 ): self.plot.setdata(self.__x,self.__y[dets[0]]) if (config.TIMEIT>0): print "time needed for updating plot %.3f" % (time.time()-t0plots) c=KeyPress.getc() if (c=="q"): print "exiting" break if (config.TIMEIT>0): print "time needed for complete scan point %.3f" % (time.time()-t0cycle) runn = "# run number (0 = not saved): %d\n" % self.runnumber() self.__scanstr+=runn filename = config.scandata_directory +'/' filename += "%04d-%02d-%02d_%02dh%02dm%02ds_run%04d.dat" % (scanstartdate.year,scanstartdate.month,scanstartdate.day,scanstartdate.hour,scanstartdate.minute,scanstartdate.second,self.runnumber()) self.savetxt(filename) print runn for i in range(len(tMot)): print "Moving back %s to initial position (%e)..." % (tMot[i].name,initial_pos[i]) tMot[i].move_silent(initial_pos[i]) print " ... done"
def __ascan(self, tMot, tPos, events_per_point, dets): try: if type(tMot) is not tuple: tMot = (tMot, ) pass ostr = "#%s" % self.status() ostr = ostr.replace("\n", "\n#") if (self.__monitor is not None): ostr += "#readings (except for monitor) are normalized\n" pass ## take care of the motor first initial_pos = [] for m in tMot: initial_pos.append(m.wm()) pass sys.stdout.flush() self.__scanstr = ostr controls = [] for m in tMot: controls.append((m.name, m.wm())) pass print "calibcycle, controls=%s" % controls self.configure(events=events_per_point, controls=controls) if (len(dets) != 0): plotid = self.__prepare_plot(dets) self.plot = Plot.Plot2D(plotid) self.plot.set_xlabel(tMot[0].name) if (self.__monitor is not None): self.plot.set_ylabel(dets[0].name + '/' + self.__monitor.name) pass else: self.plot.set_ylabel(dets[0].name) pass pass for m in tMot: self.__scanstr += "#** Scanning motor: %s (pvname: %s)\n" % ( m.name, m.pvname) pass self.__scanstr += "# number of points: %d\n" % len(tPos) self.__scanstr += "# number of shots per point: %d\n" % events_per_point for i in range(len(tMot)): if len(tMot) > 1: self.__scanstr += "# step size for motor %s: %.4e\n" % ( tMot[i].name, tPos[1][i] - tPos[0][i]) pass else: self.__scanstr += "# step size for motor %s: %.4e\n" % ( tMot[0].name, tPos[1] - tPos[0]) pass pass self.__scanstr += "# Start time: %s\n" % self.getArchiverTimestamp( ) line1, line2 = self.__prepare_dets_title(dets) self.__scanstr += "%6s" % ("") for m in tMot: self.__scanstr += "%11s" % ("") self.__scanstr += "%s\n" % (line1) self.__scanstr += "point|" for m in tMot: self.__scanstr += "%11s" % ("position") self.__scanstr += "%s\n" % (line2) print self.__scanstr, for cycle in range(len(tPos)): t0cycle = time.time() pos = tPos[cycle] if ((type(pos) is not tuple) and (type(pos) is not list)): pos = (pos, ) pass for i in range(len(pos)): tMot[i].move_silent(pos[i]) pass for i in range(len(pos)): tMot[i].wait() pass sys.stdout.flush() if (self.settling_time != 0): sleep(self.settling_time) pass if (config.TIMEIT > 0): print "time needed for moving and settling %.3f" % ( time.time() - t0move) pass self.__start_av(dets) sleep(0.05) # to make sure readback is uptodate (20ms) controls = [] for m in tMot: controls.append((m.name, m.wm())) pass print "calibcycle, controls=%s" % controls self.calibcycle(events_per_point, controls=controls) ret = self.__stop_av(dets) ostr = "%5d" % (cycle + 1) #for i in range(len(pos)): ostr+="|%11.4e" % pos[i] for m in tMot: ostr += "|%11.5e" % (m.wm()) pass ostr += "%s" % (ret[0]) print ostr self.__scanstr += "%s\n" % ostr t0plots = time.time() if (len(dets) != 0): self.__x.append(pos[0]) if (cycle > 1): self.plot.setdata(self.__x, self.__y[dets[0]]) pass pass if (config.TIMEIT > 0): print "time needed for updating plot %.3f" % (time.time() - t0plots) pass c = KeyPress.getc() if (c == "q"): print "exiting" break if (config.TIMEIT > 0): print "time needed for complete scan point %.3f" % ( time.time() - t0cycle) pass pass runn = "# run number (0 = not saved): %d\n" % self.runnumber() self.__scanstr += runn print runn #for i in range(len(tMot)): #print "Moving back %s to initial position (%e)..." % (tMot[i].name,initial_pos[i]) #tMot[i].move_silent(initial_pos[i]) #print " ... done" #pass pass finally: self.__scanstr += "# End time: %s\n" % self.getArchiverTimestamp() self.savetxt(self.getfilenamefromfile(self.scanlogfile_f), 'a')
def plot(self, event): plot_window = Plot.Plot(self.outer.hsv, self.inner.hsv, self.bottom.hsv) plot_window.plot()
seriesOfSeries[i] = np.vstack((seriesOfSeries[i], newSeries[i].T)) seriesOfVariances[i].extend(newVariances[i]) with open('series.pkl', 'wb') as fd: pickle.dump(seriesOfSeries, fd) with open('var.pkl', 'wb') as fd: pickle.dump(seriesOfVariances, fd) state_id = 1 for m, datum, series, variance, state in zip(model.models, data, seriesOfSeries, seriesOfVariances, Model.STATES): ks = KalmanSimulator(datum, m, x0) Plot.statePlot(series, variance, state, ks.startDate, 3, datum) # outputting into the csv # need to estimate daily values from the timeseries of all the compartments deads_daily = np.sum( getAgeMortality(state) * 0.01 * (series[:, 9:12] + series[:, 21:24] + series[:, 24:27]), axis=1) deads_daily = deads_daily[:-17] deads_daily = np.concatenate([np.zeros(17), deads_daily]) deads_total = np.cumsum(deads_daily) recovered_total = np.sum(series[:, 27:30], axis=1) recovered_daily = np.insert(np.diff(recovered_total), 0, recovered_total[0])
def plotCoeffs(self): """ Perform stability hydrostatics. @return True if error happens. """ # Create plot try: import Plot plt = Plot.figure('Coefficients') except ImportError: return True # Generate the set of axes Plot.grid(True) for i in range(0, 3): ax = Plot.addNewAxes() # Y axis can be placed at right ax.yaxis.tick_right() ax.spines['right'].set_color((0.0, 0.0, 0.0)) ax.spines['left'].set_color('none') ax.yaxis.set_ticks_position('right') ax.yaxis.set_label_position('right') # And X axis can be placed at bottom for loc, spine in ax.spines.iteritems(): if loc in ['bottom', 'top']: spine.set_position(('outward', (i + 1) * 35)) Plot.grid(True) disp = [] draft = [] cb = [] cf = [] cm = [] for i in range(len(self.points)): disp.append(self.points[i].disp) draft.append(self.points[i].draft) cb.append(self.points[i].Cb) cf.append(self.points[i].Cf) cm.append(self.points[i].Cm) axes = Plot.axesList() for ax in axes: ax.set_position([0.1, 0.2, 0.8, 0.75]) plt.axes = axes[0] serie = Plot.plot(draft, disp, r'$T$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.0, 0.0, 0.0)) Plot.xlabel(r'$T \; \left[ \mathrm{m} \right]$') Plot.ylabel(r'$\bigtriangleup \; \left[ \mathrm{tons} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[1] serie = Plot.plot(cb, disp, r'$Cb$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((1.0, 0.0, 0.0)) Plot.xlabel(r'$Cb$ (Block coefficient)') Plot.ylabel(r'$\bigtriangleup \; \left[ \mathrm{tons} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[2] serie = Plot.plot(cf, disp, r'$Cf$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.0, 0.0, 1.0)) Plot.xlabel(r'$Cf$ (floating area coefficient)') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[3] serie = Plot.plot(cm, disp, r'$Cm$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.2, 0.8, 0.2)) Plot.xlabel(r'$Cm$ (Main section coefficient)') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) Plot.legend(True) plt.update() return False
class Simulator: def __init__(self, simMap, robots): self.simMap = simMap self.robots = robots self.plot = Plot() def recordTrajectory(self, motion, initialPosition): """ record a trajectory (sequence of commands) for a specific motion model """ terminal = CommandLineApp() commands = [] traj = [initialPosition[0:2]] pos = initialPosition # start an interactive plot self.plot.start("Record Trajectory") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(traj) self.plot.drawRobot(pos) self.plot.draw() terminal.clearUpTo(2) terminal.println("Use a-s-d-w to navigate...") terminal.noecho() dAngle = 5.0 * pi / 180.0 dForward = 0.1 while True: key = terminal.keyPress() if key == 100: # right pos = motion.move(pos, [0, -dAngle]) commands.append([0, -dAngle]) traj.append(pos[0:2]) elif key == 97: # left pos = motion.move(pos, [0, dAngle]) commands.append([0, dAngle]) traj.append(pos[0:2]) elif key == 119: # up pos = motion.move(pos, [dForward, 0]) commands.append([dForward, 0]) traj.append(pos[0:2]) elif key == 115: # backward pos = motion.move(pos, [-dForward, 0]) commands.append([-dForward, 0]) traj.append(pos[0:2]) else: if terminal.yesno("Done?"): terminal.clearUpTo(2) break # re-draw the updated plot self.plot.clear() self.plot.drawMap(self.simMap) self.plot.drawTrajectory(traj) self.plot.drawRobot(pos) self.plot.draw() # finish the plot self.plot.clear() self.plot.stop("Record Trajectory") # close curses terminal.clearUpTo(2) terminal.echo() terminal.doneCurses() # clean up the trajectory # if we turn, combine that with a forward motion cleaned = [] accumulateTurn = 0 for i in range(0, len(commands)): if commands[i][0] == 0: accumulateTurn = accumulateTurn + commands[i][1] else: cmd = commands[i] cmd[1] = accumulateTurn accumulateTurn = 0 cleaned.append(cmd) trajName = raw_input("Please name this trajectory: ") self.saveTrajectory(cleaned, trajName) def saveTrajectory(self, traj, name): if not os.path.exists('trajectories/'): os.makedirs('trajectories/') pickle.dump(traj, open('trajectories/' + name + ".p", "wb")) def stepThroughTrajectory(self, trajName, motion, initialPosition): terminal = CommandLineApp() commands = self.loadTrajectory(trajName) if not commands: return False idealTraj = [initialPosition[0:2]] idealPos = initialPosition realTraj = [initialPosition[0:2]] realPos = initialPosition # start an interactive plot self.plot.start("Step Through Trajectory") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(idealTraj, "blue") self.plot.drawTrajectory(realTraj, "red") self.plot.drawRobot(idealPos, "blue") self.plot.drawRobot(realPos, "red") self.plot.draw() terminal.clearUpTo(2) terminal.println("Press any key to step...") terminal.noecho() for cmd in commands: key = terminal.keyPress() idealPos = motion.move(idealPos, cmd) realPos = motion.simMove(realPos, cmd) idealTraj.append(idealPos[0:2]) realTraj.append(realPos[0:2]) # update plot self.plot.clear() self.plot.drawMap(self.simMap) self.plot.drawTrajectory(idealTraj, "blue") self.plot.drawTrajectory(realTraj, "red") self.plot.drawRobot(idealPos, "blue") self.plot.drawRobot(realPos, "red") self.plot.draw() self.plot.clear() self.plot.stop("Step Through Trajectory") terminal.clearUpTo(2) terminal.echo() terminal.doneCurses() return True def loadTrajectory(self, name): if os.path.isfile("trajectories/" + name + ".p"): return pickle.load(open("trajectories/" + name + ".p", "rb")) else: return False def stepThroughRobotGraph(self, robot, trajName): terminal = CommandLineApp() commands = self.loadTrajectory(trajName) if not commands: return False robot.reset() initialPosition = robot.position() # the real positions of the robot positions = [initialPosition] pos = initialPosition robot.simSense(self.simMap, pos) # start an interactive plot self.plot.start("Building Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotGraph(robot, "green", 0.2) self.plot.drawRobotTrajectory(robot, "red") self.plot.draw() terminal.clearUpTo(2) terminal.println("Press any key to step...") terminal.noecho() for cmd in commands: key = terminal.keyPress() # move the robot. the robot updates its graph robot.move(cmd) # update where the robot really is due to errors pos = robot.motion.simMove(pos, cmd) positions.append(pos) # sense robot.simSense(self.simMap, pos) # update plot self.plot.clear() self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotGraph(robot, "green", 0.2) self.plot.drawRobotTrajectory(robot, "red") self.plot.draw() self.plot.clear() self.plot.stop("Building Robot Graph") terminal.clearUpTo(2) terminal.echo() terminal.doneCurses() return True def stepThroughRobotObservations(self, robot, trajName): terminal = CommandLineApp() commands = self.loadTrajectory(trajName) if not commands: return False robot.reset() initialPosition = robot.position() # the real positions of the robot positions = [initialPosition] pos = initialPosition robot.simSense(self.simMap, pos) # start an interactive plot self.plot.start("Drawing robot trajectory and Observations") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.draw() terminal.clearUpTo(2) terminal.println("Press any key to step...") terminal.noecho() for cmd in commands: key = terminal.keyPress() # move the robot. the robot updates its graph robot.move(cmd) # update where the robot really is due to errors pos = robot.motion.simMove(pos, cmd) positions.append(pos) # sense robot.simSense(self.simMap, pos) # update plot self.plot.clear() self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.draw() self.plot.clear() self.plot.stop("Building Robot Graph") terminal.clearUpTo(2) terminal.echo() terminal.doneCurses() return True def stepThroughRobotMotion(self, robot, trajName): terminal = CommandLineApp() commands = self.loadTrajectory(trajName) if not commands: return False robot.reset() initialPosition = robot.position() # the real positions of the robot positions = [initialPosition] pos = initialPosition robot.simSense(self.simMap, pos) # start an interactive plot self.plot.start("Drawing robot trajectory and Observations") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotMotion(robot, "green", 1) self.plot.draw() terminal.clearUpTo(2) terminal.println("Press any key to step...") terminal.noecho() for cmd in commands: key = terminal.keyPress() # move the robot. the robot updates its graph robot.move(cmd) # update where the robot really is due to errors pos = robot.motion.simMove(pos, cmd) positions.append(pos) # sense robot.simSense(self.simMap, pos) # update plot self.plot.clear() self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotMotion(robot, "green", 1) self.plot.draw() self.plot.clear() self.plot.stop("Building Robot Graph") terminal.clearUpTo(2) terminal.echo() terminal.doneCurses() return True def stepThroughRobotObservationsAndMotion(self, robot, trajName): terminal = CommandLineApp() commands = self.loadTrajectory(trajName) if not commands: return False robot.reset() initialPosition = robot.position() # the real positions of the robot positions = [initialPosition] pos = initialPosition robot.simSense(self.simMap, pos) # start an interactive plot self.plot.start("Drawing robot trajectory and Observations") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotMotion(robot, "green", 0.2) self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.draw() terminal.clearUpTo(2) terminal.println("Press any key to step...") terminal.noecho() for cmd in commands: key = terminal.keyPress() # move the robot. the robot updates its graph robot.move(cmd) # update where the robot really is due to errors pos = robot.motion.simMove(pos, cmd) positions.append(pos) # sense robot.simSense(self.simMap, pos) # update plot self.plot.clear() self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotMotion(robot, "green", 0.2) self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.draw() self.plot.clear() self.plot.stop("Building Robot Graph") terminal.clearUpTo(2) terminal.echo() terminal.doneCurses() return True def stepThroughSAM(self, robot, trajName): pr(0, "Step Through SAM") commands = self.loadTrajectory(trajName) if not commands: return False pr(1, "loaded trajectory", trajName) pr(1, "running trajectory") robot.reset() initialPosition = robot.position() # the real positions of the robot positions = [initialPosition] pos = initialPosition robot.simSense(self.simMap, pos) for cmd in commands: # move the robot. the robot updates its graph robot.move(cmd) # update where the robot really is due to errors pos = robot.motion.simMove(pos, cmd) positions.append(pos) # sense robot.simSense(self.simMap, pos) pr(1, "trajectory finished") pr(2, len(robot.graph.nodes), "nodes") pr(2, len(robot.graph.edges), "edges") pr(1, "plotting graph") self.plot.new("Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotGraph(robot, "yellow", 0.8) self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.drawRobotAngle(robot, "orange") self.plot.show() wait() beta = 0.2 maxIter = 20 minMean = 0.05 pr(1, "optimization step", 0) m = robot.graph.optimizationStep(beta) pr(1, "dx mean", m) iteration = 1 while iteration < maxIter and m > minMean: pr(1, "optimization step", iteration) m = robot.graph.optimizationStep(beta) pr(1, "dx mean", m) iteration = iteration + 1 pr(1, "done") self.plot.new("Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotGraph(robot, "yellow", 0.8) self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.drawRobotAngle(robot, "orange") self.plot.show() return True def stepIncrementalSAM(self, robot, trajName): pr(0, "Step Through SAM") commands = self.loadTrajectory(trajName) if not commands: return False pr(1, "loaded trajectory", trajName) pr(1, "running trajectory") robot.reset() initialPosition = robot.position() # the real positions of the robot positions = [initialPosition] pos = initialPosition batch = 50 i = 0 robot.simSense(self.simMap, pos) for cmd in commands: i = i + 1 # move the robot. the robot updates its graph robot.move(cmd) # update where the robot really is due to errors pos = robot.motion.simMove(pos, cmd) positions.append(pos) # sense robot.simSense(self.simMap, pos) if i == batch: i = 0 robot.graph.optimize(0.2) self.plot.new("Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotGraph(robot, "yellow", 0.6) self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.drawRobotAngle(robot, "orange") self.plot.show() wait() pr(1, "last") robot.graph.optimize(0.2) pr(1, "done") self.plot.new("Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions, "blue") self.plot.drawRobotTrajectory(robot, "red") self.plot.drawRobotGraph(robot, "yellow", 0.6) self.plot.drawRobotObservations(robot, "green", 0.2) self.plot.drawRobotAngle(robot, "orange") self.plot.show() return True def stepMultiRobotIncrementalSAM(self, robots, trajNames): pr(0, "Step Through SAM") commands0 = self.loadTrajectory(trajNames[0]) commands1 = self.loadTrajectory(trajNames[1]) robot0 = robots[0] robot1 = robots[1] # robot0.reset() initialPosition0 = robot0.graph.nodes[0].value # robot1.reset() initialPosition1 = robot0.graph.nodes[1].value # the real positions of the robot positions0 = [initialPosition0] pos0 = initialPosition0 positions1 = [initialPosition1] pos1 = initialPosition1 batch = 50 i = 0 robot0.simSense(self.simMap, pos0) robot1.simSense(self.simMap, pos1) for j in range(max(len(commands0), len(commands1))): i = i + 1 if j < len(commands0): # move the robot. the robot updates its graph robot0.move(commands0[j]) # update where the robot really is due to errors pos0 = robot0.motion.simMove(pos0, commands0[j]) positions0.append(pos0) # sense robot0.simSense(self.simMap, pos0) if j < len(commands1): # move the robot. the robot updates its graph robot1.move(commands1[j]) # update where the robot really is due to errors pos1 = robot1.motion.simMove(pos1, commands1[j]) positions1.append(pos1) # sense robot1.simSense(self.simMap, pos1) if i == batch: i = 0 robot0.graph.optimize(0.2) robot1.graph.optimize(0.2) self.plot.new("Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions0, "blue") self.plot.drawTrajectory(positions1, "blue") self.plot.drawRobotTrajectory(robot0, "red") self.plot.drawRobotTrajectory(robot1, "red") self.plot.drawRobotGraph(robot0, "yellow", 0.6) self.plot.drawRobotGraph(robot1, "yellow", 0.6) self.plot.drawRobotObservations(robot0, "green", 0.2) self.plot.drawRobotObservations(robot1, "green", 0.2) self.plot.drawRobotAngle(robot0, "orange") self.plot.drawRobotAngle(robot1, "orange") self.plot.show() wait() pr(1, "last") robot0.graph.optimize(0.2) robot1.graph.optimize(0.2) pr(1, "done") self.plot.new("Robot Graph") self.plot.drawMap(self.simMap) self.plot.drawTrajectory(positions0, "blue") self.plot.drawTrajectory(positions1, "blue") self.plot.drawRobotTrajectory(robot0, "red") self.plot.drawRobotTrajectory(robot1, "red") self.plot.drawRobotGraph(robot0, "yellow", 0.6) self.plot.drawRobotGraph(robot1, "yellow", 0.6) self.plot.drawRobotObservations(robot0, "green", 0.2) self.plot.drawRobotObservations(robot1, "green", 0.2) self.plot.drawRobotAngle(robot0, "orange") self.plot.drawRobotAngle(robot1, "orange") self.plot.show() return True
def plotVolume(self): """ Perform volumetric hydrostatics. @return True if error happens. """ try: import Plot plt = Plot.figure('Volume') except ImportError: msg = QtGui.QApplication.translate( "ship_console", "Plot module is disabled, so I cannot perform the plot", None, QtGui.QApplication.UnicodeUTF8) FreeCAD.Console.PrintWarning(msg + '\n') return True # Generate the set of axes Plot.grid(True) for i in range(0, 3): ax = Plot.addNewAxes() # Y axis can be placed at right ax.yaxis.tick_right() ax.spines['right'].set_color((0.0, 0.0, 0.0)) ax.spines['left'].set_color('none') ax.yaxis.set_ticks_position('right') ax.yaxis.set_label_position('right') # And X axis can be placed at bottom for loc, spine in ax.spines.iteritems(): if loc in ['bottom', 'top']: spine.set_position(('outward', (i + 1) * 35)) Plot.grid(True) disp = [] draft = [] warea = [] t1cm = [] xcb = [] for i in range(len(self.points)): disp.append(self.points[i].disp) draft.append(self.points[i].draft) warea.append(self.points[i].wet) t1cm.append(self.points[i].mom) xcb.append(self.points[i].xcb) axes = Plot.axesList() for ax in axes: ax.set_position([0.1, 0.2, 0.8, 0.75]) plt.axes = axes[0] serie = Plot.plot(draft, disp, r'$T$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.0, 0.0, 0.0)) Plot.xlabel(r'$T \; \left[ \mathrm{m} \right]$') Plot.ylabel(r'$\bigtriangleup \; \left[ \mathrm{tons} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[1] serie = Plot.plot(warea, disp, r'Wetted area') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((1.0, 0.0, 0.0)) Plot.xlabel(r'$Wetted \; area \; \left[ \mathrm{m}^2 \right]$') Plot.ylabel(r'$\bigtriangleup \; \left[ \mathrm{tons} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[2] serie = Plot.plot(t1cm, disp, r'Moment to trim 1cm') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.0, 0.0, 1.0)) Plot.xlabel(r'$Moment \; to \; trim \; 1 \mathrm{cm} \; \left[' r' \mathrm{tons} \; \times \; \mathrm{m} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) plt.axes = axes[3] serie = Plot.plot(xcb, disp, r'$XCB$') serie.line.set_linestyle('-') serie.line.set_linewidth(2.0) serie.line.set_color((0.2, 0.8, 0.2)) Plot.xlabel(r'$XCB \; \left[ \mathrm{m} \right]$') plt.axes.xaxis.label.set_fontsize(15) plt.axes.yaxis.label.set_fontsize(15) Plot.legend(True) plt.update() return False