Example #1
0
    def __init__(self, parent):
        tabs = parent.sp
        r = range(len(tabs))

        # Prepare unique names in ugly manner
        self.names = [n.spec.name
                      for n in tabs] if tabs[0].spec is not None else ['']
        test = []
        for n in r:
            if self.names.count(self.names[n]) > 1 or self.names[n] in test:
                test.append(self.names[n])
                self.names[n] += ' {}'.format(test.count(self.names[n]))

        plots = [[
            {
                'name': 'Calibrated',
                'curves': ['Calibrated ' + self.names[n] for n in r]
            },
            {
                'name': 'Integrated',
                'curves': ['Integrated ' + self.names[n] for n in r]
            },
            {
                'name': 'System noise',
                'curves': ['Noise ' + self.names[n] for n in r]
            },
        ]]

        df = [n.axisLimits[1] - n.axisLimits[0] for n in tabs]
        df2 = max(df) / 2

        axisLimits = [
            -df2, df2,
            min([n.axisLimits[2] for n in tabs]),
            max([n.axisLimits[3] for n in tabs])
        ]

        PlotPanel.__init__(self,
                           parent=parent,
                           plots=plots,
                           axisLimits=axisLimits)
        self.tabs = tabs
        cmap = get_cmap('tab10', len(tabs))
        self.colors = [
            QPen(QColor(x[0] * 255, x[1] * 255, x[2] * 255), 1)
            for x in cmap.colors
        ]

        cPanel = self.curves['Calibrated ' + self.names[0]].parent
        cPanel.add_item(make.legend("BL"))
        cPanel.setActive()
        cPanel = self.curves['Integrated ' + self.names[0]].parent
        cPanel.add_item(make.legend("BL"))
        cPanel.setActive()
        cPanel = self.curves['Noise ' + self.names[0]].parent
        cPanel.add_item(make.legend("BL"))
        cPanel.setActive()
Example #2
0
    def __init__(self):
        super(RealtimeDemo, self).__init__()
        self.setWindowTitle(u"Realtime Demo")

        self.data = {u"t":array("d")}
        for name in sum(PLOT_DEFINE, []):
            self.data[name] = array("d")

        self.curves = {}
        self.t = 0
        vbox = QVBoxLayout()
        vbox.addWidget(self.setup_toolbar())
        self.manager = PlotManager(self)
        self.plots = []
        for i, define in enumerate(PLOT_DEFINE):
            plot = CurvePlot()
            plot.axisScaleDraw(CurvePlot.Y_LEFT).setMinimumExtent(60)
            self.manager.add_plot(plot)
            self.plots.append(plot)
            plot.plot_id = id(plot)
            for j, curve_name in enumerate(define):
                curve = self.curves[curve_name] = make.curve([0], [0], color=COLORS[j], title=curve_name)
                plot.add_item(curve)
            plot.add_item(make.legend("BL"))
            vbox.addWidget(plot)
        self.manager.register_standard_tools()
        self.manager.get_default_tool().activate()
        self.manager.synchronize_axis(CurvePlot.X_BOTTOM, self.manager.plots.keys())
        self.setLayout(vbox)
        self.startTimer(100)
Example #3
0
def build_items():
    x = np.linspace(-10, 10, 200)
    y = np.sin(np.sin(np.sin(x)))
    filename = osp.join(osp.dirname(__file__), "brain.png")
    items = [
        make.curve(x, y, color="b"),
        make.image(filename=filename),
        make.trimage(filename=filename),
        make.maskedimage(filename=filename,
                         colormap='gray',
                         show_mask=True,
                         xdata=[0, 40],
                         ydata=[0, 50]),
        make.label("Relative position <b>outside</b>", (x[0], y[0]),
                   (-10, -10), "BR"),
        make.label("Relative position <i>inside</i>", (x[0], y[0]), (10, 10),
                   "TL"),
        make.label("Absolute position", "R", (0, 0), "R"),
        make.legend("TR"),
        make.rectangle(-3, -0.8, -0.5, -1., "rc1"),
        make.segment(-3, -0.8, -0.5, -1., "se1"),
        make.ellipse(-10, 0.0, 0, 0, "el1"),
        make.annotated_rectangle(0.5, 0.8, 3, 1., "rc1", "tutu"),
        make.annotated_segment(-1, -1, 1, 1., "rc1", "tutu"),
        Axes((0, 0), (1, 0), (0, 1)),
        PolygonShape(
            np.array([[150., 330.], [270., 520.], [470., 480.], [520., 360.],
                      [460., 200.], [250., 240.]])),
    ]
    return items
Example #4
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata
    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin
    
    mydescr = N.dtype([('Zeit', 'float'), ('T1', 'float'), ('T2', 'float'), ('T3', 'float'),('T4', 'float'),('T5', 'float'), ('T6', 'float'), ('T7', 'float'),('T8', 'float')])
    myrecarray = read_array('test.ASC', mydescr)

    x = myrecarray['Zeit']
    y = savitzky_golay(myrecarray['T1'], window_size=131, order=3)
    y2 = savitzky_golay(myrecarray['T2'], window_size=131, order=3)
    y3 = savitzky_golay(myrecarray['T3'], window_size=131, order=3)

    #x = linspace(-10, 10, 200)
    #dy = x/100.
    #y = sin(sin(sin(x)))    
    #x2 = linspace(-10, 10, 20)
    #y2 = sin(sin(sin(x2)))
    plot(make.curve(x, y, color="b"),
         make.curve(x, y2, color="g",),
         make.curve(x, y3, color="r"),
         make.label("Relative position <b>outside</b>",
                    (x[0], y[0]), (-10, -10), "BR"),
         make.label("Relative position <i>inside</i>",
                    (x[0], y[0]), (10, 10), "TL"),
         make.label("Absolute position", "R", (0,0), "R"),
         make.legend("TR"),
         )
Example #5
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata

    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin

    x = linspace(-10, 10, 200)
    dy = x / 100.0
    y = sin(sin(sin(x)))
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    curve2 = make.curve(x2, y2, color="g", curvestyle="Sticks")
    curve2.setTitle("toto")
    plot(
        make.curve(x, y, color="b"),
        curve2,
        make.curve(x, sin(2 * y), color="r"),
        make.merror(x, y / 2, dy),
        make.label("Relative position <b>outside</b>", (x[0], y[0]),
                   (-10, -10), "BR"),
        make.label("Relative position <i>inside</i>", (x[0], y[0]), (10, 10),
                   "TL"),
        make.label("Absolute position", "R", (0, 0), "R"),
        make.legend("TR"),
        make.marker(
            position=(5.0, 0.8),
            label_cb=lambda x, y: "A = %.2f" % x,
            markerstyle="|",
            movable=False,
        ),
    )
Example #6
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata

    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin

    x = linspace(-10, 10, 200)
    dy = x / 100.0
    y = sin(sin(sin(x)))
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    curve2 = make.curve(x2, y2, color="g", curvestyle="Sticks")
    curve2.setTitle("toto")
    plot(
        make.curve(x, y, color="b"),
        curve2,
        make.curve(x, sin(2 * y), color="r"),
        make.merror(x, y / 2, dy),
        make.label("Relative position <b>outside</b>", (x[0], y[0]), (-10, -10), "BR"),
        make.label("Relative position <i>inside</i>", (x[0], y[0]), (10, 10), "TL"),
        make.label("Absolute position", "R", (0, 0), "R"),
        make.legend("TR"),
        make.marker(position=(5.0, 0.8), label_cb=lambda x, y: "A = %.2f" % x, markerstyle="|", movable=False),
    )
Example #7
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata

    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin, trapz

    x = linspace(-10, 10, 1000)
    y = sin(sin(sin(x)))

    curve = make.curve(x, y, "ab", "b")
    range = make.range(-2, 2)
    disp0 = make.range_info_label(range,
                                  "BR",
                                  "x = %.1f ± %.1f cm",
                                  title="Range infos")

    disp1 = make.computation(range, "BL", "trapz=%g", curve,
                             lambda x, y: trapz(y, x))

    disp2 = make.computations(
        range,
        "TL",
        [
            (curve, "min=%.5f", lambda x, y: y.min()),
            (curve, "max=%.5f", lambda x, y: y.max()),
            (curve, "avg=%.5f", lambda x, y: y.mean()),
        ],
    )
    legend = make.legend("TR")
    plot(curve, range, disp0, disp1, disp2, legend)
    def testFcn(self):
        x = np.linspace(0, 100, 1000)

        y = (np.random.rand(len(x)) - 0.5).cumsum()

        curve = make.curve(x, y, "ab", "b")
        range = make.range(0, 5)

        disp2 = make.computations(
            range,
            "TL",
            [
                (curve, "min=%.5f", lambda x, y: y.min()),
                (curve, "max=%.5f", lambda x, y: y.max()),
                (curve, "avg=%.5f", lambda x, y: y.mean()),
            ],
        )
        legend = make.legend("TR")
        items = [curve, range, disp2, legend]

        win = CurveDialog(edit=False, toolbar=True, parent=self)
        plot = win.get_plot()
        for item in items:
            plot.add_item(item)
        win.show()
Example #9
0
    def plot(self, spectra, configs=None, titles=None):
        """ do not forget to call replot() after calling this function ! """
        self.widget.plot.del_all_items()
        self.widget.plot.add_item(self.marker)
        if titles is not None:
            self.widget.plot.add_item(make.legend("TL"))
        self.widget.plot.add_item(self.label)

        allpeaks = []
        for i in range(len(spectra)):
            peaks = spectra[i]
            allpeaks.append(peaks)
            config = configs[i] if configs is not None else None
            if config is None:
                config = dict(color = getColor(i))
            if titles is not None:
                title = titles[i]
            else:
                title = u""
            curve = make.curve([], [], title=title,\
                              curvestyle="Sticks", **config)
            curve.set_data(peaks[:, 0], peaks[:, 1])
            curve.__class__ = ModifiedCurveItem
            self.widget.plot.add_item(curve)
        self.widget.plot.add_item(self.line)
        if len(allpeaks):
            self.widget.plot.all_peaks = np.vstack(allpeaks)
        else:
            self.widget.plot.all_peaks = np.zeros((0,2))
Example #10
0
def build_items():
    x = np.linspace(-10, 10, 200)
    y = np.sin(np.sin(np.sin(x)))
    filename = osp.join(osp.dirname(__file__), "brain.png")
    items = [ 
              make.curve(x, y, color="b"),
              make.image(filename=filename),
              make.trimage(filename=filename),
              make.maskedimage(filename=filename, colormap='gray',
                               show_mask=True, xdata=[0, 40], ydata=[0, 50]),
              make.label("Relative position <b>outside</b>",
                         (x[0], y[0]), (-10, -10), "BR"),
              make.label("Relative position <i>inside</i>",
                         (x[0], y[0]), (10, 10), "TL"),
              make.label("Absolute position", "R", (0, 0), "R"),
              make.legend("TR"),
              make.rectangle(-3, -0.8, -0.5, -1., "rc1"),
              make.segment(-3, -0.8, -0.5, -1., "se1"),
              make.ellipse(-10, 0.0, 0, 0, "el1"),
              make.annotated_rectangle(0.5, 0.8, 3, 1., "rc1", "tutu"),
              make.annotated_segment(-1, -1, 1, 1., "rc1", "tutu"),
              Axes( (0, 0), (1, 0), (0, 1) ),
              PolygonShape(np.array([[150., 330.],
                                     [270., 520.],
                                     [470., 480.],
                                     [520., 360.],
                                     [460., 200.],
                                     [250., 240.]])),
              ]
    return items
Example #11
0
    def plot(self, chromatograms, titles=None, configs=None,
             withmarker=False):
        """ do not forget to call replot() after calling this function ! """
        allrts = set()
        self.widget.plot.del_all_items()
        # self.widget.plot.set_antialiasing(True)
        for i in range(len(chromatograms)):
            rts, chromatogram = chromatograms[i]
            config = None
            if configs is not None:
                config = configs[i]
            if config is None:
                config = dict(color=getColor(i))
            if titles:
                title = titles[i]
            else:
                title = ""

            curve = make.curve(rts, chromatogram, title=title, **config)
            curve.__class__ = ModifiedCurveItem
            allrts.update(rts)
            self.widget.plot.add_item(curve)

        if withmarker:
            self.widget.plot.add_item(self.label)
            allrts = sorted(allrts)
            self.marker.rts = allrts
            self.marker.attach(self.widget.plot)
            self.widget.plot.add_item(self.marker)
        if titles is not None:
            self.widget.plot.add_item(make.legend("TL"))
        self.addRangeSelector(allrts)
Example #12
0
 def addCurve(self, txy, color=None):
     (t, x, y) = txy
     curve = make.curve(x, y, t, color)
     self.plot.add_item(curve)
     if self.legend is None:
         self.legend = make.legend()
         self.plot.add_item(self.legend)
Example #13
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata

    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin

    x = linspace(-10, 10, 200)
    dy = x / 100.0
    y = sin(sin(sin(x)))
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    plot(
        [
            make.curve(x, y, color="b"),
            make.label(
                "Relative position <b>outside</b>", (x[0], y[0]), (-10, -10), "BR"
            ),
        ],
        [
            make.curve(x2, y2, color="g"),
        ],
        [
            make.curve(x, sin(2 * y), color="r"),
            make.label("Relative position <i>inside</i>", (x[0], y[0]), (10, 10), "TL"),
        ],
        [
            make.merror(x, y / 2, dy),
            make.label("Absolute position", "R", (0, 0), "R"),
            make.legend("TR"),
        ],
    )
Example #14
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata
    _app = guidata.qapplication()
    # --
    # from numpy import linspace, sin
    #x = linspace(-10, 10, 200)

    start_rec = 819
    num_rec = 10000

    x = range(start_rec, start_rec + num_rec)
    vname, y = loadBinData('ATOLOG_01R_1.atp', start_rec, num_rec)
    plot(make.curve(x, y[0], title=vname[0], color="b"),
         make.curve(x, y[1], title=vname[1], color="g"),
         #make.curve(x, sin(2*y), color="r"),
         #make.merror(x, y/2, dy),
         #make.label("Relative position <b>outside</b>",
         #           (x[0], y[0]), (-10, -10), "BR"),
         #make.label("Relative position <i>inside</i>",
         #           (x[0], y[0]), (10, 10), "TL"),
         #make.label("Absolute position", "R", (0,0), "R"),
         make.legend("TR"),
         #make.marker(position=(5., .8), label_cb=lambda x, y: u"A = %.2f" % x,
         #            markerstyle="|", movable=False)
         )
Example #15
0
   def __init__(self): 
       super(RealtimeDemo, self).__init__() 
       self.setWindowTitle(u"Realtime Demo") 
 
       self.data = {u"t": array("d")}
       for name in sum(PLOT_DEFINE, []): 
           self.data[name] = array("d") 
 
       self.curves = {} 
       self.t = 0 
       vbox = QVBoxLayout() 
       vbox.addWidget(self.setup_toolbar()) 
       self.manager = PlotManager(self) 
       self.plots = [] 
       for i, define in enumerate(PLOT_DEFINE): 
           plot = CurvePlot() 
           plot.axisScaleDraw(CurvePlot.Y_LEFT).setMinimumExtent(60) 
           self.manager.add_plot(plot) 
           self.plots.append(plot) 
           plot.plot_id = id(plot) 
           for j, curve_name in enumerate(define): 
               curve = self.curves[curve_name] = make.curve([0], [0], color=COLORS[j], title=curve_name) 
               plot.add_item(curve) 
           plot.add_item(make.legend("BL")) 
           vbox.addWidget(plot) 
       self.manager.register_standard_tools() 
       self.manager.get_default_tool().activate() 
       self.manager.synchronize_axis(CurvePlot.X_BOTTOM, self.manager.plots.keys()) 
       self.setLayout(vbox) 
       self.startTimer(100) 
Example #16
0
    def create_curves(self, labels, this_range, show_legend=True):

        self.curves = []
        plot = self.get_plot()
        plot.del_all_items(except_grid=False)
        for i, l in enumerate(labels):
            param = CurveParam()
            param.label = str(l)
            color = COLORS.get(self.colors[i % len(self.colors)],
                               self.colors[i % len(self.colors)])
            param.line.color = color

            # create a new curve
            curve = CurveItemModel(param)
            self.curves.append(curve)
            plot.add_item(curve)
            curve.setRenderHint(QwtPlotItem.RenderAntialiased,
                                USE_ANTIALIASING)
            l = make.legend("TR")
            if show_legend:
                plot.add_item(l)

        self.myranges = []
        for r in this_range:
            self.add_range_to_plot(plot, r)
Example #17
0
    def plot(self, chromatograms, titles=None, configs=None,\
                   withmarker=False):
        """ do not forget to call replot() after calling this function ! """
        allrts = set()
        self.widget.plot.del_all_items()
        #self.widget.plot.set_antialiasing(True)
        for i in range(len(chromatograms)):
            rts, chromatogram = chromatograms[i]
            config = None
            if configs is not None:
                config = configs[i]
            if config is None:
                config = dict(color = getColor(i))
            if titles:
                title = titles[i]
            else:
                title = ""

            curve = make.curve(rts, chromatogram, title=title, **config)
            curve.__class__ = ModifiedCurveItem
            allrts.update(rts)
            self.widget.plot.add_item(curve)

        if withmarker:
            self.widget.plot.add_item(self.label)
            allrts = sorted(allrts)
            self.marker.rts = allrts
            self.marker.attach(self.widget.plot)
            self.widget.plot.add_item(self.marker)
        if titles is not None:
            self.widget.plot.add_item(make.legend("TL"))
        self.addRangeSelector(allrts)
Example #18
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata

    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin, trapz

    x = linspace(-10, 10, 1000)
    y = sin(sin(sin(x)))

    curve = make.curve(x, y, "ab", "b")
    range = make.range(-2, 2)
    disp0 = make.range_info_label(range, "BR", "x = %.1f ± %.1f cm", title="Range infos")

    disp1 = make.computation(range, "BL", "trapz=%g", curve, lambda x, y: trapz(y, x))

    disp2 = make.computations(
        range,
        "TL",
        [
            (curve, "min=%.5f", lambda x, y: y.min()),
            (curve, "max=%.5f", lambda x, y: y.max()),
            (curve, "avg=%.5f", lambda x, y: y.mean()),
        ],
    )
    legend = make.legend("TR")
    plot(curve, range, disp0, disp1, disp2, legend)
Example #19
0
    def plot_next(self, data):

        pl = self.ui.curve.get_plot()
        pl.del_all_items()

        c = []
        if self.project.parameters.multiObjective:
            k = []
            l = []
            for i, j in sorted(data[1], key=lambda p: p[0]):
                k.append(i)
                l.append(j)
            self.resultslist[0].append(k)
            self.resultslist[1].append(l)

            for i in max(5, range(len(self.resultslist[0]))):
                st = self.styles(i, gen=len(self.resultslist[0]))
                c.append(
                    make.curve(self.resultslist[0][-i - 1],
                               self.resultslist[1][-i - 1], **st))
                #c.append(make.curve(d[0],d[1],**st))
            [self._plot(i) for i in reversed(c)]

            self._plot(make.legend("TR", restrict_items=c[:7]))
        else:
            self.resultslist[0].append(data[0])
            for i in range(len(data[1])):
                self.resultslist[1][i].append(data[1][i])
                if i == len(data[1]) - 1:
                    st = self.styles(-1)
                else:
                    st = self.styles(i)

                c.append(
                    make.curve(self.resultslist[0], self.resultslist[1][i],
                               **st))
            [self._plot(i) for i in reversed(c)]

            lt = len(self.resultslist[1])
            if lt > 4:
                its = c[:4]
                its.append(c[-1])
            else:
                its = c[:lt + 1]
            self._plot(make.legend("TR", restrict_items=its))
        self.zoom_the_plot(data)
        pl.replot()
 def _add_legend(self, unique_labels, items_with_label):
     # überbleibsel von zeitreihen plott
     unique_labels -= set((None, ))
     unique_labels -= set(("", ))
     if unique_labels:
         legend = make.legend("TL", restrict_items=items_with_label)
         setup_label_param(legend, {"font.size": 12})
         self.plot.add_item(legend)
Example #21
0
 def _add_legend(self, unique_labels, items_with_label):
     # überbleibsel von zeitreihen plott
     unique_labels -= set((None,))
     unique_labels -= set(("",))
     if unique_labels:
         legend = make.legend("TL", restrict_items=items_with_label)
         setup_label_param(legend, {"font.size": 12})
         self.plot.add_item(legend)
    def plot_next(self, data):

        pl=self.ui.curve.get_plot()
        pl.del_all_items()        

        c=[]
        if self.project.parameters.multiObjective:
            k=[]
            l=[]
            for i,j in sorted(data[1],key=lambda p: p[0]):
                k.append(i)
                l.append(j)
            self.resultslist[0].append(k)
            self.resultslist[1].append(l)
            
            for i in max(5,range(len(self.resultslist[0]))):
                st=self.styles(i, gen=len(self.resultslist[0]))
                c.append(make.curve(self.resultslist[0][-i-1],self.resultslist[1][-i-1],**st))
                #c.append(make.curve(d[0],d[1],**st))
            [self._plot(i) for i in reversed(c)]
            
            self._plot(make.legend("TR", restrict_items=c[:7]))         
        else:
            self.resultslist[0].append(data[0])
            for i in range(len(data[1])): 
                self.resultslist[1][i].append(data[1][i])  
                if i==len(data[1])-1:
                    st=self.styles(-1)
                else:
                    st=self.styles(i)
                
                c.append(make.curve(self.resultslist[0], self.resultslist[1][i],  **st))
            [self._plot(i) for i in reversed(c)]
            
            lt=len(self.resultslist[1])
            if  lt > 4:
                its=c[:4]
                its.append(c[-1])
            else:
                its=c[:lt+1]
            self._plot(make.legend("TR", restrict_items=its))         
        self.zoom_the_plot(data)
        pl.replot()
Example #23
0
def _correlogram_plot(win, trains, bin_size, cut_off, border_correction,
                      progress, unit):
    """ Fill a plot window with correlograms.
    """
    correlograms, bins = correlogram(trains, bin_size, cut_off,
        border_correction, unit, progress)
    x = bins[:-1] + bin_size / 2

    crlgs = []
    indices = correlograms.keys()
    for i1 in xrange(len(indices)):
        for i2 in xrange(i1, len(indices)):
            crlgs.append((correlograms[indices[i1]][indices[i2]],
                indices[i1], indices[i2]))

    for i, c in enumerate(crlgs):
        legend_items = []
        pW = BaseCurveWidget(win)
        plot = pW.plot
        plot.set_antialiasing(True)
        plot.add_item(make.curve(x, c[0]))

        # Create legend
        color = helper.get_object_color(c[1])
        color_curve = make.curve([], [], c[1].name,
            color, 'NoPen', linewidth=1, marker='Rect',
            markerfacecolor=color, markeredgecolor=color)
        legend_items.append(color_curve)
        plot.add_item(color_curve)
        if c[1] != c[2]:
            color = helper.get_object_color(c[2])
            color_curve = make.curve([], [], c[2].name,
                color, 'NoPen', linewidth=1, marker='Rect',
                markerfacecolor=color, markeredgecolor=color)
            legend_items.append(color_curve)
            plot.add_item(color_curve)
        plot.add_item(make.legend(restrict_items=legend_items))

        columns = max(2, len(indices) - 3)
        if i >= len(correlograms) - columns:
            plot.set_axis_title(BasePlot.X_BOTTOM, 'Time')
            plot.set_axis_unit(BasePlot.X_BOTTOM, unit.dimensionality.string)
        if i % columns == 0:
            plot.set_axis_title(BasePlot.Y_LEFT, 'Correlation')
            plot.set_axis_unit(BasePlot.Y_LEFT, 'count/segment')

        win.add_plot_widget(pW, i, column=i%columns)

    win.add_x_synchronization_option(True, range(len(correlograms)))
    win.add_y_synchronization_option(False, range(len(correlograms)))
    win.add_custom_curve_tools()
    progress.done()
    win.show()

    return True
Example #24
0
 def plot_init(self):
     self.manager = PlotManager(self)
     self.plots = []
     self.plot = CurvePlot(xlabel="", ylabel="")
     # self.plot.axisScaleDraw(CurvePlot.Y_LEFT).setMinimumExtent(10)
     self.manager.add_plot(self.plot)
     self.plots.append(self.plot)
     self.plot.plot_id = id(self.plot)
     self.curve = make.curve([0], [0], color="blue", title="gray value")
     self.plot.add_item(self.curve)
     self.plot.add_item(make.legend("TR"))
     self.ui_obj.line_info_display.addWidget(self.plot)
Example #25
0
 def setup_image(self, i, j, win):
     p = ImagePlot(win, xlabel=self.xlabel, ylabel=self.ylabel,
                   zlabel=self.zlabel, yreverse=self.yreverse)
     self.main_widget = p
     win.add_plot(i, j, p)
     for item in self.images+self.plots:
         if item in self.images:
             item.set_color_map(self.colormap)
         p.add_item(item)
     if self.legend_position is not None:
         p.add_item(make.legend(self.legend_position))
     return p
Example #26
0
 def setup_plot(self, i, j, win):
     p = CurvePlot(win, xlabel=self.xlabel, ylabel=self.ylabel)
     self.main_widget = p
     win.add_plot(i, j, p)
     for item in self.plots:
         p.add_item(item)
     p.enable_used_axes()
     active_item = p.get_active_item(force=True)
     p.set_scales(self.xscale, self.yscale)
     active_item.unselect()
     if self.legend_position is not None:
         p.add_item(make.legend(self.legend_position))
     return p
Example #27
0
    def plot_peakmaps(self, peakmap_ranges, configs=None, titles=None):

        has_titles = titles is not None
        configs, titles = self._setup_configs_and_titles(configs, titles, len(peakmap_ranges))

        self.plot.del_all_items()
        self.plot.add_item(self.marker)
        if has_titles:
            self.plot.add_item(make.legend("TL"))
        self.plot.add_item(self.label)

        self.plot.plot_peakmap_ranges(peakmap_ranges, configs, titles)
        self.plot.add_item(self.line)
Example #28
0
 def setup_plot(self, i, j, win):
     p = CurvePlot(win, xlabel=self.xlabel, ylabel=self.ylabel)
     self.main_widget = p
     win.add_plot(i, j, p)
     for item in self.plots:
         p.add_item(item)
     p.enable_used_axes()
     active_item = p.get_active_item(force=True)
     p.set_scales(self.xscale, self.yscale)
     active_item.unselect()
     if self.legend_position is not None:
         p.add_item(make.legend(self.legend_position))
     return p
    def plot_peakmaps(self, peakmap_ranges, configs=None, titles=None):

        has_titles = titles is not None
        configs, titles = self._setup_configs_and_titles(
            configs, titles, len(peakmap_ranges))

        self.plot.del_all_items()
        self.plot.add_item(self.marker)
        if has_titles:
            self.plot.add_item(make.legend("TL"))
        self.plot.add_item(self.label)

        self.plot.plot_peakmap_ranges(peakmap_ranges, configs, titles)
        self.plot.add_item(self.line)
Example #30
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata
    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin
    import labrad
    cx=labrad.connect('lab-rat', password='******')
    ai=cx.agilent_pna_with_vxi_11
    ai.select_device(0)
    testscan=ai.freq_sweep()
    len(testscan)
    xx=testscan[0].asarray
    yytemp=testscan[1].asarray[0]
    yy=np.square(abs(yytemp))
#    x = linspace(-10, 10, 200)
#    dy = x/100.
#    y = sin(sin(sin(x)))    
#    x2 = linspace(-10, 10, 20)
#    y2 = sin(sin(sin(x2)))
#    plot(make.curve(x, y, color="b"),
#         make.curve(x2, y2, color="g", curvestyle="Sticks"),
#         make.curve(x, sin(2*y), color="r"),
#         make.merror(x, y/2, dy),
#         make.label("Relative position <b>outside</b>",
#                    (x[0], y[0]), (-10, -10), "BR"),
#         make.label("Relative position <i>inside</i>",
#                    (x[0], y[0]), (10, 10), "TL"),
#         make.label("Absolute position", "R", (0,0), "R"),
#         make.legend("TR"),
#         make.marker(position=(5., .8), label_cb=lambda x, y: u"A = %.2f" % x,
#                     markerstyle="|", movable=False)
#         )
    plot(make.curve(xx*1e-9, 10*np.log10(yy), color="b"),
         make.curve(xx*2e-9, 10*np.log10(yy), color="g"),
#         make.curve(x, sin(2*y), color="r"),
#         make.merror(x, y/2, dy),
         make.label("PNA SCAN<b>test</b>",
                    (xx[0], yy[0]), (-10, -10), "BR"),
         make.label("PNA SCAN<b>test 2X</b>",
                    (xx[0], yy[0]), (-10, -10), "BR"),
#         make.label("Relative position <i>inside</i>",
#                    (x[0], y[0]), (10, 10), "TL"),
#         make.label("Absolute position", "R", (0,0), "R"),
         make.legend("TR"),
#         make.marker(position=(5., .8), label_cb=lambda xx, yy: u"A = %.2f" % xx,
#                     markerstyle="|", movable=False)
         )
Example #31
0
 def setup_image(self, i, j, win):
     p = ImagePlot(win,
                   xlabel=self.xlabel,
                   ylabel=self.ylabel,
                   zlabel=self.zlabel,
                   yreverse=self.yreverse)
     self.main_widget = p
     win.add_plot(i, j, p)
     for item in self.images + self.plots:
         if item in self.images:
             item.set_color_map(self.colormap)
         p.add_item(item)
     if self.legend_position is not None:
         p.add_item(make.legend(self.legend_position))
     return p
Example #32
0
    def show_data(self, label):
        data = self.raw_data[label]['data']
        xaxis = self.raw_data['Latest']['freqs']
        print('xmin', np.min(xaxis), np.max(xaxis))

        self.dshape = data.shape[0]

        vals = np.log10(data.shape[0])
        if vals > 4:
            fact = 10**int(vals - 4)
            n = int(data.shape[0] / fact)
            print('Factor', fact, 'N', n)

            s = data[0:n * fact].reshape(n, fact)
            data = np.mean(s, axis=1)

            s = xaxis[0:n * fact].reshape(n, fact)
            xaxis = np.mean(s, axis=1)

        print('Min', np.min(data), 'Max', np.max(data), data.shape)
        print('dshape', self.dshape)
        if label in list(self.item.keys()):
            if self.do_log:
                self.item[label].set_data(
                    xaxis, self.cal_slope * data + self.cal_icept)
            else:
                self.item[label].set_data(xaxis, data)
        else:
            if self.do_log:
                self.item[label] = make.curve(
                    xaxis,
                    self.cal_slope * data + self.cal_icept,
                    color=self.colours[len(self.item) % len(self.colours)],
                    title=label)
            else:
                self.item[label] = make.curve(
                    xaxis,
                    data,
                    color=self.colours[len(self.item) % len(self.colours)],
                    title=label)

            self.curvewidget.plot.add_item(self.item[label])
            self.curvewidget.plot.set_antialiasing(True)
            if self.legend is None:
                self.legend = make.legend("TR")
                self.curvewidget.plot.add_item(self.legend)

        self.item[label].plot().replot()
Example #33
0
    def loadDialog(self):
        filename = QtGui.QFileDialog.getOpenFileName(self.Form, 'Open File', '.')
        fname = open(filename)
        data = fname.read()
        #self.le.setText(filename)
        do = pandas.read_csv(str(filename), delimiter=",")
        #data = pd.read_csv('C:/Users/se00075/PycharmProjects/Test2/src' + '/' + 'data.csv')
        if (self.startD.text().isEmpty()) & (self.endD.text().isEmpty()):
            d=do
        else:
            do['time_stamp'] = do['time_stamp'].astype('datetime64[ns]')
            st = int(self.startD.text())
            en = int(self.endD.text())
            select = (do['time_stamp'] >= do.time_stamp[0]+datetime.timedelta(days=st-1)) & (do['time_stamp'] < do.time_stamp[0]+datetime.timedelta(days=en))
            d = do[select]
            #d = pandas.read_csv(str(filename), delimiter=",")
            #print d
        ##Lets add clean missing data here

        space = 0
        self.checkboxes = []
        for i in d.columns:
            c = QtGui.QCheckBox(self.Form)
            #print space
            c.setGeometry(QtCore.QRect(10 + space, 50, 70, 17))
            c.setText(_fromUtf8(i))
            c.show()
            c.clicked.connect(self.selected)
            self.checkboxes.append(c)
            space += 68
        self.original_data = d
       #self.original_data=(self.original_data-self.original_data.mean()) / self.original_data.std()

        self.dialog = CurveDialog(edit=False, toolbar=False, parent=self.widget)
        self.plot = self.dialog.get_plot()
        self.plot.set_antialiasing(True)
        self.plot.setAxisTitle(Qwt5.Qwt.QwtPlot.xBottom, 'Time')
        self.plot.setAxisTitle(Qwt5.Qwt.QwtPlot.yLeft, 'Value')
        self.manager = PlotManager(self)
        self.manager.add_plot(self.plot)
        legend = make.legend('TL')
        self.plot.add_item(legend)
        ly = QtGui.QVBoxLayout()
        ly.addWidget(self.plot)
        self.widget.setLayout(ly)
        self.widget.show()
        self.Form.update()
        self.Form.repaint()
Example #34
0
    def plot(self, data, configs=None, titles=None):
        """ do not forget to call replot() after calling this function ! """
        self.widget.plot.del_all_items()
        self.widget.plot.add_item(self.marker)
        if titles is not None:
            self.widget.plot.add_item(make.legend("TL"))
        self.widget.plot.add_item(self.label)

        all_peaks = []
        self.widget.plot.data = []
        self.widget.plot.curves = []
        for i, (pm, rtmin, rtmax, mzmin, mzmax, npeaks) in enumerate(data):
            if rtmin is None and rtmax is None:
                rtmin, rtmax = pm.rtRange()
            elif rtmin is None:
                rtmin, __ = pm.rtRange()
            elif rtmax is None:
                __, rtmax = pm.rtRange()
            if mzmin is None and mzmax is None:
                mzmin, mzmax = pm.mzRange()
            elif mzmin is None:
                mzmin, __ = pm.mzRange()
            elif mzmax is None:
                __, mzmax = pm.mzRange()
            if npeaks is None:
                npeaks = 3000


            peaks = sample_peaks(pm, rtmin, rtmax, mzmin, mzmax, npeaks)
            all_peaks.append(peaks)
            config = configs[i] if configs is not None else None
            if config is None:
                config = dict(color=getColor(i))
            if titles is not None:
                title = titles[i]
            else:
                title = u""
            curve = make.curve([], [], title=title, curvestyle="Sticks", **config)
            curve.set_data(peaks[:, 0], peaks[:, 1])
            curve.__class__ = ModifiedCurveItem
            self.widget.plot.add_item(curve)
            self.widget.plot.curves.append(curve)
            self.widget.plot.data.append((pm, rtmin, rtmax, mzmin, mzmax, npeaks))
        self.widget.plot.add_item(self.line)
        if len(all_peaks):
            self.widget.plot.all_peaks = np.vstack(all_peaks)
        else:
            self.widget.plot.all_peaks = np.zeros((0, 2))
Example #35
0
File: fit.py Project: gyenney/Tools
    def refresh(self, slider_value=None):
        """Refresh Fit Tool dialog box"""
        # Update button states
        enable = self.x is not None and self.y is not None \
                 and self.x.size > 0 and self.y.size > 0 \
                 and self.fitfunc is not None and self.fitparams is not None \
                 and len(self.fitparams) > 0
        for btn in self.button_list:
            btn.setEnabled(enable)

        if not enable:
            # Fit widget is not yet configured
            return

        fitargs, fitkwargs = self.get_fitfunc_arguments()
        yfit = self.fitfunc(self.x, [p.value for p in self.fitparams],
                            *fitargs, **fitkwargs)

        plot = self.get_plot()

        if self.legend is None:
            self.legend = make.legend(anchor=self.legend_anchor)
            plot.add_item(self.legend)

        if self.xrange is None:
            self.xrange = make.range(0., 1.)
            plot.add_item(self.xrange)
        self.xrange.set_range(self.autofit_prm.xmin, self.autofit_prm.xmax)
        self.xrange.setVisible(self.show_xrange)

        if self.data_curve is None:
            self.data_curve = make.curve([], [],
                                         _("Data"),
                                         color="b",
                                         linewidth=2)
            plot.add_item(self.data_curve)
        self.data_curve.set_data(self.x, self.y)

        if self.fit_curve is None:
            self.fit_curve = make.curve([], [],
                                        _("Fit"),
                                        color="r",
                                        linewidth=2)
            plot.add_item(self.fit_curve)
        self.fit_curve.set_data(self.x, yfit)

        plot.replot()
        plot.disable_autoscale()
Example #36
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata
    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 1000)+1
    y = sin(sin(sin(x)))+3

    curve = make.curve(x, y, "ab", "b")
    hcursor = make.hcursor(3.2, label='y = %.2f')
    vcursor = make.vcursor(7,  label='x = %.2f')
    vcursor2 = make.vcursor(-1,  label='NOT MOVABLE = %.2f', movable=False)
    xcursor = make.xcursor(-4, 2.5,  label='x = %.2f<br>y = %.2f')
    legend = make.legend("TR")
    plot(curve, hcursor, vcursor, vcursor2, xcursor, legend)
Example #37
0
 def __init__(self):
     super(SyncXAxis, self).__init__()
     
     self.data = {u"t":array("d")} 
     for name in sum(PLOT_DEFINE, []): 
         self.data[name] = array("d") 
     
     self.i = 0
     self.x = []
     self.curves = {} 
     self.t = 0
     self.sint = []
     self.get_Roll = []
     self.get_Pitch = []
     self.get_Yaw = []
     self.get_Angle1 = []
     self.get_Angle2 =[]
     self.get_Angle3 = []
     vbox = QtGui.QGridLayout()
     #工具栏
     vbox.addLayout(self.setup_toolbar(),0,0) 
     self.manager = PlotManager(self)
     self.plots = []
     #生成竖直排列图形窗口
     for i, define in enumerate(PLOT_DEFINE): 
         plot = CurvePlot() 
         plot.axisScaleDraw(CurvePlot.Y_LEFT).setMinimumExtent(60) 
         self.manager.add_plot(plot) 
         self.plots.append(plot) 
         plot.plot_id = id(plot) 
         for j, curve_name in enumerate(define): 
             curve = self.curves[curve_name] = make.curve([0], [0], color=COLORS[j], title=curve_name) 
             plot.add_item(curve) 
         plot.add_item(make.legend("BL")) 
         #vbox.addWidget(plot)
     vbox.addWidget(self.plots[0],1,0)
     vbox.addWidget(self.plots[1],1,1)
     vbox.addWidget(self.plots[2],2,0)
     vbox.addWidget(self.plots[3],2,1)
     
     self.manager.register_standard_tools()
     self.manager.get_default_tool().activate()
     self.manager.synchronize_axis(CurvePlot.X_BOTTOM, self.manager.plots.keys()) 
     self.setLayout(vbox)
     
     self.startTimer(20) 
Example #38
0
def test():
    """Test"""
    # -- Create QApplication
    import guidata
    _app = guidata.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 1000) + 1
    y = sin(sin(sin(x))) + 3

    curve = make.curve(x, y, "ab", "b")
    hcursor = make.hcursor(3.2, label='y = %.2f')
    vcursor = make.vcursor(7, label='x = %.2f')
    vcursor2 = make.vcursor(-1, label='NOT MOVABLE = %.2f', movable=False)
    xcursor = make.xcursor(-4, 2.5, label='x = %.2f<br>y = %.2f')
    legend = make.legend("TR")
    plot(curve, hcursor, vcursor, vcursor2, xcursor, legend)
Example #39
0
def _split_plot_hor(channels, spikes, ref_units, time_unit, progress, plot):
    """ Fill a plot with spikeshorizontally split by channel. Returns legend.
    """
    legend_items = []
    offset = 0 * time_unit

    for c in channels:
        for u in spikes.keys():
            first_wave = True
            color = helper.get_object_color(u)
            for s in spikes[u]:
                if s.waveform is None or s.sampling_rate is None:
                    raise SpykeException(
                        'Cannot create waveform plot: '
                        'At least one spike has no '
                        'waveform or sampling rate!')
                x = (sp.arange(s.waveform.shape[0]) /
                     s.sampling_rate).rescale(time_unit)
                curve = make.curve(
                    x + offset,
                    s.waveform[:, c].rescale(ref_units), u.name,
                    color=color)
                if c == channels[0] and first_wave:
                    legend_curve = make.curve(
                        sp.array([0]), sp.array([0]), u.name,
                        color=color, linewidth=2)
                    legend_items.append(legend_curve)
                    plot.add_item(legend_curve)
                first_wave = False
                plot.add_item(curve)
                progress.step()
        offset += x[-1]
        if c != channels[-1]:
            plot.add_item(
                make.marker((offset, 0), lambda x, y: '',
                            movable=False, markerstyle='|',
                            color='k', linestyle='-', linewidth=1))

    l = make.legend(restrict_items=legend_items)
    plot.add_item(l)
    plot.set_axis_title(BasePlot.Y_LEFT, 'Voltage')
    plot.set_axis_unit(
        BasePlot.Y_LEFT, ref_units.dimensionality.string)

    return l
def _add_legend(plot, spikes, strong):
    # Keys from spikes and strong without duplicates in original order
    seen = set()
    indices = [k for k in spikes.keys() + strong.keys()
               if k not in seen and not seen.add(k)]
    legend_items = []

    for u in indices:
        legend_curve = make.curve(
            sp.array([0]), sp.array([0]), u.name,
            color=helper.get_object_color(u), linewidth=2)
        legend_items.append(legend_curve)
        plot.add_item(legend_curve)

    l = make.legend(restrict_items=legend_items)
    plot.add_item(l)

    return l
Example #41
0
    def sample_spectra_from_peakmaps_iter(self, peakmap_ranges, configs, titles):

        self.clear()
        self.plot.add_item(self.marker)
        if titles:
            self.plot.add_item(make.legend("TL"))
        self.plot.add_item(self.label)

        mzs = []
        for r in peakmap_ranges:
            pm = r[0]
            mzs.extend(pm.mzRange(None))  # None: autodetect dominant ms level
        if mzs:
            self.set_zoom_limits(min(mzs), max(mzs))

        for _ in self.plot.plot_peakmap_ranges_iter(peakmap_ranges, configs, titles):
            yield
        self.plot.add_item(self.line)
Example #42
0
    def plot_spectra(self, all_peaks, labels):
        self.plot.del_all_items()
        self.plot.add_item(self.marker)
        self.plot.add_item(make.legend("TL"))
        self.plot.add_item(self.label)

        for i, (peaks, label) in enumerate(zip(all_peaks, labels)):
            config = dict(color=getColor(i))
            curve = make_unselectable_curve([], [], title=label, curvestyle="Sticks", **config)
            curve.set_data(peaks[:, 0], peaks[:, 1])
            self.plot.add_item(curve)
            self.plot.resample_config = []

        self.plot.add_item(self.line)
        if len(all_peaks):
            self.plot.all_peaks = np.vstack(all_peaks)
        else:
            self.plot.all_peaks = np.zeros((0, 2))
Example #43
0
    def refresh(self, slider_value=None):
        """Refresh Fit Tool dialog box"""
        # Update button states
        enable = self.x is not None and self.y is not None \
                 and self.x.size > 0 and self.y.size > 0 \
                 and self.fitfunc is not None and self.fitparams is not None \
                 and len(self.fitparams) > 0
        for btn in self.button_list:
            btn.setEnabled(enable)
            
        if not enable:
            # Fit widget is not yet configured
            return

        fitargs, fitkwargs = self.get_fitfunc_arguments()
        yfit = self.fitfunc(self.x, [p.value for p in self.fitparams],
                            *fitargs, **fitkwargs)
                            
        plot = self.get_plot()
        
        if self.legend is None:
            self.legend = make.legend(anchor=self.legend_anchor)
            plot.add_item(self.legend)
        
        if self.xrange is None:
            self.xrange = make.range(0., 1.)
            plot.add_item(self.xrange)
        self.xrange.set_range(self.autofit_prm.xmin, self.autofit_prm.xmax)
        self.xrange.setVisible(self.show_xrange)
        
        if self.data_curve is None:
            self.data_curve = make.curve([], [],
                                         _("Data"), color="b", linewidth=2)
            plot.add_item(self.data_curve)
        self.data_curve.set_data(self.x, self.y)
        
        if self.fit_curve is None:
            self.fit_curve = make.curve([], [],
                                        _("Fit"), color="r", linewidth=2)
            plot.add_item(self.fit_curve)
        self.fit_curve.set_data(self.x, yfit)
        
        plot.replot()
        plot.disable_autoscale()
Example #44
0
    def __init__(self,
                 parent,
                 spec=None,
                 count=0,
                 plots=[[{
                     'name': 'Raw spectra',
                     'curves': ['Cold', 'Hot', 'Antenna']
                 }, {
                     'name': 'System noise',
                     'curves': ['Noise']
                 }],
                        [{
                            'name': 'Calibrated',
                            'curves': ['Calibrated']
                        }, {
                            'name': 'Integrated',
                            'curves': ['Integrated']
                        }]]):
        try:
            axisLimits = spec.frequency[count] + [0, 400]
        except:
            axisLimits = [0, 40, 0, 400]
        PlotPanel.__init__(self,
                           parent=parent,
                           plots=plots,
                           axisLimits=axisLimits)
        self.spec = spec
        self.count = count
        self.name = self.spec.name if self.spec else 'Spectrometer'

        self.Pc = self.Ph = self.Pa = self.Ta = self.Ti = self.Tr = None
        self._mean = {'count': 0, 'mean': 0}
        self.chopper_pos = None

        self.curves['Cold'].setPen(QPen(Qt.blue, 1))
        self.curves['Hot'].setPen(QPen(Qt.red, 1))

        self.curves['Calibrated'].parent.set_titles(ylabel=u'Temperature')
        self.curves['Integrated'].parent.set_titles(ylabel=u'Temperature')
        self.curves['Noise'].parent.set_titles(ylabel=u'Temperature')

        cPanel = self.curves['Cold'].parent
        cPanel.add_item(make.legend("BL"))
        cPanel.setActive()
    def setupUi(self):
        """loads numpy array

        Args:
            self

        Returns:
            nothing
        """
        #self.plot = CurvePlot(self)
        self.dialog = CurveDialog(edit=False, toolbar=True, parent=self)
        self.plot = self.dialog.get_plot()
        self.plot.set_antialiasing(True)

        #x = np.linspace(-10,10,200)
        #dy = x/100.
        #y = np.sin(np.sin(np.sin(x)))
        #self.plot.add_item(make.curve(x,y))

        self.loadButton = QtGui.QPushButton("Load")
        self.trainButton = QtGui.QPushButton("Train Model")

        ly = QtGui.QVBoxLayout()
        ly.addWidget(self.plot)
        #ly.addWidget(self.loadButton)
        #ly.addWidget(self.trainButton)

        self.plot.setAxisTitle(Qwt5.Qwt.QwtPlot.xBottom, 'Time')
        self.plot.setAxisTitle(Qwt5.Qwt.QwtPlot.yLeft, 'Value')



        self.manager = PlotManager(self)
        self.manager.add_plot(self.plot)
        #self.manager.
        legend = make.legend('TL')
        self.plot.add_item(legend)

        self.setLayout(ly)
        self.move(300, 200)
        self.show()
        self.dataController = DataController.DataController()
Example #46
0
    def sample_spectra_from_peakmaps_iter(self, peakmap_ranges, configs,
                                          titles):

        self.clear()
        self.plot.add_item(self.marker)
        if titles:
            self.plot.add_item(make.legend("TL"))
        self.plot.add_item(self.label)

        mzs = []
        for r in peakmap_ranges:
            pm = r[0]
            mzs.extend(pm.mzRange(None))  # None: autodetect dominant ms level
        if mzs:
            self.set_zoom_limits(min(mzs), max(mzs))

        for _ in self.plot.plot_peakmap_ranges_iter(peakmap_ranges, configs,
                                                    titles):
            yield
        self.plot.add_item(self.line)
Example #47
0
    def testFcn(self):
        x = np.linspace(0, 100, 1000)

        y = (np.random.rand(len(x)) - 0.5).cumsum()

        curve = make.curve(x, y, "ab", "b")
        range = make.range(0, 5)

        disp2 = make.computations(range, "TL",
                                  [(curve, "min=%.5f", lambda x, y: y.min()),
                                   (curve, "max=%.5f", lambda x, y: y.max()),
                                   (curve, "avg=%.5f", lambda x, y: y.mean())])
        legend = make.legend("TR")
        items = [curve, range, disp2, legend]

        win = CurveDialog(edit=False, toolbar=True, parent=self)
        plot = win.get_plot()
        for item in items:
            plot.add_item(item)
        win.show()
Example #48
0
    def plot_chromatograms(self, chromatograms):

        self.plot.del_all_items()
        self.plot.add_item(make.legend("TR"))
        self.plot.add_item(self.marker)

        self.plot_background_items()

        rtall = set()

        for i, (rts, iis, title) in enumerate(chromatograms):
            curve = make_chromatorgram_curve(rts, iis, title, getColor(i, True))
            self.plot.add_item(curve)
            rtall.update(rts)

        self.marker.rts = sorted(rtall)

        self.plot_foreground_items()

        self.plot.reset_all_axes()
        self.replot()
    def plot_spectra(self, all_peaks, labels):
        self.plot.del_all_items()
        self.plot.add_item(self.marker)
        self.plot.add_item(make.legend("TL"))
        self.plot.add_item(self.label)

        for i, (peaks, label) in enumerate(zip(all_peaks, labels)):
            config = dict(color=getColor(i))
            curve = make_unselectable_curve([], [],
                                            title=label,
                                            curvestyle="Sticks",
                                            **config)
            curve.set_data(peaks[:, 0], peaks[:, 1])
            self.plot.add_item(curve)
            self.plot.resample_config = []

        self.plot.add_item(self.line)
        if len(all_peaks):
            self.plot.all_peaks = np.vstack(all_peaks)
        else:
            self.plot.all_peaks = np.zeros((0, 2))
Example #50
0
def Plot_Start_New(widget,PLOT_DEFINE,COLORS,x1,x2,y1,y2):
    newmanager = PlotManager(widget)
    newplots = []
    newcurves = {}
    for name in PLOT_DEFINE:
            plot = CurvePlot()
            #设置图表颜色
            plot.setStyleSheet('''QWidget{   
                                                                border: 1px solid #32435E;   
                                                                border-radius: 3px;   
                                                                font-size:11pt;   
                                                                color:white;   
                                                                font-family:"Microsoft YaHei UI";  
                                                                /* padding: 0 8px; */  
                                                                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,   
                                                                                             stop: 0 #080B10,   
                                                                                             stop: 1.0 #212C3F);   
                                                                selection-background-color: #0A246A;   
                                                            } '''  
                                         )
            plot.axisScaleDraw(CurvePlot.Y_LEFT).setMinimumExtent(20)
            newplots.append(plot)
            newmanager.add_plot(plot)
            plot.plot_id = id(plot)
            for curve_color, curve_name in map(None,COLORS,name):
                if  u"状态" in curve_name or  u"打角/100" in curve_name :
                    newcurves[curve_name] = guiqwt_make.curve([0], [0],markerfacecolor = 'black', markeredgecolor=curve_color, title=curve_name,marker = 'Diamond',linestyle = 'NoPen',markersize = 6)
                else:    
                    newcurves[curve_name] = guiqwt_make.curve([0], [0], color=curve_color, title=curve_name)
                
                plot.add_item(newcurves[curve_name])
            #设置X轴y轴
            plot.set_axis_limits(newcurves[curve_name].yAxis(),y1,y2)
            plot.set_axis_limits(newcurves[curve_name].xAxis(),x1,x2)
            plot.add_item(guiqwt_make.legend("BL"))
            
    
    newmanager.register_standard_tools()
    newmanager.get_default_tool().activate()
    return (newmanager,newplots,newcurves)
Example #51
0
def _spike_trains_plot(win, trains, units, trial_length, events, epochs):
    pW = BaseCurveWidget(win)
    plot = pW.plot

    if events is None:
        events = []
    if epochs is None:
        epochs = []

    offset = len(trains)
    legend_items = []
    for u, t in sorted(trains.iteritems(), key=lambda (u,v):u.name):
        color = helper.get_object_color(u)

        train = helper.add_spikes(plot, t, color, 2, 21, offset,
            u.name, units)

        if u.name:
            legend_items.append(train)
        if trial_length:
            plot.add_item(make.curve([0, trial_length], [offset, offset], color='k'))
        offset -= 1

    helper.add_epochs(plot, epochs, units)
    helper.add_events(plot, events, units)

    plot.set_axis_title(BasePlot.X_BOTTOM, 'Time')
    plot.set_axis_unit(BasePlot.X_BOTTOM, units.dimensionality.string)

    win.add_plot_widget(pW, 0)

    legend = make.legend(restrict_items=legend_items)
    plot.add_item(legend)
    win.add_legend_option([legend], True)

    if len(trains) > 1:
        plot.set_axis_limits(BasePlot.Y_LEFT, 0.5, len(trains) + 0.5)

    win.add_custom_curve_tools()
    win.show()
Example #52
0
def _add_legend(plot, spikes, strong):
    # Keys from spikes and strong without duplicates in original order
    seen = set()
    indices = [
        k for k in spikes.keys() + strong.keys()
        if k not in seen and not seen.add(k)
    ]
    legend_items = []

    for u in indices:
        legend_curve = make.curve(sp.array([0]),
                                  sp.array([0]),
                                  u.name,
                                  color=helper.get_object_color(u),
                                  linewidth=2)
        legend_items.append(legend_curve)
        plot.add_item(legend_curve)

    l = make.legend(restrict_items=legend_items)
    plot.add_item(l)

    return l
    def plot(self, pdDataFrame):
        ''' plot some random stuff '''
        x1 = pdDataFrame.index
        y1 = pdDataFrame['Close']
        x = np.linspace(0, 100, 1000)

        y = (np.random.rand(len(x)) - 0.5).cumsum()

        curve = make.curve(x1, y1, "ab", "b")
        range = make.range(0, 5)

        disp2 = make.computations(range, "TL",
                                  [(curve, "min=%.5f", lambda x, y: y.min()),
                                   (curve, "max=%.5f", lambda x, y: y.max()),
                                   (curve, "avg=%.5f", lambda x, y: y.mean())])
        legend = make.legend("TR")
        #        items = [ curve, range, disp2, legend]
        items = [curve]

        self.plotw = self.gWindow.get_plot()
        for item in items:
            self.plotw.add_item(item)
Example #54
0
def _split_plot_ver(channels, spikes, ref_units, time_unit, progress,
                    max_offset, plot):
    """ Fill a plot with spikes vertically split by channel. Returns legend.
    """
    legend_items = []
    offset = 0 * ref_units

    for c in channels:
        for u in spikes.keys():
            first_wave = True
            color = helper.get_object_color(u)
            for s in spikes[u]:
                if s.waveform is None or s.sampling_rate is None:
                    raise SpykeException('Cannot create waveform plot: '
                                         'At least one spike has no '
                                         'waveform or sampling rate!')
                x = (sp.arange(s.waveform.shape[0]) /
                     s.sampling_rate).rescale(time_unit)
                curve = make.curve(
                    x,
                    s.waveform[:, c].rescale(ref_units) + offset,
                    u.name, color=color)
                if c == channels[0] and first_wave:
                    legend_curve = make.curve(
                        sp.array([0]), sp.array([0]), u.name,
                        color=color, linewidth=2)
                    legend_items.append(legend_curve)
                    plot.add_item(legend_curve)
                first_wave = False
                plot.add_item(curve)
                progress.step()
        offset += max_offset

    l = make.legend(restrict_items=legend_items)
    plot.add_item(l)
    plot.set_axis_title(BasePlot.X_BOTTOM, 'Time')
    plot.set_axis_unit(BasePlot.X_BOTTOM, time_unit.dimensionality.string)
    return l
Example #55
0
    def create_curves(self, labels, this_range, show_legend=True):

        self.curves = []
        plot = self.get_plot()
        plot.del_all_items(except_grid=False)
        for i,l in enumerate(labels):
            param = CurveParam()
            param.label = str(l)
            color = COLORS.get(self.colors[i % len(self.colors)],  self.colors[i % len(self.colors)] )
            param.line.color = color

            # create a new curve
            curve = CurveItemModel(param)
            self.curves.append(curve)
            plot.add_item( curve )
            curve.setRenderHint(QwtPlotItem.RenderAntialiased, USE_ANTIALIASING)
            l = make.legend("TR")
            if show_legend:
                plot.add_item( l )

        self.myranges = []
        for r in this_range:
            self.add_range_to_plot(plot, r)
Example #56
0
    def plot(self, data, is_time_series=False, titles=None, configs=None,
             withmarker=False):
        """ do not forget to call replot() after calling this function ! """
        allrts = []
        self.widget.plot.del_all_items()

        if is_time_series:
            self._set_ts_x_axis_labels(data)
            self.widget.plot.set_axis_title("bottom", "time")
        else:
            self._set_rt_x_axis_labels()
            self.widget.plot.set_axis_title("bottom", "RT")

        labels = set()
        legend_items = []
        if is_time_series:
            seen = set()
            for i, ts in enumerate(data):
                # we do not plot duplicates, which might happen if multiple lines in the
                # table explorer are sellected !
                if id(ts) in seen:
                    continue
                seen.add(id(ts))
                config = None
                if configs is not None:
                    config = configs[i]
                if config is None:
                    config = dict(color=getColor(i))
                title = ts.label
                labels.add(title)
                for j, (x, y) in enumerate(ts.for_plotting()):
                    x = [xi.toordinal() if isinstance(xi, datetime) else xi for xi in x]
                    allrts.extend(x)
                    curve = make.curve(x, y, title="<pre>%s</pre>" % title, **config)
                    curve.__class__ = ModifiedCurveItem
                    self.widget.plot.add_item(curve)
                    self.cursor_info.is_time_series = True
                    if j == 0:
                        legend_items.append(curve)
        else:
            seen = set()
            for i, (rts, chromatogram) in enumerate(data):
                # we do not plot duplicates, which might happen if multiple lines in the
                # table explorer are sellected !
                if (id(rts), id(chromatogram)) in seen:
                    continue
                seen.add((id(rts), id(chromatogram)))
                config = None
                if configs is not None:
                    config = configs[i]
                if config is None:
                    config = dict(color=getColor(i))
                if titles:
                    title = "<pre>%s</pre>" % titles[i]
                else:
                    title = ""
                labels.add(title)
                curve = make.curve(rts, chromatogram, title=title, **config)
                curve.__class__ = ModifiedCurveItem
                allrts.extend(rts)
                self.widget.plot.add_item(curve)
                self.cursor_info.is_time_series = False


        if withmarker:
            self.widget.plot.add_item(self.label)
            allrts = sorted(set(allrts))
            self.marker.rts = allrts
            self.marker.attach(self.widget.plot)
            self.widget.plot.add_item(self.marker)

        labels -= set((None,))
        labels -= set(("",))
        if labels:
            legend = make.legend("TL", restrict_items=legend_items)
            legend.labelparam.font.size = 12
            legend.labelparam.update_label(legend)
            self.widget.plot.add_item(legend)
        if not is_time_series:
            self._add_range_selector(allrts)
Example #57
0
def raster(trains, time_unit=pq.ms, show_lines=True, events=None, epochs=None):
    """ Create a new plotting window with a rasterplot of spiketrains.

        :param dict trains: Dictionary of spike trains indexed by a
            Neo object (Unit or Segment).
        :param Quantity time_unit: Unit of X-Axis.
        :param bool show_lines: Determines if a horizontal line will be shown
            for each spike train.
        :param sequence events: A sequence of neo `Event` objects that will
            be marked on the plot.

    """
    if not trains:
        raise SpykeException('No spike trains for rasterplot')

    if not time_unit:
        time_unit = pq.ms

    win_title = 'Spike Trains'
    win = PlotDialog(toolbar=True, wintitle=win_title, major_grid=False)

    pW = BaseCurveWidget(win)
    plot = pW.plot

    if events is None:
        events = []
    if epochs is None:
        epochs = []

    offset = len(trains)
    legend_items = []
    for u, t in trains.iteritems():
        color = helper.get_object_color(u)

        train = helper.add_spikes(plot, t, color, 2, 21, offset, u.name,
                                  time_unit)

        if u.name:
            legend_items.append(train)
        if show_lines:
            plot.add_item(
                make.curve([
                    t.t_start.rescale(time_unit),
                    t.t_stop.rescale(time_unit)
                ], [offset, offset],
                           color='k'))
        offset -= 1

    helper.add_epochs(plot, epochs, time_unit)
    helper.add_events(plot, events, time_unit)

    plot.set_axis_title(BasePlot.X_BOTTOM, 'Time')
    plot.set_axis_unit(BasePlot.X_BOTTOM, time_unit.dimensionality.string)

    win.add_plot_widget(pW, 0)

    legend = make.legend(restrict_items=legend_items)
    plot.add_item(legend)
    win.add_legend_option([legend], True)

    if len(trains) > 1:
        plot.set_axis_limits(BasePlot.Y_LEFT, 0.5, len(trains) + 0.5)

    win.add_custom_curve_tools()
    win.show()

    return win
Example #58
0
    def refresh(self, slider_value=None):
        """Refresh Fit Tool dialog box"""
        # Update button states
        enable = self.x is not None and self.y is not None \
                 and self.x.size > 0 and self.y.size > 0 \
                 and self.fitfunc is not None and self.fitparams is not None \
                 and len(self.fitparams) > 0
        for btn in self.button_list:
            btn.setEnabled(enable)

        if not enable:
            # Fit widget is not yet configured
            return

        plot = self.get_plot()

        if self.xrange is None:
            self.xrange = make.range(0., 1.)
            plot.add_item(self.xrange)

        self.xrange.set_range(self.autofit_prm.xmin, self.autofit_prm.xmax)
        self.xrange.setVisible(self.show_xrange)

        if self.data_curve is None:
            self.data_curve = make.curve([], [],
                                         _("Data"),
                                         color="b",
                                         marker='o',
                                         markerfacecolor='w',
                                         markersize=8,
                                         linestyle='DashLine',
                                         linewidth=1.)
            plot.add_item(self.data_curve)
        self.data_curve.set_data(self.x, self.y)

        colors = [u'#d4f200', u'#00e639', u'#009fff', u'#7900f2']

        for i in xrange(self._idxlen):
            if len(self.fit_curves) < self._idxlen:
                self.fit_curves.append(
                    make.curve([], [],
                               _('%s' % self.fitnames[i]),
                               color=colors[i % len(colors)],
                               linestyle='--',
                               linewidth=2))
                plot.add_item(self.fit_curves[-1])

            fitargs, fitkwargs = self.get_fitfunc_arguments()

            yfit = self.fitfunc[i](self.x,
                                   *([p.value for p in self.fitparams[i]] +
                                     list(fitargs)), **fitkwargs)

            if plot.get_scales()[1] == 'log':
                self.fit_curves[i].set_data(self.x[yfit > 1e-80],
                                            yfit[yfit > 1e-80])
            else:
                self.fit_curves[i].set_data(self.x, yfit)

        self.get_itemlist_panel().show()

        if self.fit_curve is not None:
            self.fit_curve.curveparam.line.color = self.fit_curves[
                self.idx].curveparam.line.color
            self.fit_curve.curveparam.line.style = 'DashLine'

        self.fit_curve = self.fit_curves[self.idx]
        self.fit_curve.curveparam.line.color = u'#ff0000'
        self.fit_curve.curveparam.line.style = 'SolidLine'

        [item.update_params() for item in self.fit_curves]

        if self.legend is None:
            self.legend = make.legend(anchor=self.legend_anchor)
            plot.add_item(self.legend)

        plot.set_antialiasing(False)

        plot.replot()