def visualize(self, obj, **kwargs): prot = obj f1 = genfromtxt(prot._getExtraPath('f1.txt')) f2 = genfromtxt(prot._getExtraPath('f2.txt')) plotter = EmPlotter(style='seaborn-whitegrid') plotter.createSubPlot("Histogram of f1", "f1", "Count") plotter.plotHist(f1[~isnan(f1)], 50) plotter.show() plotter = EmPlotter(style='seaborn-whitegrid') plotter.createSubPlot("Histogram of f2", "f2", "Count") plotter.plotHist(f2[~isnan(f2)], 50) plotter.show()
def _visualize(self, obj, **kwargs): fnResults = self.protocol._getPath("results.txt") if exists(fnResults): X, Y, _, _ = self.protocol.getXYValues(False) minX = min(X) maxX = max(X) step = (maxX - minX) / 50 xValues = np.arange(minX, maxX + step, step) yValues = self.protocol.evalFunction(xValues) plotter = EmPlotter(style='seaborn-whitegrid') varNameX = self.protocol.labelX.get() varNameY = self.protocol.labelY.get() ax = plotter.createSubPlot( "Regression Plot", "%s [%s]" % (varNameX, strUnit( self.protocol.experiment.variables[varNameX].units.unit)), "%s [%s]" % (varNameY, strUnit( self.protocol.experiment.variables[varNameY].units.unit))) ax.plot(xValues, yValues) ax.plot(X, Y, 'o') return [plotter] else: return [ self.errorMessage("Result file '%s' not produced yet. " % fnResults) ]
def visualize(self, obj, **kwargs): prot = obj fnProfiles = prot._getPath("profiles.txt") fh = open(fnProfiles,"r") state = 0 legends = ['Iliver', 'Iinlet', 'Isys'] for line in fh: if state==0: tokens = line.split("::") title = tokens[1].strip() I3=[] state=1 elif state==1: tokens=line.strip().split() if len(tokens)==0: plotter = EmPlotter(style='seaborn-whitegrid') ax = plotter.createSubPlot("Simulation", "t [h]", "[I] [mg/mL]") t = np.asarray(I3[0],dtype=np.float64)/60 for n in range(1,len(I3)): y = np.asarray(I3[n],dtype=np.float64) ax.plot(t, y, label=legends[n-1]) ax.legend() plotter.show() state=0 else: if len(I3)==0: for n in range(len(tokens)): I3.append([]) for n in range(len(tokens)): I3[n].append(tokens[n]) fh.close()
def visualize(self, obj, **kwargs): prot = obj fn = prot._getExtraPath('D11.txt') if os.path.exists(fn): D11 = genfromtxt(fn) plotter = EmPlotter(style='seaborn-whitegrid') plotter.createSubPlot("Histogram of D11", "D11", "Count") plotter.plotHist(D11[~isnan(D11)], 50) plotter.show() fn = prot._getExtraPath('D12.txt') if os.path.exists(fn): D12 = genfromtxt(fn) plotter = EmPlotter(style='seaborn-whitegrid') plotter.createSubPlot("Histogram of D12", "D12", "Count") plotter.plotHist(D12[~isnan(D12)], 50) plotter.show()
def _onPlotSummaryClick(self, e=None): sampleKeys = self.samplesTree.selection() n = len(sampleKeys) if n == 1: self.showInfo("Please select several samples to plot.") else: if n > 1: samples = [self.experiment.samples[k] for k in sampleKeys] else: samples = list(self.experiment.samples.values()) xmin = 1e38 xmax = -1e38 for s in samples: xValues, _ = self.getPlotValues(s) xmin = min(xmin, min(xValues)) xmax = max(xmax, max(xValues)) dataDict = {} # key will be time values xrange = np.arange(xmin, xmax, (xmax - xmin) / 300.0) for s in samples: xValues, yValues = self.getPlotValues(s) xValuesUnique, yValuesUnique = uniqueFloatValues( xValues, yValues) B = InterpolatedUnivariateSpline(xValuesUnique, yValuesUnique, k=1) yrange = B(xrange) for x, y in izip(xrange, yrange): if x in dataDict: dataDict[x].append(y) else: dataDict[x] = [y] sortedTime = sorted(dataDict.keys()) # We will store five values (min, 25%, 50%, 75%, max) # for each of the time entries computed percentileList = [0, 25, 50, 75, 100] Y = np.zeros((len(sortedTime), 5)) for i, t in enumerate(sortedTime): Y[i, :] = np.percentile(dataDict[t], percentileList) plotter = EmPlotter(style='seaborn-whitegrid', figure=self.reuseFigure()) # *** Pending ax = plotter.createSubPlot("Summary Plot", self.getTimeLabel(), self.getMeasureLabel()) ax.plot(sortedTime, Y[:, 0], 'r--', label="Minimum") ax.plot(sortedTime, Y[:, 1], 'b--', label="25%") ax.plot(sortedTime, Y[:, 2], 'g', label="50% (Median)") ax.plot(sortedTime, Y[:, 3], 'b--', label="75%") ax.plot(sortedTime, Y[:, 4], 'r--', label="Maximum") ax.grid(True) ax.legend() plotter.show()
def visualize(self, obj, **kwargs): model = PKPDAllometricScale() model.load(obj.fnScale.get()) x = np.log10(np.asarray(model.X)) xlabel = "%s [%s]" % (model.predictor, model.predictorUnits) for varName, varUnits in model.scaled_vars: plotter = EmPlotter(style='seaborn-whitegrid') y = np.log10(np.asarray(model.Y[varName])) ylabel = "%s [%s]" % (varName, varUnits) ax = plotter.createSubPlot(varName, xlabel, ylabel) ax.plot(x, y, '.', label='Species') ax.plot(x, np.log10(model.models[varName][0]) + x * model.models[varName][1], 'r', label='R2=%f' % model.qualifiers[varName][0]) leg = ax.legend(loc='upper right') if leg: leg.draggable() plotter.show() for varName, varUnits in model.averaged_vars: plotter = EmPlotter(style='seaborn-whitegrid') y = np.asarray(model.Y[varName]) ylabel = "%s [%s]" % (varName, varUnits) ax = plotter.createSubPlot("Scatter Plot", xlabel, ylabel) ax.plot(x, y, '.', label='Species') ax.plot(x, model.models[varName][0] * np.ones(x.shape), 'r', label='Std=%f' % model.qualifiers[varName][0]) leg = ax.legend(loc='upper right') if leg: leg.draggable() plotter.show()
def _onPlotClick(self, e=None): selection = self.tree.selection() n = len(selection) if n < 1 or n > 2: self.showError("Select one or two variables to plot.") else: plotter = EmPlotter(style='seaborn-whitegrid') varX = self._variables[selection[0]] xValues = self.observations[:, varX.index] def _label(var): return "%s [%s]" % (var.varName, var.unitStr) if n == 1: plotter.createSubPlot("Histogram", _label(varX), "Count") plotter.plotHist(xValues, 50) else: # n == 2 varY = self._variables[selection[1]] yValues = self.observations[:, varY.index] ax = plotter.createSubPlot("Scatter Plot", _label(varX), _label(varY)) ax.plot(xValues, yValues, '.') plotter.show()
def _plot(varLabelX, varLabelY, x, y, yp): plotter = EmPlotter(style='seaborn-whitegrid', figure=self.reuseFigure()) ax = plotter.createSubPlot("Plot", varLabelX, varLabelY) xValues = _values(x, useLog=self.useTimeLog()) ax.plot(xValues, _values(y), 'x', label="Observations") idx = np.argsort(xValues) ypValues = _values(yp) ax.plot(np.asarray(xValues)[idx], np.asarray(ypValues)[idx], 'g', label="Fit") leg = ax.legend() if leg: leg.set_draggable(True) plotter.show()
def visualize(self, obj, **kwargs): prot = obj auc = np.genfromtxt(prot._getExtraPath('errorAUC.txt')) cmax = np.genfromtxt(prot._getExtraPath('errorCmax.txt')) plotter = EmPlotter(style='seaborn-whitegrid') plotter.createSubPlot("Histogram of error AUC0t", "Error AUC0t", "Count") plotter.plotHist(auc[~np.isnan(auc)], 50) plotter.show() plotter = EmPlotter(style='seaborn-whitegrid') plotter.createSubPlot("Histogram of error Cmax", "Error Cmax", "Count") plotter.plotHist(cmax[~np.isnan(cmax)], 50) plotter.show() sortedTimeTrue, Ytrue = self.getSummary(prot.inputExperiment.get().fnPKPD) sortedTimeSimulated, Ysimulated = self.getSummary(prot.inputSimulated.get().fnPKPD) plotter = EmPlotter(style='seaborn-whitegrid') ax = plotter.createSubPlot("Summary Plot", self.timeVarName, self.CVarName) ax.plot(sortedTimeTrue, Ytrue[:, 0], 'r--', label="Minimum In-vivo", linewidth=2) ax.plot(sortedTimeTrue, Ytrue[:, 1], 'b--', label="25% In-vivo", linewidth=2) ax.plot(sortedTimeTrue, Ytrue[:, 2], 'g', label="50% (Median) In-vivo", linewidth=2) ax.plot(sortedTimeTrue, Ytrue[:, 3], 'b--', label="75% In-vivo", linewidth=2) ax.plot(sortedTimeTrue, Ytrue[:, 4], 'r--', label="Maximum In-vivo", linewidth=2) ax.plot(sortedTimeSimulated, Ysimulated[:, 0], 'r--', label="Minimum Simulated") ax.plot(sortedTimeSimulated, Ysimulated[:, 1], 'b--', label="25% Simulated") ax.plot(sortedTimeSimulated, Ysimulated[:, 2], 'g', label="50% (Median) Simulated") ax.plot(sortedTimeSimulated, Ysimulated[:, 3], 'b--', label="75% Simulated") ax.plot(sortedTimeSimulated, Ysimulated[:, 4], 'r--', label="Maximum Simulated") ax.grid(True) ax.legend() plotter.show() plotter = EmPlotter(style='seaborn-whitegrid') ax = plotter.createSubPlot("Mean Plot", self.timeVarName, self.CVarName) ax.plot(sortedTimeTrue, Ytrue[:, 2], 'g', label="50% (Median) In-vivo", linewidth=2) ax.plot(sortedTimeSimulated, Ysimulated[:, 2], 'g', label="50% (Median) Simulated") ax.grid(True) ax.legend() plotter.show()
def visualize(self, obj, **kwargs): prot = obj fnProfiles = prot._getPath("profiles.txt") fh = open(fnProfiles, "r") Rtype = [] Rlegends = [] R = [] state = 0 for line in fh: if state == 0: tokens = line.split("::") Rtype.append(tokens[0]) Rlegends.append(tokens[1].strip()) Ri = [] state = 1 elif state == 1: tokens = line.strip().split() if len(tokens) == 0: R.append(Ri) state = 0 else: if len(Ri) == 0: for n in range(len(tokens)): Ri.append([]) for n in range(len(tokens)): Ri[n].append(tokens[n]) fh.close() plotter = None previousType = "" for legend, Ri, Rtypei in izip(Rlegends, R, Rtype): if plotter is None or Rtypei != previousType: if previousType != "": self.addLimits(plotter, previousType, minX, maxX) plotter = EmPlotter(style='seaborn-whitegrid') doShow = True if Rtypei == "ReversibleLiver" or Rtypei == "TimeDependentLiver" or Rtypei == "InductionLiver" or Rtypei == "StaticLiver" or Rtypei == "TransporterLiver": Ilabel = "[Ih] [uM]" elif Rtypei == "ReversibleGut" or Rtypei == "TimeDependentGut" or Rtypei == "InductionGut" or Rtypei == "StaticGut" or Rtypei == "TransporterGut": Ilabel = "[Ig] [uM]" elif Rtypei == "TransporterRenal": Ilabel = "[Cmax] [uM]" ax = plotter.createSubPlot("Plot", Ilabel, "R") previousType = Rtypei minX = None maxX = None else: doShow = False ax = plotter.getLastSubPlot() x = np.asarray(Ri[0], dtype=np.float64) if len(Ri) == 2: y = np.asarray(Ri[1], dtype=np.float64) else: y = np.asarray(Ri[2], dtype=np.float64) ax.plot(x, y, label=legend) minXi = np.min(x) maxXi = np.max(x) if minX == None: minX = minXi maxX = maxXi minX = min(minXi, minX) maxX = min(maxXi, maxX) leg = ax.legend() if leg: leg.draggable() if doShow: plotter.show() else: plotter.draw() self.addLimits(plotter, previousType, minX, maxX)
class PKPDResponsiveDialog(dialog.Dialog): def __init__(self, parent, title, **kwargs): """ From kwargs: message: message tooltip to show when browsing. selected: the item that should be selected. validateSelectionCallback: a callback function to validate selected items. """ self.values = [] self.plotter = None self.targetProtocol = kwargs['targetProtocol'] self.experiment = self.targetProtocol.experiment self.varNameX = kwargs['varNameX'] self.varNameY = kwargs['varNameY'] self.provider = SamplesTreeProvider(self.experiment) self.model = self.loadModel() self.validateSelectionCallback = kwargs.get('validateSelectionCallback', None) self.setLabels() dialog.Dialog.__init__(self, parent, title, buttons=[('Select', dialog.RESULT_YES), ('Cancel', dialog.RESULT_CANCEL)]) def setLabels(self): pass def loadModel(self): model = self.targetProtocol.createModel() model.setExperiment(self.experiment) # if hasattr(self.protODE, "deltaT"): # model.deltaT = self.protODE.deltaT.get() model.setXVar(self.varNameX) model.setYVar(self.varNameY) return model def body(self, bodyFrame): bodyFrame.config(bg='white') gui.configureWeigths(bodyFrame) self._createSamplesFrame(bodyFrame) self._createSlidersFrame(bodyFrame) self._createLogsFrame(bodyFrame) def _createSamplesFrame(self, content): frame = tk.Frame(content, bg='white') #frame = tk.LabelFrame(content, text='General') lfSamples = tk.LabelFrame(frame, text="Samples", bg='white') gui.configureWeigths(frame) lfSamples.grid(row=0, column=0, sticky='news', padx=5, pady=5) self.samplesTree = self._addBoundTree(lfSamples, self.provider, 10) self.samplesTree.itemClick = self._onSampleChanged frame.grid(row=0, column=0, sticky='news', padx=5, pady=5) def _createSlidersFrame(self, content): frame = tk.Frame(content, bg='white') lfBounds = tk.LabelFrame(frame, text="Parameter Bounds", bg='white') gui.configureWeigths(frame) i = 0 self.sliders = {} paramUnits = self.targetProtocol.parameterUnits for paramName, bounds in self.targetProtocol.getParameterBounds().items(): bounds = bounds or (0, 1) slider = MinMaxSlider(lfBounds, "%s [%s]"%(paramName,strUnit(paramUnits[i])), bounds[0], bounds[1], callback=self._onVarChanged) slider.grid(row=i, column=0, padx=5, pady=5) self.sliders[paramName] = slider i += 1 lfBounds.grid(row=0, column=0, sticky='news', padx=5, pady=5) frame.grid(row=0, column=1, sticky='news', padx=5, pady=5) def _createLogsFrame(self, content): frame = tk.Frame(content) def addVar(text, col, varName): varFrame = tk.Frame(frame) varFrame.grid(row=0, column=col, sticky='new') label = tk.Label(varFrame, text=text)#, font=self.fontBold) label.grid(row=0, column=0, padx=5, pady=2, sticky='nw') combo = tk.Label(varFrame, text=varName, width=10) combo.grid(row=0, column=1, sticky='nw', padx=5, pady=5) radioVar = tk.IntVar() radio = tk.Checkbutton(varFrame, text='Log10', variable=radioVar) radio.grid(row=0, column=2, sticky='nw', padx=5, pady=5) return combo, radio, radioVar self.timeWidget = addVar('Time variable', 0, self.varNameX) self.timeWidget[2].trace('w', self._onLogChanged) self.measureWidget = addVar('Measure variable', 1, self.varNameY) measureVar = self.measureWidget[2] measureVar.set(True) measureVar.trace('w', self._onLogChanged) frame.grid(row=1, column=0, columnspan=2, sticky='news', padx=5, pady=5) def _addBoundTree(self, parent, provider, height): bt = BoundTree(parent, provider, height=height) bt.grid(row=0, column=0, sticky='news', padx=5, pady=5) gui.configureWeigths(parent) return bt def apply(self): self.values = [] def _onVarChanged(self, *args): sampleKeys = self.samplesTree.selection() if sampleKeys: self.computeFit() self.plotResults() else: dialog.showInfo("Warning","Please select some sample(s) to plot.",self) def computeFit(self): currentParams = [] for paramName in self.targetProtocol.getParameterNames(): currentParams.append(self.sliders[paramName].getValue()) self.targetProtocol.setParameters(currentParams) self.ypValues = self.targetProtocol.forwardModel(currentParams, self.xpValues) def getBoundsList(self): boundList = [] for paramName in self.targetProtocol.getParameterNames(): boundList.append(self.sliders[paramName].getMinMax()) return boundList def useTimeLog(self): return self.timeWidget[2].get() def useMeasureLog(self): return self.measureWidget[2].get() def getUnits(self, varName): return self.experiment.variables[varName].getUnitsString() def getLabel(self, varName, useLog): varLabel = '%s [%s]' % (varName, self.getUnits(varName)) if useLog: varLabel = "log10(%s)" % varLabel return varLabel def getTimeLabel(self): return self.getLabel(self.varNameX, self.useTimeLog()) def getMeasureLabel(self): return self.getLabel(self.varNameY, self.useMeasureLog()) def computePlotValues(self, xValues, yValues): useMeasureLog = self.useMeasureLog() useTimeLog = self.useTimeLog() if not (useMeasureLog or useTimeLog): newXValues = xValues newYValues = yValues else: # If log will be used either for time or measure var # we need to filter elements larger than 0 newXValues = [] newYValues = [] def _value(v, useLog): if useLog: return math.log10(v) if v > 0 else None return v for x, y in izip(xValues, yValues): x = _value(x, useTimeLog) y = _value(y, useMeasureLog) if x is not None and y is not None: newXValues.append(x) newYValues.append(y) return newXValues, newYValues def _updateModel(self): """ This function should be called whenever the sample changes """ pass def _onLogChanged(self, *args): # We will treat a log change as a sample change to plot self._onSampleChanged() def _onSampleChanged(self, e=None): sampleKeys = self.samplesTree.selection() if sampleKeys: # When the sample is changed we need to re-compute (with log or not) # the x, y values self.sample = self.experiment.samples[sampleKeys[0]] self.xValues, self.yValues = self.sample.getXYValues(self.varNameX, self.varNameY) self.newXValues, self.newYValues = self.computePlotValues(self.xValues[0], self.yValues[0]) self._updateModel() self.computeFit() self.plotResults() else: dialog.showInfo("Warning","Please select some sample(s) to plot.",self) def plotResults(self): if self.plotter is None or self.plotter.isClosed(): self.plotter = EmPlotter(style='seaborn-whitegrid') doShow = True else: doShow = False ax = self.plotter.getLastSubPlot() self.plotter.clear() ax = self.plotter.createSubPlot("Sample: %s" % self.sample.sampleName, self.getTimeLabel(), self.getMeasureLabel()) self.newXPValues, self.newYPValues = self.computePlotValues(self.xpValues[0], self.ypValues[0]) ax.plot(self.newXValues, self.newYValues, 'x', label="Observations") ax.plot(self.newXPValues, self.newYPValues, label="Fit") ax.legend() if doShow: self.plotter.show() else: self.plotter.draw() def destroy(self): """Destroy the window""" if not (self.plotter is None or self.plotter.isClosed()): self.plotter.close() dialog.Dialog.destroy(self)
class ExperimentWindow(gui.Window): """ This class creates a Window that will display some Point's contained in a Data object. It will allow to launch 1D, 2D and 3D plots by selecting any combination of the x1, x2...xn from the Point dimension. Points can be selected by either Click and Drag in the Scatter plot or.. by creating an Expression. Finally, there is a button 'Create Cluster' that will call a callback fuction to take care of it. """ def __init__(self, **kwargs): gui.Window.__init__(self, minsize=(420, 200), **kwargs) self.experiment = kwargs.get('experiment') self.fitting = kwargs.get('fitting', None) self.callback = kwargs.get('callback', None) content = tk.Frame(self.root) self._createContent(content) content.grid(row=0, column=0, sticky='news') content.columnconfigure(0, weight=1) content.rowconfigure(0, weight=1) self.plotter = None def _createContent(self, content): # Create and fill the frame containing the Experiment # info, variables and doses p = tk.PanedWindow(content, orient=tk.VERTICAL, bg='white') p.grid(row=0, column=0, sticky='news', padx=5, pady=5) self._createTopFrame(p) # Create the middle frame containing the Samples Box self._createSamplesFrame(p) # Create the last frame with the buttons self._createButtonsFrame(content) #self._updateSelectionLabel() def _createTopFrame(self, content): frame = tk.Frame(content) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) tab = ttk.Notebook(frame) tab.grid(row=0, column=0, sticky='news', padx=5, pady=5) def addTab(label): lf = tk.Frame(tab) tab.add(lf, text=label) return lf lfGeneral = addTab('General') self._addLabel(lfGeneral, 'Title', 0, 0) self._titleVar = tk.StringVar() if 'title' in self.experiment.general: self._titleVar.set(self.experiment.general['title']) else: self._titleVar.set("") titleEntry = tk.Entry(lfGeneral, width=26, textvariable=self._titleVar, bg='white') titleEntry.grid(row=0, column=1, sticky='nw', padx=5, pady=(5, 0)) self._addLabel(lfGeneral, 'Comment', 1, 0) commentText = gui.text.Text(lfGeneral, width=30, height=3, bg='white') if 'comment' in self.experiment.general: commentText.setText(self.experiment.general['comment']) else: commentText.setText("") commentText.grid(row=1, column=1, sticky='nw', padx=5, pady=(5, 0)) self._commentText = commentText lfVars = addTab('Variables') self.varsTree = self._addBoundTree(lfVars, VariablesTreeProvider, 5) lfVias = addTab('Vias') self.viasTree = self._addBoundTree(lfVias, ViasTreeProvider, 5) lfDoses = addTab('Doses') self.dosesTree = self._addBoundTree(lfDoses, DosesTreeProvider, 5) lfGroups = addTab('Groups') self.groupsTree = self._addBoundTree(lfGroups, GroupsTreeProvider, 5) # Fitting tab if self.fitting: tabFitting = addTab('Fitting') t = TaggedText(tabFitting, width=80, height=10, bg='white') t.grid(row=0, column=0, sticky='nw', padx=10, pady=10) t.setText('Select one of the samples to see more information.') t.setReadOnly(True) self.fittingText = t # Buttons for fitting buttonsFrame = self._createFittingButtonsFrame(tabFitting) buttonsFrame.grid(row=0, column=1, sticky='news', padx=5, pady=5) #frame.grid(row=0, column=0, sticky='news', padx=5, pady=(10, 5)) content.add(frame, sticky='news', padx=5, pady=5) def _createSamplesFrame(self, content): frame = tk.Frame(content) #frame = tk.LabelFrame(content, text='General') lfSamples = tk.LabelFrame(frame, text='Samples') gui.configureWeigths(frame) lfSamples.grid(row=0, column=0, sticky='news', padx=5, pady=5) self.samplesTree = self._addBoundTree(lfSamples, SamplesTreeProvider, 10, fitting=self.fitting) self.samplesTree.itemDoubleClick = self._onSampleDoubleClick self.samplesTree.itemClick = self._onSampleClick plotFrame = tk.Frame(lfSamples) plotFrame.grid(row=1, column=0, sticky='ws', padx=5, pady=5) # Add a combobox with the variable for time timeVars = [ v.varName for v in self.experiment.variables.values() if v.role == v.ROLE_TIME ] timeVars += [ v.varName for v in self.experiment.variables.values() if v.role == v.ROLE_MEASUREMENT ] measureVars = [ v.varName for v in self.experiment.variables.values() if v.role == v.ROLE_MEASUREMENT ] def addVar(text, col, choices): varFrame = tk.Frame(plotFrame) varFrame.grid(row=0, column=col, sticky='new') label = tk.Label(varFrame, text=text, font=self.fontBold) label.grid(row=0, column=0, padx=5, pady=2, sticky='nw') if len(choices) == 0: choices = [''] combo = ComboBox(varFrame, choices, width=10) combo.grid(row=0, column=1, sticky='nw', padx=5, pady=5) radioVar = tk.IntVar() radio = tk.Checkbutton(varFrame, text='Log10', variable=radioVar) radio.grid(row=0, column=2, sticky='nw', padx=5, pady=5) return combo, radio, radioVar self.timeWidget = addVar('Time variable', 0, timeVars) self.measureWidget = addVar('Measure variable', 1, list(set(measureVars + timeVars))) self.measureWidget[2].set(True) self.plotButton = Button(plotFrame, ' Plot ', font=self.fontBold, command=self._onPlotClick, tooltip='Select one or more samples to plot ' 'their measures of the selected ' 'variables (optionally in log).') self.plotButton.grid(row=0, column=2, sticky='ne', padx=5) self.useCurrentPlotVar = tk.IntVar() self.useCurrentPlot = tk.Checkbutton(plotFrame, text='Use current plot', variable=self.useCurrentPlotVar) self.useCurrentPlot.grid(row=1, column=0, sticky='nw', padx=5, pady=5) self.plotSummaryButton = Button( plotFrame, ' Summary Plot ', font=self.fontBold, command=self._onPlotSummaryClick, tooltip='Select several samples to plot' ' their statistics' ' (min, max, avg and std).') self.plotSummaryButton.grid(row=1, column=2, sticky='ne', padx=5, pady=5) #frame.grid(row=1, column=0, sticky='news', padx=5, pady=5) content.add(frame, sticky='news', padx=5, pady=5) def _createButtonsFrame(self, content): frame = tk.Frame(content) gui.configureWeigths(frame) buttonsFrame = tk.Frame(frame) buttonsFrame.grid(row=0, column=0, sticky='ne') closeButton = Button(buttonsFrame, 'Close', command=self.close, imagePath='fa-times.png') closeButton.grid(row=0, column=0, sticky='ne', padx=5) self.newButton = HotButton(buttonsFrame, ' New Experiment ', command=self._onCreateClick, tooltip='Create a new experiment with the ' 'selected samples. You can also edit' 'title and comment.') self.newButton.grid(row=0, column=1, sticky='ne', padx=5) frame.grid(row=1, column=0, sticky='news', padx=5, pady=5) def _createFittingButtonsFrame(self, content): buttonsFrame = tk.Frame(content) buttonsFrame.grid(row=0, column=0, sticky='ne') plotValuesButton = Button(buttonsFrame, 'Plot Fit', command=self._onPlotFitClick) plotValuesButton.grid(row=0, column=0, sticky='sew', padx=5, pady=5) openValuesButton = Button(buttonsFrame, 'Open Fit', command=self._onOpenFitClick) openValuesButton.grid(row=1, column=0, sticky='sew', padx=5, pady=5) return buttonsFrame def _addLabel(self, parent, text, r, c): label = tk.Label(parent, text=text, font=self.fontBold) label.grid(row=r, column=c, padx=5, pady=5, sticky='ne') return label def _addBoundTree(self, parent, ProviderClass, height, **kwargs): bt = BoundTree(parent, ProviderClass(self.experiment, **kwargs), height=height) bt.grid(row=0, column=0, sticky='news', padx=5, pady=5) gui.configureWeigths(parent) return bt def getUnits(self, varName): return self.experiment.variables[varName].getUnitsString() def getLabel(self, varName, useLog): varLabel = '%s [%s]' % (varName, self.getUnits(varName)) if useLog: varLabel = "log10(%s)" % varLabel return varLabel def getTimeVarName(self): return self.timeWidget[0].getText() def useTimeLog(self): return self.timeWidget[2].get() def getTimeLabel(self): return self.getLabel(self.getTimeVarName(), self.useTimeLog()) def getMeasureVarName(self): return self.measureWidget[0].getText() def useMeasureLog(self): return self.measureWidget[2].get() def getMeasureLabel(self): return self.getLabel(self.getMeasureVarName(), self.useMeasureLog()) def getPlotValues(self, sample): xValues, yValues = sample.getXYValues(self.getTimeVarName(), self.getMeasureVarName()) xValues = xValues[0] # From [array(...)] to array(...) yValues = yValues[0] useMeasureLog = self.useMeasureLog() useTimeLog = self.useTimeLog() if not (useMeasureLog or useTimeLog): return xValues, yValues # If log will be used either for time or measure var # we need to filter elements larger than 0 newXValues = [] newYValues = [] def _value(v, useLog): if useLog: return math.log10(v) if v > 0 else None return v for x, y in izip(xValues, yValues): x = _value(x, useTimeLog) y = _value(y, useMeasureLog) if x is not None and y is not None: newXValues.append(x) newYValues.append(y) return newXValues, newYValues def reuseFigure(self): return None if not self.useCurrentPlotVar.get() else 'active' def _onPlotClick(self, e=None): sampleKeys = self.samplesTree.selection() if sampleKeys: if self.plotter is None or self.plotter.isClosed(): self.plotter = EmPlotter(style='seaborn-whitegrid', figure=self.reuseFigure()) doShow = True ax = self.plotter.createSubPlot("Plot", self.getTimeLabel(), self.getMeasureLabel()) self.plotDict = {} else: doShow = False ax = self.plotter.getLastSubPlot() samples = [self.experiment.samples[k] for k in sampleKeys] for s in samples: if not s.sampleName in self.plotDict or not doShow: x, y = self.getPlotValues(s) label = s.sampleName if not doShow: label += " " + self.getTimeVarName( ) + " vs " + self.getMeasureVarName() ax.plot(x, y, label=label) self.plotDict[s.sampleName] = True leg = ax.legend() if leg: leg.set_draggable(True) if doShow: self.plotter.show() else: self.plotter.draw() else: self.showInfo("Please select some sample(s) to plot.") def _onPlotSummaryClick(self, e=None): sampleKeys = self.samplesTree.selection() n = len(sampleKeys) if n == 1: self.showInfo("Please select several samples to plot.") else: if n > 1: samples = [self.experiment.samples[k] for k in sampleKeys] else: samples = list(self.experiment.samples.values()) xmin = 1e38 xmax = -1e38 for s in samples: xValues, _ = self.getPlotValues(s) xmin = min(xmin, min(xValues)) xmax = max(xmax, max(xValues)) dataDict = {} # key will be time values xrange = np.arange(xmin, xmax, (xmax - xmin) / 300.0) for s in samples: xValues, yValues = self.getPlotValues(s) xValuesUnique, yValuesUnique = uniqueFloatValues( xValues, yValues) B = InterpolatedUnivariateSpline(xValuesUnique, yValuesUnique, k=1) yrange = B(xrange) for x, y in izip(xrange, yrange): if x in dataDict: dataDict[x].append(y) else: dataDict[x] = [y] sortedTime = sorted(dataDict.keys()) # We will store five values (min, 25%, 50%, 75%, max) # for each of the time entries computed percentileList = [0, 25, 50, 75, 100] Y = np.zeros((len(sortedTime), 5)) for i, t in enumerate(sortedTime): Y[i, :] = np.percentile(dataDict[t], percentileList) plotter = EmPlotter(style='seaborn-whitegrid', figure=self.reuseFigure()) # *** Pending ax = plotter.createSubPlot("Summary Plot", self.getTimeLabel(), self.getMeasureLabel()) ax.plot(sortedTime, Y[:, 0], 'r--', label="Minimum") ax.plot(sortedTime, Y[:, 1], 'b--', label="25%") ax.plot(sortedTime, Y[:, 2], 'g', label="50% (Median)") ax.plot(sortedTime, Y[:, 3], 'b--', label="75%") ax.plot(sortedTime, Y[:, 4], 'r--', label="Maximum") ax.grid(True) ax.legend() plotter.show() def _onCreateClick(self, e=None): sampleKeys = self.samplesTree.selection() if sampleKeys and self.callback: self.callback() else: self.showInfo( "Please select some sample(s) to create a new experiment.") def _onSampleClick(self, obj): # In fitting mode we need to display some information for # the given sample fit if self.fitting: selection = self.samplesTree.selection() if selection: sampleKey = selection[0] sampleFit = self.fitting.getSampleFit(sampleKey) textMsg = sampleFit.getBasicInfo() else: textMsg = 'Select one of the samples to see more information.' self.fittingText.setReadOnly(False) self.fittingText.setText(textMsg) self.fittingText.setReadOnly(True) if not (self.plotter is None or self.plotter.isClosed()): self._onPlotClick() def _onSampleDoubleClick(self, obj): sampleKeys = self.samplesTree.selection() if sampleKeys: MeasureWindow( masterWindow=self, sample=self.experiment.samples[sampleKeys[0]]).show() def _onPlotFitClick(self, e=None): sampleKeys = self.samplesTree.selection() if sampleKeys: def _value(v, useLog): if useLog: return math.log10(v) if v > 0 else None return v def _values(values, useLog=self.useMeasureLog()): return [_value(float(x), useLog) for x in values] def _plot(varLabelX, varLabelY, x, y, yp): plotter = EmPlotter(style='seaborn-whitegrid', figure=self.reuseFigure()) ax = plotter.createSubPlot("Plot", varLabelX, varLabelY) xValues = _values(x, useLog=self.useTimeLog()) ax.plot(xValues, _values(y), 'x', label="Observations") idx = np.argsort(xValues) ypValues = _values(yp) ax.plot(np.asarray(xValues)[idx], np.asarray(ypValues)[idx], 'g', label="Fit") leg = ax.legend() if leg: leg.set_draggable(True) plotter.show() # Get first selected element fit = self.fitting.getSampleFit(sampleKeys[0]) if fit == None: return varLabelX = self.getLabel(self.fitting.predictor.varName, self.useTimeLog()) if type(self.fitting.predicted) == list: i = 0 for v in self.fitting.predicted: varLabelY = self.getLabel(v.varName, self.useMeasureLog()) _plot(varLabelX, varLabelY, fit.x[i], fit.y[i], fit.yp[i]) i += 1 else: varLabelY = self.getLabel(self.fitting.predicted.varName, self.useMeasureLog()) _plot(varLabelX, varLabelY, fit.x[0], fit.y[0], fit.yp[0]) else: self.showInfo("Please select some sample(s) to plot.") def _onOpenFitClick(self, e=None): sampleKeys = self.samplesTree.selection() if sampleKeys: # Get first selected element fit = self.fitting.getSampleFit(sampleKeys[0]) FitWindow(masterWindow=self, fitting=self.fitting, sampleFit=fit).show() else: self.showInfo("Please select some sample(s) to plot.") def _onClosing(self): if self.plotter: self.plotter.close() gui.Window._onClosing(self)
def visualize(self, obj, **kwargs): self.prot = obj plotter = EmPlotter(style='seaborn-whitegrid') title = "Summary plot" if self.prot.showSummary else "Individual plots" ax = plotter.createSubPlot("Summary Plot", self.prot.X1.get(), self.prot.Y1.get()) if self.prot.twoExperiments.get() == 0: X2 = self.prot.X1.get() if self.prot.X2.get( ) == "" else self.prot.X2.get() Y2 = self.prot.Y1.get() if self.prot.Y2.get( ) == "" else self.prot.Y2.get() sortedX1, Y1 = self.getData( self.prot.inputExperiment1.get().fnPKPD, self.prot.X1.get(), self.prot.Y1.get()) sortedX2, Y2 = self.getData( self.prot.inputExperiment2.get().fnPKPD, X2, Y2) if self.prot.showSummary: ax.plot(sortedX1, Y1[:, 0], 'r--', label="Minimum Exp1", linewidth=2) ax.plot(sortedX1, Y1[:, 1], 'b--', label="25% Exp1", linewidth=2) ax.plot(sortedX1, Y1[:, 2], 'g', label="50% (Median) Exp1", linewidth=2) ax.plot(sortedX1, Y1[:, 3], 'b--', label="75% Exp1", linewidth=2) ax.plot(sortedX1, Y1[:, 4], 'r--', label="Maximum Exp1", linewidth=2) ax.plot(sortedX2, Y2[:, 0], 'r--', label="Minimum Exp2") ax.plot(sortedX2, Y2[:, 1], 'b--', label="25% Exp2") ax.plot(sortedX2, Y2[:, 2], 'g', label="50% (Median) Exp2") ax.plot(sortedX2, Y2[:, 3], 'b--', label="75% Exp2") ax.plot(sortedX2, Y2[:, 4], 'r--', label="Maximum Exp2") else: ax.plot(sortedX1, Y1, linewidth=2, label="Exp1") ax.plot(sortedX2, Y2, label="Exp2") else: listColors = ['b', 'g', 'r', 'k', 'c', 'm', 'y'] for idx, experimentPtr in enumerate(self.prot.inputExperiments): sortedX, Y = self.getData(experimentPtr.get().fnPKPD, self.prot.X1.get(), self.prot.Y1.get()) if self.prot.showSummary: ax.plot(sortedX, Y[:, 0], linestyle='--', color=listColors[idx], label="Minimum Exp%d" % idx) ax.plot(sortedX, Y[:, 1], linestyle='--', color=listColors[idx], label="25%% Exp%d" % idx) ax.plot(sortedX, Y[:, 2], color=listColors[idx], label="50%% (Median) Exp%d" % idx) ax.plot(sortedX, Y[:, 3], linestyle='--', color=listColors[idx], label="75%% Exp%d" % idx) ax.plot(sortedX, Y[:, 4], linestyle='--', color=listColors[idx], label="Maximum Exp%d" % idx) else: ax.plot(sortedX, Y[:, 0], color=listColors[idx], label="Exp%d" % idx) ax.plot(sortedX, Y[:, 1:], color=listColors[idx]) ax.legend() ax.grid(True) plotter.show()