예제 #1
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
예제 #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)
예제 #4
0
    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)
    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)
예제 #6
0
    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)
예제 #7
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
예제 #8
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
예제 #9
0
    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)
예제 #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
예제 #11
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
예제 #12
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))
예제 #13
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
예제 #14
0
	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
예제 #15
0
    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)
예제 #16
0
 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
예제 #17
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
예제 #18
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)
예제 #19
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
예제 #20
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)
예제 #21
0
파일: EAGraph.py 프로젝트: iverasp/it3708
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]))
예제 #22
0
class PsiScreen(Screen):
    graph = Graph(xlabel=' ',
                  ylabel='',
                  x_ticks_minor=5,
                  x_ticks_major=0,
                  y_ticks_major=10,
                  y_ticks_minor=2,
                  y_grid_label=True,
                  x_grid_label=False,
                  padding=5,
                  x_grid=True,
                  y_grid=True,
                  xmin=-0,
                  xmax=50,
                  ymin=0,
                  ymax=100,
                  label_options={
                      'color': [0, 1, 1, 1],
                      'bold': False
                  },
                  border_color=[0, 1, 1, .1],
                  tick_color=[1, 1, 1, 1])
    plot = LinePlot(color=[1, 0, 0, 1], line_width=1.5)
    plot.points = [(0, 0)]
    graph.add_plot(plot)
    clock = Clock

    def __init__(self, *args, **kwargs):
        super(PsiScreen, self).__init__(*args, **kwargs)
        self.ids["flt"].add_widget(self.graph)
예제 #23
0
파일: MTSPGraph.py 프로젝트: iverasp/it3708
    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)
예제 #24
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
예제 #25
0
    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)
예제 #26
0
 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 __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])
예제 #28
0
    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)
예제 #30
0
    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
예제 #31
0
 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
예제 #32
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)
예제 #33
0
    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)
예제 #34
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."
예제 #35
0
파일: line.py 프로젝트: simbtrix/debontrix
        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
예제 #36
0
 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)
예제 #37
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
예제 #38
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)
예제 #39
0
 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)
예제 #40
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
예제 #41
0
 def __init__(self, n=3, xmin=0, xmax=10, ymin=-1, ymax=1, xlabel='Time'):
     """
     n: number of graphs
     xmin: minimum x
     xmax: maximum x
     ymin: minimum y
     ymax: maximum y
     xlabel: label for x axis (time of freq)
     """
     super(Grapher, self).__init__(orientation='vertical')
     self.graph = []
     self.plots = []
     if xlabel == 'Time':
         self.plots.append(MeshLinePlot(color=[1, 0, 0, 1]))
         self.plots.append(MeshLinePlot(color=[0, 1, 0, 1]))
         self.plots.append(MeshLinePlot(color=[0, 0, 1, 1]))
     else:
         self.plots.append(MeshStemPlot(color=[1, 0, 0, 1]))
         self.plots.append(MeshStemPlot(color=[0, 1, 0, 1]))
         self.plots.append(MeshStemPlot(color=[0, 0, 1, 1]))
     self.reset_plots()
     for i in range(n):
         self.graph.append(
             Graph(xlabel=xlabel,
                   ylabel='Amp',
                   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=xmin,
                   xmax=xmax,
                   ymin=ymin,
                   ymax=ymax))
         self.graph[i].add_plot(self.plots[i])
         self.add_widget(self.graph[i])
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')
예제 #43
0
파일: MTSPGraph.py 프로젝트: iverasp/it3708
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)
예제 #44
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.]
예제 #45
0
class PowerMeterControl(TabbedPanel):
    fpower = StringProperty('0.0')
    power = NumericProperty(0.0)
    max_power = NumericProperty(0.0)
    voltage = NumericProperty(0)
    tick_color = ListProperty([0, 1, 0, 1])
    wavelength = BoundedNumericProperty(780.0,
                                        min=340.0,
                                        max=1180,
                                        errorhandler=lambda x: 1180
                                        if x > 1180 else 340)
    connected = BooleanProperty(False)
    logo = 'CQTtools_inverted.png'
    graph = Graph()

    plot = ObjectProperty(None)

    powermeter = None

    pm_range = 4

    iteration = 0

    dt = 0.25

    def update(self, dt):
        #adding by ChiHuan in v1.0. Averaging the reading.
        v = []
        average_v = 0
        for i in range(0, 50):
            v.append(float(self.powermeter.get_voltage()))
            average_v = np.mean(v)
        #self.voltage = float(self.powermeter.get_voltage())
        self.voltage = float(average_v)
        self.power = self.amp2power(self.voltage, self.wavelength,
                                    int(self.pm_range))
        self.fpower = self.formated_power()  #
        #self.power_max()
        self.plot.points.append((self.iteration * dt, self.power * 1000))
        #print self.plot.points
        self.iteration += 1 * dt
        if self.iteration > 150:
            self.iteration = 0
            self.plot.points = []
            self.ids.graph1.remove_plot(self.plot)

    def update_range(self, value):
        self.pm_range = value
        if self.connected == True:
            self.pm_range = value
            self.powermeter.set_range(int(self.pm_range))
            print self.pm_range
            return self.pm_range

    def connect_to_powermeter(self, connection):
        if not self.connected:
            if platform == 'android':  #to get access to serial port on android
                os.system(
                    "su -c chmod 777 " + connection
                )  #has to run as child otherwise will not work with all su binarys
            self.data = self._read_cal_file()
            self.powermeter = pm.pmcommunication(connection)
            Clock.schedule_interval(self.update, self.dt)
            self.connected = True
            self.update_range(self.pm_range)
            plot = MeshLinePlot(color=[0, 1, 0, 1])
            self.ids.graph1.add_plot(plot)
            self.plot = plot
            return self.powermeter

    def serial_ports_android(self):
        #Lists serial ports
        ports = glob.glob('/dev/ttyACM*')
        return ports
        """this section of the code deals with converting between the voltage value and the
    optical power at the wavelength of interest"""

    resistors = [1e6, 110e3, 10e3, 1e3,
                 20]  #sense resistors adjust to what is on the board

    file_name = 's5106_interpolated.cal'  #detector calibration file

    def _read_cal_file(self):  # read in calibration file for sensor
        f = open(self.file_name, 'r')
        x = json.load(f)
        f.close()
        return x

    def volt2amp(self, voltage, range_number):
        self.amp = voltage / self.resistors[range_number]
        return self.amp

    def amp2power(self, voltage, wavelength, range_number):
        amp = self.volt2amp(voltage, range_number - 1)
        xdata = self.data[0]
        ydata = self.data[1]
        i = xdata.index(int(wavelength))
        responsivity = ydata[i]
        power = amp / float(responsivity)
        return power

    def formated_power(self):
        power = self.amp2power(self.voltage, self.wavelength,
                               int(self.pm_range))
        fpower = power * 1000
        if 1 < fpower < 500:
            fpower = round(fpower, 2)
            out = str(fpower) + 'mW'
        elif 0.001 < fpower < 1:
            fpower = round(fpower * 1000, 2)
            out = str(fpower) + 'uW'
        elif 10e-6 < fpower < 0.001:
            fpower = round(fpower * 1e6, 2)
            out = str(fpower) + 'nW'
        elif fpower < 10e-6:
            out = 'Low'
        else:
            out = 'High'
        return out

    def power_max(self):
        if self.max_power < self.power:
            self.max_power = self.power
        return self.max_power
예제 #46
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'
        )
예제 #47
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)
예제 #48
0
    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
예제 #49
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
    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
예제 #51
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)
예제 #52
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)
예제 #53
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
예제 #54
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 )
예제 #55
0
파일: dash.py 프로젝트: x4rMa/Dash
class Performance(StackLayout):
    """
    This class contains the graphing application for the Kivy Dashboard
    Application. It accepts a buffer string from a socket connection
    established elsewhere in the software, then parses the data to be
    inserted into a graph"""
    graph = Graph(xlabel='Time', ylabel='', x_ticks_minor=5,
        x_ticks_major=100, y_ticks_major=12,
        y_grid_label=True, x_grid_label=True, padding=5,
        x_grid=True, y_grid=True, xmin=-0, xmax=300, ymin=0, ymax=120, size_hint=(1,.9))

    ## creates graph object to be accessed by updateUI function

    plot1 = MeshLinePlot(color=[1, 0, 0, 1])
    plot2 = MeshLinePlot(color=[0, 1, 0, 1])
    plot3 = MeshLinePlot(color=[0, 0, 1, 1])

    last_data = '0,0,0,0'
    ## creates the initial plot objects for the garden.graph function
    ## with defining color

    RPMbtn = ToggleButton(text='RPM', size_hint=(.33,.1))
    ENGbtn = ToggleButton(text='Engine Load', size_hint=(.33,.1))
    COTbtn = ToggleButton(text='Coolant Temp', size_hint=(.33,.1))

    RPMstate = 0
    ENGstate = 0
    COTstate = 0

    RPMlist = []
    while(len(RPMlist)<300):
        RPMlist.append(0)   
    
    ENGlist = []
    while(len(ENGlist)<300):
        ENGlist.append(0)

    COTlist = []
    while(len(COTlist)<300):
        COTlist.append(0)
    ## Creates three lists, of length 300, all initialized to zero
    ## The graph will build from this list, and if it is not initialized to
    ## zero beforehand, it will get an indexing error
    
    def __init__(self, **kwargs):
        """Creates the layout and widget tree for performance class"""
        super(Performance, self).__init__(**kwargs)
        self.add_widget(self.RPMbtn)
        self.add_widget(self.ENGbtn)
        self.add_widget(self.COTbtn)
        self.add_widget(self.graph)

        self.RPMbtn.bind(on_press = self.RPMplot)
        self.ENGbtn.bind(on_press = self.ENGplot)
        self.COTbtn.bind(on_press = self.COTplot)

        Clock.schedule_interval(self.updateUI, 1.0/10.0)
        ## pings the updateUI function ten times a second, giving
        ## the graph a framerate of 10fps

    def RPMplot(self, RPMbtn):
        """sets the state for the RPM button widget"""
        if (self.RPMstate == 0):
            self.RPMstate = 1
        else:
            self.RPMstate = 0
            
    def ENGplot(self, ENGbtn):
        """sets the state for the Engine Load button widget"""
        if (self.ENGstate == 0):
            self.ENGstate = 1
        else:
            self.ENGstate = 0
            
    def COTplot(self, COTbtn):
        """sets the state for the Coolant Temp button widget"""
        if (self.COTstate == 0):
            self.COTstate = 1
        else:
            self.COTstate = 0
        
    
    def updateUI(self, dt):
        """Updates the parameters of the graph.

        This function will remove redundant plots on the graph
        then receive new data from bluetooth socket.
        The data is broken up and placed on the graph
        depending on the state of the button widgets
        """
        try:
            self.graph.remove_plot(plot1)
        except:
            pass
        try:
            self.graph.remove_plot(plot2)
        except:
            pass
        try:
            self.graph.remove_plot(plot3)
        except:
            pass
        ## tries to remove the previously added plots to the graph
        ## this prevents ghosting on the graph itself
        
        # try:
        #     data = client_sock.recv(1024)

        #     if (len(data) < 1):
        #         data = self.last_data
        #     else:
        #         print data

        #     self.last_data = data

        ## Receive data as a string into 'data'. If the
        ## socket produces no information, as the vehicle will
        ## typically vary on how long between data is sent
        ## the data will either get '0,0,0,0' indicating no data
        ## has been sent yet, or it will use the last good data received
            
        # except IOError, NameError:
        #     data = last_data
            
        # if (client_sock == False):
        #     print "Socket Connection Lost"
            
        # values = data.split(',')

        ## data is split into
        
        self.RPMlist.insert(0, random.randint(60,80))
        if(len(self.RPMlist)>300):
             self.RPMlist = self.RPMlist[:300]
        
        self.ENGlist.insert(0, random.randint(20,40))
        if(len(self.ENGlist)>300):
             self.ENGlist = self.ENGlist[:300]
        
        self.COTlist.insert(0, random.randint(1,30))
        if(len(self.COTlist)>300):
             self.COTlist = self.COTlist[:300]
        
        # Used for testing random numbers in the graph
        
        
        # self.RPMlist.insert(0, int(values[1])/100)
        # if(len(self.RPMlist)>300):
        #     self.RPMlist = self.RPMlist[:300]

        # self.ENGlist.insert(0, int(values[2]))
        # if(len(self.ENGlist)>300):
        #     self.ENGlist = self.ENGlist[:300]

        # self.COTlist.insert(0, int(values[3]))
        # if(len(self.COTlist)>300):
        #     self.COTlist = self.COTlist[:300]

        ## The values (data) are inserted into their respective
        ## performance metric lists
        
		self.RPMbtn.text = str('RPM: ' + str(self.RPMlist[0]))
		self.ENGbtn.text = str('Engine Load: ' + str(self.ENGlist[0]))
		self.COTbtn.text = str('Coolant Temp: ' + str(self.COTlist[0]))
		
		## Used to place random numbers in graph for testing

        # self.RPMbtn.text = str('RPM: ' + values[1])
        # self.ENGbtn.text = str('Engine Load: ' + values[2])
        # self.COTbtn.text = str('Coolant Temp: ' + values[3])

        ## Updates the buttons on screen to the correct values

        self.RPMlist.reverse()
        self.ENGlist.reverse()
        self.COTlist.reverse()

        ## Reverses each list so that the graph is displayed as scrolling from
        ## the right, rather than the left

        if(self.RPMstate == 1):
            self.plot1.points = ((x, self.RPMlist[x]) for x in xrange(0,300))
            self.graph.add_plot(self.plot1)
        
        if(self.ENGstate == 1):
            self.plot2.points = ((x, self.ENGlist[x]) for x in xrange(0,300))
            self.graph.add_plot(self.plot2)
    
        if(self.COTstate == 1):
            self.plot3.points = ((x, self.COTlist[x]) for x in xrange(0,300))
            self.graph.add_plot(self.plot3)

        ## The App checks the state of the buttons, and updates the graph
        ## if the buttons are toggled
        
        self.RPMlist.reverse()
        self.ENGlist.reverse()
        self.COTlist.reverse()
예제 #56
0
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 "================="
    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)
예제 #58
0
class Chart(MDBoxLayout):
    volume_graph = Graph(xlabel='time',
                         ylabel='volume',
                         x_ticks_minor=1,
                         x_ticks_major=5,
                         y_ticks_major=1,
                         y_grid_label=True,
                         x_grid_label=True,
                         padding=5,
                         x_grid=True,
                         y_grid=True,
                         xmin=0,
                         xmax=50,
                         ymin=-1,
                         ymax=1)
    pressure_graph = Graph(xlabel='time',
                           ylabel='pressure',
                           x_ticks_minor=1,
                           x_ticks_major=5,
                           y_ticks_major=1,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=True,
                           y_grid=True,
                           xmin=0,
                           xmax=50,
                           ymin=-1,
                           ymax=1)
    flow_graph = Graph(xlabel='time',
                       ylabel='flow',
                       x_ticks_minor=1,
                       x_ticks_major=5,
                       y_ticks_major=1,
                       y_grid_label=True,
                       x_grid_label=True,
                       padding=5,
                       x_grid=True,
                       y_grid=True,
                       xmin=0,
                       xmax=50,
                       ymin=-1,
                       ymax=1)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.plot_pressure = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.plot_flow = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.plot_volume = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.data = {'time': [], 'pressure': [], 'flow': [], 'volume': []}
        threading.Thread(target=self.generate_data, daemon=True).start()
        self.start()

    def start(self):
        self.pressure_graph.add_plot(self.plot_pressure)
        self.flow_graph.add_plot(self.plot_flow)
        self.volume_graph.add_plot(self.plot_volume)
        self.add_widget(self.pressure_graph)
        self.add_widget(self.flow_graph)
        self.add_widget(self.volume_graph)
        Clock.schedule_interval(self.get_value, 0.05)

    def stop(self):
        Clock.unschedule(self.get_value)

    def get_value(self, dt):
        self.update_axis()
        self.plot_pressure.points = [(x, self.data['pressure'][i])
                                     for i, x in enumerate(self.data['time'])]
        self.plot_flow.points = [(x, self.data['flow'][i])
                                 for i, x in enumerate(self.data['time'])]
        self.plot_volume.points = [(x, self.data['volume'][i])
                                   for i, x in enumerate(self.data['time'])]

    def update_axis(self, *args):
        if len(self.data['time']) == NUMBEROFPOINTS:
            self.pressure_graph.xmin = self.data['time'][0]
            self.pressure_graph.xmax = self.data['time'][-1]
            self.flow_graph.xmin = self.data['time'][0]
            self.flow_graph.xmax = self.data['time'][-1]
            self.volume_graph.xmin = self.data['time'][0]
            self.volume_graph.xmax = self.data['time'][-1]

    def generate_data(self):
        x = -10
        while True:
            current_pressure_value = math.cos(x)
            current_flow_value = math.sin(x)
            current_volume_value = -math.cos(x)
            if len(self.data['time']) == NUMBEROFPOINTS:
                for data in self.data:  # deleting the first elements to keep the number of elements constant
                    del self.data[data][0]

            self.data['pressure'].append(current_pressure_value)
            self.data['flow'].append(current_flow_value)
            self.data['volume'].append(current_volume_value)
            self.data['time'].append(x)

            x += 1  # Incrementing the horizontal axis or the time axis
            time.sleep(.1)
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)
예제 #60
0
class Chart(MDBoxLayout):
    volume_graph = ObjectProperty(defaultvalue=Graph(xlabel='Time (s)',
                                                     ylabel='Volume (ml)',
                                                     x_ticks_minor=1,
                                                     x_ticks_major=1,
                                                     y_ticks_major=1,
                                                     y_grid_label=True,
                                                     x_grid_label=True,
                                                     padding=5,
                                                     xmin=0,
                                                     xmax=50,
                                                     ymin=VOLUME_Y_LIMITS[0],
                                                     ymax=VOLUME_Y_LIMITS[1]))
    pressure_graph = ObjectProperty(
        defaultvalue=Graph(xlabel='Time (s)',
                           ylabel='Pressure (cm H20)',
                           x_ticks_minor=1,
                           x_ticks_major=1,
                           y_ticks_major=1,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           xmin=0,
                           xmax=50,
                           ymin=PRESSURE_Y_LIMITS[0],
                           ymax=PRESSURE_Y_LIMITS[1]))
    flow_graph = ObjectProperty(defaultvalue=Graph(xlabel='Time (s)',
                                                   ylabel='Flow (l/min)',
                                                   x_ticks_minor=1,
                                                   x_ticks_major=1,
                                                   y_ticks_major=1,
                                                   y_grid_label=True,
                                                   x_grid_label=True,
                                                   padding=5,
                                                   xmin=0,
                                                   xmax=50,
                                                   ymin=FLOW_Y_LIMITS[0],
                                                   ymax=FLOW_Y_LIMITS[1]))

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.plot_pressure = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.plot_flow = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.plot_volume = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.data = {'time': [], 'pressure': [], 'flow': [], 'volume': []}
        threading.Thread(target=self.generate_data, daemon=True).start()
        self.start()

    def start(self):
        self.pressure_graph.add_plot(self.plot_pressure)
        self.flow_graph.add_plot(self.plot_flow)
        self.volume_graph.add_plot(self.plot_volume)
        self.add_widget(self.pressure_graph)
        self.add_widget(self.flow_graph)
        self.add_widget(self.volume_graph)
        # Clock.schedule_interval(self.get_value, 0.05)
        threading.Thread(target=self.get_value, args=(0.05, ),
                         daemon=True).start()

    def stop(self):
        Clock.unschedule(self.get_value)

    def get_value(self, delay=.05):
        while True:
            self.update_axis()
            self.plot_pressure.points = [
                (x, self.data['pressure'][i])
                for i, x in enumerate(self.data['time'])
            ]
            self.plot_flow.points = [(x, self.data['flow'][i])
                                     for i, x in enumerate(self.data['time'])]
            self.plot_volume.points = [(x, self.data['volume'][i])
                                       for i, x in enumerate(self.data['time'])
                                       ]

            # Make the program sleep before resuming the iteration
            time.sleep(delay)

    def update_axis(self, *args):
        # Modifying the x-axis
        if len(self.data['time']) == NUMBER_OF_POINTS:
            self.pressure_graph.xmin = self.data['time'][0]
            self.pressure_graph.xmax = self.data['time'][-1]
            self.flow_graph.xmin = self.data['time'][0]
            self.flow_graph.xmax = self.data['time'][-1]
            self.volume_graph.xmin = self.data['time'][0]
            self.volume_graph.xmax = self.data['time'][-1]

        # Modifying the y-axis
        if max(self.data['pressure']) >= PRESSURE_Y_LIMITS[1]:
            self.pressure_graph.ymax = max(self.data['pressure']) + 1
        if max(self.data['flow']) >= FLOW_Y_LIMITS[1]:
            self.flow_graph.ymax = max(self.data['flow']) + 1
        if max(self.data['volume']) >= VOLUME_Y_LIMITS[1]:
            self.volume_graph.ymax = max(self.data['volume']) + 1

    def generate_data(self):
        x = -10
        while True:
            if ((x - (x % 10)) / 10) % 2 == 0:
                current_pressure_value = self.triangular_wave(t=x,
                                                              period=2,
                                                              scale=1,
                                                              duty_cycle=.5)
                current_flow_value = self.triangular_wave(t=x,
                                                          period=2,
                                                          scale=1,
                                                          duty_cycle=.2)
                current_volume_value = self.triangular_wave(t=x,
                                                            period=2,
                                                            scale=4,
                                                            duty_cycle=.6)
            else:
                current_pressure_value = self.triangular_wave(t=x,
                                                              period=2,
                                                              scale=1,
                                                              duty_cycle=.5)
                current_flow_value = self.triangular_wave(t=x,
                                                          period=2,
                                                          scale=2,
                                                          duty_cycle=.2)
                current_volume_value = self.triangular_wave(t=x,
                                                            period=2,
                                                            scale=1,
                                                            duty_cycle=.6)
            if len(self.data['time']) == NUMBER_OF_POINTS:
                for data in self.data:  # deleting the first elements to keep the number of elements constant
                    del self.data[data][0]

            self.data['pressure'].append(current_pressure_value)
            self.data['flow'].append(current_flow_value)
            self.data['volume'].append(current_volume_value)
            self.data['time'].append(x)

            x += .2  # Incrementing the horizontal axis or the time axis
            time.sleep(.1)

    @staticmethod
    def triangular_wave(t, period, scale=1, duty_cycle=.5):
        actual_time = t % period
        if actual_time <= duty_cycle * period:
            return scale * actual_time
        else:
            return 0