Esempio n. 1
0
class ScreenRace:

    sogMemory = 30  # seconds
    sogHistory = []

    def __init__(self, gui=None):
        if gui == None:
            print("ScreenRace __init__ with gui == None - need to set it up!")
        else:
            self.gui = gui

        self.th = TimeHelper()

    def setGui(self, gui):
        self.gui = gui

    def setupGui(self):
        self.sogG = Graph(
            ymax=1.0,
            ymin=-1.0,
        )
        self.sogP = MeshLinePlot(color=[1, 1, 0, 1])
        self.sogG.add_plot(self.sogP)
        self.gui.rl.ids.flRace.add_widget(self.sogG)

    def on_settings(self, o=None):
        print("on_settings")

    def update(self, fromWho, vals):
        #print("sogUpdate" ,fromWho, vals)
        self.sogHistory.append(vals['speed'])
Esempio n. 2
0
    def create_graph(self, dates):
        if len(dates) > 0:
            graph = Graph(x_ticks_minor=5,
                          y_ticks_minor=5,
                          x_ticks_major=5,
                          y_ticks_major=5,
                          y_grid_label=True,
                          x_grid_label=True,
                          padding=5,
                          border_color=[0, 0, 0, 0],
                          font_size=8,
                          xmin=0,
                          xmax=calendar.monthrange(dates[0].year,
                                                   dates[0].month)[1],
                          ymin=int(min([x.weight for x in dates]) - 5),
                          ymax=int(max([x.weight for x in dates]) + 5))
        else:
            graph = Graph(x_ticks_minor=5,
                          y_ticks_minor=5,
                          x_ticks_major=5,
                          y_ticks_major=5,
                          y_grid_label=True,
                          x_grid_label=True,
                          padding=5,
                          border_color=[0, 0, 0, 0],
                          font_size=8,
                          xmin=0,
                          ymin=0)

        plot = SmoothLinePlot(color=[1, 105 / 255, 97 / 255, 1])
        plot.points = [(x.day, float(x.weight)) for x in dates]
        graph.add_plot(plot)

        return graph
Esempio n. 3
0
class LiveView(Widget):
    def __init__(self, **kwargs):
        super().__init__()
        self.graph = Graph(x_ticks_minor=4,
                           x_ticks_major=16,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=True,
                           y_grid=True,
                           xmin=-0,
                           xmax=SAMPLES,
                           ymin=0,
                           **kwargs)
        self.plot = MeshLinePlot(color=[1, 1, 0, 1])
        self.plot.points = [(x, 0) for x in range(0, SAMPLES + 1)]
        self.graph.add_plot(self.plot)
        self.total_plot = MeshLinePlot(color=[0, 1, 1, 1])
        self.total_plot.points = [(x, 0) for x in range(0, SAMPLES + 1)]
        self.graph.add_plot(self.total_plot)

        self.values = collections.defaultdict(
            lambda: [0 for x in range(0, SAMPLES + 1)])

    def update(self, sender, date, value):
        self.values[sender][date] = value
        total = [self.values[sender][date] for sender in self.values.keys()]

        self.plot.points[date] = (date, value)
        self.total_plot.points[date] = (date, sum(total))
Esempio n. 4
0
    def create_graph(self):
        colors = itertools.cycle([
            rgb('7dac9f'), rgb('dc7062'), rgb('66a8d4'), rgb('e5b060')
        ])
        graph_theme = {
            'label_options': {
                'color': (0, 0, 0, 1),
                'bold': False},
            'background_color': (.9, .9, .9, 1),
            'tick_color': rgb('808080'),
            'border_color': rgb('808080')
        }
        graph = Graph(xlabel='',
                      ylabel='Glicemia',
                      font_size=14,
                      x_ticks_minor=0,
                      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_theme)

        #plot = MeshLinePlot(color=[1, 0, 0, 1])
        plot = MeshLinePlot(color=next(colors))
        plot.points = [(x, sin(x/10.)) for x in range(0, 101)]
        graph.add_plot(plot)
        return graph
Esempio n. 5
0
def make_plot(plot_price,
              plot_dates,
              tickers_on_plot,
              plot_colors,
              xlabel='Bitcoin'):
    x = list(range(1, (len(plot_price) + 1)))
    y = plot_price
    y_axis_ticks = (max(y) - min(y)) / 5
    plot = None
    graph = Graph(xlabel=xlabel,
                  x_ticks_major=1,
                  y_ticks_major=y_axis_ticks,
                  y_grid_label=True,
                  x_grid_label=True,
                  padding=10,
                  x_grid=False,
                  y_grid=False,
                  xmin=min(x),
                  xmax=max(x),
                  ymin=min(y),
                  ymax=max(y))

    for i in range(0, len(tickers_on_plot)):
        plot = MeshLinePlot(color=plot_colors[i])
        plot.points = [(i, j) for i, j in zip(x, (y))]
        graph.add_plot(plot)
    return graph
def make_plot(ratings_list, plot_dates, plot_tickers, plot_colors):
    # Prepare the data
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    # make the graph
    graph = Graph(ylabel='Ratings',
                  x_ticks_major=1,
                  y_ticks_minor=1,
                  y_ticks_major=1,
                  y_grid_label=True,
                  x_grid_label=False,
                  padding=5,
                  x_grid=True,
                  y_grid=True,
                  xmin=0,
                  xmax=10,
                  ymin=0,
                  ymax=10)

    if (len(plot_tickers) > 0):
        i = 0
        while (i < len(plot_tickers)):
            plot = MeshLinePlot(color=plot_colors[i])
            plot.points = [(i, j) for i, j in zip(x, ratings_list[i])]

            graph.add_plot(plot)
            i += 1

    return graph
Esempio n. 7
0
 def build(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)
     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
Esempio n. 8
0
    def rainGraph(self):
        rainY = []
        for i in range(len(self.fileData) - 19, len(self.fileData)):
            rainY.append(str(math.floor((float(self.fileData[i][8])))))
        plot = None
        graph = Graph(size_hint = (0.5,0.8), pos_hint = {'x': .24, 'y': 0}, ylabel='Rain Events', xlabel='Time', x_ticks_major=1, y_ticks_minor=1,
                      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=50, background_color = [1,1,1,.2])

        plot = MeshLinePlot(color=[.5, 0, .5, 1])
        plot.points = [(int(i), int(rainY[i])) for i in range(0, 19)]
        graph.add_plot(plot)

        return graph
Esempio n. 9
0
    def humidGraph(self):
        humidY = []

        for i in range(len(self.fileData) - 19, len(self.fileData)):
            humidY.append(str(math.floor((float(self.fileData[i][4])))))

        humidityPlot = None
        humidityGraph = Graph(size_hint = (0.5,0.8), pos_hint = {'x': .24, 'y': 0}, ylabel='% Humidity', xlabel='Time', x_ticks_major=1, y_ticks_minor=1, 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=100, background_color = [1,1,1,.2])

        humidityPlot = MeshLinePlot(color=[.5,0 ,.5, 1])
        humidityPlot.points = [(int(i), int(humidY[i])) for i in range(0, 19)]
        humidityGraph.add_plot(humidityPlot)

        return humidityGraph
Esempio n. 10
0
class linechart():
    def __init__(self, ticker):
        self.CurrentPrice = 100
        self.ticker = ticker
        self.cryptos = []
        self.yticks = 100

        self.xticks = 10
        self.xmax = 50
        self.chart = Graph(
            xlabel='Time',
            ylabel='Price',
            x_ticks_minor=0,
            x_ticks_major=self.xticks,
            y_ticks_major=self.yticks,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            x_grid=True,
            y_grid=True,
            xmin=0,
            xmax=self.xmax,
            ymin=0,
        )

        self.plot = SmoothLinePlot(color=[1, 1, 1, 1])
        self.chart.add_plot(self.plot)

    def update(self, data):

        #sizing graph adding upper buffer
        self.chart.ymax = round((data['ymax'] + data['ymax'] / 4) / 10) * 10
        self.chart.ymin = round((data['ymin'] - data['ymin'] / 4) / 10) * 10
        #sizing xmax
        self.xmax = len(data['plot'])

        self.plots = data['plot']
        self.CurrentPrice = data['CurrentPrice']

        self.yticks = (self.chart.ymax - self.chart.ymin) / 4
        self.chart.y_ticks_major = self.yticks
        self.plot.points = self.plots
        self.xmax = len(self.plot.points) - 1
        self.chart.xmax = self.xmax

    def Get_graph(self):
        return self.chart
Esempio n. 11
0
    def tempGraph(self):

        tempY =[]

        for i in range(len(self.fileData) - 19, len(self.fileData)):
            tempY.append(str(math.floor((float(self.fileData[i][6])))))

        plot = None
        graph = Graph(size_hint = (.5,.8), ylabel='Outside Temperature (C)', xlabel = 'Time', x_ticks_major = 1, y_ticks_minor = 1, 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=-10, ymax=50, pos_hint = {'x': .24, 'y': .2}, background_color = [1,1,1,.2])

        plot = MeshLinePlot(color = [1,1,1,1])

        plot.points = [(int(i), int(tempY[i])) for i in range(0, 19)]
        graph.add_plot(plot)
        return graph
Esempio n. 12
0
def all_graph(Shear_list, length, position, label):
    datapoints = np.arange(0, length, 0.01)
    point_data_list = []
    multiplier = 1
    if label == "Bending moment (kNm)" or label == "Deflection (1/EI)" or 'Axial Stress (kN)':
        multiplier = -1
    ymax = 0
    ymin = 0
    min_y = 0
    max_y = 0
    for i in range(len(datapoints)):
        point_data = 0
        for all in Shear_list:
            point_data += all.calculate(datapoints[i])*multiplier
        if point_data + abs(point_data / 5) > ymax:
            ymax = point_data + abs(point_data / 5)
        elif ymin > point_data - abs(point_data / 5):
            ymin = point_data - abs(point_data / 5)
        point_data_list.append((datapoints[i], point_data))
        if i == 0:
            max_y = point_data
            min_y = point_data
        else:
            max_y = max(point_data, max_y)
            min_y = min(point_data, min_y)
    ymax = int(round(ymax, 0))
    ymin = int(round(ymin, 0))
    max_y = round(max_y, 3)
    min_y = round(min_y, 3)
    if ymax == 0:
        ymax = 1
    if ymin == 0:
        ymin = -1
    graph = Graph(pos_hint=position, size_hint=(0.7, 0.9), xlabel='Position', ylabel=label, x_ticks_minor=5,
                  x_ticks_major=length / 10, x_grid_label=True, y_grid_label=True, y_ticks_major=(ymax-ymin)/5,
                  y_ticks_minor=5, padding=5, x_grid=True, y_grid=True, xmax=length, xmin=0, ymin=ymin, ymax=ymax)
    plot = MeshLinePlot()
    plot.points = point_data_list
    graph.add_plot(plot)
    return graph, [min_y, max_y]
Esempio n. 13
0
class MainScreen(FloatLayout):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.thread = None
        self.started = False
        self.ie_val = 2
        self.av_val = 200
        self.rr_val = 20
        self.mainlabel = Label(text="DEX-IC smart vent",
                               font_size=60,
                               size_hint=(1, 0.2),
                               pos_hint={
                                   'x': 0,
                                   'y': 0.8
                               })
        self.githublabel = Label(text="github.com/VPetras/dexic-hackathon",
                                 font_size=25,
                                 size_hint=(1.6, 0.1),
                                 pos_hint={
                                     'x': 0.08,
                                     'y': 0
                                 })
        self.button = Button(text='Start',
                             font_size=30,
                             size_hint=(0.3, 0.1),
                             pos_hint={
                                 'x': 0.35,
                                 'y': 0.01
                             })
        self.button.bind(on_press=self.stop_btn)
        self.add_widget(self.mainlabel)
        self.add_widget(self.githublabel)
        self.add_widget(self.button)
        #self.button.disabled=True

        self.dex = Image(source="dex-logo.jpg",
                         size_hint=(0.15, 0.15),
                         pos_hint={
                             'x': 0.16,
                             'y': 0.05
                         })
        self.add_widget(self.dex)
        self.eit = Image(source="EIT-Health.jpg",
                         size_hint=(0.15, 0.15),
                         pos_hint={
                             'x': 0.01,
                             'y': 0.05
                         })
        self.add_widget(self.eit)

        self.ier_button = Button(text="IE / R = 1:{}".format(self.ie_val),
                                 font_size=30,
                                 size_hint=(0.15, 0.1),
                                 pos_hint={
                                     'x': 0.01,
                                     'y': 0.75
                                 })
        self.add_widget(self.ier_button)
        self.ier_p_button = Button(text='+',
                                   font_size=30,
                                   size_hint=(0.075, 0.05),
                                   pos_hint={
                                       'x': 0.085,
                                       'y': 0.68
                                   })
        self.ier_p_button.bind(on_press=self.ie_p)
        self.add_widget(self.ier_p_button)
        self.ier_m_button = Button(text='-',
                                   font_size=30,
                                   size_hint=(0.075, 0.05),
                                   pos_hint={
                                       'x': 0.01,
                                       'y': 0.68
                                   })
        self.ier_m_button.bind(on_press=self.ie_m)
        self.add_widget(self.ier_m_button)

        self.av_button = Button(text="A V = {}".format(self.av_val),
                                font_size=30,
                                size_hint=(0.15, 0.1),
                                pos_hint={
                                    'x': 0.01,
                                    'y': 0.55
                                })
        self.add_widget(self.av_button)
        self.av_p_button = Button(text='+',
                                  font_size=30,
                                  size_hint=(0.075, 0.05),
                                  pos_hint={
                                      'x': 0.085,
                                      'y': 0.48
                                  })
        self.av_p_button.bind(on_press=self.av_p)
        self.add_widget(self.av_p_button)
        self.av_m_button = Button(text='-',
                                  font_size=30,
                                  size_hint=(0.075, 0.05),
                                  pos_hint={
                                      'x': 0.01,
                                      'y': 0.48
                                  })
        self.av_m_button.bind(on_press=self.av_m)
        self.add_widget(self.av_m_button)

        self.rr_button = Button(text="R / R = {}".format(self.rr_val),
                                font_size=30,
                                size_hint=(0.15, 0.1),
                                pos_hint={
                                    'x': 0.01,
                                    'y': 0.35
                                })
        self.add_widget(self.rr_button)
        self.rr_p_button = Button(text='+',
                                  font_size=30,
                                  size_hint=(0.075, 0.05),
                                  pos_hint={
                                      'x': 0.085,
                                      'y': 0.28
                                  })
        self.rr_p_button.bind(on_press=self.rr_p)
        self.add_widget(self.rr_p_button)
        self.rr_m_button = Button(text='-',
                                  font_size=30,
                                  size_hint=(0.075, 0.05),
                                  pos_hint={
                                      'x': 0.01,
                                      'y': 0.28
                                  })
        self.rr_m_button.bind(on_press=self.rr_m)
        self.add_widget(self.rr_m_button)

        self.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=10,
                           xlog=False,
                           ylog=False,
                           x_grid=False,
                           y_grid=False,
                           ymin=0,
                           ymax=200,
                           size_hint=(0.7, 0.5),
                           pos_hint={
                               'x': 0.25,
                               'y': 0.3
                           })
        self.plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1])
        values = [0]
        self.plot.points = [(x, values[x]) for x in range(-0, len(values))]
        self.graph.add_plot(self.plot)
        self.add_widget(self.graph)

    def stop_btn(self, x):
        if self.started:
            self.button.text = "Start"
            self.started = False
        else:
            self.button.text = "Stop"
            self.started = True

    def ie_p(self, x):
        if self.ie_val + 0.1 < 3.1:
            self.ie_val += 0.1
            self.ier_button.text = "IE / R = 1:{:.1f}".format(self.ie_val)

    def ie_m(self, x):
        if self.ie_val - 0.1 > 0.9:
            self.ie_val -= 0.1
            self.ier_button.text = "IE / R = 1:{:.1f}".format(self.ie_val)

    def av_p(self, x):
        if self.av_val + 50 < 850:
            self.av_val += 50
            self.av_button.text = "A V = {}".format(self.av_val)

    def av_m(self, x):
        if self.av_val - 50 > 150:
            self.av_val -= 50
            self.av_button.text = "A V = {}".format(self.av_val)

    def rr_p(self, x):
        if self.rr_val + 1 < 41:
            self.rr_val += 1
            self.rr_button.text = "R / R = {}".format(self.rr_val)

    def rr_m(self, x):
        if self.rr_val - 1 > 5:
            self.rr_val -= 1
            self.rr_button.text = "R / R = {}".format(self.rr_val)

    def update_graph(self, *args):
        print("update graph")
        #log = open('test.log','a')
        try:
            headers = {'content-type': 'application/json'}
            r = requests.get('http://0.0.0.0:8000/update')
            #log.write(str(r) + "\n")
            print(r.text)
            values = json.loads(r.text)
            print(values)
            self.graph.xmax = len(values)
            self.plot.points = [(x, values[x]) for x in range(-0, len(values))]
        except Exception as e:
            print(e)
Esempio n. 14
0
class AircraftLoadLayout(GridLayout):
    def __init__(self, aircraft_config, **kwargs):
        super(AircraftLoadLayout, self).__init__(**kwargs)
        self.cols = 1
        self.cfg = load_aircraft_config(aircraft_config)
        self.loads = create_loads_list(self.cfg)

        acft = self.cfg.aircraft
        self.lbl_info = Label(text="%s (%s)" % (acft.designation, acft.immat))
        self.add_widget(self.lbl_info)

        self.sliders = SlidersLayout(self.cfg, self.loads)
        self.add_widget(self.sliders)

        self.lbl_center_gravity = Label(text="")
        self.add_widget(self.lbl_center_gravity)

        self.graph = Graph(
            xlabel="X",
            ylabel="mass",
            # x_ticks_minor=0.05, x_ticks_major=0.5,
            # y_ticks_major=100, # y_ticks_minor=20,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            x_grid=True,
            y_grid=True,
            xmin=0.7,
            xmax=1.1,
            ymin=0,
            ymax=1000,
        )
        self.mesh_line_plot = MeshLinePlot(color=[0, 0, 1, 1])
        self.graph.add_plot(self.mesh_line_plot)

        self.add_widget(self.graph)

        self.btn_toggle = ToggleButton(
            text="lever arm / moment",
            group="xaxis",
        )
        self.btn_toggle.bind(on_press=self.on_touch_move)
        self.add_widget(self.btn_toggle)

        # point = Point(0.8, 400)
        # plot = ScatterPlot(color=(1,0,0,1), pointsize=5)
        self.scatter_plot = ScatterPlot(color=[1, 0, 0, 1], point_size=5)
        # plot.points.append((0.8, 400))
        self.graph.add_plot(self.scatter_plot)

        self.update_label_plot()

    def on_touch_move(self, touch):
        # print("AircraftLoadLayout.on_touch_move")
        self.sliders.update()
        self.update_label_plot()

    def update_label_plot(self):
        G = calculate_cg(self.cfg, self.loads)

        if self.btn_toggle.state == "normal":
            self.graph.xlabel = "lever_arm"
            self.scatter_plot.points = [(G.lever_arm, G.mass)]
            self.mesh_line_plot.points = [(pt.lever_arm, pt.mass)
                                          for pt in self.cfg.centrogram]
        else:
            self.graph.xlabel = "moment"
            self.scatter_plot.points = [(G.moment, G.mass)]
            self.mesh_line_plot.points = [(pt.moment, pt.mass)
                                          for pt in self.cfg.centrogram]
        self.mesh_line_plot.points.append(self.mesh_line_plot.points[0])
        delta_x_pc, delta_y_pc = 0.05, 0.05
        self.graph.xmin = min(
            x[0] for x in self.mesh_line_plot.points) * (1 - delta_x_pc)
        self.graph.xmax = max(
            x[0] for x in self.mesh_line_plot.points) * (1 + delta_x_pc)
        self.graph.ymin = min(
            x[1] for x in self.mesh_line_plot.points) * (1 - delta_x_pc)
        self.graph.ymax = max(
            x[1] for x in self.mesh_line_plot.points) * (1 + delta_x_pc)
        is_inside_centrogram = inside_centrogram(G, self.cfg.centrogram)
        self.lbl_center_gravity.text = (
            "G: (mass=%.1f kg, lever_arm=%.3f m, moment=%.1f kg.m)" %
            (G.mass, G.lever_arm, G.moment))
        if is_inside_centrogram:
            self.lbl_center_gravity.disabled = False
            self.lbl_center_gravity.color = (0, 1, 0, 1)
            self.mesh_line_plot.color = (0, 0, 1, 1)
        else:
            self.lbl_center_gravity.disabled = True
            self.lbl_center_gravity.color = (1, 0, 0, 1)
            self.mesh_line_plot.color = (1, 0, 0, 1)
Esempio n. 15
0
class Screen2(Screen):

    graph_id = ObjectProperty()
    titre = StringProperty("Capteur")
    # Affichage sur le bouton au dessus du graphique
    period = StringProperty("Période")

    def __init__(self, **kwargs):
        """self.graph ne peut pas être initié ici.
        Il doit être dans une autre méthode et appelé plus tard.
        """

        super().__init__(**kwargs)
        self.app = App.get_running_app()

        self.unit_x = "tutu"
        self.unit_y = "tata"
        self.graph = None
        self.y_major = 1
        self.titre = "Accelerometer"
        self.reset = None
        self.xlabel = ""

        # Initialisation de la courbe avec sa couleur
        # mode='points',
        self.curve_plot = MeshLinePlot(mode='points', color=[1, 0, 0, 1])
        # #self.curve_plot.mode = 'triangle_strip'
        self.curve_plot.points = [(0, 0)] * 101

        # Appel tous les 2 secondes
        Clock.schedule_interval(self.update, 2)

    def graph_init(self):
        """Initialisation de self.graph.
        plot initié avec 100 couples [(x, y), ...]
        """

        print("Initialisation du graph")
        # ## Si existe je détruits
        if self.graph:
            self.ids.graph_id.remove_widget(self.graph)
            print("self.graph détruit")

        if self.y_major:  # int
            if len(self.app.osc.histo) > 5:
                self.create_graph()
            else:
                self.reset = 1

    def create_graph(self):
        """Création du graph seul et pas d'ajout au widget"""

        print("Appel de la création du graph ..")
        self.unit_x = "minutes"

        # Paramètres du graph en x
        self.xmin = 0
        self.xmax = 1000
        self.x_ticks_major = 3600
        self.x_ticks_minor = 600

        # Paramètres du graph en y
        self.ymin = 0
        self.ymax = self.y_major
        self.ylabel = self.unit_y
        self.y_ticks_major = self.y_major / 10
        self.y_ticks_minor = 0  #5

        # Je crée ou recrée
        self.graph = Graph(background_color=(0.8, 0.8, 0.8, 1),
                           border_color=(0, 0.1, 0.1, 1),
                           xlabel=self.xlabel,
                           ylabel=self.ylabel,
                           x_ticks_minor=self.x_ticks_minor,
                           x_ticks_major=self.x_ticks_major,
                           y_ticks_major=self.y_ticks_major,
                           x_grid_label=True,
                           y_grid_label=True,
                           padding=10,
                           view_pos=(10, -10),
                           x_grid=True,
                           y_grid=True,
                           xmin=self.xmin,
                           xmax=self.xmax,
                           ymin=self.ymin,
                           ymax=self.ymax,
                           tick_color=(1, 0, 1, 1),
                           label_options={'color': (0.2, 0.2, 0.2, 1)})

        self.graph.add_plot(self.curve_plot)
        self.ids.graph_id.add_widget(self.graph)

    def update(self, dt):
        if self.reset:
            self.reset = None
            self.y_major = 0
            self.graph_init()
        else:
            if not self.graph:
                self.graph_init()

        # Reset des points
        self.curve_plot.points = []

        # Echelle des y
        y_major = self.get_y_major()
        if y_major != self.y_major:
            self.y_major = y_major
            # reset du graph
            # #self.graph_init()

        # Apply value to plot
        for h in self.app.osc.histo:
            self.curve_plot.points.append([h[0], h[1]])

        # #self.curve_plot.update()

    def get_y_major(self):
        """Le maxi de l'echelle des y"""

        # Recherche du maxi
        maxi = 0
        for couple in self.app.osc.histo:
            # #print(couple)
            if couple[1] > maxi:
                maxi = couple[1]

        # Définition de l'échelle sur y soit 0 à y_major
        if 1 <= maxi < 10:
            a = 1
        elif 10 <= maxi < 100:
            a = 10
        elif 100 <= maxi < 1000:
            a = 100
        elif 1000 <= maxi < 10000:
            a = 1000
        elif 10000 <= maxi < 100000:
            a = 10000
        else:
            a = 1
        # 756 --> 800 int(756/100) + 1 * 1000
        if maxi < 0:
            y_major = 1
        else:
            y_major = (int(maxi * 1.1 / a) + 1) * a

        # #print("maxi:", maxi, "y_major", y_major)
        return y_major
Esempio n. 16
0
class ThirdWindow(Screen):
    def __init__(self, **kwargs):
        super(ThirdWindow, self).__init__(**kwargs)
        Clock.schedule_once(self.yap, 0)

    def yap(self, za):
        box = self.ids.deneme
        graph_theme = {
            'label_options': {
                'color': rgb('444444'),  # color of tick labels and titles
                'bold': True
            },
            'background_color': rgb('2b2b2b'),  # canvas background color
            'tick_color': rgb('7ba21d'),  # ticks and grid
            'border_color': rgb('000000')
        }  # border drawn around each graph
        self.graph = Graph(
            xlabel='Time (s)',
            ylabel='Temparature (°F)',
            x_ticks_major=10,
            y_ticks_major=10,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            #xmin=0,
            #ymin=0,
            **graph_theme)
        box.add_widget(self.graph)
        self.plot = LinePlot(line_width=2, color=[0.48, 0.63, 0.11, 1])
        self.graph.add_plot(self.plot)
        self.salise = 0
        self.saniye = 0
        self.dakika = 0
        self.values = []

    def start(self):
        self.tan = Clock.schedule_interval(self.arttirici, 0.5)
        self.zam = Clock.schedule_interval(self.zamanlayici, 0.1)

    def stop(self):
        if self.tan:
            Clock.unschedule(self.tan)
        self.ids.current_temp.text = ""
        self.ids.slider_temp.value = 0
        self.ids.slider_fan.value = 0
        self.salise = 0
        self.saniye = 0
        self.dakika = 0
        self.graph.remove_plot(self.plot)
        self.etiketteGoster()
        if self.zam:
            Clock.unschedule(self.zam)

    def zamanlayici(self, za):
        self.salise += 1
        if self.salise == 10:
            self.salise = 0
            self.saniye += 1
        if self.saniye == 60:
            self.saniye = 0
            self.dakika += 1
        self.etiketteGoster()

    def etiketteGoster(self):

        self.ids.etiket.text = "%s:%s:%s" % (self.dakika, str(
            self.saniye).zfill(2), str(self.salise).zfill(2))

    def arttirici(self, za):
        derece = self.ids.slider_temp.value
        fan_deger = self.ids.slider_fan.value
        self.son_deger = derece - fan_deger / 2
        if len(self.values) >= 100:
            self.values = []
        self.values.append(self.son_deger)
        self.ids.current_temp.text = "%.2f" % self.son_deger
        self.plot.points = [(i, j) for i, j in enumerate(self.values)]
Esempio n. 17
0
    def on_start(self):
        self.animate_background()
        self.animate_card()
        counter = 0

        wall_user_options = {
            "checkerboard-plus": "Add New Problem",
            "cloud-download-outline": "Load Problem",
            "engine-outline": "Generate Problem",
            "new-box": "Reset Wall",
            "home-lightbulb": "Show Problem",
        }

        wall_ids = {
            1: "A11",
            2: "B11",
            3: "C11",
            4: "D11",
            5: "E11",
            6: "F11",
            7: "G11",
            8: "H11",
            9: "I11",
            10: "J11",
            11: "K11",
            13: "A10",
            14: "B10",
            15: "C10",
            16: "D10",
            17: "E10",
            18: "F10",
            19: "G10",
            20: "H10",
            21: "I10",
            22: "J10",
            23: "K10",
            25: "A9",
            26: "B9",
            27: "C9",
            28: "D9",
            29: "E9",
            30: "F9",
            31: "G9",
            32: "H9",
            33: "I9",
            34: "J9",
            35: "K9",
            37: "A8",
            38: "B8",
            39: "C8",
            40: "D8",
            41: "E8",
            42: "F8",
            43: "G8",
            44: "H8",
            45: "I8",
            46: "J8",
            47: "K8",
            49: "A7",
            50: "B7",
            51: "C7",
            52: "D7",
            53: "E7",
            54: "F7",
            55: "G7",
            56: "H7",
            57: "I7",
            58: "J7",
            59: "K7",
            61: "A6",
            62: "B6",
            63: "C6",
            64: "D6",
            65: "E6",
            66: "F6",
            67: "G6",
            68: "H6",
            69: "I6",
            70: "J6",
            71: "K6",
            73: "A5",
            74: "B5",
            75: "C5",
            76: "D5",
            77: "E5",
            78: "F5",
            79: "G5",
            80: "H5",
            81: "I5",
            82: "J5",
            83: "K5",
            85: "A4",
            86: "B4",
            87: "C4",
            88: "D4",
            89: "E4",
            90: "F4",
            91: "G4",
            92: "H4",
            93: "I4",
            94: "J4",
            95: "K4",
            97: "A3",
            98: "B3",
            99: "C3",
            100: "D3",
            101: "E3",
            102: "F3",
            103: "G3",
            104: "H3",
            105: "I3",
            106: "J3",
            107: "K3",
            109: "A2",
            110: "B2",
            111: "C2",
            112: "D2",
            113: "E2",
            114: "F2",
            115: "G2",
            116: "H2",
            117: "I2",
            118: "J2",
            119: "K2",
            121: "A1",
            122: "B1",
            123: "C1",
            124: "D1",
            125: "E1",
            126: "F1",
            127: "G1",
            128: "H1",
            129: "I1",
            130: "J1",
            131: "K1",
        }
        """ Fill Side Menu with items START"""
        for icon_name in wall_user_options.keys():
            self.root.ids.content_drawer.ids.md_list.add_widget(
                ItemDrawer(icon=icon_name, text=wall_user_options[icon_name]))
            """ serves as a seperator for two itemdrawers"""
        self.root.ids.content_drawer.ids.md_list.add_widget(
            OneLineListItem(text=""))
        """ Adds logout option in the drawer menu"""
        self.root.ids.content_drawer.ids.md_list.add_widget(
            ItemDrawer(icon="logout", text="Sign Out"))
        """ Fill Side Menu with items END"""
        """ Fill ClimbingGrid with holds START"""

        for i in range(0, 132):
            if i % 12 == 0 or i == 0:
                self.root.ids.wall_system.add_widget(
                    MDLabel(text=str(11 - counter),
                            halign="center",
                            size_hint_x=None,
                            width=25,
                            theme_text_color="Custom",
                            text_color=(1, 1, 1, 1),
                            font_style="H6",
                            font_name="JetBrainsMono"))
                counter = counter + 1
            else:
                self.root.ids.wall_system.add_widget(
                    HoldLayout(id=wall_ids[i]))
        """Draw GRAPH"""

        graph = Graph(xlabel='X',
                      ylabel='Y',
                      x_ticks_minor=5,
                      x_ticks_major=25,
                      y_ticks_major=1,
                      y_grid_label=True,
                      x_grid_label=True,
                      padding=5,
                      x_grid=True,
                      y_grid=True,
                      xmin=-0,
                      xmax=100,
                      ymin=-1,
                      ymax=1)
        plot = MeshLinePlot(color=[1, 0, 0, 1])
        plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
        graph.add_plot(plot)
        self.root.ids.screen_three.add_widget(graph)
        self.initiate_problem_list()
        """ Fill ClimbingGrid with holds END"""
Esempio n. 18
0
class Screen2(Screen):

    graph_id = ObjectProperty()
    titre = StringProperty("Capteur")
    # Affichage sur le bouton au dessus du graphique
    period = StringProperty("Période")

    def __init__(self, **kwargs):
        """self.graph ne peut pas être initié ici.
        Il doit être dans une autre méthode et appelé plus tard.
        """

        super().__init__(**kwargs)

        self.sensor_id = None
        self.unit_x = ""
        self.unit_y = ""
        self.graph = None
        self.histo = []
        self.histo_data = None
        self.y_major = 0
        self.titre = "Capteur"
        self.reset = None
        self.xlabel = ""
        self.duration = None

        # Initialisation de la courbe avec sa couleur
        self.curve_plot = MeshLinePlot(color=[0, 0, 0, 1])
        self.curve_plot.points = [(0, 0)]*101

        # horizontal_line
        self.line_plot = LinePlot(line_width=2, color=[1, 0, 0.5, 1])

        # Appel tous les 2 secondes
        Clock.schedule_interval(self.update, 2)

    def get_datetime(self, date):
        """de "2020-01-15", retourne datetime.date"""
        d = date.split("-")
        return datetime.date(int(d[0]), int(d[1]), int(d[2]))

    def graph_init(self):
        """Initialisation de self.graph.
        plot initié avec 100 couples [(x, y), ...]
        """

        print("Initialisation du graph")

        # Si existe je détruits
        if self.graph:
            self.ids.graph_id.remove_widget(self.graph)
            print("self.graph détruit")

        # Récup de data dans Screen1
        screen1 = self.manager.get_screen("screen1")
        # ['Digital Ambient Light Sensor', 'Lux', 31.79]
        #   description                     unit  value
        self.labels_text = screen1.labels_text

        if self.y_major:  # int
            if len(self.histo) > 20:
                self.create_graph()
            else:
                self.reset = 1

    def create_graph(self):
        """Création du graph seul et pas d'application au widget"""

        print("Appel de la création du graph ..")

        if self.xlabel == "Unité en Minutes: 0 = valeur actuelle":
            self.duration = "jour"
            self.unit_x = "minutes"
        else:
            self.duration = "semaine"
            self.unit_x = "heures"

        # Paramètres du graph en x
        # Jour
        self.xmin = 0
        if self.duration == "jour":
            # un jour = 24*60 = 1440 mn
            # 1440/6 = 240 valeurs dans l'histo
            # self.xmax = 1440 mn
            self.xmax = len(self.histo) * 6
            # 1440/4 = 360
            self.x_ticks_major = 360
            self.x_ticks_minor = 6 # divise en 6 les 360

        # Semaine
        else:
            self.xmax = len(self.histo)
            self.x_ticks_major = 24
            self.x_ticks_minor = 6  # divise en 6 les 24

        if "PM 10" in self.titre or "PM 2.5" in self.titre:
            self.xlabel += "\nEn rouge: valeur réglementaire maxi"

        # Paramètres du graph en y
        self.ymin = 0
        self.ymax = self.y_major
        self.ylabel = self.unit_y
        self.y_ticks_major = self.y_major/10
        self.y_ticks_minor = 0  #5

        # Je crée ou recrée
        self.graph = Graph( background_color=(0.8, 0.8, 0.8, 1),
                            border_color=(0, 0.1, 0.1, 1),
                            xlabel=self.xlabel,
                            ylabel=self.ylabel,
                            x_ticks_minor=self.x_ticks_minor,
                            x_ticks_major=self.x_ticks_major,
                            #y_ticks_minor=self.y_ticks_minor,
                            y_ticks_major=self.y_ticks_major,
                            x_grid_label=True,
                            y_grid_label=True,
                            padding=5,
                            x_grid=True,
                            y_grid=True,
                            xmin=self.xmin,
                            xmax=self.xmax,
                            ymin=self.ymin,
                            ymax=self.ymax,
                            tick_color=(1, 0, 1, 1),
                            label_options={'color': (0.2, 0.2, 0.2, 1)})

        self.graph.add_plot(self.curve_plot)
        self.graph.add_plot(self.line_plot)
        self.ids.graph_id.add_widget(self.graph)

    def update(self, dt):
        """Update de cette class toutes les 2 secondes,
        appelée par set_histo() de SmartCitizen
        """

        if self.reset:
            self.reset = None
            self.y_major = 0
            self.graph_init()
        else:
            if not self.graph:
                self.graph_init()

        # Reset des points
        self.curve_plot.points = []

        # Echelle des y
        y_major = self.get_y_major()
        if y_major != self.y_major:
            self.y_major = y_major
            # reset du graph
            self.graph_init()

        # Apply value to plot
        for i in range(len(self.histo)):
            y = self.histo[i][1]
            if self.duration == "jour":
                self.curve_plot.points.append([i * 6, y])
            else:
                self.curve_plot.points.append([i, y])

        # Construit horizontal line
        self.apply_horizontal_line()

    def get_y_major(self):
        """Le maxi de l'echelle des y"""

        # Recherche du maxi
        maxi = 0
        for couple in self.histo:
            # #print(couple)
            if couple[1] > maxi:
                maxi = couple[1]

        # Définition de l'échelle sur y soit 0 à y_major

        if 1 <= maxi < 10:
            a = 1
        elif 10 <= maxi < 100:
            a = 10
        elif 100 <= maxi < 1000:
            a = 100
        elif 1000 <= maxi < 10000:
            a = 1000
        elif 10000 <= maxi < 100000:
            a = 10000
        else:
            a = 1
        # 756 --> 800 int(756/100) + 1 * 1000
        if maxi < 0:
            y_major = 1
        else:
            y_major = (int(maxi*1.1/a) + 1) * a

        # #print("maxi:", maxi, "y_major", y_major)
        return y_major

    def apply_horizontal_line(self):
        """si self.y_major = 90 équivalent à 1
        y = 30 devient 30/90*1=0.33
        """

        if self.graph:
            y = 0
            if self.titre:
                if self.y_major != 0:

                    if "PM 10" in self.titre:
                        y = 30  # 30
                        # #self.xlabel += ": en rouge valeur réglementaire maxi"

                    if "PM 2.5" in self.titre:
                        y = 10  # 10
                        # #self.xlabel += ": en rouge valeur réglementaire maxi"
            if y:
                self.line_plot.points = [(i, y) for i in range(self.xmax)]
            else:
                self.line_plot.points = []
Esempio n. 19
0
class MainScreen(GridLayout):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)

        #Set the number of columns
        self.cols = 3

        #Heading
        self.add_widget(Label(size_hint=(1, 0.5)))
        self.heading = Label(size_hint=(1, 0.5))
        self.heading.font_size = 30
        self.heading.text = "Automatic Blinds & Live Weather"
        self.heading.bold = True

        self.add_widget(self.heading)
        self.add_widget(Label(size_hint=(1, 0.5)))

        #Current temperature label
        self.tempLabel = Label(size_hint=(1, 0.05))
        self.add_widget(self.tempLabel)

        self.add_widget(Label(size_hint=(1, 0.05)))

        #Current Humidity Label
        self.humLabel = Label(size_hint=(1, 0.05))
        self.add_widget(self.humLabel)

        #Graph theme
        graph_theme = {
            'background_color': (0, 0, 0, 0),
            'tick_color': (128 / 255, 128 / 255, 128 / 255, 1)
        }

        #Temperature Graph
        self.tempGraph = Graph(xlabel='Time',
                               ylabel='Temperature',
                               x_ticks_minor=5,
                               x_ticks_major=10,
                               y_ticks_minor=1,
                               y_ticks_major=5,
                               x_grid_label=True,
                               y_grid_label=True,
                               padding=5,
                               x_grid=True,
                               y_grid=True,
                               xmin=-0,
                               xmax=60,
                               ymin=-0,
                               ymax=50,
                               size_hint=(3, 1),
                               **graph_theme)

        #Temperature plot (where to send the data points)
        self.tempPlot = LinePlot(color=(64 / 255, 224 / 255, 208 / 255, 1),
                                 line_width=1.5)
        self.tempGraph.add_plot(self.tempPlot)

        self.add_widget(self.tempGraph)

        self.add_widget(Label())

        #Humidity Graph
        self.humGraph = Graph(xlabel='Time',
                              ylabel='Humidity',
                              x_ticks_minor=5,
                              x_ticks_major=10,
                              y_ticks_minor=1,
                              y_ticks_major=10,
                              x_grid_label=True,
                              y_grid_label=True,
                              padding=5,
                              x_grid=True,
                              y_grid=True,
                              xmin=-0,
                              xmax=60,
                              ymin=-0,
                              ymax=100,
                              size_hint=(3, 1),
                              **graph_theme)

        #Humidity plot (where to send the data points)
        self.humPlot = LinePlot(color=(64 / 255, 224 / 255, 208 / 255, 1),
                                line_width=1.5)

        self.humGraph.add_plot(self.humPlot)

        self.add_widget(self.humGraph)

        self.add_widget(Label())

        #Config button, sends you to the config screen
        self.button = Button(text="Configure",
                             font_size=30,
                             bold=True,
                             size_hint=(3, 1))
        self.add_widget(self.button)

        #Starts a thread which collects the data from the sensor, then graphs it using 'PlotTempHum'
        _thread.start_new_thread(sensors.graphDHT11, (self.PlotTempHum, ))

    def PlotTempHum(self, temp, hum, timeStamp, reset):
        #Resets the graph
        if (reset):
            self.tempPlot.points.clear()
            self.humPlot.points.clear()

        #updates the labels, (current temp/current hum)
        self.tempLabel.text = str(temp)
        self.humLabel.text = str(hum)

        #adds the points to the graph
        self.tempPlot.points.append((float(timeStamp), temp))
        self.humPlot.points.append((float(timeStamp), hum))
Esempio n. 20
0
class mainApp(App):
    def build(self):
        self.icon = 'diceSmall.png'
        mainPanel = TabbedPanel()
        mainPanel.default_tab_text = 'Dice Roll'
        
        mainPanel.add_widget(self.tabProbabilityTesting())
        mainPanel.default_tab_content = self.tabDiceRoll()
        return mainPanel
    
    def addButtons(self,buttonList,buttonFunctionList,layout):
        for rowIndex, rowButtons in enumerate(buttonList):
            rowLayout = BoxLayout(
                size_hint = (1,1),
                padding = [0,0.5,0,0.5],
                )
            for buttonIndex, buttonLabel in enumerate(rowButtons):
                button = Button(
                    text = buttonLabel,
                    pos_hint={"center_x": 0.5, "center_y": 0.5},
                    size_hint = (1,1),
                    )
                button.bind(on_press=buttonFunctionList[rowIndex][buttonIndex])
                rowLayout.add_widget(button)
            layout.add_widget(rowLayout)
        
    def tabDiceRoll(self):
        mainLayout = BoxLayout(orientation = 'vertical')
        fontSize = 35
        labelList = ['d4','d6','d8','d10','d12','d20','d100','custom']
        self.diceDict = {}
        buttons = [
            ['Roll Inputs','Clear Inputs'],
            ['D20','2d6'],
            ['Roll Stats', '(dis)Advantage'],
            ]
        buttonFunctionList = [
            [self.fireRollButton, self.fireClearButton],
            [self.fireD20Button,self.fireMonopolyButton],
            [self.fireStatsButton, self.fireAdvantageButton], 
            ]
        
        for label in labelList:
            rowLayout = BoxLayout()
            self.kivyLabel = TextInput(
                text = label if label != 'custom' else '',
                hint_text = 'Custom dice' if label == 'custom' else '',
                background_color = [0.75,0.75,0.75,1],
                font_size = '{size}sp'.format(size = int(fontSize/2)),
                readonly = True if label != 'custom' else False,
                input_filter = 'int',
                size_hint = (0.3,1))
            self.diceDict[label] = numberInput(
                multiline = False, 
                font_size = '{size}sp'.format(size = int(fontSize/2)), 
                hint_text = 'Enter number of dice here',
                input_filter = 'int',
                size_hint = (0.7,1))
            rowLayout.add_widget(self.kivyLabel)
            rowLayout.add_widget(self.diceDict[label])
            mainLayout.add_widget(rowLayout)
            
        self.addButtons(buttons,buttonFunctionList,mainLayout)
            
        self.resultTextBox = TextInput(
            text = '\n\n\n\n\n',
            multiline = True, 
            readonly = True, 
            font_size = '{size}sp'.format(size = int(fontSize/2)),
            halign = 'left',
            background_color = [109/255,162/255,1,1],
            background_active = 'd20Skeleton.png',
            background_normal = 'd20Skeleton.png',
            size_hint = (0.9,8),
            pos_hint = {'center_x': .5, 'center_y': .5}
            )
        mainLayout.add_widget(self.resultTextBox)
        
        return mainLayout
    
    def tabProbabilityTesting(self):
        '''
        tab containing plot of probability distributions from various user-specificed pools of dice
        '''
        self.plotColorMap = [
            [1,0,0,1],
            [0,1,0,1],
            [0,0,1,1],
            [1,1,0,1],
            [1,0,1,1],
            [0,1,1,1],
            [1,1,1,1],
            [0.75,0.75,0.75,1]]
        tabProb = TabbedPanelItem(text = 'Prob. Plots')
        self.statsMainLayout = BoxLayout(orientation = 'vertical')
        self.entryLayout =  BoxLayout(orientation = 'vertical',size_hint = (1,0.45))
        buttonLayout = BoxLayout(size_hint = (1,0.05))
        self.graphLayout = BoxLayout(size_hint = (1,0.5))
        self.graph = Graph(xlabel='Value', ylabel='Counts', 
            x_ticks_minor=1,x_ticks_major=2, y_ticks_minor = 100, y_ticks_major=500,
            y_grid_label=True, x_grid_label=True, padding=5,
            x_grid=True, y_grid=True, xmin=-0, xmax=15, ymin=0,ymax = 5000)
        self.graphLayout.add_widget(self.graph)
        self.plotList = []
        self.statsMainLayout.add_widget(self.entryLayout)
        self.statsMainLayout.add_widget(buttonLayout)
        self.statsMainLayout.add_widget(self.graphLayout)
        self.testList = []
        self.appendNewTest(self.entryLayout,readOnly = True) 
        self.testList.append(self.appendNewTest(self.entryLayout)) 
        buttonList = [['Add New Test','Plot Results','Reset']]
        buttonFunctionList = [[self.fireNewTestButton,self.firePlotButton,self.fireResetTestsButton]]
        self.addButtons(buttonList,buttonFunctionList,buttonLayout)
        tabProb.add_widget(self.statsMainLayout)
        return tabProb    
    
    def appendNewTest(self,layout,readOnly = False):
        '''
        Add new test to probability distribution tab
        readOnly should be true for the first line to give a header column, and false thereafter
        '''
        rowLayout = BoxLayout(orientation = 'horizontal',)
        testIndex = len(self.testList) if not readOnly else -1
        testDice = TextInput(
            hint_text = 'Dice', 
            text = 'Enter dice list' if readOnly else '',
            readonly = readOnly,
            background_color = self.plotColorMap[testIndex])
        testBonus = numberInput(
            hint_text = 'Bonus', 
            text = 'Enter fixed bonus' if readOnly else '',
            readonly = readOnly,
            background_color = self.plotColorMap[testIndex])
        testMode = numberInput(
            hint_text = 'Expected Value (output)', 
            text = 'Expected Value' if readOnly else '',
            readonly = True,
            background_color = self.plotColorMap[testIndex])
        rowLayout.add_widget(testDice)
        rowLayout.add_widget(testBonus)
        rowLayout.add_widget(testMode)
        layout.add_widget(rowLayout)
        return(testDice,testBonus,testMode,rowLayout)
    
        
    def createPlot(self):
        '''
        Clear existing plots, and add a plot for each specificed test to the graph.
        Each will be colour coded to match the background of the test rowButtons
        Could (should!) do actual stats stuff to get expected values of each dice pool, but 10k tests takes negligible time even on a phone
        '''
        for plot in self.plotList:
            self.graph.remove_plot(plot)
        self.plotList = []
        maxCount = [500]
        maxValue = [6]
        numberOfTests = 10000
        for index, test in enumerate(self.testList):
            outcomes = {}
            diceList = re.findall(r"[\w\d']+", test[0].text)
            if len(diceList) > 0:
                bonus = 0 if len(test[1].text) == 0 else int(test[1].text)
                for i in range(0,numberOfTests):
                    diceResult = diceRoll.rollDicePool(diceList = diceList, bonus = bonus)[0]
                    if diceResult in outcomes:
                        outcomes[diceResult]+=1
                    else:
                        outcomes[diceResult] = 1
                plot = MeshLinePlot(color=self.plotColorMap[index],mode = 'points')
                xList = [key for key in outcomes]
                xList.sort()
                plot.points = [(key, outcomes[key]) for key in xList]
                maxCount.append(max(outcomes[key] for key in outcomes))
                maxValue.append(max(key for key in outcomes))
                expectedValue = round(sum([key * outcomes[key] for key in outcomes])/numberOfTests,1)
                test[2].text = str(expectedValue) if expectedValue != 0 else 'Error with {diceList}'.format(diceList = diceList)
                self.results=outcomes
                self.graph.add_plot(plot)
                self.plotList.append(plot)
        #Pad graph axes to make maximum values clear and prevent them being lost over the edge of the visible space
        self.graph.xmax = max(maxValue) + 2
        self.graph.ymax = max(maxCount) + 500
    
    
    def diceRollOutput(self,diceList):
        dicePool =  diceRoll.dicePool(diceList = diceList)
        dicePool.roll()
        message = dicePool.diceString+ ' \n'
        for diceType in dicePool.resultDict:
            message += 'd{diceType} : {diceResults}\n'.format(
                diceType = diceType,
                diceResults = ', '.join(map(str,dicePool.resultDict[diceType])))
        message += 'Result: ' + str(dicePool.rollSum)
        return message
    
    def fireRollButton(self,instance):
        diceList = []
        for dice in self.diceDict:
            no_of_dice = self.diceDict[dice].text
            if dice == 'custom':
                dice = 'd' + self.kivyLabel.text.lower()
            if no_of_dice != '' and no_of_dice != 0:
                diceList.append(no_of_dice + dice)
        if len(diceList) > 0:
            message = self.diceRollOutput(diceList)
            self.resultTextBox.text = '\n' + message + '\n'
        
    def fireD20Button(self,instance):
        result = diceRoll.rollDice(20)
        self.resultTextBox.text = '\n\nRolled 1d20\nResult: ' + str(result) + '\n'
         
    def fireAdvantageButton(self,instance,sides=20):
        result1 = diceRoll.rollDice(sides)
        result2 = diceRoll.rollDice(sides)
        message = 'Rolled 2d{sides}\nResult: {r1} , {r2}'.format(sides = sides, r1 = result1, r2 = result2)
        self.resultTextBox.text = '\n\n' + message + '\n'
    
    def fireMonopolyButton(self,instance):
        message = self.diceRollOutput(['2d6'])
        self.resultTextBox.text = '\n' + message + '\n'
       
    def fireStatsButton(self,instance):
        stats = diceRoll.rollStats(6)
        outString = 'Stats rolled : \n' + str(stats[0]) + ' ' + str(stats[1]) + ' ' + str(stats[2]) +'\n' + str(stats[3]) + ' ' + str(stats[4]) + ' ' + str(stats[5])
        outString += '\nAverage of ' + str(np.round( sum(stats) / len(stats) , 2))
        self.resultTextBox.text = '\n' + outString + '\n'
        
    def fireClearButton(self,instance):
        for label in self.diceDict:
            self.diceDict[label].text = ''
        self.kivyLabel.text = ''
        
    def fireNewTestButton(self,instance):
        if len(self.testList) <7:
            self.testList.append(self.appendNewTest(self.entryLayout)) 
            
    def fireResetTestsButton(self,instance):
        while len(self.testList) >1:
            self.entryLayout.remove_widget(self.testList.pop()[-1])
        for textBox in self.testList[0]:
            textBox.text = ''
        for plot in self.plotList:
            self.graph.remove_plot(plot)
    
    def firePlotButton(self,instance):
        self.createPlot()
Esempio n. 21
0
class UIApp(App):
    def init(self):
        self.read_pulse_table()

    def build(self):
        self.savef = None
        self.state = None
        self.baselineHR = 60.0  # baseline HR
        self.Ts = 1.0 / 50.0  # sampling period
        self.modulation = 0.1  # how much to modulate the pressure wave via RR
        self.pressure = Pressure()
        superBox = BoxLayout(orientation='vertical')
        HB = BoxLayout(orientation='horizontal')
        cell1 = BoxLayout(orientation='vertical')
        self.textinputHomePos = FloatInput(text='100')
        cell1h = BoxLayout(orientation='horizontal')
        label = Label(text='Home Pos')
        cell1h.add_widget(label)
        cell1h.add_widget(self.textinputHomePos)

        self.textinputCalibMax = FloatInput(text='1500')
        cell1bh = BoxLayout(orientation='horizontal')
        label = Label(text='Calib Max')
        cell1bh.add_widget(label)
        cell1bh.add_widget(self.textinputCalibMax)

        self.textinputCalibInc = FloatInput(text='25')
        cell1ch = BoxLayout(orientation='horizontal')
        label = Label(text='Calib Inc')
        cell1ch.add_widget(label)
        cell1ch.add_widget(self.textinputCalibInc)

        self.textinputCalibDelay = FloatInput(text='0.1')
        cell1dh = BoxLayout(orientation='horizontal')
        label = Label(text='Calib Delay')
        cell1dh.add_widget(label)
        cell1dh.add_widget(self.textinputCalibDelay)

        self.home_button = Button(text='Home')
        self.home_button.bind(on_press=self.home)
        self.home_button.background_color = default_bgnd
        self.calib_button = Button(text='Calibrate')
        self.calib_button.background_color = default_bgnd
        self.calib_button.bind(on_press=self.calibrate)

        cell1.add_widget(cell1h)
        cell1.add_widget(self.home_button)
        cell1.add_widget(cell1ch)
        cell1.add_widget(cell1bh)
        cell1.add_widget(cell1dh)
        cell1.add_widget(self.calib_button)

        HB.add_widget(cell1)
        self.pressure_button = Button(text='Read\nPressure')

        self.pressure_button.background_color = default_bgnd
        self.pressure_button.bind(on_press=self.read_pressure)

        cell1b = BoxLayout(orientation='vertical')
        cell1b.add_widget(self.pressure_button)
        self.pressure_label = Label(text='0.0 mmHg')
        cell1b.add_widget(self.pressure_label)

        HB.add_widget(cell1b)

        cell3 = BoxLayout(orientation='vertical')
        cell3a = BoxLayout(orientation='horizontal')
        label = Label(text='Systolic')
        self.textinputSystolic = FloatInput(text='120.0')
        cell3a.add_widget(label)
        cell3a.add_widget(self.textinputSystolic)
        cell3.add_widget(cell3a)

        cell3b = BoxLayout(orientation='horizontal')
        label = Label(text='Diastolic')
        self.textinputDiastolic = FloatInput(text='80.0')
        cell3b.add_widget(label)
        cell3b.add_widget(self.textinputDiastolic)
        cell3.add_widget(cell3b)

        cell3c = BoxLayout(orientation='horizontal')
        label = Label(text='HR')
        self.textinputHR = FloatInput(text='75.0')
        cell3c.add_widget(label)
        cell3c.add_widget(self.textinputHR)
        cell3.add_widget(cell3c)

        cell3d = BoxLayout(orientation='horizontal')
        label = Label(text='RR')
        self.textinputRR = FloatInput(text='10.0')
        cell3d.add_widget(label)
        cell3d.add_widget(self.textinputRR)
        cell3.add_widget(cell3d)

        HB.add_widget(cell3)

        self.play_button = Button(text='Play Waveform')

        self.play_button.background_color = default_bgnd
        self.play_button.bind(on_press=self.play_waveform)

        HB.add_widget(self.play_button)

        self.exit_button = Button(text='Exit')

        self.exit_button.background_color = default_bgnd
        self.exit_button.bind(on_press=self.exit_app)
        HB.add_widget(self.exit_button)

        superBox.add_widget(HB)
        #self.graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
        #     x_ticks_major=25, y_ticks_major=50,
        #     y_grid_label=True, x_grid_label=True, padding=5,
        #     x_grid=True, y_grid=True, xmin=-0, xmax=500, ymin=0, ymax=200)
        #self.plot = MeshLinePlot(color=[1, 1, 1, 1])
        #self.plot.points = [(x, 50+50*math.sin(x / 10.)) for x in range(0, 501)]
        #self.graph.add_plot(self.plot)
        self.default_graph_waveform()
        superBox.add_widget(self.graph)
        #print(self.plot.points)
        return superBox

    def read_pulse_table(self):
        f = open('pulse256.dat', 'rb')
        a = f.read()
        f.close()
        self.pulse256 = struct.unpack("256h", a)
        #print(self.pulse256)

    def resample_HR(self, values, heartrate):
        out = []
        ratio = heartrate / self.baselineHR
        index = range(len(values))
        index0 = []
        x = 0
        while (x < (len(values) - 1)):
            index0.append(x)
            v = np.interp(x, index, values)
            out.append(v)
            x = x + ratio  # advance more slowly in time
        return out

    def default_graph_waveform(self):
        self.graph = Graph(xlabel='t (s) or steps',
                           ylabel='BP (mmHg)',
                           x_ticks_minor=5,
                           x_ticks_major=1.0,
                           y_ticks_major=50,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=True,
                           y_grid=True,
                           xmin=-0,
                           xmax=10.0,
                           ymin=0,
                           ymax=240)
        self.plot = MeshLinePlot(color=[1, 1, 1, 1])
        self.plot.points = [(x * 0.02, 5) for x in range(0, 501)]
        self.graph.add_plot(self.plot)

    def reset_graph_waveform(self):
        self.graph.xmin = 0
        self.graph.xmax = 10.0
        self.graph.x_ticks_major = 1.0
        self.plot.points = [(x * 0.02, 5) for x in range(0, 501)]

    def read_pressure_callback(self, x):
        (p, mm, t) = self.pressure.quick_read()
        swp = self.plot.points[self.index]
        copy = (self.index * 0.02, mm)
        self.plot.points[self.index] = copy
        self.index = (self.index + 1) % 500
        self.pressure_label.text = "%3.1f mmHg / %2.1f C" % (mm, t)

    def home_callback(self, x):
        h = int(self.textinputHomePos.text)
        print("home to %d" % h)
        self.pressure.home(h)
        self.state = None
        self.home_button.text = "Home Pos"
        self.home_button.background_color = [0.7, 0.7, 0.7, 1]
        return False

    def calibrate_inc_callback(self, x):
        p = self.pressure.one_calibrate(self.calib_inc, self.calib_delay)
        if (p >= self.calib_max):
            print("End calibrate")
            self.pressure.end_calibrate()
            self.state = None
            self.calib_button.text = "Calibrate"
            self.calib_button.background_color = [0.7, 0.7, 0.7, 1]
        else:
            self.home_event = Clock.schedule_once(self.calibrate_inc_callback,
                                                  0.0)
        print(self.calib_index, self.pressure.calib_mmHg,
              len(self.plot.points))
        self.plot.points[self.calib_index] = (
            self.pressure.calib_s[self.calib_index],
            self.pressure.calib_mmHg[self.calib_index])
        #print(self.plot.points)
        self.calib_index = self.calib_index + 1
        return False

    def calibrate_start_callback(self, x):
        h = int(self.textinputHomePos.text)
        cm = int(self.textinputCalibMax.text)
        ci = int(self.textinputCalibInc.text)

        cd = float(self.textinputCalibDelay.text)
        print("calibrate %d,%d, %d, %f" % (h, cm, ci, cd))
        h0 = h
        x = [h]
        while (h0 <= cm):
            h0 = h0 + ci
            x.append(h0)
        print(x)
        self.graph.xmin = h
        self.graph.xmax = cm
        self.graph.x_ticks_major = 100
        self.plot.points = []
        for x0 in x:
            self.plot.points.append((x0, 0))
        #self.graph.add_plot(self.plot)

        self.pressure.start_calibrate_curve(h, ci)
        self.calib_inc = ci
        self.calib_max = cm
        self.calib_delay = cd
        self.calib_index = 0
        self.home_event = Clock.schedule_once(self.calibrate_inc_callback,
                                              0.01)
        return False

    def play_more_callback(self, x):
        out = []
        for a in range(10):
            R = self.pressure.one_read_timeout()
            if (R is None):
                break
            else:
                s, t, pos = R
                p0 = np.interp(pos, self.steps, self.mmHgs)

                p1 = self.pressure.psi2mmHg(
                    int(s) * self.pressure.pressure_multiplier)
                t1 = float(t) * self.pressure.temp_multiplier
                #print(p0,p1)
                out.append(p0)
                out.append(p1)
                self.plot.points[self.play_i] = (
                    self.plot.points[self.play_i][0], p1)
                self.play_i = (self.play_i + 1) % 500
                self.pressure_label.text = "%3.1f mmHg / %2.1f C" % (p1, t1)
        if (self.savef):
            #print(out)
            s = struct.pack("{}f".format(len(out)), *out)
            self.savef.write(s)
        self.play_more_event = Clock.schedule_once(self.play_more_callback, 0)

    def play_calibrate_callback(self, x):
        # first get our waveform parameters
        h = int(self.textinputHomePos.text)
        cm = int(self.textinputCalibMax.text)
        ci = int(self.textinputCalibInc.text)
        systolic = float(self.textinputSystolic.text)
        diastolic = float(self.textinputDiastolic.text)
        heartrate = float(self.textinputHR.text)
        resprate = float(self.textinputRR.text)

        cd = float(self.textinputCalibDelay.text)
        print("play calibrate %d,%d, %d" % (h, cm, ci))
        print("Sys %f Dia %f" % (systolic, diastolic))
        (steps0, psi0, mmHg0) = self.pressure.calibrate_curve(h, cm, ci)
        self.steps = np.array(steps0)
        self.psis = np.array(psi0)
        self.mmHgs = np.array(mmHg0)
        # Now branch on whether using pulse_table (single pulse with cyclic indexing),
        # OR - whole waveform repeated.
        if (USE_PULSE_TABLE):
            print("Down with UPT....")
            v = self.pulse256
            minb = 0.0
            maxb = 8192.0
            print(minb, maxb)
            span = maxb - minb
            v0 = []
            # now convert to float actual mmHg value cycle
            for b in v:
                x = (float(b) - minb) / span * (systolic -
                                                diastolic) + diastolic
                v0.append(x)
            # and now calibrate to the right number of steps
            ys0 = []
            i = 0
            while (i < (len(v0))):
                x = v0[i]
                s = round(np.interp(x, self.mmHgs, self.steps))
                ys0.append(s)
                i = i + 1
            ys0.append(
                ys0[0])  # append the first value at the end for wrap-around
            self.pressure.write_table(ys0)
            hrindex = heartrate / 60.0 * 256.0 / 50.0  # index value per 20ms interval
            rrindex = resprate / 60.0 * 256.0 / 50  # index value per 20ms interval
            # now convert to X.8 format`
            print("Playing table...\n")
            self.pressure.play_table(round(hrindex * 256.0),
                                     round(rrindex * 256.0), cm, h)

        else:  # single recorded waveform sequence, possibly repeated
            f = open('TestPulses.dat', 'rb')
            a = f.readlines()
            f.close()
            values = []
            for l in a:
                x = float(l)
                values.append(x)

            v = values[:-20]
            if (not (self.baselineHR == heartrate)):
                print("RESAMPLING @ %f from %f" % (heartrate, self.baselineHR))
                values = self.resample_HR(values, heartrate)
            minb = 50000
            maxb = -50000
            for b in v:
                if (b > maxb):
                    maxb = b
            if (b < minb):
                minb = b
            print(minb, maxb)
            span = maxb - minb

            runs = 1
            v0 = []
            for i in range(runs):
                for b in v:
                    x = (b - minb) / span * (systolic - diastolic) + diastolic
                    v0.append(x)
            ys = []
            ys0 = []
            i = 0
            t = 0
            dt = 20e-3
            ts = []
            ps = []
            mms = []
            while (i < (len(v0))):
                x = v0[i]
                s = round(np.interp(x, self.mmHgs, self.steps))
                i = i + 25
                ts.append(t)
                t = t + dt
                ys0.append(s)

            for i in range(runs):
                for y in ys0:
                    ys.append(y)
            print(len(ys))
            self.pressure.write_waveform(ys)
            self.pressure.play_waveform(-1, cm, h)

        #self.pressure.start_reading()
        self.play_i = 0
        self.play_button.background_color = [0.7, 0.7, 0.7, 1]
        self.play_button.text = "Stop Playing..."
        self.state = "PLAY2"
        self.savef = open(SAVEFILE_NAME, "wb")
        self.play_more_event = Clock.schedule_once(self.play_more_callback, 0)
        return False

    def read_pressure(self, button):
        print("READ PRESSURE")
        if (self.state == None):
            self.index = 0
            self.state = 'PRESSURE'
            button.text = "Stop Reading\nPressure & Temp"
            button.background_color = [1, 0.5, 0.5, 1]
            self.reset_graph_waveform()
            self.pressure_event = Clock.schedule_interval(
                self.read_pressure_callback, 0.25)
        elif (self.state == 'PRESSURE'):
            self.state = None
            button.text = "Read\nPressure & Temp"
            button.background_color = [0.7, 0.7, 0.7, 1]
            self.pressure_event.cancel()

    def home(self, button):
        print("HOME")
        if (self.state == None):
            self.index = 0
            self.state = 'HOME'
            button.text = "Going Home"
            button.background_color = [1, 0.5, 0.5, 1]
            self.home_event = Clock.schedule_once(self.home_callback, 0.1)

    def calibrate(self, button):
        print("CALIBRATE")
        if (self.state == None):
            self.state = 'CALIBRATE'
            button.text = "Calibrating..."
            button.background_color = [1, 0.5, 0.5, 1]
            self.home_event = Clock.schedule_once(
                self.calibrate_start_callback, 0.25)

    def play_stop_callback(self, x):
        print("PLAY STOP CALLBACK")
        if (self.savef):
            self.savef.close()
            self.savef = None
        self.play_more_event.cancel()
        for i in range(1):  # drain any old readings
            s = self.pressure.one_read_timeout()
            if (not s):
                break
        #self.pressure.stop_reading()
        self.play_button.text = "Play Waveform"
        self.play_button.background_color = [0.7, 0.7, 0.7, 1]

        self.play_event.cancel()

    def play_waveform(self, button):
        print("PLAY WAVEFORM")
        if (self.state == None):
            self.state = 'PLAY'
            self.play_button.text = "Calibrating..."
            self.play_button.background_color = [1, 0.5, 0.5, 1]
            self.play_event = Clock.schedule_once(self.play_calibrate_callback,
                                                  0.25)
        elif (self.state == 'PLAY2'):
            print("STOPPING")
            self.pressure.set_params(1)
            print("STOPPING")
            self.state = None
            self.play_button.text = "Stopping Waveform"
            self.play_button.background_color = [0.5, 0.5, 1, 1]
            self.play_event = Clock.schedule_once(self.play_stop_callback,
                                                  0.25)

    def exit_app(self, button):
        print("EXIT")
        self.stop()
        self.root_window.close()
Esempio n. 22
0
class StockDetailScreen(Screen):
    def __init__(self, **kwargs):
        super(StockDetailScreen, self).__init__(**kwargs)

        self.layout = CustomLayout()
        back_img = lm.createImage(source='images/back.png', rel_size=lm.rel_square(rel_width=.1))
        self.layout.add_item(CustomButton(back_img, on_release_func=lambda: back(self.manager), alignment='left'))

        self.stock_name = lm.createLabel(bold= False, rel_size= (1, .1), text_rel_size = (.95, .1), halign='center', valign='middle')
        self.layout.add_item(self.stock_name)

        self.layout.add_widget(Button(text="TRADE", bold=True, font_size=40,
                                        background_color=DARK_GREEN, on_release=self.trade),                                        
                                        rel_size=(.8, .1))

        self.current_price = lm.createLabel(font_size= 50, rel_size= (1, .1))

        self.layout.add_item(self.current_price)
        self.center_image = lm.createImage(source='images/up_arrow.png', rel_size=lm.rel_square(rel_width=.5))
        self.layout.add_item(self.center_image)

        self.stock_symbol = lm.createLabel(font_size= 50, rel_size= (1, .1))
        self.layout.add_item(self.stock_symbol)

        self.num_shares = lm.createLabel(font_size= 28, rel_size= (1, .1))
        self.layout.add_item(self.num_shares)

        self.layout.add_item(lm.createLabel(text = 'Past Week Performace', font_size= 28, rel_size= (1, .1)))

        # graph
        self.graph = Graph(x_ticks_major=1, tick_color = (0,0,0,.5), xlabel='Days',
              y_grid_label=True, x_grid_label=True, precision='%.2f', padding=5,
              x_grid=True, y_grid=True, xmin=-5, xmax=-1, ymin=0, ymax=100,
              border_color = (0,0,0,0), label_options = {'color': (0,0,0,1)})        

        self.plot = [(i-7, .3*i*100) for i in range(7)]

        self.layout.add_widget(self.graph, rel_size=(.90, .3))

        self.add_widget(self.layout.create())

    def on_pre_enter(self):
        position = Position(current_stock_symbol)
        position.update_price()
        self.stock_name.widget.text = symbol_data[position.tag]['NAME']
        self.current_price.widget.text = f'${position.current_price:,.2f}'
        self.stock_symbol.widget.text = position.tag
        self.center_image.widget.source = 'images/up_arrow.png' if position.day_change >= 0 else 'images/down_arrow.png'
        share_count = current_portfolio[position.tag].num_shares if current_portfolio[position.tag] else 0
        self.num_shares.widget.text = f'You own {share_count} share{"s" if share_count != 1 else ""}'
        self.plot_data(position.get_prev_week_data())

    def plot_data(self, data):
        """
        Change the data shown on the stock graph.
        data should be a list of tuples showing (x,y) pairs on the graph.
        """
        self.graph.ymax = max(price for _,price in data) * 1.01
        self.graph.ymin = min(price for _,price in data) * .99
        self.graph.y_ticks_major = (self.graph.ymax - self.graph.ymin) / 4
        self.graph.remove_plot(self.plot)
        self.plot = LinePlot(color=WHITE, line_width=3)
        self.plot.points = data
        self.graph.add_plot(self.plot)

    def trade(self, trade_button):
        """
        Enter the trade screen
        """
        global trade_mode
        trade_mode = 'BUY'
        screen_transition(self.manager, 'detail', 'trade', SLIDE_LEFT)
Esempio n. 23
0
from math import sin
from kivy_garden.graph import Graph, MeshLinePlot

graph = Graph(xlabel='X',
              ylabel='Y',
              x_ticks_minor=5,
              x_ticks_major=25,
              y_ticks_major=1,
              y_grid_label=True,
              x_grid_label=True,
              padding=5,
              x_grid=True,
              y_grid=True,
              xmin=-0,
              xmax=100,
              ymin=-1,
              ymax=1)
plot = MeshLinePlot(color=[1, 0, 0, 1])
plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
graph.add_plot(plot)
Esempio n. 24
0
class Logic(BLayout):
    def __init__(self, information=None):
        super(Logic, self).__init__()

        if information is None:
            information = dict()

        self.information = information

        self.mi = dict()
        self.nmi = dict()
        self.tmi = dict()
        self.twomi = dict()

        self.graph = Graph(xlabel='X',
                           ylabel='Y',
                           x_ticks_minor=.25,
                           x_ticks_major=1,
                           y_ticks_minor=1,
                           y_ticks_major=1,
                           y_grid_label=True,
                           x_grid_label=True,
                           padding=5,
                           x_grid=True,
                           y_grid=True,
                           xmin=-1,
                           xmax=24,
                           ymin=-1,
                           ymax=1)
        self.red_plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.gre_plot = MeshLinePlot(color=[0, 1, 0, 1])
        self.blu_plot = MeshLinePlot(color=[0, 0, 1, 1])
        self.yel_plot = MeshLinePlot(color=[1, 1, 0, 1])

        self.add_widget(widget=self.graph)

    def parse_information(self):
        if len(self.information.values()) > 0:
            self.mi = self.information['Mask'][1]
            self.nmi = self.information['NoMask'][1]
            self.tmi = self.information['TookMask'][1]
            self.twomi = self.information['WoMask'][1]

            self.graph.ymax = self.information["Total"] + 5

            self.red_plot.points = [
                (self.set_float(y), x)
                for x, y in zip(self.mi.keys(), self.mi.values())
            ]
            self.gre_plot.points = [
                (self.set_float(y), x)
                for x, y in zip(self.nmi.keys(), self.nmi.values())
            ]
            self.blu_plot.points = [
                (self.set_float(y), x)
                for x, y in zip(self.tmi.keys(), self.tmi.values())
            ]
            self.yel_plot.points = [
                (self.set_float(y), x)
                for x, y in zip(self.twomi.keys(), self.twomi.values())
            ]

    @staticmethod
    def set_float(_input=str()) -> float:
        # format is 00:00:00
        # We need 00.00

        _time = _input.split(":")
        _hour = int(_time[0]) * 1.0
        _minute = int(_time[1]) / 60.0
        _float = _hour + _minute

        return _float

    def update(self):
        self.parse_information()
        self.graph.add_plot(self.red_plot)
        self.graph.add_plot(self.gre_plot)
        self.graph.add_plot(self.blu_plot)
        self.graph.add_plot(self.yel_plot)
Esempio n. 25
0
class GraphPlot(RelativeLayout):
    def __init__(self, **kwargs):
        super(GraphPlot, self).__init__(**kwargs)
        self.y_range = 10
        self.x_range = 10
        self.range_multiplier = [2, 2.5, 2]
        self.graph = Graph(xlabel="x",
                           ylabel="y",
                           x_ticks_major=self.x_range / 2,
                           y_ticks_major=self.y_range / 2,
                           y_grid_label=True,
                           x_grid_label=True,
                           x_grid=True,
                           y_grid=True,
                           xmin=-self.x_range,
                           xmax=self.x_range,
                           ymin=-self.y_range,
                           ymax=self.y_range,
                           draw_border=False)
        # graph.size = (1200, 400)
        # self.graph.pos = self.center

        self.plot = MeshLinePlot(color=[1, 1, 1, 1])
        x = -self.x_range
        self.plot.points = []
        while x < self.x_range:
            try:
                self.plot.points.append((x, sin(x)))
            except ZeroDivisionError:
                pass

            x += self.x_range / 100
        self.add_widget(self.graph)

        self.graph.add_plot(self.plot)

    def on_touch_down(self, touch):
        if touch.is_mouse_scrolling:
            # for whatever reason, the definition of scrollup and scrolldown are reversed
            if touch.button == 'scrollup':
                self.zoomOut()
            elif touch.button == 'scrolldown':
                self.zoomIn()

    def zoomIn(self):
        print(self.x_range)
        self.x_range = multiplyByFloat(self.x_range,
                                       1 / self.range_multiplier[0])
        self.y_range = multiplyByFloat(self.y_range,
                                       1 / self.range_multiplier[0])
        self.range_multiplier.insert(0, self.range_multiplier[2])
        del self.range_multiplier[-1]
        self.update()

    def zoomOut(self):
        print(self.x_range)
        self.x_range = multiplyByFloat(self.x_range, self.range_multiplier[0])
        self.y_range = multiplyByFloat(self.y_range, self.range_multiplier[0])
        self.range_multiplier.append(self.range_multiplier[0])
        self.range_multiplier.remove(self.range_multiplier[0])
        self.update()

    def update(self):
        self.remove_widget(self.graph)
        self.graph = Graph(xlabel="x",
                           ylabel="y",
                           x_ticks_major=self.x_range / 2,
                           y_ticks_major=self.y_range / 2,
                           y_grid_label=True,
                           x_grid_label=True,
                           x_grid=True,
                           y_grid=True,
                           xmin=-self.x_range,
                           xmax=self.x_range,
                           ymin=-self.y_range,
                           ymax=self.y_range,
                           draw_border=False)
        self.plot = MeshLinePlot(color=[1, 1, 1, 1])
        x = -self.x_range
        self.plot.points = []
        while x < self.x_range:
            try:
                self.plot.points.append((x, sin(x)))
            except ZeroDivisionError:
                pass

            x += self.x_range / 100
        self.add_widget(self.graph)

        self.graph.add_plot(self.plot)
Esempio n. 26
0
class linechart():
    def __init__(self, ticker):
        self.CurrentPrice = 0
        self.dt = 0
        self.ticker = ticker
        self.cryptos = []
        self.yticks = 100
        for dicto in json.loads(
                requests.get(
                    'https://finnhub.io/api/v1/crypto/symbol?exchange=binance&token=bvtss4748v6pijnevmqg'
                ).text):

            self.cryptos.append(dicto['symbol'])

        self.xticks = 10
        self.xmax = 50
        self.chart = Graph(
            xlabel='Time',
            ylabel='Price',
            x_ticks_minor=0,
            x_ticks_major=self.xticks,
            y_ticks_major=self.yticks,
            y_grid_label=True,
            x_grid_label=True,
            padding=5,
            x_grid=True,
            y_grid=True,
            xmin=0,
            xmax=self.xmax,
            ymin=0,
        )

        self.plot = SmoothLinePlot(color=[1, 1, 1, 1])
        self.chart.add_plot(self.plot)

    #main
    def get_point_data(self):
        if self.dt + 5 < time.time():
            data = self.getPointsFromApi()

            self.dt = time.time()
            self.data_handle(data)

    def data_handle(self, data):
        if data is None:
            return
        timestamps = data['t']
        prices = data['c']
        plot = []
        ymax = max(data['c'])
        ymin = min(data['c'])
        for times, value in zip(range(len(prices)), prices):
            plot.append((times, value))

        self.plot.points = plot

        self.CurrentPrice = data['c'][-1]
        self.yticks = (self.chart.ymax - self.chart.ymin) / 4
        self.chart.y_ticks_major = self.yticks
        self.plot.points = plot
        self.xmax = len(self.plot.points) - 1
        self.chart.xmax = self.xmax

        #sizing graph adding upper buffer
        self.chart.ymax = round((ymax + ymax / 4) / 10) * 10
        self.chart.ymin = round((ymin - ymin / 4) / 10) * 10
        #sizing xmax
        self.xmax = len(plot)

    def getPointsFromApi(self, *dt):
        if self.ticker in self.cryptos:
            data = jsonhelper.getCrytpoPlot(self.ticker,
                                            'bvtss4748v6pijnevmqg')
        else:
            data = jsonhelper.GetStockPlot(self.ticker, 'bvtss4748v6pijnevmqg')
        return data

    def Get_graph(self):
        return self.chart
Esempio n. 27
0
class graphicsScreen(GridLayout):
    def __init__(self, **kwargs):
        super(graphicsScreen, self).__init__(**kwargs)

        global dataFile
        self.dataFile = dataFile
        global refreshRate
        self.refreshRate = refreshRate
        Window.size = (800, 600)
        self.cols = 2
        self.rows = 2

        ############################ SCORE ##################################################
        self.graphScore = Graph(xlabel='Generation',
                                ylabel='Score',
                                font_size='20sp',
                                x_ticks_major=1,
                                y_ticks_major=1,
                                y_grid_label=True,
                                x_grid_label=True,
                                padding=5,
                                xlog=False,
                                ylog=False,
                                x_grid=True,
                                y_grid=True,
                                ymin=0,
                                xmin=0)

        self.scorePlot = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.scorePlotMedian = LinePlot(color=[0.3, 0.3, 1, 1], line_width=2)
        self.scorePlot.points = [(0, 0)]
        self.scorePlotMedian.points = [(0, 0)]
        self.graphScore.add_plot(self.scorePlot)
        self.graphScore.add_plot(self.scorePlotMedian)

        ############################ FITNESS ##################################################
        self.graphFitness = Graph(xlabel='Generation',
                                  ylabel='Fitness',
                                  font_size='20sp',
                                  x_ticks_major=1,
                                  y_ticks_major=1,
                                  y_grid_label=True,
                                  x_grid_label=True,
                                  padding=5,
                                  xlog=False,
                                  ylog=False,
                                  x_grid=True,
                                  y_grid=True,
                                  ymin=0,
                                  xmin=0)

        self.fitnessPlot = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.fitnessPlotMedian = LinePlot(color=[0.3, 0.3, 1, 1], line_width=2)
        self.fitnessPlot.points = [(0, 0)]
        self.fitnessPlotMedian.points = [(0, 0)]
        self.graphFitness.add_plot(self.fitnessPlot)
        self.graphFitness.add_plot(self.fitnessPlotMedian)

        ############################ SCORE TIME ##################################################
        self.graphScoreTime = Graph(xlabel='Time [min]',
                                    ylabel='Score',
                                    font_size='20sp',
                                    x_ticks_major=1,
                                    y_ticks_major=1,
                                    y_grid_label=True,
                                    x_grid_label=True,
                                    padding=5,
                                    xlog=False,
                                    ylog=False,
                                    x_grid=True,
                                    y_grid=True,
                                    ymin=0,
                                    xmin=0)

        self.scoreTimePlot = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.scoreTimePlotMedian = LinePlot(color=[0.3, 0.3, 1, 1],
                                            line_width=2)
        self.scoreTimePlot.points = [(0, 0)]
        self.scoreTimePlotMedian.points = [(0, 0)]
        self.graphScoreTime.add_plot(self.scoreTimePlot)
        self.graphScoreTime.add_plot(self.scoreTimePlotMedian)

        ############################ GENERATION TIME ##################################################
        self.graphGenTime = Graph(xlabel='Generation',
                                  ylabel='Time [min]',
                                  font_size='20sp',
                                  x_ticks_major=1,
                                  y_ticks_major=1,
                                  y_grid_label=True,
                                  x_grid_label=True,
                                  padding=5,
                                  xlog=False,
                                  ylog=False,
                                  x_grid=True,
                                  y_grid=True,
                                  ymin=0,
                                  xmin=0)

        self.genTimePlot = LinePlot(color=[1, 0, 0, 1], line_width=2)
        self.genTimePlot.points = [(0, 0)]
        self.graphGenTime.add_plot(self.genTimePlot)

        self.add_widget(self.graphScore)
        self.add_widget(self.graphFitness)
        self.add_widget(self.graphScoreTime)
        self.add_widget(self.graphGenTime)

        if self.refreshRate > 0:
            self.readHandle = Clock.schedule_interval(self.readPipeData,
                                                      self.refreshRate)
        else:
            self.readCsvData()

    def readCsvData(self):
        with open(self.dataFile) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            score = []
            generation = []
            fitness = []
            seconds = []
            for row in csv_reader:
                if row[0] == 'score':
                    score = list(map(int, row[1][1:-1].split(",")))
                elif row[0] == 'generation':
                    generation = list(map(int, row[1][1:-1].split(",")))
                elif row[0] == 'fitness':
                    fitness = list(map(int, row[1][1:-1].split(",")))
                elif row[0] == 'seconds':
                    seconds = list(map(float, row[1][1:-1].split(",")))

            self.scorePoints = []
            self.scorePointsMedian = []
            self.fitnessPoints = []
            self.fitnessPointsMedian = []
            self.scoreTimePoints = []
            self.scoreTimePointsMedian = []
            self.timeGenPoints = []
            for i in range(len(score)):
                self.scorePoints.append((generation[i], score[i]))
                self.fitnessPoints.append((generation[i], fitness[i]))
                self.scoreTimePoints.append((seconds[i] / 60, score[i]))
                self.timeGenPoints.append((generation[i], seconds[i] / 60))

            self.scorePointsMedian = self.floatMedian(self.scorePoints)
            self.fitnessPointsMedian = self.floatMedian(self.fitnessPoints)
            self.scoreTimePointsMedian = self.floatMedian(self.scoreTimePoints)
            self.graphsUpdate()

    def readPipeData(self, *args):
        self.scorePoints = []
        self.scorePointsMedian = []
        self.fitnessPoints = []
        self.fitnessPointsMedian = []
        self.scoreTimePoints = []
        self.scoreTimePointsMedian = []
        self.timeGenPoints = []
        if os.path.exists(self.dataFile):
            with open(self.dataFile, "r") as file:
                for line in file:
                    data = list(line.split(","))
                    score = int(data[0])
                    generation = int(data[1])
                    fitness = int(data[2])
                    minutes = float(data[3]) / 60

                    self.scorePoints.append((generation, score))
                    self.fitnessPoints.append((generation, fitness))
                    self.scoreTimePoints.append((minutes, score))
                    self.timeGenPoints.append((generation, minutes))

            self.scorePointsMedian = self.floatMedian(self.scorePoints)
            self.fitnessPointsMedian = self.floatMedian(self.fitnessPoints)
            self.scoreTimePointsMedian = self.floatMedian(self.scoreTimePoints)
            self.graphsUpdate()
        else:
            self.readHandle.cancel()

    def graphsUpdate(self):
        self.scorePlot.points = self.scorePoints
        self.scorePlotMedian.points = self.scorePointsMedian

        self.fitnessPlot.points = self.fitnessPoints
        self.fitnessPlotMedian.points = self.fitnessPointsMedian

        self.scoreTimePlot.points = self.scoreTimePoints
        self.scoreTimePlotMedian.points = self.scoreTimePointsMedian

        self.genTimePlot.points = self.timeGenPoints

        xmax = self.scorePlot.points[-1][0]
        self.graphScore.xmax = 10 if xmax < 10 else xmax

        xmax = self.fitnessPlot.points[-1][0]
        self.graphFitness.xmax = 10 if xmax < 10 else xmax

        xmax = round(self.scoreTimePlot.points[-1][0], 1) + 0.1
        self.graphScoreTime.xmax = 1 if xmax < 1 else xmax

        xmax = self.genTimePlot.points[-1][0]
        self.graphGenTime.xmax = 10 if xmax < 10 else xmax

        yListScore = []
        for point in self.scorePlot.points:
            yListScore.append(point[1])
        ymax = max(yListScore)
        self.graphScore.ymax = 10 if ymax < 10 else ymax

        yListFitnesse = []
        for point in self.fitnessPlot.points:
            yListFitnesse.append(point[1])
        ymax = max(yListFitnesse)
        self.graphFitness.ymax = 10 if ymax < 10 else ymax

        yListTime = []
        for point in self.scoreTimePlot.points:
            yListTime.append(point[1])
        ymax = max(yListTime)
        self.graphScoreTime.ymax = 10 if ymax < 10 else ymax

        yListGenTime = []
        for point in self.genTimePlot.points:
            yListGenTime.append(point[1])
        ymax = round(max(yListGenTime), 1)
        self.graphGenTime.ymax = 1 if ymax < 1 else ymax

        self.graphScore.x_ticks_major = int(self.graphScore.xmax / 10)
        self.graphFitness.x_ticks_major = int(self.graphFitness.xmax / 10)
        self.graphScoreTime.x_ticks_major = float(self.graphScoreTime.xmax /
                                                  10)
        self.graphGenTime.x_ticks_major = int(self.graphGenTime.xmax / 10)

        self.graphScore.y_ticks_major = int(self.graphScore.ymax / 10)
        self.graphFitness.y_ticks_major = int(self.graphFitness.ymax / 10)
        self.graphScoreTime.y_ticks_major = int(self.graphScoreTime.ymax / 10)
        self.graphGenTime.y_ticks_major = float(self.graphGenTime.ymax / 10)

    def floatMedian(self, points):
        retPoints = []
        if len(points) > 4:
            tmpPoints = [0] * len(points)

            for i in range(len(points)):
                tmpPoints[i] = points[i][1]

            for i in range(4):
                retPoints.append((points[i][0], points[i][1]))

            for i in range(len(points) - 9 - 4):
                retPoints.append(
                    (points[i + 4][0], sorted(tmpPoints[i + 4:i + 4 + 9])[4]))

        return retPoints
Esempio n. 28
0
class Screen2(Screen):
    """Affichage en courbe de la dernière minute des normes du vecteur
    Accélération, actualisée toutes les 2 secondes
    """
    def __init__(self, **kwargs):
        """self.graph ne peut pas être initié ici.
        Il doit être dans une autre méthode et appelé plus tard.
        """

        super().__init__(**kwargs)
        self.app = App.get_running_app()

        self.graph = None
        self.ylabel = "Valeur des accélérations sur x y z"
        self.titre = "Accelerometer"
        self.xlabel = "500 valeurs"
        self.x_ticks_minor = 5
        self.x_ticks_major = 100
        self.y_ticks_major = 3000
        self.freq = 1
        self.xmax = 0
        self.ymin = -10000
        self.ymax = 10000
        self.gap = 0
        self.lenght = 500
        self.bf = 0

        # Initialisation des courbes avec la couleur
        self.curve_norme = MeshLinePlot(color=[0, 0, 0, 1])
        self.curve_norme.points = []

        self.curve_x = MeshLinePlot(color=[0, 0.8, 0, 1])
        self.curve_x.points = []

        self.curve_y = MeshLinePlot(color=[0.8, 0, 0, 1])
        self.curve_y.points = []

        self.curve_z = MeshLinePlot(color=[0, 0, 0.8, 1])
        self.curve_z.points = []

        Clock.schedule_once(self._once, 1)

    def _once(self, dt):
        Clock.schedule_interval(self.update, 0.1)
        self.create_graph()

    def histo_correction(self):
        """Les valeurs de temps manquantes sont mal affichée par Graph,
        il y a un saut du graphique au défilement, donc on ne voit pas le "trou"
        Correction de histo pour ajouter ces valeurs manquantes
        avec des valeurs xyz = 000
        """
        # hist = tout l'historique
        hist = self.app.osc.histo_xyz
        if len(hist) > 2:
            for i in range(len(hist)):
                trou = hist[i][0] - hist[i - 1][0]
                # #print(trou)
                if trou > 2:
                    index = i  # 21
                    manque = int(trou - 1)
                    # Ajout des valeurs manquantes
                    debut = hist[index - 1][0] + 1
                    for p in range(manque):
                        hist.insert(index + p, (debut + p * 1.01, [0, 0, 0]))

        self.app.osc.histo_xyz = hist

    def update(self, dt):
        """Affichage de 500 valeurs
        10 Hz = 50 s = 500 * 0.1 = 500 dizième
        20 Hz = 25 s = 500 * 0.05s
        self.lenght = 500
        f = 10, 50s = 500/10; de - 50s à 0
        f = 20, 25s = 500/20; de - 25s à 0

        self.gap = int de -beaucoup à 0, fait décalage sur les 500 couples
        """

        # Actualisation de la fréquence
        f = int(self.app.config.get('accelerometer', 'frequency'))
        if self.freq != f:
            self.freq = f
            self.create_graph()

        self.histo_correction()
        self.curve_norme.points = []
        self.curve_x.points = []
        self.curve_y.points = []
        self.curve_z.points = []

        # J'affiche 500 couples soit self.lenght = 500
        if len(self.app.osc.histo_xyz) > 5:
            nb = len(self.app.osc.histo_xyz)
            # La pile est remplie, décalage possible avec gap
            if nb > self.lenght:
                debut = nb + self.gap - self.lenght
                fin = nb + self.gap
                # La 1ère coupe est -500:500 et non pas -500:0
                if fin == 0: fin = nb
                t_debut = self.app.osc.histo_xyz[debut][0]
                # il faut [-500:500] puis [-501:-1] puis [-502:-2]
                for couple in self.app.osc.histo_xyz[debut:fin]:
                    self.add_couple(couple, t_debut)
            # Ajout de tous les couples pour remplir la pile
            # pas de décalage possible avec gap
            else:
                t_debut = self.app.osc.histo_xyz[0][0]
                for couple in self.app.osc.histo_xyz:
                    self.add_couple(couple, t_debut)

    def add_couple(self, couple, t_debut):
        x = couple[0] - t_debut - self.lenght / self.freq
        y = couple[1][0]
        self.curve_x.points.append((x, y))
        y = couple[1][1]
        self.curve_y.points.append((x, y))
        y = couple[1][2]
        self.curve_z.points.append((x, y))

    def get_xmin(self):
        """Affichage de 500 valeurs
        10 Hz = 50 s = 500 * 0.1 = 500 dizième
        20 Hz = 25 s = 500 * 0.05s
        self.lenght = 500
        f = 10, 50s = 500/10; de xmin=-50s à xmax=0
        f = 20, 25s = 500/20; de xmin=-25s à xmax=0
        """
        f = int(self.app.config.get('accelerometer', 'frequency'))

        xmin = -int(500 / f)
        print("xmin = ", xmin)
        return xmin

    def create_graph(self):
        print("Création du graph ...")
        if self.graph:
            self.ids.graph_id.remove_widget(self.graph)

        xmin = self.get_xmin()

        self.graph = Graph(background_color=(0.8, 0.8, 0.8, 1),
                           border_color=(0, 0.1, 0.1, 1),
                           xlabel=self.xlabel,
                           ylabel=self.ylabel,
                           x_ticks_minor=self.x_ticks_minor,
                           x_ticks_major=self.x_ticks_major,
                           y_ticks_major=self.y_ticks_major,
                           x_grid_label=True,
                           y_grid_label=True,
                           padding=10,
                           x_grid=True,
                           y_grid=True,
                           xmin=xmin,
                           xmax=self.xmax,
                           ymin=self.ymin,
                           ymax=self.ymax,
                           tick_color=(1, 0, 1, 1),
                           label_options={'color': (0.2, 0.2, 0.2, 1)})

        self.graph.add_plot(self.curve_x)
        self.graph.add_plot(self.curve_y)
        self.graph.add_plot(self.curve_z)
        self.ids.graph_id.add_widget(self.graph)

    def do_back_forward(self, sens):
        self.bf = 1
        bt = Thread(target=self.back_forward_loop, args=(sens, ), daemon=True)
        bt.start()

    def back_forward_loop(self, sens):
        step = 0
        while self.bf:
            step += 1
            sleep(0.1)
            self.gap += sens * 50 * step
            if self.gap > 0: self.gap = 0
            l = len(self.app.osc.histo_xyz)
            if self.gap < -l + 500: self.gap = -l + 500
            print("Gap:", self.gap)

    def do_end(self):
        self.bf = 0

    def do_last(self):
        self.gap = 0
        print("Gap:", self.gap)