def __init__(self, **kwargs):
        super(case, self).__init__(**kwargs)
        box = FloatLayout()
        graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
            x_ticks_major=25, y_ticks_major=1,
            y_grid_label=True, x_grid_label=True, padding=5,
            x_grid=True, y_grid=True, xmin=-0, xmax=20, ymin=0, ymax=10)
        plot = LinePlot()
        # plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]

        # data = np.array([[0,0], [1,1],[2,2]])

        data = collections.deque(maxlen = 20)
        time = collections.deque(maxlen = 20)

        d = (0,1,2,3,4,5,6,7,8,9)
        t = (0,1,2,3,4,5,6,7,8,9)

        data.append(d)
        time.append(t)

        toplot = np.vstack((time,data)).T

        print toplot

        plot.points = tuple(map(tuple, toplot))

        graph.add_plot(plot)
        box.add_widget(graph)

        self.add_widget(box)
Exemple #2
0
    def init(self):
        # use kivy garden's graph widget
        graph = Graph(
            xlabel='t',
            ylabel='HFR',
            x_ticks_minor=5,
            x_ticks_major=10,
            y_ticks_minor=1,
            y_ticks_major=5,
            y_grid_label=True,
            x_grid_label=False,
            padding=0,
            y_grid=False,
            x_grid=False,
            xmin=0,
            ymin=0,
            xmax=100,
            ymax=30,
            _with_stencilbuffer=False,  # or it does not work in ScreenManager
            label_options={'color': rgb('808080')})
        y = (float(i) for i in range(50))
        x = (float(i) for i in range(50))
        plot = MeshLinePlot(color=rgb('1100aa'))
        pts = list(zip(x, y))
        plot.points = pts
        graph.add_plot(plot)

        self.ids.plot.add_widget(graph)

        self.plot = plot
        self.graph = graph
 def __init__(self, **kwargs):
     super(BElGenLiveGraph, self).__init__(**kwargs)
     graph = Graph(
         xlabel="X",
         ylabel="Y",
         x_ticks_minor=5,
         x_ticks_major=25,
         y_ticks_major=1,
         y_grid_label=True,
         x_grid_label=True,
         padding=5,
         x_grid=True,
         y_grid=True,
         xmin=-0,
         xmax=10,
         ymin=-12,
         ymax=12,
     )
     plot = SmoothLinePlot(color=[0.49, 0.98, 1, 1])
     with open("adclog.txt") as fh:
         coords = []
         for line in fh:
             line = line.strip("()\n")  # Get rid of the newline and parentheses
             line = line.split(", ")  # Split into two parts
             c = tuple(float(x) for x in line)  # Make the tuple
             coords.append(c)
     plot.points = coords
     graph.add_plot(plot)
     self.add_widget(graph)
Exemple #4
0
class Plot(RelativeLayout):
    def __init__(self, **kwargs):
        super(Plot, self).__init__(**kwargs)
        self.graph = Graph(xlabel="x",
                           ylabel="y",
                           x_ticks_minor=5,
                           x_ticks_major=25,
                           y_ticks_major=1,
                           y_grid_label=True,
                           x_grid_label=True,
                           x_grid=True,
                           y_grid=True,
                           xmin=-0,
                           xmax=100,
                           ymin=-1,
                           ymax=1,
                           draw_border=False)
        # graph.size = (1200, 400)
        # self.graph.pos = self.center

        self.plot = MeshLinePlot(color=[1, 1, 1, 1])
        self.plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
        self.plot2 = MeshLinePlot(color=[1, 0, 0, 1])
        self.plot2.points = [(x, cos(x / 10.)) for x in range(0, 101)]
        self.add_widget(self.graph)

        self.graph.add_plot(self.plot)
        self.graph.add_plot(self.plot2)
Exemple #5
0
    def graph_create(self):
        global graph1
        graph1 = Graph(
            label_options={'color': rgb('001933'), 'bold': True},
            background_color=rgb('f8f8f2'),
            tick_color=rgb('001933'),
            border_color=rgb('808080'),
            xlabel='X',
            ylabel='Y',
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            x_ticks_major=5,
            y_ticks_major=0.2,
            x_grid=True,
            y_grid=True,
            xmin=-0,
            xmax=30,
            ymin=-1,
            ymax=1)

        k = np.random.normal()
        global plot1
        plot1 = MeshLinePlot(color=[0, 0, 0.75, 1])
        y = (0.5 - 0.2)/30*np.linspace(0, max_year-1, max_year) + 0.2*np.ones(max_year) + np.random.normal(0, 0.05, max_year)
        plot1.points = [(x, y[x]) for x in range(0, 30)]
        graph1.add_plot(plot1)
        self.add_widget(graph1)
        return graph1
Exemple #6
0
    def init(self, octoprint):
        self.octoprint = octoprint
        # use kivy garden's graph widget
        graph = Graph(
            xlabel='',
            ylabel='°C',
            x_ticks_minor=5,
            x_ticks_major=25,
            y_ticks_minor=0,
            y_ticks_major=50,
            y_grid_label=True,
            x_grid_label=False,
            padding=5,
            y_grid=True,
            xmax=len(self.hotend_temps),
            ymax=230,
            _with_stencilbuffer=False,  # or it does not work in ScreenManager
            label_options={'color': rgb('000000')})
        self.hotend_plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.bed_plot = MeshLinePlot(color=[0, 0, 1, 1])
        graph.add_plot(self.hotend_plot)
        graph.add_plot(self.bed_plot)

        self.ids.plot.add_widget(graph)
        self.graph = graph
        self.update_plot()

        self.status = "Ready."
Exemple #7
0
 def f_u_wid(self):
     graph = Graph(xlabel='displacement', ylabel='force', x_ticks_minor=5,
                   x_ticks_major=1, y_ticks_major=100,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=0, xmax=self.max_displacement, ymin=-100, ymax=500)
     self.f_u_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.f_u_line.points = [(0, 0)]
     graph.add_plot(self.f_u_line)
     return graph
Exemple #8
0
 def eps_sig_wid(self):
     graph = Graph(xlabel='slip', ylabel='bond', x_ticks_minor=5,
                   x_ticks_major=0.5, y_ticks_major=0.2,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=-0.0 * self.max_displacement, xmax=0.8 * self.max_displacement, ymin=-1, ymax=1)
     self.eps_sig_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.eps_sig_line.points = [(0, 0)]
     graph.add_plot(self.eps_sig_line)
     return graph
Exemple #9
0
 def cb_wid(self):
     graph = Graph(xlabel='z', ylabel='matrix stress', x_ticks_minor=5,
                   x_ticks_major=25, y_ticks_major=5,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=-50, xmax=50, ymin=0, ymax=20)
     self.cb_line = MeshLinePlot(color=[1, 0, 0, 1])
     self.sctt.get_sig_m_cb()
     self.cb_line.points = self.list_tuple(self.sctt.z, self.sctt.sig_m_cb)
     graph.add_plot(self.cb_line)
     return graph
Exemple #10
0
 def shear_flow_wid(self):
     graph = Graph(xlabel='length', ylabel='shear flow', background_color=[0, 0, 0, 1],
                   x_ticks_major=100., y_ticks_major=0.2,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=0.0, xmax=self.tl.ts.L_x, ymin=-1, ymax=1)
     self.shear_flow_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.shear_flow_line.points = self.list_tuple(
         self.x_coord, np.zeros_like(self.x_coord))
     graph.add_plot(self.shear_flow_line)
     return graph
Exemple #11
0
class GaugeGraph:
    """
    Graph data presentation
    """
    def __init__(self, **kwargs):
        self.grid = True or kwargs['grid']
        self.color = kwargs['color']
        self.name = kwargs['name'].upper()
        self.label = kwargs['name']
        self.parent = kwargs['parent']
        self.gtype = kwargs['gtype']
        self.graph = Graph(ylabel=self.label,
                           x_ticks_minor=1,
                           x_ticks_major=5,
                           y_ticks_major=20,
                           x_grid_label=True,
                           y_grid_label=True,
                           padding=5,
                           x_grid=self.grid,
                           y_grid=self.grid,
                           xmin=0,
                           xmax=50,
                           ymin=0,
                           ymax=20)
        self.plot = SmoothLinePlot(color=self.color)
        self.plot.points = []
        self.graph.add_plot(self.plot)

    def update(self):
        """
        Method to update the graph
        :return:
        """
        try:
            values = list(map(int, self.parent.pids[self.name]['values']))
            if len(values) > 1:
                y_max = max(values)
                y_min = min(values)
                self.graph.ymin = y_min
                self.graph.ymax = y_max
                if y_max > 10:
                    self.graph.y_ticks_minor = int(y_max / 10)
                    self.graph.y_ticks_major = int(y_max / 5)
                else:
                    self.graph.y_ticks_minor = 1
                    self.graph.y_ticks_major = 5
            self.plot.points = []
            i = 0
            while i < len(values):
                self.plot.points.append([i, values[i]])
                i += 1
            self.graph.add_plot(self.plot)

        except Exception as exceptn:
            print("Exception in graph update occured: " + str(exceptn))
Exemple #12
0
 def curve_wid(self):
     graph = Graph(xlabel='strain', ylabel='stress',
                   x_ticks_major=0.001, y_ticks_major=2,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=0, xmax=0.01,
                   ymin=0, ymax=self.sctt.sig_cu)
     self.eps_sig_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.eps_sig_line.points = self.list_tuple(
         self.sctt.eps_c_K, self.sctt.sig_c_K)
     graph.add_plot(self.eps_sig_line)
     return graph
	def build(self):
		self.title = "HP4156C Parameter Analyser"
		## Main screen has a title and two accordions
		root = BoxLayout(orientation='vertical')
		## Add a title header to the window
		graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5, x_ticks_major=25, y_ticks_major=1,y_grid_label=True, x_grid_label=True, padding=5, x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
		plot = MeshLinePlot(color=[1, 0, 0, 1])
		plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
		graph.add_plot(plot)
		root.add_widget(graph)        
		return root
 def build(self):
     print 'create graph'
     #self.canvas.add(Color(1., 1., 0))
     graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
                   x_ticks_major=25, y_ticks_major=1,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
     plot = MeshLinePlot(color=[1, 0, 0, 1])
     plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
     graph.add_plot(plot)
     return graph
Exemple #15
0
 def cracking_wid(self):
     graph = Graph(xlabel='x', ylabel='matrix stress', x_ticks_minor=5,
                   x_ticks_major=100, y_ticks_major=1,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=0, xmax=1000, ymin=0, ymax=5)
     self.sig_mu_line = MeshLinePlot(color=[1, 0, 0, 1])
     self.sig_mu_line.points = self.list_tuple(
         self.sctt.x, self.sctt.sig_mu_x)
     self.sig_line = MeshLinePlot(color=[1, 1, 1, 1])
     graph.add_plot(self.sig_mu_line)
     graph.add_plot(self.sig_line)
     return graph
Exemple #16
0
class Main(App):

    def build(self):
        root = BoxLayout()
        self.graph = Graph(
            y_grid_label=False, x_grid_label=False, padding=5,
            xmin=0, xmax=100, ymin=0, ymax=30)

        line = MeshLinePlot(points=[(0, 0), (100, 30)])
        self.graph.add_plot(line)

        root.add_widget(self.graph)
        return root
Exemple #17
0
class EAGraph(BoxLayout):
    def __init__(self):
        super(EAGraph, self).__init__()

        self.graph = Graph(
            xlabel="Generation",
            ylabel="Y",
            x_ticks_minor=5,
            x_ticks_major=25,
            y_ticks_minor=5,
            y_ticks_major=40,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            x_grid=True,
            y_grid=True,
            xmin=0,
            xmax=120,
            ymin=0,
            ymax=200,
            size=(800, 600)
        )

        red = [1, 0, 0, 1]
        green = [0, 1, 0, 1]
        blue = [0, 0, 1, 1]

        self.cols = 2
        self.orientation = 'vertical'
        self.add_widget(self.graph)
        legends = BoxLayout()
        legends.orientation = 'horizontal'
        legends.add_widget(Label(text='Standard deviation', color=red, size=(100, 200)))
        legends.add_widget(Label(text='Average fitness', color=green, size=(100, 200)))
        legends.add_widget(Label(text='Highest fitness', color=blue, size=(100, 200)))
        self.add_widget(legends)

        self.plot = []
        self.plot.append(MeshLinePlot(color=red)) #X - Red
        self.plot.append(MeshLinePlot(color=green)) #Y - Green
        self.plot.append(MeshLinePlot(color=blue)) #Z - Blue

        for plot in self.plot:
            self.graph.add_plot(plot)

    def add_datas(self, datas, generation):
        for i in range(len(datas)):
            self.plot[i].points.append((generation, datas[i]))
Exemple #18
0
class SuccessGraph(object):
    PLOT_LINE_COLOR = [1, 0, 0, 1]
    DEFAULT_LEVEL = "Overall"

    X_LABEL = "sessions"
    Y_LABEL = "success rates"

    Y_MAX_VAL = 100

    HISTORY_MAX = 200

    X_MAJOR_TICKS_SCALE = 8.0

    def __init__(self):
        self._plot = MeshLinePlot(color=self.PLOT_LINE_COLOR)
        self._graph = Graph(xlabel=self.X_LABEL, ylabel=self.Y_LABEL,
                            x_ticks_minor=5,
                            y_ticks_major=10, y_ticks_minor=2, y_grid=True,
                            y_grid_label=True, x_grid_label=True, padding=10,
                            xmin=0, ymin=0, ymax=self.Y_MAX_VAL,
                            xmax=self.HISTORY_MAX)
        self.level = None
        self.stats = App.get_running_app().stats
        self.display_level(self.DEFAULT_LEVEL)
        self._graph.add_plot(self._plot)

    def display_level(self, level):
        if self.DEFAULT_LEVEL == level:
            self.level = None
        else:
            self.level = int(level)
        success_rates = self.stats.success_rates(self.level)
        # limit items to last HISTROY_MAX items
        success_rates = success_rates[-self.HISTORY_MAX:]
        self._plot.points = [(x, y) for x, y in enumerate(success_rates)]
        points_count = len(success_rates)
        self._graph.xmax = points_count

        self._graph.x_ticks_major = round_up(points_count /
                                             self.X_MAJOR_TICKS_SCALE)

    def get_view(self):
        return self._graph

    def clear_statistics(self, *largs):
        """Delete actually selected statistics"""
        self.stats.delete_rows(self.level)
        self.display_level(self.DEFAULT_LEVEL)
Exemple #19
0
    def build(self):
        self.availablePorts = listSerialPorts()
        if len(self.availablePorts) == 0:
            self.availablePorts.append("----")
        
        tabbedPannel = TabbedPanel(do_default_tab=False)
        
        # Connection Tab
        self.connectionTab = TabbedPanelItem(text="Connection")
        
        self.layout1 = BoxLayout(orientation='vertical', spacing=10, padding=(200, 200))
        self.connectionTab.add_widget(self.layout1)
        
        self.lblSerialSettings = Label(text="Connection settings")
        self.layout1.add_widget(self.lblSerialSettings)
        
        self.dlBaudrate = Spinner(values = ["57600", "115200", "230400", "460800", "921600"],
                                  text = "115200")
        self.layout1.add_widget(self.dlBaudrate)
        
        self.dlPort = Spinner(values = self.availablePorts,
                              text = self.availablePorts[0])
        self.layout1.add_widget(self.dlPort)
        
        self.btnConnect = Switch()
        self.btnConnect.bind(active = self.connect)
        
        self.layout1.add_widget(self.btnConnect)
        
        # Graph tab
        self.graphTab = TabbedPanelItem(text = "Graph")
#         self.layout2 = BoxLayout(orientation='vertical', spacing=10, padding=(200, 200))
#         self.graphTab.add_widget(self.layout2)
        
        graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
        x_ticks_major=25, y_ticks_major=1,
        y_grid_label=True, x_grid_label=True, padding=5,
        x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
        plot = MeshLinePlot(color=[1, 1, 0, 1])
        plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
        graph.add_plot(plot)
        self.graphTab.add_widget(graph)
        
        
        tabbedPannel.add_widget(self.connectionTab)
        tabbedPannel.add_widget(self.graphTab)
        return tabbedPannel
Exemple #20
0
	def build(self):
		root = FloatLayout(orientation='horizontal')
		btnRight = Button(text='Scroll', size_hint=(.05,1),pos_hint={'right':1})#,'y':0})
		btnLeft = Button(text='Scroll', size_hint=(.05,1),pos_hint={'left':1})			
		root.add_widget(btnRight)
		root.add_widget(btnLeft)
#		scrollV = ScrollView(size_hint=(None,None),size=(800,400))
#		scrollV.do_scroll_y=False
		graph = Graph()
		plot = LinePlot(mode='line_strip', color=[1,0,0,1])
		plot.points = [(x[i],y[i]) for i in xrange(len(x))]
		graph.add_plot(plot)
		graph.x_ticks_major=1
		graph.xmin=xmin
		graph.xmax=xmax
		graph.ymin=ymin
		graph.ymax=ymax
		graph.y_ticks_major=25
		graph.y_grid_label=True
		graph.x_grid_label=True
		graph.xlabel='X axis'
		graph.ylabel='Y axis'
		graph.y_grid = True
		graph.x_grid = True
		def moveRight(obj):
			global xmin
			global xmax
			xmin=xmin+.5
			xmax=xmax+.5
			graph.xmin=xmin
			graph.xmax=xmax
			#graph.remove_plot(plot)
			#graph.add_plot(plot)
			#graph._redraw_size(xmin,ymin,xmax,ymax)
		btnRight.bind(on_release=moveRight)
		def moveLeft(obj):
			global xmin
			global xmax
			xmin=xmin-.5
			xmax=xmax-.5
			graph.xmin=xmin
			graph.xmax=xmax
		btnLeft.bind(on_release=moveLeft)
		root.add_widget(graph)
#		graph.bind(minimum_height=graph.setter('height'))
#		scrollV.add_widget(graph)
		return root
 def build(self):
     print 'create graph'
     graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
                   x_ticks_major=25, y_ticks_major=1,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=-0, xmax=10, ymin=-12, ymax=12)
     plot = MeshLinePlot(color=[1, 0, 0, 1])
     with open("adclog.txt") as fh:
         coords = []
         for line in fh:
             line = line.strip('()\n')  # Get rid of the newline and parentheses
             line = line.split(', ')  # Split into two parts
             c = tuple(float(x) for x in line)  # Make the tuple
             coords.append(c)
     plot.points = coords
     graph.add_plot(plot)
     return graph
    def mostrar_histograma(self):
        """
        Mostra o histograma da imagem.
        """
        histograma = self.imagem_core.get_histograma()

        graph = Graph(xlabel='Tom de Cinza',
                      ylabel='Quantidade de tons',
                      padding=5,
                      xmin=0,
                      xmax=max(histograma.keys()),
                      ymin=0,
                      ymax=max(histograma.values()))
        plot = MeshLinePlot()
        plot.points = histograma.items()
        graph.add_plot(plot)
        self.widgets_dinamicos.append(graph)
        self.add_widget(graph)
 def __init__(self, **kwargs):
     super(BElGenLiveGraph, self).__init__(**kwargs)
     graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
                   x_ticks_major=25, y_ticks_major=1,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=-0, xmax=10, ymin=-12,
                   ymax=12)
     plot = SmoothLinePlot(color=[0.49, 0.98, 1, 1])
     with open("adclog.txt") as fh:
         coords = []
         for line in fh:
             line = line.strip('()\n')
             line = line.split(', ')
             c = tuple(float(x) for x in line)
             coords.append(c)
     plot.points = coords
     graph.add_plot(plot)
     self.add_widget(graph)
Exemple #24
0
    def __init__(self, **kwargs):
        super(case, self).__init__(**kwargs)
        box = FloatLayout()
        graph = Graph(xlabel='X',
                      ylabel='Y',
                      x_ticks_minor=5,
                      x_ticks_major=25,
                      y_ticks_major=1,
                      y_grid_label=True,
                      x_grid_label=True,
                      padding=5,
                      x_grid=True,
                      y_grid=True,
                      xmin=-0,
                      xmax=20,
                      ymin=0,
                      ymax=10)
        plot = LinePlot()
        # plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]

        # data = np.array([[0,0], [1,1],[2,2]])

        data = collections.deque(maxlen=20)
        time = collections.deque(maxlen=20)

        d = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
        t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

        data.append(d)
        time.append(t)

        toplot = np.vstack((time, data)).T

        print toplot

        plot.points = tuple(map(tuple, toplot))

        graph.add_plot(plot)
        box.add_widget(graph)

        self.add_widget(box)
Exemple #25
0
class GraphApp(App):
    def build(self):
        super().__init__()
        self.graph = Graph(xlabel='X',
                           ylabel='Y',
                           x_ticks_minor=5,
                           x_ticks_major=25,
                           y_ticks_major=1,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=True,
                           y_grid=True,
                           xmin=-0,
                           xmax=100,
                           ymin=-1,
                           ymax=1)
        self.plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
        self.graph.add_plot(self.plot)
        return self.graph
Exemple #26
0
        def build(self):
            b = BoxLayout(orientation='vertical')

            graph2 = Graph(
                xlabel='x',
                ylabel='y',
                x_ticks_major=10,
                y_ticks_major=10,
                y_grid_label=True,
                x_grid_label=True,
                padding=5,
                xlog=False,
                ylog=False,
                xmin=0,
                ymin=0)

            plot = LinePlot(color=[255, 255, 255], width=100.)
            plot.points = [(10, 10), (90, 90)]
            graph2.add_plot(plot)

            b.add_widget(graph2)

            return b
Exemple #27
0
        def build(self):
            b = BoxLayout(orientation='vertical')

            graph2 = Graph(
                xlabel='x',
                ylabel='y',
                x_ticks_major=10,
                y_ticks_major=10,
                y_grid_label=True,
                x_grid_label=True,
                padding=0,
                xlog=False,
                ylog=False,
                xmin=0,
                ymin=0)

            plot = FilledRect(color=[255, 255, 255])
            plot.xrange = [40, 70]
            plot.yrange = [30, 50]
            graph2.add_plot(plot)

#             plot2 = FilledRect(color=[255, 255, 255])
#             plot2.xrange = [50, 70]
#             plot2.yrange = [30, 50]
            label = Label(text='test', font_size=20)
            label.pos = (100, 100)
#             text = label.texture
#             plot2.texture = text
            graph2.add_widget(label)

            b.add_widget(graph2)
            self.rectangle = plot

#             Clock.schedule_interval(self.update_color, 1)
#             Clock.schedule_interval(self.update_pos, 1)

            return b
Exemple #28
0
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)

        graph = Graph(xlabel='X',
                      ylabel='Y',
                      x_ticks_minor=5,
                      x_ticks_major=25,
                      y_ticks_major=1,
                      y_grid_label=True,
                      x_grid_label=True,
                      padding=5,
                      x_grid=True,
                      y_grid=True,
                      xmin=-0,
                      xmax=100,
                      ymin=-1,
                      ymax=1)

        graph.background_color = 0, 0, 1, 1  # blue color

        plot = MeshLinePlot(color=[1, 0, 0, 1])
        plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
        graph.add_plot(plot)
        self.add_widget(graph)
Exemple #29
0
 def disp_slip_wid(self):
     graph = Graph(xlabel='length', ylabel='displacement',  background_color=[0, 0, 0, 1],
                   x_ticks_major=100., y_ticks_major=1.0,
                   y_grid_label=True, x_grid_label=True, padding=5,
                   x_grid=True, y_grid=True, xmin=0.0, xmax=self.tl.ts.L_x, ymin=0., ymax=self.max_displacement)
     self.reinf_disp_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.reinf_disp_line.points = self.list_tuple(
         self.x_coord, np.zeros_like(self.x_coord))
     self.matrix_disp_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.matrix_disp_line.points = self.list_tuple(
         self.x_coord, np.zeros_like(self.x_coord))
     self.slip_line = MeshLinePlot(color=[1, 1, 1, 1])
     self.slip_line.points = self.list_tuple(
         self.x_coord, np.zeros_like(self.x_coord))
     graph.add_plot(self.reinf_disp_line)
     graph.add_plot(self.matrix_disp_line)
     graph.add_plot(self.slip_line)
     return graph
Exemple #30
0
class DrawScreen(Screen):

    def __init__(self, **kwargs):
        super(DrawScreen, self).__init__(**kwargs)

        self.graph_layout = BoxLayout(orientation = 'vertical',pos_hint = {'center_y': .55, 'center_x': .25 },
        size_hint= (.45, .85), spacing = 10)


        self.draw_layout  = BoxLayout(orientation = 'vertical',pos_hint = {'center_y': .55, 'center_x': .75},
        size_hint= (.45, .85), color = [.5,.5,.5,1], spacing = 10)

        self.button_layout = BoxLayout(orientation = 'horizontal',pos_hint = {'center_y': .0001, 'center_x': .5},
        size_hint= (.9, .1), color = [.5,.5,.5,1], spacing = 100)

        self.add_widget(self.graph_layout)
        self.add_widget(self.draw_layout)
        self.add_widget(self.button_layout)

        self.plots   = []
        self.anim_counter = 0

        self.graph = Graph(draw_border = False, background_color = [1, 1, 1, 1], border_color = [.3, .5, .6, .7])
        self.graph.pos_hint={'center_y': .5}
        self.graph.size_hint_y = .9

        clear_graph_btn_image = os.path.join(app.resource_folder, 'eraser.png')
        self.clear_graph = Button(background_normal = clear_graph_btn_image, border = [1,1,1,1],
        size_hint=(.00000001, .5),
        pos_hint = {'center_y': 1, 'center_x': .4 })
        self.clear_graph.opacity = 1
        self.clear_graph.disabled = False
        self.clear_graph.bind(on_press = self.clear_plot)


        self.gap_btn1 = Button(border = [1,1,1,1],
        size_hint=(.00000005, .5),
        pos_hint = {'center_y': 1, 'center_x': .4 })
        self.gap_btn1.opacity = 0
        self.gap_btn1.disabled = True

        self.gap_btn2 = Button(border = [1,1,1,1],
        size_hint=(.00000005, .5),
        pos_hint = {'center_y': 1, 'center_x': .4 })
        self.gap_btn2.opacity = 0
        self.gap_btn2.disabled = True

        next_btn_image = os.path.join(app.resource_folder, 'next.png')
        self.next_graph = Button(background_normal = next_btn_image, border = [1,1,1,1],
        size_hint=(.00000001, .7),
        pos_hint = {'center_y': 1, 'center_x': .5 })
        self.next_graph.opacity = 1
        self.next_graph.disabled = False
        self.next_graph.bind(on_press = self.next_plot)

        eraser_btn_image = os.path.join(app.resource_folder, 'eraser.png')
        self.eraser = Button(background_disabled_normal = eraser_btn_image,background_normal = eraser_btn_image, border = [1,1,1,1],
        size_hint=(.00000001, .5), pos_hint = {'center_y': 1, 'center_x': .8 })
        self.eraser.opacity = 1
        self.eraser.disabled = True

        # self.animate_btn = Button(background_normal = 'next.png', border = [1,1,1,1],
        # size_hint=(.00000001, .4),
        # pos_hint = {'center_y': 1, 'center_x': .5 })
        # self.animate_btn.opacity = 1
        # self.animate_btn.disabled = False
        # self.animate_btn.bind(on_press=self.start_animation)

        self.painterbox = PainterBox(btn = self.eraser)


        self.eraser.bind(on_press=self.painterbox.clear_letter)

        child_btn_image = os.path.join(app.resource_folder, 'child.png')
        self.child_btn = Button(background_disabled_normal = child_btn_image, background_normal = child_btn_image, border = [1,1,1,1],
        size_hint=(.1, .1), pos_hint = {'center_y': .9, 'center_x': .5 })
        self.child_btn.opacity = 1
        self.child_btn.disabled = False
        self.child_btn.bind(on_press=self.start_animation)

        nao_btn_image = os.path.join(app.resource_folder, 'nao.png')
        self.nao_btn = Button(background_disabled_normal = nao_btn_image, background_normal = nao_btn_image, border = [1,1,1,1],
        size_hint=(.1, .1), pos_hint = {'center_y': .9, 'center_x': .5 })
        self.nao_btn.opacity = 1
        self.nao_btn.disabled = False
        self.nao_btn.bind(on_press=self.on_nao_turn)

        self.graph_layout.add_widget(self.nao_btn)
        self.graph_layout.add_widget(self.graph)

        self.button_layout.add_widget(self.clear_graph)
        # self.button_layout.add_widget(self.animate_btn)
        self.button_layout.add_widget(self.gap_btn1)
        self.button_layout.add_widget(self.next_graph)
        self.button_layout.add_widget(self.gap_btn2)
        self.button_layout.add_widget(self.eraser)

        self.draw_layout.add_widget(self.child_btn)
        self.draw_layout.add_widget(self.painterbox)

        return

    def on_nao_turn(self, *args):
        if self.on_send_char is not None:
            #call this
            self.on_send_char()
        return

    def create_plot(self, *args):
        return LinePlot(color=[0,  0.443, 0.737, 1], line_width = 3)  # orange

    def clear_plot(self, *args):
        # self.graph.remove_plot(self.plot)
        # self.graph.remove_plot(self.plot1)
        for plot in self.plots:
            self.graph.remove_plot(plot)
        self.plots = []
        return

    def next_plot(self, *args):
        self.clear_plot()
        self.painterbox.clear_letter()
        self.eraser.disabled = True
        app.counter += 1

        if app.counter > 14 or app.counter >= len(self.keys):
            app.sm.current = 'fs'
        else:
            self.curr_char = self.keys[app.counter]
            self.curr_data = self.data[self.curr_char][0]
            self.draw(self.curr_data)
        return


    def on_enter(self):
        data_file = os.path.join(app.resource_folder, 'file_p', app.file_p)
        self.data = cp.load(open(data_file, 'rb'))
        self.keys = self.data.keys()
        self.curr_char = self.keys[0]
        self.curr_data = self.data[self.curr_char][5]
        self.draw(self.curr_data)
        return

    def max_min_range(self, data):

        d = 0
        x_ma = []
        y_mi = []
        x_mi = []
        y_ma = []
        for stroke in data:
            #print stroke
            x_max = x_ma.append(int(round(max(stroke[ :, 0]) + d)))
            y_max = y_ma.append(int(round(max(stroke[ :, 1]) + d)))
            x_min = x_mi.append(int(round(min(stroke[ :, 0]) + d)))
            y_min = y_mi.append(int(round(min(stroke[ :, 1]) + d)))
        x_max = max(x_ma)
        y_max = max(y_ma)
        x_min = min(x_mi)
        y_min = min(y_mi)

        return x_max, y_max, x_min, y_min
    def set_graph_margin(self, strokes):
        self.x_max, self.y_max, self.x_min, self.y_min = self.max_min_range(strokes)
        x_margin = round(np.abs(self.x_max - self.x_min) * 0.2)
        y_margin = round(np.abs(self.y_max - self.y_min) * 0.2)
        x_margin = 1 if x_margin < 1 else x_margin
        y_margin = 1 if y_margin < 1 else y_margin
        a = max([x_margin, y_margin])
        self.graph.xmin = self.x_min -a
        self.graph.xmax = self.x_max +a
        self.graph.ymin = self.y_max +a
        self.graph.ymax = self.y_min -a

        # print self.x_max, self.y_max, self.x_min, self.y_min
        return

    def draw(self, strokes):
        self.clear_plot()
        self.set_graph_margin(strokes)
        # process each stroke
        for s in strokes:
            self.plots.append(self.create_plot())
            self.plots[-1].points = s
            self.graph.add_plot(self.plots[-1])
        return

    def update(self, stroke):
        """
        update the last stroke plot with the given stroke, if there's currently no stroke, create one
        """
        if not self.plots:
            self.plots.append(self.create_plot())
            self.plots[-1].points = stroke
            self.graph.add_plot(self.plots[-1])
        else:
            #update the last stroke
            self.plots[-1].points = stroke

        return

    def start_animation(self, *args):
        self.animate(strokes=self.curr_data, wait=2.5, freq=10, strk_interval=2.5)
        return

    def animate(self, strokes, wait=0.5, freq=20, strk_interval=1.0):
        """
        Animating the stroke trajectories with given settings:
        wait - how long to wait before start the animating: unit - sec
        freq - how often to update the plot
        strk_interval - interval between strokes
        """
        self.set_graph_margin(strokes)
        self.clear_plot()
        # process each stroke
        self.anim_counter = 0
        self.anim_counter_strk_len = np.array([len(s) for s in strokes])
        self.anim_wait = wait
        self.anim_freq = freq
        self.anim_strk_interval = strk_interval
        self.anim_n_strks = len(strokes)
        self.anim_strk_idx = 0
        self.anim_strokes = strokes

        def schedule_stroke_handler(dt):
            Clock.schedule_interval(animate_stroke_handler, 1. / self.anim_freq)
            return False

        def animate_stroke_handler(dt):
            #check if we are at the end of te stroke
            if self.anim_counter >= self.anim_counter_strk_len[self.anim_strk_idx]:
                #close the schedule if reached the last point
                if self.anim_strk_idx >= self.anim_n_strks - 1:
                    return False
                else:
                    #refresh counter and move to the next stroke
                    self.anim_counter = 0
                    self.anim_strk_idx += 1
                    #also remember to add a new plot to this stroke
                    self.plots.append(self.create_plot())
                    self.graph.add_plot(self.plots[-1])

                    Clock.schedule_once(schedule_stroke_handler, self.anim_strk_interval)
                    return False
            #process the plot update
            stroke_update = self.anim_strokes[self.anim_strk_idx][:(self.anim_counter+1), :]
            self.update(stroke_update)
            #increase the counter
            self.anim_counter += 1
            return

        #start the schedule after specified waitting time
        Clock.schedule_once(schedule_stroke_handler, self.anim_wait)
        return
class DatabaseScreen(Screen):
    def __init__(self, **kwargs):
        super(Screen, self).__init__(**kwargs)

        self.allowed_receive_database = True

        self.error = Image(
            source='Img/error.png',
            allow_stretch=False,
            keep_ratio=True,
            pos_hint={"center_x": 0.095, "center_y": 0.64},
            size_hint=(0.11, 0.11))

        self.wait = Image(
            source='Img/wait.png',
            allow_stretch=False,
            keep_ratio=True,
            pos_hint={"center_x": 0.095, "center_y": 0.64},
            size_hint=(0.11, 0.11))

        graph_theme = {
            'label_options': {
                'color': rgb('444444'),  # color of tick labels and titles
                'bold': True},
            'background_color': rgb('f8f8f2'),  # back ground color of canvas
            'tick_color': rgb('808080'),  # ticks and grid
            'border_color': rgb('808080')}  # border drawn around each graph

        self.graph1 = Graph(
            xlabel='Time [s]',
            ylabel='Value',
            x_ticks_minor=5,
            x_ticks_major=5,
            y_ticks_minor=1,
            y_ticks_major=10,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            xlog=False,
            ylog=False,
            x_grid=False,
            y_grid=False,
            xmin=0,
            xmax=30,
            ymin=0,
            ymax=100,
            pos_hint={'center_x': 0.5, 'center_y': 0.5},
            _with_stencilbuffer=False,
            **graph_theme)

        self.graph2 = Graph(
            xlabel='Time [s]',
            ylabel='Value',
            x_ticks_minor=5,
            x_ticks_major=5,
            y_ticks_minor=1,
            y_ticks_major=1,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            xlog=False,
            ylog=False,
            x_grid=False,
            y_grid=False,
            xmin=0,
            xmax=30,
            ymin=-5,
            ymax=5,
            pos_hint={'center_x': 0.5, 'center_y': 0.5},
            _with_stencilbuffer=False,
            **graph_theme)

        self.plot1 = LinePlot(line_width=2, color=[1, 0, 0, 1])
        self.plot1.points = [(i, j*10/3) for i, j in enumerate(range(31))]
        self.graph1.add_plot(self.plot1)
        self.ids.panel1.add_widget(self.graph1)

        self.plot2 = LinePlot(line_width=2, color=[1, 0, 0, 1])
        self.plot2.points = [(i, j/3 - 5) for i, j in enumerate(range(31))]
        self.graph2.add_plot(self.plot2)
        self.ids.panel2.add_widget(self.graph2)

    def wait_for_database(self, dt):
        self.allowed_receive_database = True
        self.remove_widget(self.error)
        self.remove_widget(self.wait)

    def get_database(self):
        if GlobalShared.wifi is True:
            if self.allowed_receive_database is True:
                self.allowed_receive_database = False
                Clock.schedule_once(self.wait_for_database, 2)
                check = None

                try:
                    s.send(str.encode('DB'))
                    answer = s.recv(4096)
                    check = answer[-2:]
                except IOError:
                    GlobalShared.error = True
                    GlobalShared.wifi = False

                if check == b'GD':
                    self.data = pickle.loads(answer[:-2])
                    if self.data != []:
                        try:
                            xmin = min([el[0] for el in self.data])
                            xmax = max([el[0] for el in self.data])
                            self.graph1.xmin = xmin
                            self.graph1.xmax = xmax
                            self.graph2.xmin = xmin
                            self.graph2.xmax = xmax
                            x_points = [el[0] for el in self.data]
                            panel1_points = [el[1] for el in self.data]
                            panel2_points = [el[2] for el in self.data]
                            self.plot1.points = [el for el in zip(x_points, panel1_points)]
                            self.plot2.points = [el for el in zip(x_points, panel2_points)]
                            self.remove_widget(self.error)
                            self.remove_widget(self.wait)
                        except:
                            pass
                    else:
                        self.remove_widget(self.error)
                        self.remove_widget(self.wait)
                        self.add_widget(self.error)
                elif check == b'':
                    GlobalShared.error = True
                    GlobalShared.wifi = False
                    self.remove_widget(self.error)
                    self.remove_widget(self.wait)
                    self.add_widget(self.error)
                else:
                    self.remove_widget(self.error)
                    self.remove_widget(self.wait)
                    self.add_widget(self.error)
            else:
                self.remove_widget(self.error)
                self.remove_widget(self.wait)
                self.add_widget(self.wait)
        else:
            self.remove_widget(self.error)
            self.remove_widget(self.wait)
            self.add_widget(self.error)

    def delete_all(self):
        self.remove_widget(self.wait)
        self.remove_widget(self.error)
Exemple #32
0
    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)

        def redraw(self, args):
            self.bg_rect.size = self.size
            self.bg_rect.pos = self.pos

        with self.canvas:
            self.bg_rect = Rectangle(source="steel.jpg",
                                     pos=self.pos,
                                     size=self.size)
            self.bind(pos=redraw, size=redraw)

        root = BoxLayout(orientation='vertical', padding=[15], spacing=15)

        # Add loading file with data
        gl = GridLayout(cols=2,
                        size_hint=(1, 0.95),
                        size_hint_min=(100, 100),
                        spacing=10)

        # Results section
        resl = BoxLayout(size_hint=(0.6, 0.98),
                         size_hint_min=(100, 100),
                         orientation='vertical',
                         spacing=15)

        # Graph
        graph = Graph(xlabel='X',
                      ylabel='Y',
                      x_ticks_minor=5,
                      x_ticks_major=25,
                      y_ticks_major=1,
                      y_grid_label=True,
                      x_grid_label=True,
                      padding=5,
                      x_grid=True,
                      y_grid=True,
                      xmin=-0,
                      xmax=100,
                      ymin=-1,
                      ymax=1)
        plot = MeshLinePlot(color=[1, 0, 0, 1])
        plot.points = [(x, x) for x in range(0, 101)]
        graph.add_plot(plot)

        resl.add_widget(graph)

        # Options section
        bl = BoxLayout(size_hint=(0.4, 0.98),
                       size_hint_min=(100, 100),
                       orientation='vertical',
                       spacing=15)

        bl.add_widget(
            Label(text='Wybierz plik danych',
                  size_hint=(1, 0.05),
                  size_hint_min=(200, 20)))
        files = FileChooserListView(size_hint=(1, 0.95),
                                    path=os.environ['HOMEDRIVE'] \
                                    + os.environ['HOMEPATH'])
        bl.add_widget(files)

        bl.add_widget(
            Label(text='Wybierz metodę interpolacji',
                  size_hint=(1, 0.05),
                  size_hint_min=(200, 30)))

        # Choosing interpolation method
        dd = DropDown()
        for interpolation in ['liniowa', 'wielomianowa']:
            btn = Button(text=interpolation, size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: dd.select(btn.text))
            dd.add_widget(btn)

        dd_interpol_btn = Button(text='liniowa',
                                 size_hint=(1, 0.05),
                                 size_hint_min=(80, 30))
        dd_interpol_btn.bind(on_release=dd.open)
        dd.bind(
            on_select=lambda instance, x: setattr(dd_interpol_btn, 'text', x))

        bl.add_widget(dd_interpol_btn)

        # Add widgets to root layout
        root.add_widget(
            Label(text='Entalpy Calculator',
                  size_hint=(1, 0.05),
                  size_hint_min_y=20))
        gl.add_widget(
            Label(text='Wyniki', size_hint=(0.6, 0.02), size_hint_min_y=20))
        gl.add_widget(
            Label(text='Opcje', size_hint=(0.4, 0.02), size_hint_min_y=20))
        gl.add_widget(resl)
        gl.add_widget(bl)
        root.add_widget(gl)

        calculate_btn = Button(text='Oblicz',
                               size_hint=(1, 0.05),
                               size_hint_min_y=30)
        calc_callback = partial(calculate,
                                file_chooser=files,
                                ip_btn=dd_interpol_btn)
        calculate_btn.bind(on_release=calc_callback)
        root.add_widget(calculate_btn)

        self.add_widget(root)
class VisualizationApp(App):
    def __init__(self,
                 data_file,
                 measure_collections_f,
                 additional_interval,
                 restart=True,
                 **kwargs):
        super(VisualizationApp, self).__init__(**kwargs)

        self.restart = restart
        self.data_file = data_file
        self.additional_interval = additional_interval
        self.camera_folder = data_file + '_images_Camera\\'
        self.camera_files = sorted([
            f for f in os.listdir(self.camera_folder)
            if os.path.isfile(os.path.join(self.camera_folder, f))
            and f.endswith('.jpg')
        ])
        self.ground_truth_file = [
            os.path.join(self.camera_folder, f)
            for f in os.listdir(self.camera_folder)
            if os.path.isfile(os.path.join(self.camera_folder, f))
            and f.startswith('00gt')
        ][0]

        self.image = Image(source=os.path.join(self.camera_folder,
                                               self.camera_files[0]),
                           size=(352, 288),
                           pos=(0, 0))
        #with self.image.canvas as canvas:
        #    Color(1., 0, 0)
        #   Rectangle(size=(1, 10000))

        self.graph = Graph(
            xlabel='Time [s]',
            ylabel='Distance [m]',  #x_ticks_minor=0.5,
            x_ticks_major=2,
            y_ticks_major=1,
            y_grid_label=True,
            x_grid_label=True,
            padding=10,
            x_grid=True,
            y_grid=True,
            xmin=0,
            xmax=0,
            ymin=-1,
            ymax=11)

        last_mc = None
        self.first_timestamp = measure_collections_f[0].first_measure(
        ).timestamp
        for mc in measure_collections_f:
            color = [1, 1, 0, 1]
            if mc.prediction == 'FREE_SPACE':
                color = [1, 0, 1, 1]
            elif mc.prediction == 'PARKING_CAR':
                color = [0, 1, 1, 1]
            elif mc.prediction == 'OVERTAKING_SITUATION':
                color = [0, 0, 1, 1]
            plot = MeshLinePlot(color=color)
            plot.points = [(m.timestamp - self.first_timestamp, m.distance)
                           for m in mc.measures]
            self.graph.add_plot(plot)

            color_actual = [1, 1, 0, 1]
            if mc.get_probable_ground_truth() == GroundTruthClass.FREE_SPACE:
                color_actual = [1, 0, 1, 1]
            elif GroundTruthClass.is_parking_car(
                    mc.get_probable_ground_truth()):
                color_actual = [0, 1, 1, 1]
            elif GroundTruthClass.is_overtaking_situation(
                    mc.get_probable_ground_truth()):
                color_actual = [0, 0, 1, 1]
            plot_actual = MeshLinePlot(color=color_actual)
            plot_actual.points = [(m.timestamp - self.first_timestamp,
                                   m.distance - 0.1) for m in mc.measures]
            self.graph.add_plot(plot_actual)

            if last_mc is not None:
                plot_next = MeshLinePlot(color=[1, 1, 1, 1])
                plot_next.points = [
                    (last_mc.last_measure().timestamp - self.first_timestamp,
                     last_mc.last_measure().distance),
                    (mc.first_measure().timestamp - self.first_timestamp,
                     mc.first_measure().distance)
                ]
                self.graph.add_plot(plot_next)

            last_mc = mc

        # plot = MeshLinePlot(color=[1, 1, 1, 1])
        # plot.points = [(m.timestamp - self.first_timestamp, m.distance) for m in self.measurements]
        # self.graph.add_plot(plot)

        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

        self.running = True
        self.cur_index = -1
        self.show_next_image(0)

    def build(self):
        flow_layout = FloatLayout()
        layout = BoxLayout(size=(300, 300), orientation='vertical')
        # Window.size = (1000, 700)
        layout.add_widget(self.image)
        layout.add_widget(self.graph)

        flow_layout.add_widget(layout)
        with flow_layout.canvas as canvas:
            Color(1., 0, 0)
            Rectangle(size=(1, 10000))
        return flow_layout

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'spacebar':
            self.on_start_stop()
        elif keycode[1] == 'right':
            self.move_forward()
        elif keycode[1] == 'left':
            self.move_backward()
        return True

    def on_start_stop(self):
        if not self.running:
            self.running = True
            self.show_next_image(0)
        else:
            self.running = False

    def move_forward(self):
        if not self.running:
            self.cur_index += 4
            self.show_next_image(0)

    def move_backward(self):
        if not self.running:
            self.cur_index -= 6
            self.show_next_image(0)

    def show_next_image(self, dt):
        self.cur_index += 1
        if self.cur_index >= len(self.camera_files):
            if self.restart:
                self.cur_index = 0
            else:
                self.running = False
                return 0

        self.image.source = os.path.join(self.camera_folder,
                                         self.camera_files[self.cur_index])
        cur_time = self.get_timestamp(self.cur_index)

        self.graph.xmin = cur_time - self.first_timestamp - 2
        self.graph.xmax = cur_time - self.first_timestamp + 2

        #self.graph.export_to_png('C:\\sw\\master\\scenario_snapshots\\export_' + self.camera_files[self.cur_index] + '.png')

        next_dt = 1
        if self.cur_index + 1 < len(self.camera_files):
            next_time = self.get_timestamp(self.cur_index + 1)
            next_dt = next_time - cur_time + self.additional_interval
            if self.running:
                if self.additional_interval < 0:
                    while self.cur_index < len(
                            self.camera_files) and self.get_timestamp(
                                self.cur_index
                            ) - cur_time < -self.additional_interval:
                        self.cur_index += 1
                        next_dt = 0.001

                if self.running:
                    Clock.schedule_once(self.show_next_image, abs(next_dt))
        else:
            self.cur_index = -1
            if self.running:
                Clock.schedule_once(self.show_next_image, next_dt)

            if next_dt <= 0:
                skip_images = int(-next_dt / 0.03)
                self.cur_index += skip_images
                Clock.schedule_once(self.show_next_image, 0.001)

    def get_timestamp(self, index):
        f = self.camera_files[index]
        dt = datetime.strptime(f.split('.')[0], '%Y%m%d_%H%M%S_%f')
        return (dt - datetime(1970, 1, 1)).total_seconds()
class CottrellGraph(CottrellGraphBase, EventDispatcher):
    """Crée le graphique contenant les courbes de Cottrell en utilisant 
    `kivy.garden.graph`.
    """
    legend = BooleanProperty(True)
    ticks_labels = BooleanProperty(True)

    def __init__(self, t=[], I=[]):
        """
        Paramètres
        ----------
        t : list
            Tableau de valeurs de temps.
        I : list
            Tableau de valeurs d'intensité.
        """
        super(CottrellGraph, self).__init__(t, I)

        graph_theme = {
            'label_options': {
                'color': [0, 0, 0, 1],  # color of tick labels and titles
                'bold': False
            },
            'background_color': [1, 1, 1, 1],  # back ground color of canvas
            'tick_color': [0, 0, 0, 1],  # ticks and grid
            'border_color': [0, 0, 0, 1]
        }  # border drawn around each graph

        self.graph = Graph(title='Courbes de Cottrell',
                           xlabel='Temps (s)',
                           ylabel='Intensité (A)',
                           x_ticks_minor=5,
                           x_ticks_major=5,
                           y_ticks_major=0.2,
                           y_ticks_minor=4,
                           y_grid_label=self.ticks_labels,
                           x_grid_label=self.ticks_labels,
                           padding=5,
                           x_grid=False,
                           y_grid=False,
                           xmin=float(self.tleft),
                           xmax=float(self.tright),
                           ymin=float(self.Ibottom),
                           ymax=float(self.Itop),
                           legend=self.legend,
                           precision="%#.4g",
                           **graph_theme)

        self.thplot = SmoothLinePlot(color=[0, 0, 1, 1])
        self.thplot.label = "Théorique"

        self.expplot = SmoothLinePlot(color=[1, 0, 0, 1])
        self.expplot.label = "Expérimentale"

        self.bind(legend=self.graph.setter('legend'))
        self.bind(ticks_labels=self.graph.setter('y_grid_label'))
        self.bind(ticks_labels=self.graph.setter('x_grid_label'))

        self._trigger = Clock.create_trigger(self.update_ticks)
        self.graph.bind(size=self._trigger)
        self.graph._plot_area.bind(pos=self._trigger)

        #self._update_ticks_counts = 0 # Pour éviter un clignotement
        #with self.graph.canvas:
        #    Callback(self._trigger)

    def update(self, *args):
        """Met à jour le graphique en redessinant les courbes.
        """
        if self._display_theoric:
            self.thplot.points = list(zip(self.t, self.I))
            if self.thplot not in self.graph.plots:
                self.graph.add_plot(self.thplot)
        else:
            if self.thplot in self.graph.plots:
                self.graph.remove_plot(self.thplot)

        if self._display_experimental:
            self.expplot.points = list(zip(self.expt, self.expI))

            if self.expplot not in self.graph.plots:
                self.graph.add_plot(self.expplot)
        else:
            if self.expplot in self.graph.plots:
                self.graph.remove_plot(self.expplot)

        self.graph.xmin = float(self.tleft)
        self.graph.xmax = float(self.tright)

        self.graph.ymin = float(self.Ibottom)
        self.graph.ymax = float(
            self.Itop) if self.Ibottom != self.Itop else 1.0

        self.update_ticks()

    def update_ticks(self, *args):
        """Met à jour l'échelle.
        """
        width, height = self.graph.get_plot_area_size()
        self.graph.x_ticks_major = (self.graph.xmax -
                                    self.graph.xmin) / (width / 100)
        self.graph.x_ticks_minor = 10
        self.graph.y_ticks_major = (self.graph.ymax -
                                    self.graph.ymin) / (height / 50)
        self.graph.y_ticks_minor = 5

    def update_colors(self, *args):
        theme_cls = App.get_running_app().theme_cls
        self.graph.label_options['color'] = get_color_from_hex(
            colors[theme_cls.primary_palette][theme_cls.primary_hue])
        self.graph.background_color = get_color_from_hex(
            colors[theme_cls.theme_style]["Background"])
        self.graph.tick_color = get_color_from_hex(
            colors[theme_cls.accent_palette][theme_cls.accent_hue])
        self.graph.border_color = get_color_from_hex(
            colors[theme_cls.accent_palette][theme_cls.accent_hue])

    def get_canvas(self):
        return self.graph

    def to_widget(self, x, y, relative=False):
        """Voir `kivy.widget.Widget.to_widget`.
        """
        return self.graph.to_widget(x, y, relative)

    def collide_plot(self, x, y):
        """Détermine si les coordonées tombent dans la zone des courbes.
        Utilisez `x, y = self.to_widget(x, y, relative=True)` pour d'abord les
        convertir en coordonées widget si elles sont dans les coordonées de la
        fenêtre.

        Paramètres
        ----------
        `x, y` : floats
                Les coordonnées à tester.
        """
        return self.graph.collide_plot(x, y)

    def zoom(self, dx, dy, cx, cy):
        """
        Zoom dans le graphique par un facteur.
        
        Une valeur de `dx` ou de `dy` supérieure à 1 effectue un zoom,
        inferieure à 1 effectue un dézoom.
        Par défaut `dx=1`, `dy=1`.
        
        Paramètres
        ----------
        dx : float
            Facteur de zoom horizontal.
        dy : float
            Facteur de zoom vertical.
        cx : float
            Abscisse du point sur lequel on zoom. Doit être exprimé dans les 
            coordonnées du widget.
        cy : float
            Ordonnée du point sur lequel on zoom. Doit être exprimé dans les 
            coordonnées du widget.
            
        Pour convertir le point depuis les coordonnées de la fenêtre dans les
        coordonnées du widget:
            `cx, cy = self.graph.to_widget(cx, cy, relative=True)`
        """
        if dx <= 0 or dy <= 0:
            return
        if self.Itop == self.Ibottom or self.tleft == self.tright:
            return
        dcx, dcy = self.graph.to_data(cx, cy)
        xratio = (dcx - self.tleft) / (self.tright - self.tleft)
        yratio = (dcy - self.Ibottom) / (self.Itop - self.Ibottom)

        xrange = (self.tright - self.tleft) / dx
        yrange = (self.Itop - self.Ibottom) / dy

        tleft = dcx - xratio * xrange
        tright = tleft + xrange

        Ibottom = dcy - yratio * yrange
        Itop = Ibottom + yrange

        self.set_limit_interval(tleft, tright, Ibottom, Itop)
        self.update()
class CoxGraph():
    """Crée le graphique contenant la courbe de Cox en utilisant 
    `kivy.garden.graph`.
    """
    
    def __init__(self, x=[], cox=[]):
        """
        Paramètres
        ----------
        x : list
            Tableau des distances à l'électrode.
        cox : list
            Tableau de la concentration.
        """
        self.x = x
        self.cox = cox

        theme_cls = App.get_running_app().theme_cls
        graph_theme={}
        if App.get_running_app().theme == 'default':
            graph_theme = {
                    'label_options': {
                        'color': [0, 0, 0, 1],  # color of tick labels and titles
                        'bold': False,
                        'markup': True},
                    'background_color': [1, 1, 1, 1],  # back ground color of canvas
                    'tick_color': [0, 0, 0, 1],  # ticks and grid
                    'border_color': [0, 0, 0, 1]}  # border drawn around each graph
        elif App.get_running_app().theme ==  'material-design':
            graph_theme = {
                    'label_options': {
                        'color': get_color_from_hex(colors[theme_cls.primary_palette][theme_cls.primary_hue]),#[0, 0, 0, 1],  # color of tick labels and titles
                        'bold': False,
                        'markup': True},
                    'background_color': get_color_from_hex(colors[theme_cls.theme_style]["Background"]),#[1, 1, 1, 1],  # back ground color of canvas
                    'tick_color': get_color_from_hex(colors[theme_cls.accent_palette][theme_cls.accent_hue]),#[0, 0, 0, 1],  # ticks and grid
                    'border_color': get_color_from_hex(colors[theme_cls.accent_palette][theme_cls.accent_hue])}#[0, 0, 0, 1]}  # border drawn around each graph
                
        self.graph = Graph(title = 'Courbe C[sub]ox[/sub]',
                           xlabel='x',
                           ylabel='C[sub]ox[/sub] / C[sup]*[/sup] [sub]ox[/sub]',
                           x_ticks_minor=5,
                           x_ticks_major=5,
                           y_ticks_major=1,
                           y_ticks_minor=4,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=False,
                           y_grid=False, 
                           xmin=float(0),
                           xmax=float(0.05), 
                           ymin=float(0),
                           ymax=float(1),
                           precision="%#.4g",
                           **graph_theme)
        
        self.coxplot = SmoothLinePlot(color=[0, 0, 1, 1])
        self.coxplot.label = "Concentration"

        self.graph.add_plot(self.coxplot)
        
        self._trigger = Clock.create_trigger(self.update_ticks)
        self.graph._plot_area.bind(pos=self._trigger)
        
    def update(self, *args): 
        """Met à jour l'affichage.
        """
        self.coxplot.points = list(zip(self.x,self.cox))

        self.graph.xmin = min(self.x)
        self.graph.xmax = max(self.x)
        
        self.update_ticks()
    
    def update_ticks(self, *args):
        """Met à jour l'échelle.
        """
        width, height = self.graph.get_plot_area_size()
        self.graph.x_ticks_major = (self.graph.xmax-self.graph.xmin)/(width/100)
        self.graph.x_ticks_minor = 10
        self.graph.y_ticks_major = (self.graph.ymax-self.graph.ymin)/(height/50)
        self.graph.y_ticks_minor = 5
        
    def get_canvas(self):
        return (self.graph)
Exemple #36
0
    def playVideo(self,FourthScreen):
	#get data for patient
	with open('choosePatient.txt','r') as f:
      	    patientName=f.read()
#      	data = data.split(',')
      	fileName ='videos/' + patientName + ".mp4"
	
	dataMatrix1 = genfromtxt('DemoEEGFile.txt')
	x = dataMatrix1[:,0]
	x = x - 5.539
	y = dataMatrix1[:,1]
	
	xmin = math.trunc(x[0])
	ymin = math.trunc(min(y))#math.trunc(y[0])
	xmax = xmin+1
	xGlobalmax = math.trunc(x[len(x)-1])
	ymax = math.trunc(max(y))#math.trunc(y[len(y)-1])
	# create buttons
        btnRight = Button(text='Scroll', size_hint=(.05,1),pos_hint={'x':0.45})#,'y':0})
        btnLeft = Button(text='Scroll', size_hint=(.05,1),pos_hint={'left':1})			
        FourthScreen.add_widget(btnRight)
        FourthScreen.add_widget(btnLeft)
        
	# create graph
        graph = Graph()
        plot = LinePlot(mode='line_strip',color=[1,0,0,1])
        plot.points = [(x[i],y[i]) for i in xrange(len(x))]
        graph.add_plot(plot)
        graph.x_ticks_major=.5
        graph.xmin=xmin
        graph.xmax=xmax
        graph.ymin=ymin
        graph.ymax=ymax
        graph.y_ticks_major=10
        graph.xlabel='Time (min)'
        graph.ylabel='Brain Wave Amplitude (mV)'
        graph.y_grid = True
        graph.x_grid = True
        graph.size_hint=(0.4,0.9)
        graph.x_grid_label=True
        graph.y_grid_label=True

        # create video player
        video = VideoPlayer(source=fileName)
        video.play=False
        video.size_hint=(0.5,0.9)
        video.pos_hint={'right':1,'top':1}       

        graph.pos_hint={'x':0.05,'top':1}
        def moveRight(obj):
	    global xmin
            global xmax
            global xGlobalmax
            xmin=xmin+.5
            xmax=xmax+.5
            graph.xmin=xmin
            graph.xmax=xmax
            
            percent = 1-(xGlobalmax-xmin)/xGlobalmax
            video.seek(percent)

        btnRight.bind(on_release=moveRight)
        def moveLeft(obj):
            global xmin
            global xmax
            global xGlobalmax
            xmin=xmin-.5
            xmax=xmax-.5
            graph.xmin=xmin
            graph.xmax=xmax

            percent = 1-(xGlobalmax-xmin)/xGlobalmax
            video.seek(percent)
        btnLeft.bind(on_release=moveLeft)
        FourthScreen.add_widget(graph)
        FourthScreen.add_widget(video)
Exemple #37
0
    def __init__(self, **kwargs):
        super(FourthScreen, self).__init__(**kwargs)

	# create buttons
        btnRight = Button(text='Scroll', size_hint=(.05,1),pos_hint={'x':0.45})#,'y':0})
        btnLeft = Button(text='Scroll', size_hint=(.05,1),pos_hint={'left':1})			
        self.add_widget(btnRight)
        self.add_widget(btnLeft)
        
	# create graph
        graph = Graph()
        plot = LinePlot(mode='line_strip',color=[1,0,0,1])
        plot.points = [(x[i],y[i]) for i in xrange(len(x))]
        graph.add_plot(plot)
        graph.x_ticks_major=.5
        graph.xmin=xmin
        graph.xmax=xmax
        graph.ymin=ymin
        graph.ymax=ymax
        graph.y_ticks_major=10
        graph.xlabel='Time (min)'
        graph.ylabel='Brain Wave Amplitude (mV)'
        graph.y_grid = True
        graph.x_grid = True
        graph.size_hint=(0.4,0.9)
        graph.x_grid_label=True
        graph.y_grid_label=True

        # create video player
        video = VideoPlayer(source='Momona.mp4')
        video.play=False
        video.size_hint=(0.5,0.9)
        video.pos_hint={'right':1,'top':1}       

        graph.pos_hint={'x':0.05,'top':1}
        def moveRight(obj):
	    global xmin
            global xmax
            global xGlobalmax
            xmin=xmin+.5
            xmax=xmax+.5
            graph.xmin=xmin
            graph.xmax=xmax
            
            percent = 1-(xGlobalmax-xmin)/xGlobalmax
            video.seek(percent)

        btnRight.bind(on_release=moveRight)
        def moveLeft(obj):
            global xmin
            global xmax
            global xGlobalmax
            xmin=xmin-.5
            xmax=xmax-.5
            graph.xmin=xmin
            graph.xmax=xmax

            percent = 1-(xGlobalmax-xmin)/xGlobalmax
            video.seek(percent)
        btnLeft.bind(on_release=moveLeft)
        self.add_widget(graph)
        self.add_widget(video)
Exemple #38
0
class MTSPGraph(BoxLayout):

    green = [0, 1, 0, 1]
    blue = [0, 0, 1, 1]

    def __init__(self):
        super(MTSPGraph, self).__init__()

        self.graph = Graph(
            xlabel="Distance",
            ylabel="Cost",
            x_ticks_minor=0,
            x_ticks_major=10000,
            y_ticks_minor=0,
            y_ticks_major=100,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            x_grid=True,
            y_grid=True,
            xmin=0,
            xmax=200000,
            ymin=0,
            ymax=2000,
            size=(1200, 800)
        )

        self.plot = []
        self.plot.append(MeshLinePlot(color=self.green))
        self.plot.append(MeshLinePlot(color=self.blue))
        self.plot[1]._set_mode('points')

        self.orientation = 'vertical'
        self.add_widget(self.graph)

    def generate_color(self, n):
        return [random() for _ in range(4)]

    def add_datas(self, fronts, end=False):
        if end:
            for plot in self.plot:
                self.graph.remove_plot(plot)
            self.plot = []
            ## add first pareto front
            self.plot.append(MeshLinePlot(color=self.green))
        else:
            self.plot[0].points.clear()
            self.plot[1].points.clear()

        for individual in fronts[0].getIndividuals():
            self.plot[0].points.append((individual.getDistanceValue(), individual.getCostValue()))

        ## add all other fronts
        if end:
            for i in range(1, len(fronts)):
                self.plot.append(MeshLinePlot(color=self.generate_color(i)))
                #self.plot[i]._set_mode('points')
                for individual in fronts[i].getIndividuals():
                    self.plot[i].points.append((individual.getDistanceValue(), individual.getCostValue()))
        else:
            for i in range(1, len(fronts)):
                for individual in fronts[i].getIndividuals():
                    self.plot[1].points.append((individual.getDistanceValue(), individual.getCostValue()))

        for plot in self.plot:
            self.graph.add_plot(plot)
Exemple #39
0
class RealtimeGCCNMFInterfaceWindow(GridLayout):
    def __init__(self, params, gccPHATHistory, tdoaHistory,
                 inputSpectrogramHistory, outputSpectrogramHistory,
                 coefficientMaskHistories, togglePlayAudioProcessQueue,
                 togglePlayAudioProcessAck, togglePlayGCCNMFProcessQueue,
                 togglePlayGCCNMFProcessAck, tdoaParamsGCCNMFProcessQueue,
                 tdoaParamsGCCNMFProcessAck):

        super(RealtimeGCCNMFInterfaceWindow, self).__init__()
        self.numTDOAs = params.numTDOAs
        self.tdoaIndexes = np.arange(self.numTDOAs)
        self.targetTDOAIndex = self.numTDOAs / 2.0
        self.tdoaHistory = tdoaHistory
        self.gccPHATHistory = gccPHATHistory
        self.inputSpectrogramHistory = inputSpectrogramHistory
        self.outputSpectrogramHistory = outputSpectrogramHistory
        self.coefficientMaskHistories = coefficientMaskHistories

        self.togglePlayAudioProcessQueue = togglePlayAudioProcessQueue
        self.togglePlayAudioProcessAck = togglePlayAudioProcessAck
        self.togglePlayGCCNMFProcessQueue = togglePlayGCCNMFProcessQueue
        self.togglePlayGCCNMFProcessAck = togglePlayGCCNMFProcessAck
        self.tdoaParamsGCCNMFProcessQueue = tdoaParamsGCCNMFProcessQueue
        self.tdoaParamsGCCNMFProcessAck = tdoaParamsGCCNMFProcessAck
        # self.toggleSeparationGCCNMFProcessQueue = toggleSeparationGCCNMFProcessQueue
        # self.toggleSeparationGCCNMFProcessAck = toggleSeparationGCCNMFProcessAck

        self.timer = Clock.schedule_interval(self.updateSlider, 0.01)
        self.tdoas = np.arange(self.numTDOAs).astype(np.float32)
        self.tdoaT = np.arange(self.numTDOAs)
        self.initWindow()

    def initWindow(self):
        self.rows = 4
        self.targetModeTDOASlider = Slider(orientation='horizontal',
                                           min=0,
                                           max=100,
                                           value=50)
        self.targetModeWindowTDOASlider = Slider(orientation='horizontal',
                                                 min=0,
                                                 max=100,
                                                 value=50)
        self.targetModeWindowTDOASlider.bind(value=self.OnSliderValueChange)

        self.playIconString = 'Play'
        self.pauseIconString = 'Pause'
        self.playButton = Button(text='Play')
        self.playButton.bind(on_press=self.togglePlay)
        self.initGraph()
        self.add_widget(self.targetModeWindowTDOASlider)
        self.add_widget(self.playButton)

    def initGraph(self):
        self.graph = Graph(xlabel='TDOAs',
                           ylabel='Y',
                           x_ticks_minor=10,
                           x_ticks_major=10,
                           y_ticks_major=0.5,
                           x_grid_label=False,
                           padding=5,
                           x_grid=False,
                           y_grid=False,
                           xmin=0,
                           xmax=self.numTDOAs,
                           ymin=-0.5,
                           ymax=1.5)
        self.gaussianplot = MeshLinePlot(
            color=[1, 0, 0, 1])  # 사용자가 선택하는 target TDOA 정규 분포
        self.calculated_plot = MeshLinePlot(
            color=[0, 1, 0, 1])  # gccPHAT으로 분석된 TDOA plot

        self.graph.add_plot(self.gaussianplot)
        self.add_widget(self.graph)

    def OnSliderValueChange(self, instance, value):
        self.tdoaRegionChanged()

    def queueParams(self, queue, ack, params, label='params'):
        ack.clear()
        logging.debug('GCCNMFInterface: putting %s' % label)
        queue.put(params)
        logging.debug('GCCNMFInterface: put %s' % label)
        ack.wait()
        logging.debug('GCCNMFInterface: ack received')

    def updateTogglePlayParamsAudioProcess(self, playing):
        self.queueParams(self.togglePlayAudioProcessQueue,
                         self.togglePlayAudioProcessAck,
                         {'start' if playing else 'stop': ''},
                         'audioProcessParameters')

    def updateTogglePlayParamsGCCNMFProcess(self):
        self.queueParams(self.togglePlayGCCNMFProcessQueue,
                         self.togglePlayGCCNMFProcessAck, {
                             'numTDOAs': self.numTDOAs,
                             'dictionarySize': 256
                         }, 'gccNMFProcessTogglePlayParameters')

    def togglePlay(self, value):
        playing = self.playButton.text == self.playIconString
        self.playButton.text = (self.pauseIconString
                                if playing else self.playIconString)
        logging.info('1111GCCNMFInterface: setting playing: %s' % playing)

        if playing:
            self.timer()
            self.tdoaRegionChanged()
            self.updateTogglePlayParamsGCCNMFProcess()
            self.updateTogglePlayParamsAudioProcess(playing)
        else:
            self.updateTogglePlayParamsAudioProcess(playing)
            self.timer.cancel()

    def getTDOA(self):
        tdoa = self.targetModeWindowTDOASlider.value / 100.0 * self.numTDOAs
        return tdoa

    def getBeta(self):
        lnBeta = 50 / 100.0  # 임의 값 self.targetModeWindowBetaSlider.value() / 100.0
        lnBeta *= 10.0
        lnBeta -= 5.0
        beta = np.exp(lnBeta)
        return beta

    def getNoiseFloor(self):
        noiseFloorValue = 0 / 100.0  # 임의 값self.targetModeWindowNoiseFloorSlider.value() / 100.0
        return noiseFloorValue

    def getWindowWidth(self):
        # windowWidth = self.targetModeWindowWidthSlider.value / 100.0 * self.numTDOAs
        windowWidth = 50 / 100.0 * self.numTDOAs  # 임의 값
        return windowWidth

    def tdoaRegionChanged(self):
        self.queueParams(
            self.tdoaParamsGCCNMFProcessQueue,
            self.tdoaParamsGCCNMFProcessAck,
            {
                'targetTDOAIndex': self.getTDOA(),
                'targetTDOAEpsilon': self.getWindowWidth(),
                # 'targetTDOAEpsilon': self.targetWindowFunctionPlot.getWindowWidth(),  # targetTDOAEpsilon,
                'targetTDOABeta': self.getBeta(),
                'targetTDOANoiseFloor': self.getNoiseFloor()
            },
            'gccNMFProcessTDOAParameters (region)')

    def updateSlider(self, value):
        sliderValue = self.tdoaHistory.get()[0] / (self.numTDOAs - 1) * 100
        self.targetModeTDOASlider.value = int(sliderValue)
        self.updatePlot()

    def updatePlot(self):
        self.graph.remove_plot(self.gaussianplot)  # 기존의 plot 삭제, gui로 보기 좋도록
        self.graph.remove_plot(self.calculated_plot)  # 삭제

        mu = self.getTDOA()
        alpha = self.getWindowWidth()
        beta = self.getBeta()
        noiseFloor = self.getNoiseFloor()
        data = generalizedGaussian(self.tdoas, alpha, beta,
                                   mu)  # 이것이 현재 들리는 소리의 tdoa를 표현
        data -= min(data)
        data = data / max(data) * (1 - noiseFloor) + noiseFloor

        self.gaussianplot.points = [(x, data[x])
                                    for x in range(0, self.numTDOAs)]
        self.graph.add_plot(self.gaussianplot)

        gccPHATValues = np.squeeze(np.mean(self.gccPHATHistory.values,
                                           axis=-1))
        gccPHATValues -= min(gccPHATValues)
        gccPHATValues /= max(gccPHATValues)
        self.calculated_plot.points = [(x, gccPHATValues[x])
                                       for x in range(gccPHATValues.shape[0])]
        self.graph.add_plot(self.calculated_plot)
Exemple #40
0
  def __init__( self, **kwargs ):
    super( RobRehabGUI, self ).__init__( **kwargs )

    self.configStorage = JsonStore( 'config.json' )
    if self.configStorage.exists( 'server' ): self.ids[ 'address_input' ].text = self.configStorage.get( 'server' )[ 'address' ]
    if self.configStorage.exists( 'user' ): self.ids[ 'user_name_input' ].text = self.configStorage.get( 'user' )[ 'name' ]

    self.deviceSelectors = ( self.ids[ 'joint_selector' ], self.ids[ 'axis_selector' ] )
    self.deviceEntries = [ DropDown() for selector in self.deviceSelectors ]
    for index in range( len(self.deviceEntries) ):
      def SelectEntry( instance, name, index=index ):
        self.SetDevice( index, name )
      self.deviceEntries[ index ].bind( on_select=SelectEntry )
      self.deviceSelectors[ index ].bind( on_release=self.deviceEntries[ index ].open )

    dataGraph = self.ids[ 'data_graph' ]

    measure_range = self.ids[ 'measure_slider' ].range
    GRAPH_PROPERTIES = { 'xlabel':'Last Samples', 'x_ticks_minor':5, 'x_ticks_major':25, 'y_ticks_major':0.25, 'y_grid_label':True, 'x_grid_label':True,
                         'padding':5, 'x_grid':True, 'y_grid':True, 'xmin':0, 'xmax':len(self.INITIAL_VALUES) - 1, 'ymin':measure_range[ 0 ], 'ymax':measure_range[ 1 ],
                         'background_color':[ 1, 1, 1, 1 ], 'tick_color':[ 0, 0, 0, 1 ], 'border_color':[ 0, 0, 0, 1 ], 'label_options':{ 'color': [ 0, 0, 0, 1 ], 'bold':True } }

    axisPositionGraph = Graph( ylabel='Position', **GRAPH_PROPERTIES )
    axisPositionPlot = SmoothLinePlot( color=[ 0, 0, 1, 1 ] )
    axisPositionGraph.add_plot( axisPositionPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisPositionPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_POSITION ) )
    axisVelocityPlot = SmoothLinePlot( color=[ 0, 1, 0, 1 ] )
    axisPositionGraph.add_plot( axisVelocityPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisVelocityPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_VELOCITY ) )
    refPositionPlot = SmoothLinePlot( color=[ 0, 0, 0.5, 1 ] )
    axisPositionGraph.add_plot( refPositionPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( refPositionPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_POSITION ) )
    refVelocityPlot = SmoothLinePlot( color=[ 0, 0.5, 0, 1 ] )
    axisPositionGraph.add_plot( refVelocityPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( refVelocityPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_VELOCITY ) )
    axisAccelerationPlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] )
    axisPositionGraph.add_plot( axisAccelerationPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisAccelerationPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_ACCELERATION ) )
    dataGraph.add_widget( axisPositionGraph )

    dataGraph.add_widget( Label( size_hint_y=0.05 ) )

    axisForceGraph = Graph( ylabel='Torque', **GRAPH_PROPERTIES )
    axisForcePlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] )
    axisForceGraph.add_plot( axisForcePlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisForcePlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_FORCE ) )
    dataGraph.add_widget( axisForceGraph )

    Clock.schedule_interval( self.NetworkUpdate, self.UPDATE_INTERVAL / 2 )
    Clock.schedule_interval( self.GraphUpdate, self.UPDATE_INTERVAL * 2 )
    Clock.schedule_interval( self.SliderUpdate, self.UPDATE_INTERVAL )
class Eyeball_DAQApp(App):

    #=========================
    def _update_pos(self, dt):
        if self.ser!=0:
           try:
              dat = get_nmea(self)
              e = dat['e_1']
              n = dat['n_1']
              z = dat['alt']
              self.textinput3.text = 'Easting: '+str(e)+', Northing: '+str(n)+', Elevation: '+str(z)+'\n'
           except:
              self.textinput3.text = 'Easting: NaN, Northing: NaN, Elevation: NaN\n'

    #=========================
    def _update_time(self, dt):
        self.item.title = 'Current time is '+time.asctime()

    #=========================
    def _draw_me(self, dt):
        try:
           e = self.textinput3.text.split(':')[1].split(',')[0]
           n = self.textinput3.text.split(':')[2].split(',')[0]
           self.plot.points.append((float(e),float(n)))
           self.graph.xmax = 10+max(self.plot.points)[0]
           self.graph.xmin = min(self.plot.points)[0]-10
           self.graph.ymax = 10+max(self.plot.points)[1]
           self.graph.ymin = min(self.plot.points)[1]-10
        except:
           pass
        #xmax = random.randint(10, 100)
        #self.plot.points = [(x, sin(x / 10.)) for x in range(0, xmax)]
        #self.graph.xmax = xmax

    #=========================        
    def build(self):

        self.ser = init_serial(self)

        root = Accordion(orientation='horizontal')
        
        self.item = AccordionItem(title='Current time is '+time.asctime())

        image = CameraWidget(size_hint = (2.0, 1.0)) 

        # log
        layout = GridLayout(cols=1)
        self.textinput = Log(text='Data Acquisition Log\n', size_hint = (0.5, 1.0), markup=True)
        layout.add_widget(self.textinput)
        image.textinput = self.textinput
       
        # read nav station positions
        with open('nav_stat_gps.txt') as f:
           dump = f.read()
        f.close()
        dump = dump.split('\n')
        for k in dump:
            if k.startswith('e'):
               ep = float(k.split('=')[1].lstrip())
            elif k.startswith('n'):
               np = float(k.split('=')[1].lstrip())
            elif k.startswith('z'):
               zp = float(k.split('=')[1].lstrip())         

        # for map
        #layout.add_widget(Button(text='Map', width=100)) 
        self.graph = Graph(xlabel='E', ylabel='N', x_ticks_minor=1,
        x_ticks_major=25, y_ticks_major=10, y_ticks_minor=1,
        y_grid_label=True, x_grid_label=True, padding=5,
        x_grid=True, y_grid=True, xmin=ep-10, xmax=ep+10, ymin=np-10, ymax=np+10)

        self.plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.plot.points = [(ep,np)]
        self.graph.add_plot(self.plot)
        layout.add_widget(self.graph)
        image.graph1 = self.plot
        
        # for quotes
        self.textinput2 = Log(text='', size_hint = (0.5, 1.0), markup=True)
        layout.add_widget(self.textinput2)
        image.textinput2 = self.textinput2
        
        self.textinput3 = Log(text='\n', size_hint = (0.25, 0.25), markup=True)
        layout.add_widget(self.textinput3)
        image.textinput3 = self.textinput3

        # add image to AccordionItem
        self.item.add_widget(image)
        #item.add_widget(self.textinput)
        self.item.add_widget(layout)

        Clock.schedule_interval(self._update_pos, 5)
        Clock.schedule_interval(self._update_time, 1)
        Clock.schedule_interval(self._draw_me, 10)

        root.add_widget(self.item)
        
        return root

    #=========================
    def on_stop(self):
        # write session log to file
        with open(os.path.expanduser("~")+os.sep+'log_'+time.asctime().replace(' ','_').replace(':','_')+'.txt','wb') as f:
           f.write(self.textinput.text)
        f.close()

        with open('station_start.txt','rb') as f:
           st=str(f.read()).split('\n')[0]
        f.close()

        countmax=22; counter=0
        with open('eyedaq.kv','rb') as oldfile, open('eyedaq_new.kv','wb') as newfile:
           for line in oldfile:
              counter += 1
              if counter==countmax:
                 newfile.write("            text: '"+st+"'\n")
              else:
                 newfile.write(line)
        mv('eyedaq_new.kv','eyedaq.kv')
              
        ## close the csv results files
        #bedf_csv.close()
        #print "output files closed"

        # close the serial port
        if self.ser!=0:
           self.ser.close()
           print "================="
           print "GPS is closed"
           print "================="
Exemple #42
0
class Reminder(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.app_ = App.get_running_app()
        # Get the dates clicked
        self.model_ = self.app_.calendar_.dates_.model_
        # Information to be added
        self.body = self.model_.printSelectedResults()

        # Layout arrangementw
        self.orientation = 'vertical'
        # Elevators information
        self.layout_comp = BoxLayout(orientation='horizontal',
                                     size_hint=(1, 1))
        self.layout_map = BoxLayout(orientation='horizontal', size_hint=(1, 1))

        self.img_comp_1 = Image(source='component_1.png',
                                keep_ratio=False,
                                size_hint=(1, 1),
                                allow_stretch=False,
                                mipmap=True)
        self.img_comp_2 = Image(source='component_2.png',
                                keep_ratio=False,
                                size_hint=(1, 1),
                                allow_stretch=False,
                                mipmap=True)
        self.layout_comp.add_widget(self.img_comp_1)
        self.layout_comp.add_widget(self.img_comp_2)

        self.img_map_1 = Image(source='map_kunshan.png',
                               keep_ratio=False,
                               size_hint=(1, 1),
                               allow_stretch=True)
        self.img_map_2 = Image(source='map_sh.png',
                               keep_ratio=False,
                               size_hint=(1, 1),
                               allow_stretch=True)
        self.layout_map.add_widget(self.img_map_1)
        self.layout_map.add_widget(
            Label(size_hint=(0.1, 1),
                  text='昆\n山\n地\n区\n电\n梯\n分\n布\n图',
                  font_name=font_name,
                  font_size='20sp',
                  color=(0, 0, 0, 1)))
        self.layout_map.add_widget(self.img_map_2)
        self.layout_map.add_widget(
            Label(size_hint=(0.1, 1),
                  text='上\n海\n地\n区\n电\n梯\n分\n布\n图',
                  font_name=font_name,
                  font_size='20sp',
                  color=(0, 0, 0, 1)))

        self.layout_fig = BoxLayout(orientation='vertical', size_hint=(1, 0.7))
        #self.layout_fig.add_widget(self.layout_comp)
        self.layout_fig.add_widget(self.layout_map)
        self.add_widget(self.layout_fig)

        #self.layout_scroll_lb=Label(text=self.body,size_hint=(1,None))
        #self.layout_scroll_lb.height=self.layout_scroll_lb.texture_size[1]
        #self.layout_scroll=ScrollableLabel(text=self.body)
        #self.layout_scroll.add_widget(self.layout_scroll_lb)

        #self.layout1_title=Label(text='以下电梯预测将在30天内发生故障:\n'+self.body,font_name=font_name)
        #self.layout1_title.size=self.layout1_title.texture_size
        #self.layout1.add_widget(self.layout1_title)
        #self.layout1.add_widget(self.layout_scroll)
        # Plots
        self.graph_theme = {
            'label_options': {
                'color': (0, 0, 0, 1),  # color of tick labels and titles
                'bold': True
            },
            'tick_color': (0, 0, 0, 1)
        }  # ticks and grid

        self.graph = Graph(xlabel='Current time',
                           ylabel='Maintenance date',
                           x_ticks_major=5,
                           y_ticks_major=5,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=True,
                           y_grid=True,
                           xmin=-0,
                           xmax=31,
                           ymin=-0,
                           ymax=31,
                           **self.graph_theme)

        self.plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.best_maint_dates = joblib.load('mon_best_int_np.asv')
        self.best_maint_dates = self.best_maint_dates[self.model_.month - 1]
        self.plot.points = [(x + 1, x + 1 + self.best_maint_dates[x])
                            for x in range(len(self.best_maint_dates))]
        self.graph.add_plot(self.plot)

        self.layout_graph = BoxLayout(orientation='vertical',
                                      size_hint=(0.7, 1))
        self.layout_graph.add_widget(
            Label(text='本月最优维保日期随时间变化图',
                  font_name=font_name,
                  size_hint=(1, 0.1),
                  font_size='16sp',
                  color=(0, 0, 0, 1)))
        self.layout_graph.add_widget(self.graph)

        # Note for user
        self.layout_info = BoxLayout(orientation='vertical',
                                     size_hint=(0.3, 1))
        self.layout_info.add_widget(
            Label(
                text=
                '待预防性维护电梯信息:\n设备编号\n设备所在区域类型\n故障信息\n所在城市\n电梯运行速度\n设备型号\n距离上一次维修天数',
                font_name=font_name,
                pos_hint={
                    'x': 0.5,
                    'center_y': .5
                },
                font_size='16sp',
                color=(0, 0, 0, 1)))

        self.layout_note = BoxLayout(orientation='vertical',
                                     size_hint=(0.5, 0.8))
        self.layout_note.add_widget(
            Button(on_press=self.on_press,
                   text='输出\n电梯\n信息',
                   font_name=font_name,
                   pos_hint={
                       'x': .5,
                       'y': 1
                   },
                   size_hint=(0.4, 0.2),
                   font_size='20sp',
                   color=(0, 0, 0, 1),
                   background_color=color_shadow_blue))

        self.layout_graph_note = BoxLayout(orientation='horizontal',
                                           size_hint=(1, 0.5))
        self.layout_graph_note.add_widget(self.layout_graph)
        self.layout_graph_note.add_widget(self.layout_info)
        self.layout_graph_note.add_widget(self.layout_note)

        self.add_widget(self.layout_graph_note)

        self.layout2 = BoxLayout(orientation='horizontal', size_hint=(1, .15))
        self.add_widget(self.layout2)
        self.layout2.add_widget(
            Label(text="请按 'ESC'键或点击窗外以关闭窗口",
                  font_name=font_name,
                  font_size='20sp',
                  color=(1, 0, 0, 1)))

    def on_release(self, event):
        print("Reminder OK Clicked!")

    def on_press(self, event):
        file_name = 'Log-{:}-{:}-{:}.tsv'.format(self.model_.year,
                                                 self.model_.month,
                                                 self.model_.day)
        f = open(file_name, 'w', encoding="utf-8")
        f.write(self.body)
        f.close()
class customGraph:
    def __init__(self):
        self.graph_theme = {
            'label_options': {
                'color': rgb('444444'),  # color of tick labels and titles
                'bold': True
            },
            'background_color': rgb('b8b7bb'),  # back ground color of canvas
            'tick_color': rgb('808080'),  # ticks and grid
            'border_color': rgb('808080')
        }  # border drawn around each graph
        self.graph_canvas = BoxLayout(orientation='vertical', padding=5)
        self.graph_rain = Graph(ylabel="rainfall(mm/s)",
                                y_grid_label=True,
                                x_grid_label=True,
                                xmin=0,
                                xmax=10,
                                ymin=0,
                                ymax=5000,
                                x_ticks_major=5,
                                y_ticks_major=2500,
                                x_ticks_minor=1,
                                y_ticks_minor=100,
                                x_grid=True,
                                y_grid=True,
                                padding=5,
                                **self.graph_theme)

        self.graph_temp = Graph(ylabel="temperature (C)",
                                y_grid_label=True,
                                x_grid_label=True,
                                xmin=0,
                                xmax=10,
                                ymin=0,
                                ymax=50,
                                x_ticks_major=5,
                                y_ticks_major=25,
                                x_ticks_minor=1,
                                y_ticks_minor=5,
                                x_grid=True,
                                y_grid=True,
                                padding=5,
                                **self.graph_theme)

        self.plot_rain = MeshLinePlot(color=[0, 0, 1, 1])
        self.plot_temp = MeshLinePlot(color=[1, 0, 0, 1])

    def update_data(self, data):
        for item in data:
            print item

        try:
            self.graph_rain.remove_plot(self.plot_rain)
            self.graph_canvas.remove_widget(self.graph_rain)
        except:
            pass

        try:
            self.graph_temp.remove_plot(self.plot_temp)
            self.graph_canvas.remove_widget(self.graph_temp)
        except:
            pass

        if data[0]:
            max_value = max(data[0])
            self.resize_graph(self.graph_rain, max_value)
            self.plot_rain.points = [(float(x), float(y))
                                     for x, y in enumerate(data[0])]
            self.graph_rain.add_plot(self.plot_rain)
            self.graph_canvas.add_widget(self.graph_rain)
        if data[1]:
            self.plot_temp.points = [(float(x), float(y))
                                     for x, y in enumerate(data[1])]
            self.graph_temp.add_plot(self.plot_temp)
            self.graph_canvas.add_widget(self.graph_temp)

    def resize_graph(self, graph, value):
        # print "value" + str(self.graph_rain.ymax)
        self.graph_rain.ymax = int(value) + 10
        self.graph_rain.y_ticks_major = int(self.graph_rain.ymax / 2)

    def get_graph(self):
        return self.graph_canvas
Exemple #44
0
class PlotScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(PlotScreen, self).__init__(*args, **kwargs)
        self.graph_figure = None
        self.colors = itertools.cycle(
            [rgb('7dac9f'),
             rgb('dc7062'),
             rgb('66a8d4'),
             rgb('e5b060')])

    def create_kivy_plot(self,
                         series=np.array(range(12)),
                         label_y='Average Response Time'):
        if self.graph_figure:
            self.destroy()

        series_len = len(series)
        if series_len == 0:
            return False
        max_y = max(series)
        min_y = min(series)
        #arg_max_y = series.index(max_y) # use this to label max and min...
        #arg_min_y = series.index(min_y) # with their resp time stamp
        ticks_y = round(max_y / 10., 2)

        graph_theme = {
            'label_options': {
                'color': rgb('444444'),  # color of tick labels and titles
                'bold': True
            },
            'background_color': rgb('000000'),  # back ground color of canvas
            'tick_color': rgb('444444'),  # ticks and grid
            'border_color': rgb('444444')
        }  # border drawn around each graph

        self.graph_figure = Graph(xlabel='Last {} games'.format(series_len),
                                  ylabel=label_y,
                                  x_ticks_minor=5,
                                  x_ticks_major=5,
                                  y_ticks_major=ticks_y,
                                  y_grid_label=True,
                                  x_grid_label=True,
                                  padding=10,
                                  x_grid=False,
                                  y_grid=True,
                                  xmin=0,
                                  xmax=series_len,
                                  ymin=0,
                                  ymax=int(1.2 * max_y + 1),
                                  _with_stencilbuffer=False,
                                  **graph_theme)
        plot = SmoothLinePlot(color=next(self.colors))  #mode='line_strip',
        plot.points = [(x, series[x - 1]) for x in range(1, len(series) + 1)]
        self.graph_figure.add_plot(plot)

        self.add_widget(self.graph_figure)

    def destroy(self):
        """ This must be called before a new graph is plotted.
		"""
        self.remove_widget(self.graph_figure)
        self.graph_figure = None
        Logger.info(
            'PlotScreen: Destroyed the child widget (the plot/graph) of PlotScreen'
        )
Exemple #45
0
class GraphLinearRegression(LinearRegression):
    """Crée le graphique des courbes de régression linéaire.
    """
    def __init__(self, n, S, C, t, I):
        """
        Paramètres
        ----------
        n : int
            Nombre d'électrons échangés au cours de la réaction.
        S : float
            Surface d'échange.
        C : float
            Concentration de l'espèce.
        t : list
            Tableau de valeurs des temps expérimentaux.
        I : list
            Tableau de valeurs des intensités mesurées expérimentalement.
        """
        super(GraphLinearRegression, self).__init__(t, I)
        self.n = n
        self.S = S
        self.C = C

        graph_theme = {
            'label_options': {
                'color': [0, 0, 0, 1],  # color of tick labels and titles
                'bold': False
            },
            'background_color': [1, 1, 1, 1],  # back ground color of canvas
            'tick_color': [0, 0, 0, 1],  # ticks and grid
            'border_color': [0, 0, 0, 1]
        }  # border drawn around each graph

        self.graph = Graph(title='Courbes de Regression lineaire',
                           xlabel='log Temps (s)',
                           ylabel='log Intensité (A)',
                           x_ticks_minor=5,
                           x_ticks_major=5,
                           y_ticks_major=0.2,
                           y_ticks_minor=4,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=False,
                           y_grid=False,
                           precision="%#.4g",
                           **graph_theme)

        self.logexpplot = SmoothLinePlot(color=[1, 0, 0, 1])
        self.logexpplot.label = "Expérimentale"

        self.linlogexpplot = SmoothLinePlot(color=[1, 0, 1, 1])

        self.graph.legend = True

        self.graph.add_plot(self.logexpplot)
        self.graph.add_plot(self.linlogexpplot)

        self._trigger = Clock.create_trigger(self.update_ticks)
        self.graph._plot_area.bind(pos=self._trigger)

    def update(self, *args):
        """Met à jour l'affichage des courbes de régression linéaire et le 
        calcul du coefficient de diffusion expérimental. 
        """
        self.logexp_and_linear_curves_tab(self.t, self.I)
        _, intercept = self.linregress()
        self.Dexp = self.calculate_D(intercept, self.n, self.S, self.C)

        self.linlogexpplot.label = "Régression linéaire\nD=" + str(self.Dexp)

        self.logexpplot.points = list(zip(self.logexpt, self.logexpI))
        self.linlogexpplot.points = list(zip(self.logexpt, self.linlogexpI))

        self.graph.xmin = float(min(self.logexpt))
        self.graph.xmax = float(max(self.logexpt))
        self.graph.ymin = float(min(self.logexpI))
        self.graph.ymax = float(max(self.logexpI))

        self.update_ticks()

    def update_ticks(self, *args):
        """Met à jour l'échelle.
        """
        width, height = self.graph.get_plot_area_size()
        self.graph.x_ticks_major = (self.graph.xmax -
                                    self.graph.xmin) / (width / 100)
        self.graph.x_ticks_minor = 10
        self.graph.y_ticks_major = (self.graph.ymax -
                                    self.graph.ymin) / (height / 50)
        self.graph.y_ticks_minor = 5

    def update_colors(self, *args):
        theme_cls = App.get_running_app().theme_cls
        self.graph.label_options['color'] = get_color_from_hex(
            colors[theme_cls.primary_palette][theme_cls.primary_hue])
        self.graph.background_color = get_color_from_hex(
            colors[theme_cls.theme_style]["Background"])
        self.graph.tick_color = get_color_from_hex(
            colors[theme_cls.accent_palette][theme_cls.accent_hue])
        self.graph.border_color = get_color_from_hex(
            colors[theme_cls.accent_palette][theme_cls.accent_hue])

    def get_canvas(self):
        return self.graph
Exemple #46
0
    def __init__(self, **kwargs):
        super(RobRehabGUI, self).__init__(**kwargs)

        self.configStorage = JsonStore('config.json')
        if self.configStorage.exists('server'):
            self.ids['address_input'].text = self.configStorage.get(
                'server')['address']
        if self.configStorage.exists('user'):
            self.ids['user_name_input'].text = self.configStorage.get(
                'user')['name']

        self.robotSelector = self.ids['robot_selector']
        self.robotEntries = DropDown()
        self.robotEntries.bind(
            on_select=lambda instance, name: self.SetRobot(name))
        self.robotSelector.bind(on_release=self.robotEntries.open)
        self.axisSelector = self.ids['axis_selector']
        self.axisEntries = DropDown()
        self.axisEntries.bind(
            on_select=lambda instance, name: self.SetAxis(name))
        self.axisSelector.bind(on_release=self.axisEntries.open)

        self.enableToggle = self.ids['enable_button']
        self.offsetToggle = self.ids['offset_button']
        self.calibrationToggle = self.ids['calibration_button']
        self.operationToggle = self.ids['operation_button']

        self.measureSlider = self.ids['measure_slider']
        self.setpointSlider = self.ids['setpoint_slider']
        self.forceSlider = self.ids['force_slider']
        self.inertiaSlider = self.ids['inertia_slider']
        self.stiffnessSlider = self.ids['stiffness_slider']
        self.dampingSlider = self.ids['damping_slider']

        self.motionSelector = self.ids['motion_selector']
        self.motionEntries = DropDown()
        self.motionEntries.bind(
            on_select=lambda instance, name: self.SetMotion(name))
        self.motionSelector.bind(on_release=self.motionEntries.open)
        setpointMotions = []
        for fileName in os.listdir(self.MOTIONS_DIR):
            if fileName.endswith('.txt'):
                setpointMotions.append(os.path.splitext(fileName)[0])
        self._UpdateSelectorEntries(self.motionSelector, self.motionEntries,
                                    setpointMotions)
        self.SetMotion(self.DEFAULT_MOTION)

        self.setpointUpdateEvent = None

        dataGraph = self.ids['data_graph']

        measure_range = self.measureSlider.range
        GRAPH_PROPERTIES = {
            'x_ticks_minor': 5,
            'x_ticks_major': 25,
            'y_ticks_minor': 0.25,
            'y_ticks_major': 0.5,
            'y_grid_label': True,
            'x_grid_label': True,
            'padding': 5,
            'x_grid': True,
            'y_grid': True,
            'xmin': 0,
            'xmax': len(self.INITIAL_VALUES) - 1,
            'background_color': [1, 1, 1, 1],
            'tick_color': [0, 0, 0, 1],
            'border_color': [0, 0, 0, 1],
            'label_options': {
                'color': [0, 0, 0, 1],
                'bold': True
            }
        }

        axisPositionGraph = Graph(ylabel='Position/Setpoint',
                                  ymin=measure_range[0],
                                  ymax=measure_range[1],
                                  **GRAPH_PROPERTIES)
        positionPlot = SmoothLinePlot(color=[0, 0, 1, 1])
        axisPositionGraph.add_plot(positionPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(positionPlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_POSITION))
        velocityPlot = SmoothLinePlot(color=[0, 1, 0, 1])
        axisPositionGraph.add_plot(velocityPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(velocityPlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_VELOCITY))
        accelerationPlot = SmoothLinePlot(color=[1, 1, 0, 1])
        axisPositionGraph.add_plot(accelerationPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(accelerationPlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_ACCELERATION))
        refPositionPlot = SmoothLinePlot(color=[0, 0, 0.5, 1])
        axisPositionGraph.add_plot(refPositionPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(refPositionPlot, self.INITIAL_VALUES[:],
                                 self.setpoints, DOF_POSITION))
        dataGraph.add_widget(axisPositionGraph)

        dataGraph.add_widget(Label(size_hint_y=0.05))

        force_range = self.forceSlider.range
        axisForceGraph = Graph(ylabel='Force/Impedance',
                               ymin=force_range[0],
                               ymax=force_range[1],
                               **GRAPH_PROPERTIES)
        forcePlot = SmoothLinePlot(color=[1, 0, 0, 1])
        axisForceGraph.add_plot(forcePlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(forcePlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_FORCE))
        dampingPlot = SmoothLinePlot(color=[0, 0, 1, 1])
        axisForceGraph.add_plot(dampingPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(dampingPlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_DAMPING))
        inertiaPlot = SmoothLinePlot(color=[0, 1, 0, 1])
        axisForceGraph.add_plot(inertiaPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(inertiaPlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_INERTIA))
        stiffnessPlot = SmoothLinePlot(color=[1, 1, 0, 1])
        axisForceGraph.add_plot(stiffnessPlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(stiffnessPlot, self.INITIAL_VALUES[:],
                                 self.measures, DOF_STIFFNESS))
        refForcePlot = SmoothLinePlot(color=[0.5, 0, 0, 1])
        axisForceGraph.add_plot(refForcePlot)
        self.dataPlots.append(
            RobRehabGUI.DataPlot(refForcePlot, self.INITIAL_VALUES[:],
                                 self.setpoints, DOF_FORCE))
        dataGraph.add_widget(axisForceGraph)

        dataGraph.add_widget(Label(text='Last Samples', size_hint_y=0.1))

        Clock.schedule_interval(self.DataUpdate, self.UPDATE_INTERVAL / 2)
        Clock.schedule_interval(self.GraphUpdate, self.UPDATE_INTERVAL * 2)
        Clock.schedule_interval(self.SliderUpdate, self.UPDATE_INTERVAL)
Exemple #47
0
class Stats(BoxLayout):
    def __init__(self, **kwargs):
        super(Stats, self).__init__(**kwargs)
        self.flag = 0
        # flag = 1: Daily cost
        # flag = 2: Weekly cost
        # flag = 3: Monthly cost
        # flag = 4: Daily mistakes
        # flag = 5: Weekly mistakes
        # flag = 6: Monthly mistakes
        # flag = 7: Omission Category
        # flag = 8: Commission Category

        self.calculate_day_cost()

        self.graph_theme = {
            'label_options': {
                'color': (182 / 255.0, 174 / 255.0, 183 / 255.0,
                          1),  # color of tick labels and titles
                'bold': False
            },
            'tick_color': (1, 1, 1, 1),  # ticks and grid
            'border_color': (182 / 255.0, 174 / 255.0, 183 / 255.0, 1)
        }  # border drawn around each graph

        # Monthly cost graph
        self.graph1 = Graph(xlabel='Months',
                            ylabel='Costs',
                            size_hint=(0.7, 0.9),
                            pos_hint={
                                'center_x': .5,
                                'center_y': 0.5
                            },
                            x_ticks_major=5,
                            y_ticks_major=10,
                            y_grid_label=True,
                            x_grid_label=True,
                            padding=5,
                            xmin=0,
                            xmax=12,
                            ymin=0,
                            ymax=80,
                            **self.graph_theme)

        # Weekly cost graph
        self.graph2 = Graph(xlabel='Weeks',
                            ylabel='Costs',
                            size_hint=(0.7, 0.9),
                            pos_hint={
                                'center_x': .5,
                                'center_y': 0.5
                            },
                            x_ticks_major=5,
                            y_ticks_major=10,
                            y_grid_label=True,
                            x_grid_label=True,
                            padding=5,
                            xmin=0,
                            xmax=20,
                            ymin=0,
                            ymax=80,
                            **self.graph_theme)

        # Daily cost graph
        self.graph8 = Graph(xlabel='Days',
                            ylabel='Costs',
                            size_hint=(0.7, 0.9),
                            pos_hint={
                                'center_x': .5,
                                'center_y': 0.5
                            },
                            x_ticks_major=5,
                            y_ticks_major=10,
                            y_grid_label=True,
                            x_grid_label=True,
                            padding=5,
                            xmin=0,
                            xmax=150,
                            ymin=0,
                            ymax=80,
                            **self.graph_theme)

        # Monthly mistakes graph
        self.graph5 = Graph(xlabel='Months',
                            ylabel='Mistakes',
                            size_hint=(0.7, 0.9),
                            pos_hint={
                                'center_x': .5,
                                'center_y': 0.5
                            },
                            x_ticks_major=5,
                            y_ticks_major=1,
                            y_grid_label=True,
                            x_grid_label=True,
                            padding=5,
                            xmin=0,
                            xmax=12,
                            ymin=0,
                            ymax=5,
                            **self.graph_theme)

        # Weekly mistakes graph
        self.graph6 = Graph(xlabel='Weeks',
                            ylabel='Mistakes',
                            size_hint=(0.7, 0.9),
                            pos_hint={
                                'center_x': .5,
                                'center_y': 0.5
                            },
                            x_ticks_major=5,
                            y_ticks_major=1,
                            y_grid_label=True,
                            x_grid_label=True,
                            padding=5,
                            xmin=0,
                            xmax=25,
                            ymin=0,
                            ymax=5,
                            **self.graph_theme)

        # Daily mistakes graph
        self.graph7 = Graph(xlabel='Days',
                            ylabel='Mistakes',
                            size_hint=(0.7, 0.9),
                            pos_hint={
                                'center_x': .5,
                                'center_y': 0.5
                            },
                            x_ticks_major=5,
                            y_ticks_major=1,
                            y_grid_label=True,
                            x_grid_label=True,
                            padding=5,
                            xmin=0,
                            xmax=150,
                            ymin=0,
                            ymax=5,
                            **self.graph_theme)

    def make_pairs(self, list1, list2):
        points = []
        for (month, cost) in zip(list1, list2):
            points.append((month, cost))
        return points

    def calculate_day_cost(self):
        self.ids['opportunity_cost'].text = "Total cost: $" + str(
            get_total_cost())

    def get_daily_cost(self):
        if self.flag == 1:
            return

        self.flag = 1
        day_list = days_to_ints(get_all_days())
        my_day_list = {}

        for (m, d) in day_list:
            if m in my_day_list:
                my_day_list[m].append(d)
            else:
                my_day_list[m] = []
                my_day_list[m].append(d)

        new_day_list = []

        for eachMonth in my_day_list:
            for eachDay in my_day_list[eachMonth]:
                new_day_list.append(eachDay + (eachMonth - 1) * 30)

        day_cost = get_daily_cost()

        points_list = self.make_pairs(new_day_list, day_cost)
        print(points_list)

        plot = SmoothLinePlot(color=[162 / 255.0, 121 / 255.0, 119 / 255.0, 1])
        plot.points = points_list

        self.graph8.add_plot(plot)

        self.ids['graph1'].remove_widget(self.graph2)
        self.ids['graph1'].remove_widget(self.graph1)
        self.ids['graph1'].add_widget(self.graph8)

    def get_monthly_cost(self):
        if self.flag == 3:
            return

        self.flag = 3

        month_list = get_all_months()
        month_cost = get_monthly_cost()
        points_list = self.make_pairs(month_list, month_cost)
        print(points_list)

        plot = SmoothLinePlot(color=[162 / 255.0, 121 / 255.0, 119 / 255.0, 1])
        plot.points = points_list
        self.graph1.add_plot(plot)
        self.ids['graph1'].remove_widget(self.graph8)
        self.ids['graph1'].remove_widget(self.graph2)
        self.ids['graph1'].add_widget(self.graph1)

    def get_weekly_cost(self):
        if self.flag == 2:
            return

        self.flag = 2

        week_list = get_all_weeks()
        week_cost = get_weekly_cost()
        points_list = self.make_pairs(week_list, week_cost)
        print(points_list)

        plot = SmoothLinePlot(color=[162 / 255.0, 121 / 255.0, 119 / 255.0, 1])
        plot.points = points_list
        self.graph2.add_plot(plot)
        self.ids['graph1'].remove_widget(self.graph8)
        self.ids['graph1'].remove_widget(self.graph1)
        self.ids['graph1'].add_widget(self.graph2)

    def get_om_cates(self):
        if self.flag == 7:
            return

        self.flag = 7

        all_om_verbs = get_all_verbs(True)
        self.ids['graph2'].clear_widgets()

        scroll = ScrollView()
        grid = GridLayout(id='grid',
                          size_hint_y=None,
                          cols=1,
                          row_default_height='30dp',
                          row_force_default=True,
                          spacing=20,
                          padding=20)
        grid.bind(minimum_height=grid.setter('height'))
        scroll.add_widget(grid)
        self.ids['graph2'].add_widget(scroll)

        for (name, times) in zip(all_om_verbs, get_verb_graph(True)):
            label_om = CateEntry(name=name, times=str(times))
            # print(name)
            # print(times)
            grid.add_widget(label_om)

    def get_cm_cates(self):
        if self.flag == 8:
            return

        self.flag = 8

        all_cm_verbs = get_all_verbs(False)
        self.ids['graph2'].clear_widgets()

        scroll = ScrollView()
        grid = GridLayout(id='grid',
                          size_hint_y=None,
                          cols=1,
                          row_default_height='30dp',
                          row_force_default=True,
                          spacing=20,
                          padding=20)
        grid.bind(minimum_height=grid.setter('height'))
        scroll.add_widget(grid)
        self.ids['graph2'].add_widget(scroll)

        for (name, times) in zip(all_cm_verbs, get_verb_graph(False)):
            label_om = CateEntry(name=name, times=str(times))
            # print(name)
            # print(times)
            grid.add_widget(label_om)

    def get_daily_mistakes(self):
        if self.flag == 4:
            return

        self.flag = 4

        day_list = days_to_ints(get_all_days())
        my_day_list = {}

        for (m, d) in day_list:
            if m in my_day_list:
                my_day_list[m].append(d)
            else:
                my_day_list[m] = []
                my_day_list[m].append(d)

        new_day_list = []

        for eachMonth in my_day_list:
            for eachDay in my_day_list[eachMonth]:
                new_day_list.append(eachDay + (eachMonth - 1) * 30)

        day_om_cost = get_daily_mistake_tuple()[0]
        day_cm_cost = get_daily_mistake_tuple()[1]
        points_om_list = self.make_pairs(new_day_list, day_om_cost)
        points_cm_list = self.make_pairs(new_day_list, day_cm_cost)
        plot_om = SmoothLinePlot(
            color=[255 / 255.0, 125 / 255.0, 125 / 255.0, 1])
        plot_om.points = points_om_list
        plot_cm = SmoothLinePlot(
            color=[125 / 255.0, 177 / 255.0, 255 / 255.0, 1])
        plot_cm.points = points_cm_list

        print("om:" + str(points_om_list))  #Blue
        print("cm:" + str(points_cm_list))  # Red

        self.graph7.add_plot(plot_om)
        self.graph7.add_plot(plot_cm)
        self.ids['graph3'].remove_widget(self.graph5)
        self.ids['graph3'].remove_widget(self.graph6)
        self.ids['graph3'].add_widget(self.graph7)

    def get_monthly_mistakes(self):
        if self.flag == 6:
            return

        self.flag = 6

        month_list = get_all_months()

        month_om_cost = get_monthly_mistake_tuple()[0]
        month_cm_cost = get_monthly_mistake_tuple()[1]
        points_om_list = self.make_pairs(month_list, month_om_cost)
        points_cm_list = self.make_pairs(month_list, month_cm_cost)
        plot_om = SmoothLinePlot(
            color=[255 / 255.0, 125 / 255.0, 125 / 255.0, 1])
        plot_om.points = points_om_list
        plot_cm = SmoothLinePlot(
            color=[125 / 255.0, 177 / 255.0, 255 / 255.0, 1])
        plot_cm.points = points_cm_list

        # print("om:" + str(points_om_list)) #Blue
        # print("cm:" + str(points_cm_list)) # Red

        # month_mistakes = get_monthly_mistake_num()
        # points_list = self.make_pairs(month_list, month_mistakes)
        # print(points_list)

        plot = SmoothLinePlot(color=[1, 0, 0, 1])
        self.graph5.add_plot(plot_om)
        self.graph5.add_plot(plot_cm)
        self.ids['graph3'].remove_widget(self.graph7)
        self.ids['graph3'].remove_widget(self.graph6)
        self.ids['graph3'].add_widget(self.graph5)

    def get_weekly_mistakes(self):
        if self.flag == 5:
            return

        self.flag = 5

        week_list = get_all_weeks()

        week_om_cost = get_monthly_mistake_tuple()[0]
        week_cm_cost = get_monthly_mistake_tuple()[1]
        points_om_list = self.make_pairs(week_list, week_om_cost)
        points_cm_list = self.make_pairs(week_list, week_cm_cost)
        plot_om = SmoothLinePlot(
            color=[255 / 255.0, 125 / 255.0, 125 / 255.0, 1])
        plot_om.points = points_om_list
        plot_cm = SmoothLinePlot(
            color=[125 / 255.0, 177 / 255.0, 255 / 255.0, 1])
        plot_cm.points = points_cm_list

        # print("om:" + str(points_om_list)) #Blue
        # print("cm:" + str(points_cm_list)) # Red

        # week_mistakes = get_weekly_mistake_num()
        # points_list = self.make_pairs(week_list, week_mistakes)
        # print(points_list)

        plot = SmoothLinePlot(color=[1, 0, 0, 1])
        self.graph6.add_plot(plot_om)
        self.graph6.add_plot(plot_cm)
        self.ids['graph3'].remove_widget(self.graph7)
        self.ids['graph3'].remove_widget(self.graph5)
        self.ids['graph3'].add_widget(self.graph6)
Exemple #48
0
class PidLayout(TabDrawerItem, Receiver):
    def __init__(self, tree, **kwargs):
        # make sure we aren't overriding any important functionality
        super(PidLayout, self).__init__(**kwargs)

        self.text = tree[0]

        self.mys = ()
        for values in tree[1]:
            self.mys += (MyS(values), )

        self.bm = BoxLayout(
            orientation='vertical',
            spacing=10,
            padding=10,
        )
        self.bm.add_widget(self.build_bouton_layout(tree[2]))
        self.bm.add_widget(self.build_graph(tree[2]))
        self.add_widget(self.bm)

        #APP.add_receiver( self, self.text )
        self.key = self.text

    def on_menu(self, *args):
        if self.menu:
            for s in self.mys:
                self.bm.add_widget(s)
        else:
            for s in self.mys:
                self.bm.remove_widget(s)

    def build_graph(self, tree):
        # example of a custom theme
        graph_theme = {
            'label_options': {
                'color':
                (0.27, 0.27, 0.27, 1),  # color of tick labels and titles
                'bold': True
            },
            'background_color':
            (0.97, 0.97, 0.95, 1),  # back ground color of canvas
            'tick_color': (0.5, 0.5, 0.5, 1),  # ticks and grid
            'border_color':
            (0.5, 0.5, 0.5, 1)  # border drawn around each graph
        }

        self.graph = Graph(xlabel='Seconde',
                           ylabel='Apples',
                           x_ticks_minor=0.5,
                           x_ticks_major=1,
                           y_ticks_minor=1,
                           y_ticks_major=10,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           xlog=False,
                           ylog=False,
                           x_grid=True,
                           y_grid=True,
                           xmin=-3,
                           xmax=0,
                           ymin=-30,
                           ymax=30,
                           **graph_theme)

        self.dpoints = []
        for nom, couleur in tree:
            self.dpoints.append((nom, MeshLinePlot(color=couleur)))
        for dpoints in self.dpoints:
            self.graph.add_plot(dpoints[1])

        #self.lpoints = [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
        self.lpoints = []

        return self.graph

    def update_points(self, points):
        # points sous forme ( x, y1, y2,...)
        #print self.text + str(points)

        # passe le temps de ms en s
        #points[0] = points[0]/1000
        # Ajoute les derniers points a la liste temporaire
        self.lpoints.append(points)
        # trie la liste
        self.lpoints.sort(key=lambda x: x[0])
        temps = self.lpoints[-1][0]
        # supprime les valeurs de plus de 3s
        while self.lpoints[0][0] < temps - 3000:
            del self.lpoints[0]
        #print self.lpoints

        for i in range(0, len(self.dpoints)):
            self.dpoints[i - 1][1].points = ()
        # pour chaque point de la liste
        for point in self.lpoints:
            # les range dans leurs listes de points sous forme (x,y)
            for i in range(1, len(point)):
                self.dpoints[i - 1][1].points.append(
                    ((point[0] - temps) / 1000,
                     point[i] / 10 if i > 1 else point[i]))

    def courbe_visibility(self, bout):
        if bout.state is 'normal':
            self.graph.add_plot(self.dpoints[bout.index][1])
            bout.background_color = bout.couleur + (1, )
        else:
            self.graph.remove_plot(self.dpoints[bout.index][1])
            bout.background_color = bout.couleur + (0.5, )

    def build_bouton_layout(self, tree):
        bl = BoxLayout(
            size_hint=(1, None),
            orientation='horizontal',
            spacing=10,
            height=30,
        )
        i = 0
        for nom, couleur in tree:
            bl.add_widget(self.build_bouton(nom, couleur, i))
            i += 1
        return bl

    def build_bouton(self, nom, couleur, i):
        b = ToggleButton(text=nom, background_normal="", background_down="")
        b.nom = nom
        b.index = i
        b.couleur = couleur
        b.background_color = b.couleur + (1, )
        b.bind(on_release=self.courbe_visibility)
        return b

    def on_msg_received(self, *args):
        #print self.msg_received
        msg = [float(x) for x in self.msg_received.split()]
        self.update_points(msg)
class Eyeball_DAQApp(App):

    #=========================
    def _update_pos(self, dt):

        with open('C:\Users\User\Desktop\capture.txt') as f:
          last = f.readline().split('\r')[-2]
   
        f.close()

        last = last.split('99=')[1]

        if ~last.startswith(' '):
           sd = float(last.split(';')[0].lstrip())/1000
           ha = 0.0009*float(last.split(';')[1].lstrip())/10
           va = 0.0009*float(last.split(';')[2].lstrip())/10

        ha = (ha - self.hca) % 360

        Za = va*0.0174532925

        n = self.np + sd * sin(Za) * cos(ha*0.0174532925)
        z = self.zp + sd * cos(Za)
        e = self.ep + sd * sin(Za) * sin(ha*0.0174532925)

        self.textinput3.text = 'Easting: '+str(e)+', Northing: '+str(n)+', Elevation: '+str(z)+'\n'

    #=========================
    def _update_time(self, dt):
        self.item.title = 'Current time is '+time.asctime()

    #=========================
    def _draw_me(self, dt):
        e = self.textinput3.text.split(':')[1].split(',')[0]
        n = self.textinput3.text.split(':')[2].split(',')[0]
        self.plot.points.append((float(e),float(n)))
        self.graph.xmax = 5+max(self.plot.points)[0]
        self.graph.xmin = min(self.plot.points)[0]-5
        self.graph.ymax = 5+max(self.plot.points)[1]
        self.graph.ymin = min(self.plot.points)[1]-5

        #xmax = random.randint(10, 100)
        #self.plot.points = [(x, sin(x / 10.)) for x in range(0, xmax)]
        #self.graph.xmax = xmax

    #=========================        
    def build(self):

        root = Accordion(orientation='horizontal')
        
        self.item = AccordionItem(title='Current time is '+time.asctime())

        image = CameraWidget(size_hint = (2.0, 1.0)) 

        # log
        layout = GridLayout(cols=1)
        self.textinput = Log(text='Data Acquisition Log\n', size_hint = (0.5, 1.0), markup=True)
        layout.add_widget(self.textinput)
        image.textinput = self.textinput
       
        # read nav station positions
        with open('nav_stat.txt') as f:
           dump = f.read()
        f.close()
        dump = dump.split('\n')
        for k in dump:
            if k.startswith('e'):
               self.ep = float(k.split('=')[1].lstrip())
            elif k.startswith('n'):
               self.np = float(k.split('=')[1].lstrip())
            elif k.startswith('z'):
               self.zp = float(k.split('=')[1].lstrip())   
            elif k.startswith('hca'):
               self.hca = float(k.split('=')[1].lstrip())

        # for map
        #layout.add_widget(Button(text='Map', width=100)) 
        self.graph = Graph(xlabel='E', ylabel='N', x_ticks_minor=1,
        x_ticks_major=25, y_ticks_major=10, y_ticks_minor=1,
        y_grid_label=True, x_grid_label=True, padding=5,
        x_grid=True, y_grid=True, xmin=self.ep-5, xmax=self.ep+5, ymin=self.np-5, ymax=self.np+5)

        self.plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.plot.points = [(self.ep,self.np)]
        self.graph.add_plot(self.plot)
        layout.add_widget(self.graph)
        image.graph1 = self.plot
        
        # for quotes
        self.textinput2 = Log(text='', size_hint = (0.5, 1.0), markup=True)
        layout.add_widget(self.textinput2)
        image.textinput2 = self.textinput2
        
        self.textinput3 = Log(text='\n', size_hint = (0.25, 0.25), markup=True)
        layout.add_widget(self.textinput3)
        image.textinput3 = self.textinput3

        # add image to AccordionItem
        self.item.add_widget(image)
        #item.add_widget(self.textinput)
        self.item.add_widget(layout)

        Clock.schedule_interval(self._update_pos, 1)
        Clock.schedule_interval(self._update_time, 1)
        Clock.schedule_interval(self._draw_me, 2)

        root.add_widget(self.item)
        
        return root

    #=========================
    def on_stop(self):
        # write session log to file
        with open(os.path.expanduser("~")+os.sep+'log_'+time.asctime().replace(' ','_').replace(':','_')+'.txt','wb') as f:
           f.write(self.textinput.text)
        f.close()

        with open('station_start.txt','rb') as f:
           st=str(f.read()).split('\n')[0]
        f.close()

        countmax=22; counter=0
        with open('eyedaq.kv','rb') as oldfile, open('eyedaq_new.kv','wb') as newfile:
           for line in oldfile:
              counter += 1
              if counter==countmax:
                 newfile.write("            text: '"+st+"'\n")
              else:
                 newfile.write(line)
        mv('eyedaq_new.kv','eyedaq.kv')
Exemple #50
0
class Specimen(BoxLayout):

    def __init__(self, **kwargs):
        super(Specimen, self).__init__(**kwargs)
        self.max_displacement = 4.0
        self.tl = TLoop()
        # set the keyword parameters (to replace the default values)
        for key, value in kwargs.iteritems():
            setattr(self, key, value)
        self.add_graph()
        self.add_break_line()
        self.x_current = 53.
        self.selected = False
        self.x_coord = np.linspace(0, self.tl.ts.L_x, self.tl.ts.n_e_x + 1)
        self.x_ip_coord = np.repeat(self.x_coord, 2)[1:-1]

    def add_graph(self):
        self.graph = Graph(
            y_grid_label=False, x_grid_label=False, padding=5,
            xmin=0, xmax=100, ymin=0, ymax=30)
        self.matrix = FilledRect(xrange=[10, 50],
                                 yrange=[5, 25],
                                 color=[255, 255, 255])
        self.reinf = FilledRect(xrange=[10, 50],
                                yrange=[13, 17],
                                color=[255, 0, 0])
        self.controller = FilledRect(xrange=[50, 56],
                                     yrange=[12, 18],
                                     color=[0, 0, 255])
        self.graph.add_plot(self.matrix)
        self.graph.add_plot(self.reinf)
        self.graph.add_plot(self.controller)
        self.add_widget(self.graph)

    def add_break_line(self):
        break_line3 = LinePlot(
            color=[0, 0, 0], width=4)
        break_line3.points = [
            (30, 2), (30, 9), (28, 12), (32, 18), (30, 21), (30, 28)]
        self.graph.add_plot(break_line3)

    @property
    def f_u_wid(self):
        graph = Graph(xlabel='displacement', ylabel='force', x_ticks_minor=5,
                      x_ticks_major=1, y_ticks_major=100,
                      y_grid_label=True, x_grid_label=True, padding=5,
                      x_grid=True, y_grid=True, xmin=0, xmax=self.max_displacement, ymin=-100, ymax=500)
        self.f_u_line = MeshLinePlot(color=[1, 1, 1, 1])
        self.f_u_line.points = [(0, 0)]
        graph.add_plot(self.f_u_line)
        return graph

    @property
    def eps_sig_wid(self):
        graph = Graph(xlabel='slip', ylabel='bond', x_ticks_minor=5,
                      x_ticks_major=0.5, y_ticks_major=0.2,
                      y_grid_label=True, x_grid_label=True, padding=5,
                      x_grid=True, y_grid=True, xmin=-0.0 * self.max_displacement, xmax=0.8 * self.max_displacement, ymin=-1, ymax=1)
        self.eps_sig_line = MeshLinePlot(color=[1, 1, 1, 1])
        self.eps_sig_line.points = [(0, 0)]
        graph.add_plot(self.eps_sig_line)
        return graph

    @property
    def shear_flow_wid(self):
        graph = Graph(xlabel='length', ylabel='shear flow', background_color=[0, 0, 0, 1],
                      x_ticks_major=100., y_ticks_major=0.2,
                      y_grid_label=True, x_grid_label=True, padding=5,
                      x_grid=True, y_grid=True, xmin=0.0, xmax=self.tl.ts.L_x, ymin=-1, ymax=1)
        self.shear_flow_line = MeshLinePlot(color=[1, 1, 1, 1])
        self.shear_flow_line.points = self.list_tuple(
            self.x_coord, np.zeros_like(self.x_coord))
        graph.add_plot(self.shear_flow_line)
        return graph

    @property
    def disp_slip_wid(self):
        graph = Graph(xlabel='length', ylabel='displacement',  background_color=[0, 0, 0, 1],
                      x_ticks_major=100., y_ticks_major=1.0,
                      y_grid_label=True, x_grid_label=True, padding=5,
                      x_grid=True, y_grid=True, xmin=0.0, xmax=self.tl.ts.L_x, ymin=0., ymax=self.max_displacement)
        self.reinf_disp_line = MeshLinePlot(color=[1, 1, 1, 1])
        self.reinf_disp_line.points = self.list_tuple(
            self.x_coord, np.zeros_like(self.x_coord))
        self.matrix_disp_line = MeshLinePlot(color=[1, 1, 1, 1])
        self.matrix_disp_line.points = self.list_tuple(
            self.x_coord, np.zeros_like(self.x_coord))
        self.slip_line = MeshLinePlot(color=[1, 1, 1, 1])
        self.slip_line.points = self.list_tuple(
            self.x_coord, np.zeros_like(self.x_coord))
        graph.add_plot(self.reinf_disp_line)
        graph.add_plot(self.matrix_disp_line)
        graph.add_plot(self.slip_line)
        return graph

    @staticmethod
    def list_tuple(xdata, ydata):
        '''convert the x and y data for line plot'''
        return list(map(tuple, np.vstack((xdata, ydata)).T))

    def on_touch_down(self, touch):
        print self.tl.U
        print self.tl.ts.n_e_x
        if self.collide_point(touch.x, touch.y):
            x0, y0 = self.graph._plot_area.pos  # position of the lower-left
            x0 += self.x
            y0 += self.y
#             print x0, y0
#             print touch.x, touch.y
#             print self.x, self.y
            gw, gh = self.graph._plot_area.size  # graph size
            x = (touch.x - x0) / gw * self.graph.xmax
            y = (touch.y - y0) / gh * self.graph.ymax
            # to check is the controller is selected
            x0, x1 = self.controller.xrange
            y0, y1 = self.controller.yrange
            if (x >= x0) * (x <= x1) * (y >= y0) * (y <= y1):
                self.selected = True

    def on_touch_up(self, touch):
        self.selected = False

    def on_touch_move(self, touch):
        if self.selected:
            if self.collide_point(touch.x, touch.y):
                # position of the lower-left
                x0, y0 = self.graph._plot_area.pos
                gw, gh = self.graph._plot_area.size  # graph size
                x = (touch.x - x0 - self.x) / gw * self.graph.xmax
                # make sure the controller doesn't enter the matrix
                x = max(x, 53.)
                x = min(x, 93.)
                if abs(x - self.x_current) >= 1:
                    d_u = (x - self.x_current) * self.max_displacement / 40.
                    self.tl.get_p(d_u)
                    self.x_current = x
    #                 print self.tl.U_record[-1]
    #                 print self.tl.F_record[-1]
                    self.f_u_line.points.append(
                        (self.tl.U_record[-1], self.tl.F_record[-1]))
                    self.eps_sig_line.points.append(
                        (self.tl.eps_record[-1], self.tl.sig_record[-1]))

                    U = np.reshape(self.tl.U, (-1, 2)).T
                    self.matrix_disp_line.points = self.list_tuple(
                        self.x_coord, U[0])
                    self.reinf_disp_line.points = self.list_tuple(
                        self.x_coord, U[1])
                    self.slip_line.points = self.list_tuple(
                        self.x_coord, U[1] - U[0])

                    shear_flow = self.tl.sig[:, :, 1].flatten()
                    self.shear_flow_line.points = self.list_tuple(
                        self.x_ip_coord, shear_flow)

                self.controller.xrange = [x - 3., x + 3.]
                self.reinf.xrange = [
                    min(10 + self.tl.U[1] * 40. / self.max_displacement, 30.), x - 3.]
Exemple #51
0
from math import sin
from kivy.garden.graph import Graph, MeshLinePlot
graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
x_ticks_major=25, y_ticks_major=1,
y_grid_label=True, x_grid_label=True, padding=5,
x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
plot = MeshLinePlot(color=[1, 0, 0, 1])
plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
graph.add_plot(plot)