def requirement_level_distributions(json):
    if not json:
        json = test_json

    req_map  ={}
    requirements_apply(json, lambda r, c: set_dictionary_insert(req_map,r['desc'],(c['name'],r['level'])))

    high_dists = []
    med_dists = []
    low_dists = []
    reqs = []
    for req, req_data in req_map.items():
        reqs.append(req)
        high_dists.append(0)
        med_dists.append(0)
        low_dists.append(0)
        for com_data in req_data:
            level = com_data[1].lower()
            if level == 'high':
                high_dists[-1] += 1
            elif level == 'medium':
                med_dists[-1] += 1
            elif level == 'low':
                low_dists[-1] += 1

    barWidth = 0.25

    # Set position of bar on X axis
    r1 = np.arange(len(high_dists))
    r2 = [x + barWidth for x in r1]
    r3 = [x + barWidth for x in r2]

    labels = []
    table_data = [("'#'", "'Component Distibution'")]
    for idx, val in enumerate(reqs, start=1):
        txt = '{}: {}'.format(idx, val)
        table_data.append((str(idx), txt))
        labels.append(str(idx))

    # Make the plot
    plt.clf()
    plt.bar(r1, high_dists, color='red', width=barWidth, edgecolor='white', label='High')
    plt.bar(r2, med_dists, color='yellow', width=barWidth, edgecolor='white', label='Medium')
    plt.bar(r3, low_dists, color='green', width=barWidth, edgecolor='white', label='Low')

    # Add xticks on the middle of the group bars
    plt.xlabel('group', fontweight='bold')
    plt.xticks([r + barWidth for r in range(len(high_dists))], labels)

    plt.title('Component Level Distribution')
    return FigureCanvasKivyAgg(plt.gcf()), table_data, None
Beispiel #2
0
    def show_graphs(self):
        if self.button_text4 == 'Show possibilities':
            pop_results("invalid input",
                        "invalid input, you must choose an option")
        else:
            x = []
            y = []
            self.data = []
            plt.clf()
            if self.button_text4 == 'Location':
                self.data = database.get_data_on_location()
                for i in self.data:
                    x.append(i[0])
                    y.append(i[1])
                plt.bar(x, y)
                plt.ylabel('Amounts')
                plt.title('Amounts by location')

            elif self.button_text4 == 'Category':
                self.data = database.get_data_on_category()
                for i in self.data:
                    x.append(i[0])
                    y.append(i[1])
                plt.plot(x, y)
                plt.ylabel('Amounts')
                plt.title('Amounts by category')
            else:
                self.data = database.get_data_on_amounts()
                for i in self.data:
                    x.append(i[0])
                    y.append(i[1])
                fig = plt.figure()
                ax = fig.add_axes([0, 0, 1, 1])
                ax.axis('equal')
                ax.set_title("Distribution of quantities")
                ax.pie(y, labels=x, autopct='%1.2f%%')

            welcomePage = FloatLayout()
            box = BoxLayout(orientation='vertical',
                            size_hint=(0.95, 0.5),
                            padding=8,
                            pos_hint={
                                'top': 0.7,
                                'center_x': 0.5
                            })

            box.add_widget(FigureCanvasKivyAgg(plt.gcf()))

            welcomePage.add_widget(box)
            self.add_widget(welcomePage)
 def plot_waveform(self):
     plt.close('all')
     y, sr = librosa.load(self.audio_file)
     fig = plt.figure(frameon=False)
     fig.patch.set_facecolor('#000000')
     fig.patch.set_alpha(0)
     plt.subplot(1, 1, 1)
     # getting subplot to fill the figure
     plt.gca().set_position([0, 0, 1, 1])
     plt.axis('off')
     librosa.display.waveplot(y, sr=sr)
     canvas = FigureCanvasKivyAgg(plt.gcf(), pos_hint={'x': 0, 'y': 0})
     canvas.canvas.opacity = 0.9
     self.waveform.add_widget(canvas)
Beispiel #4
0
    def print_output(self, co, res, err):
        self._hide_widget(co, False)
        co.clear_widgets()

        if err:
            co.text = str(err)
            co.color = (1, 0, 0, 1)
        else:
            if isinstance(res, ndarray):
                co.text = ' ' + sub(r'[\[\]]', '', str(res))
            elif isinstance(res, Figure):
                plot_widget = FigureCanvasKivyAgg(res)
                plot_widget.size = self.size
                co.size = plot_widget.size
                co.add_widget(plot_widget)
                return
            else:
                co.text = str(res)
            co.color = (1, 1, 1, 1)

        co.text_size = self.width, None
        co.size_update()
        self._hide_widget(co, True)
Beispiel #5
0
def get_squarewave_plot():
    settings, burstmode, burstperiod, burstduration, \
    dutycycle, interburst, anodic, phase_1_current, \
    phase_2_current, interphase, phasetime1, phasetime2, \
    interstim, frequency, ramp_up, short, burstfrequency, \
    pulsenumber, stimduration, burstnumber, pulseperiod, \
    vref_lower_output_input, vref_upper_output_input = get_stimulator_input()

    # points on y-axis
    if anodic:
        I = [0, phase_1_current, phase_1_current, 0, 0, -phase_2_current, -phase_2_current, 0, 0]
    else:
        I = [0, -phase_1_current, -phase_1_current, 0, 0, phase_2_current, phase_2_current, 0, 0]

    # points on x-axis
    # timing of first cycle
    T = [0, 0, phasetime1, phasetime1, phasetime1 + interphase, phasetime1 + interphase,
         phasetime1 + phasetime2 + interphase, phasetime1 + phasetime2 + interphase,
         phasetime1 + phasetime2 + interphase + interstim]

    # if its continuous stim, graph stop plotting after one period
    # if its burst stim, graph stop plotting after one burst period
    if burstmode:
        # constantly add last element of previous "T list"to all element in previous T to make the point on y-axis
        b = T.copy()
        while (b[len(b) - 1] + pulseperiod < (burstduration)):
            for i in range(len(b)):
                b[i] = T[i] + b[len(b) - 1]
            T = T + b

        # change the T[-1]to burstduration
        T[len(T) - 1] = burstduration
        # count how many element in the T list, divide by the 9, and repeat V list this many time, make set V2
        m = I.copy()
        for i in range(int(len(T) / 9.0 - 1)):
            m = m + I
        I = m
        # add one more element to T, that is burstduration + interburst
        T.append(burstduration + interburst)
        I.append(0)

    plt.close("all")

    if burstduration > pulseperiod and burstmode or not burstmode:
        plt.plot(T, I)
        plt.xlabel('Time (us)')
        plt.ylabel('Current (uA)')

    return FigureCanvasKivyAgg(plt.gcf())
Beispiel #6
0
def get_squarewave_plot():
    settings, burst, burstperiod, burstduration, \
    dutycycle, interburst, anodic, current, interphase, \
    phasetime1, phasetime2, interstim, frequency, burstfrequency, \
    pulsenumber, stimduration, burstnumber = get_stimulator_input()

    # points on y-axis
    andoic = [0, 1, 1, 0, 0, -1, -1, 0, 0]
    cathodic = [0, -1, -1, 0, 0, 1, 1, 0, 0]
    if anodic:
        I = [i * current for i in andoic]
    else:
        I = [i * current for i in cathodic]

    # points on x-axis
    # timing of frist cycle
    T = [0, 0, phasetime1, phasetime1, phasetime1 + interphase, phasetime1 + interphase,
         phasetime1 + phasetime2 + interphase, phasetime1 + phasetime2 + interphase,
         phasetime1 + phasetime2 + interphase + interstim]

    # if its continous stim, graph stop plotting after one period
    # if its burst stim, graph stop plotting after one burst period
    if burst:
        # constantly add last element of previous "T list"to all element in previous T to make the point on y-axis
        b = T.copy()
        while (b[len(b) - 1] + phasetime1 + phasetime2 + interphase + interstim < (burstduration)):
            for i in range(len(b)):
                b[i] = T[i] + b[len(b) - 1]
            T = T + b

        # change the T[-1]to burstduration
        T[len(T) - 1] = burstduration
        # count how many element in the T list, divide by the 9, and repeat V list this many time, make set V2
        m = I.copy()
        for i in range(int(len(T) / 9.0 - 1)):
            m = m + I
        I = m
        # add one more element to T, that is burstduration + interburst
        T.append(burstduration + interburst)
        I.append(0)

    #if burstduration > interstim + phasetime1 + phasetime2 + interphase:
        plt.close("all")
        plt.plot(T, I)
        plt.xlabel('Time (us)')
        plt.ylabel('Current (uA)')

    return FigureCanvasKivyAgg(plt.gcf())
Beispiel #7
0
    def __init__(self, **kwargs):
        super(Bar_Chart, self).__init__(**kwargs)

        ## Set View Constraints ##
        self.size_hint = (0.8, 0.8)
        self.pos_hint = {
            'center_y': 0.503,
            'center_x': 0.5
        }  #left right top bottom

        ## Create Graph ##
        plt.clf()  # Clear all
        plt.rcParams['font.size'] = 25.0  # Set Font Size of Words
        # print(selectedButton.freqdata)
        default_arr = selectedButton.freqdata
        #remove @ entry if exists
        if ("@" in default_arr):
            del default_arr["@"]

        #Limits data to max 5
        sorted_arr = sorted(default_arr, key=default_arr.get, reverse=True)
        frequencyarr = {}
        count = 0
        #others_count = 0
        for i in sorted_arr:
            if (count <= 5):
                frequencyarr[i] = selectedButton.freqdata[i]
                count += 1
        #else:
        #others_count+=selectedButton.freqdata[i]
        #if(len(sorted_arr)>5):
        #frequencyarr["others"] = others_count

        objects = []
        performance = []
        for item in frequencyarr.keys():
            objects.append(item)
            performance.append(frequencyarr[item])
        objects = tuple(objects)
        y_pos = np.arange(len(objects))

        plt.bar(y_pos, performance, align='center', alpha=0.5)
        plt.xticks(y_pos, objects)
        plt.ylabel('Responses')
        plt.title('Amount of Responses')

        ## Add Graph to Self ##
        self.add_widget(FigureCanvasKivyAgg(plt.gcf()))
def component_level_distributions(json):
    if not json:
        json = test_json
    com_req = JSON.loads(json)['components']
    high_dists = []
    med_dists = []
    low_dists = []
    coms = []
    for cr in com_req:
        coms.append(cr['name'])
        high_dists.append(0)
        med_dists.append(0)
        low_dists.append(0)
        for req in cr['requirements']:
            level = req['level'].lower()
            if level == 'high':
                high_dists[-1] += 1
            elif level == 'medium':
                med_dists[-1] += 1
            elif level == 'low':
                low_dists[-1] += 1

    barWidth = 0.25

    # Set position of bar on X axis
    r1 = np.arange(len(high_dists))
    r2 = [x + barWidth for x in r1]
    r3 = [x + barWidth for x in r2]

    labels = []
    table_data = [("'#'", "'Component Distibution'")]
    for idx, val in enumerate(coms, start=1):
        txt = '{}: {}'.format(idx, val)
        table_data.append((str(idx), txt))
        labels.append(str(idx))

    # Make the plot
    plt.clf()
    plt.bar(r1, high_dists, color='red', width=barWidth, edgecolor='white', label='High')
    plt.bar(r2, med_dists, color='yellow', width=barWidth, edgecolor='white', label='Medium')
    plt.bar(r3, low_dists, color='green', width=barWidth, edgecolor='white', label='Low')

    # Add xticks on the middle of the group bars
    plt.xlabel('group', fontweight='bold')
    plt.xticks([r + barWidth for r in range(len(high_dists))], labels)

    plt.title('Component Level Distribution')
    return FigureCanvasKivyAgg(plt.gcf()), table_data, None
def component_correlation(json):
    if not json:
        json = test_json
    com_req = JSON.loads(json)['components']
    com_dict = {}
    com_scores = {}
    coms = []
    reqs = set()
    reverse_keys = set()

    for cr in com_req:
        coms.append(cr['name'])
        com_dict[cr['name']] = cr['requirements']
        for req in cr['requirements']:
            reqs.add(req['desc'])

    for com_pair in itertools.product(coms,coms):
        if com_pair[0] == com_pair[1]:
            continue
        key = '{}~.~{}'.format(com_pair[0],com_pair[1])
        reverse_key =  '{}~.~{}'.format(com_pair[1],com_pair[0])
        if key not in com_scores and key not in reverse_keys:
            idx1 = coms.index(com_pair[0])
            idx2 = coms.index(com_pair[1])
            score = generate_correlation_score(com_req[idx1]['requirements'],com_req[idx2]['requirements'],len(reqs))
            if score > 0.0:
                com_scores[key] = score
            reverse_keys.add(reverse_key) #prevent duplicate

    sorted_table =[('#','Correlation')]
    sorted_scores = []
    sorted_labels = []

    for i, x in enumerate(sorted(com_scores.items(), key=itemgetter(1), reverse=True)):
        comps = '{}: {:.2%}'.format(x[0].replace('~.~',' <--> '),x[1])
        sorted_table.append((str(i+1),comps))
        sorted_scores.append(x[1]*100)
        sorted_labels.append(str(i+1))

    labels_tuple = tuple(sorted_labels[:20])
    y_pos = np.arange(len(labels_tuple))
    plt.clf()
    plt.barh(y_pos, sorted_scores[:20], align='center', alpha=0.5)
    plt.yticks(y_pos, labels_tuple)
    plt.xlabel('Component Composition')

    plt.title('Component Correlation')
    return FigureCanvasKivyAgg(plt.gcf()), sorted_table, (coms,reqs)
 def filter_and_plot(self, photo, threshold):
     show_greyscale = ""
     if (self.switch.active):
         if (self.vertical_button.state == "down"):
             show_greyscale = "Vertical"
         elif (self.horizontal_button.state == "down"):
             show_greyscale = "Horizontal"
     else:
         self.vertical_button.state = "normal"
         self.horizontal_button.state = "normal"
         show_greyscale = "None"
     self.ids.plot_field.clear_widgets()
     plt.clf()
     self.preprocessed_digits = filter_and_plot(photo, threshold,
                                                show_greyscale)
     self.ids.plot_field.add_widget(FigureCanvasKivyAgg(plt.gcf()))
Beispiel #11
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        global FRAME_TIME
        global FRAME_NUM

        # 初期化に用いるデータ
        x = np.linspace(1, FRAME_NUM, FRAME_NUM)
        y = np.zeros(FRAME_NUM)

        # Figure, Axis を保存しておく
        self.fig, self.ax = plt.subplots(4, facecolor="0.1")
        self.ax[0].tick_params(axis='x', colors="0.8")
        self.ax[0].tick_params(axis='y', colors="0.8")
        self.ax[0].set_facecolor((0.4, 0.4, 0.4, 1))
        self.ax[0].grid(axis='y')
        self.ax[0].set_ylim([-100, 160])
        self.ax[1].tick_params(axis='x', colors="0.8")
        self.ax[1].tick_params(axis='y', colors="0.8")
        self.ax[1].set_facecolor((0.4, 0.4, 0.4, 1))
        self.ax[1].set_ylim([-1, 4.2])
        self.ax[2].tick_params(axis='x', colors="0.8")
        self.ax[2].tick_params(axis='y', colors="0.8")
        self.ax[2].set_facecolor((0.4, 0.4, 0.4, 1))
        self.ax[2].set_ylim([-0.5, 200])
        self.ax[3].set_facecolor((0.4, 0.4, 0.4, 1))

        # 最初に描画したときの Line も保存しておく
        self.line11, = self.ax[0].plot(x, y, label="sensor1")
        self.line12, = self.ax[0].plot(x, y, label="sensor2")
        self.line13, = self.ax[0].plot(x, y, label="sensor3")
        self.line14, = self.ax[0].plot(x, y, label="sensor4")

        self.line21, = self.ax[1].plot(x, y, label="position")
        self.line22, = self.ax[1].plot(x, y, label="activeSensorsNum")
        self.line23, = self.ax[1].plot(x, y, label="PIDresponse")

        self.line31, = self.ax[2].plot(x, y, label="rightPower")
        self.line32, = self.ax[2].plot(x, y, label="leftPower")

        self.line41, = self.ax[3].plot([], [])
        # ウィジェットとしてグラフを追加する
        widget = FigureCanvasKivyAgg(self.fig)
        self.add_widget(widget)

        # frame_time秒ごとに表示を更新するタイマーを仕掛ける
        Clock.schedule_interval(self.update_view, FRAME_TIME / 1000)
def requirement_correlation(json):
    if not json:
        json = test_json
    com_req = JSON.loads(json)['components']
    req_dict = {}
    req_scores = {}
    reverse_keys = set()
    reqs = []
    for cr in com_req:
        for req in cr['requirements']:
            if req['desc'] not in reqs:
                reqs.append(req['desc'])
                req_dict[req['desc']] = []
            req_dict[req['desc']].append({'desc':cr['name'],'level':req['level']})

    for req_pair in itertools.product(reqs,reqs):
        if req_pair[0] == req_pair[1]:
            continue
        key = '{}~.~{}'.format(req_pair[0],req_pair[1])
        reverse_key = '{}~.~{}'.format(req_pair[1], req_pair[0])

        if key not in req_scores and key not in reverse_keys:
            score = generate_correlation_score(req_dict[req_pair[0]],req_dict[req_pair[1]], len(com_req))
            if score > 0.0:
                req_scores[key] = score
            reverse_keys.add(reverse_key)  # prevent duplicate

    sorted_table =[('#','Correlation')]
    sorted_scores = []
    sorted_labels = []

    for i, x in enumerate(sorted(req_scores.items(), key=itemgetter(1), reverse=True)):
        comps = '{}: {:.2%}'.format(x[0].replace('~.~', ' -> '),x[1])
        sorted_table.append((str(i+1),comps))
        sorted_scores.append(x[1]*100)
        sorted_labels.append(str(i+1))

    #sorted_scores = [(str(i),x[0].replace('~.~','->')+': '+str(x[1])) for i,x in enumerate(sorted(com_scores.items(), key=itemgetter(1),reverse=True))]
    labels_tuple = tuple(sorted_labels[:20])
    y_pos = np.arange(len(labels_tuple))
    plt.clf()
    plt.barh(y_pos, sorted_scores[:20], align='center', alpha=0.5)
    plt.yticks(y_pos, labels_tuple)
    plt.xlabel('Requirement Composition')

    plt.title('Requirement Correlation')
    return FigureCanvasKivyAgg(plt.gcf()), sorted_table, None
Beispiel #13
0
    def view_CV(self, instance):
        if self.param_CV_scores is None: return

        choose_param_val = int(self.method_param.text)
        if choose_param_val not in self.values_param: return
        param_val_i = self.values_param.index(choose_param_val)

        self.box_CV.remove_widget(self.param_CV)
        self.param_CV = FigureCanvasKivyAgg(plt.figure(6))
        self.box_CV.add_widget(self.param_CV)
        plt.figure(6)
        plt.clf() ; plt.cla()
        CV_scores = self.param_CV_scores[param_val_i]
        plt.plot(list(range(1, len(CV_scores)+1)), CV_scores)
        plt.ylabel("Точность")
        plt.xlabel("Номер эксперимента")
        plt.title(f"CV для параметра '{self.method_param_name.text}'({self.values_param[param_val_i]})", fontsize=self.fs)
Beispiel #14
0
    def __init__(self, name, data):
        super(StatusScreen, self).__init__()
        self.size_hint = (.9, .9)
        self.title = name

        last_cleared = 0

        clear_text = ""

        for i in range(1, len(data)):
            if data[-i] - data[-i - 1] < 0:
                last_cleared = i - 1
                break

            else:
                last_cleared = -1

        days_cleared = last_cleared // 24

        if last_cleared == -1:
            clear_text = "Bin has not been cleared"

        else:
            if days_cleared == 0:
                clear_text = "Bin was last cleared " + str(
                    last_cleared) + " hours ago"
            else:
                clear_text = "Bin was last cleared " + str(
                    days_cleared) + " days and " + str(
                        last_cleared - days_cleared * 24) + " hours ago"

        box = BoxLayout(orientation="vertical")

        #plot the measured data in a graph
        plt.clf()
        plt.plot(data)

        label = Label(text="7 Day Statistics", size_hint=(1, 0.1))
        label1 = Label(text=clear_text, size_hint=(1, 0.1))

        box.add_widget(label)
        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        box.add_widget(label1)

        with self.canvas:
            self.add_widget(box)
Beispiel #15
0
 def press(self, instance):
     if len(self.binaryNumberGraph.text) != 12:
         print("El número debe ser de 12 bits")
     else:
         print("entré")
         plt.clf()
         self.plotGrid.remove_widget(self.plot)
         self.plotGrid.remove_widget(self.volverGrid)
         x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
         y = self.binaryNumberGraph.text
         print("dato y:")
         print(y)
         y = [int(x) for x in y]
         plt.step(x, y)
         plt.xticks(x)
         plt.yticks([0, 1])
         self.plot = FigureCanvasKivyAgg(plt.gcf())
         self.plotGrid.add_widget(self.plot)
         self.plotGrid.add_widget(self.volverGrid)
Beispiel #16
0
    def __init__(self, **kwargs):
        super(SetupScreen, self).__init__(orientation="vertical", **kwargs)
        self.add_widget(FigureCanvasKivyAgg(p.fig))

        def click_update(event):
            p.on_click(event)

        p.fig.canvas.mpl_connect('button_press_event', click_update)

        self.parameters_box = BoxLayout(size_hint=(1, 0.1))

        self.steps = ParameterSlider(text="Steps",
                                     lb=100,
                                     ub=2000,
                                     value=500,
                                     round_to=0)
        self.parameters_box.add_widget(self.steps)

        self.temperature = ParameterSlider(text="Temperature",
                                           lb=10,
                                           ub=100,
                                           value=20)
        self.parameters_box.add_widget(self.temperature)

        self.alpha = ParameterSlider(text="Alpha",
                                     lb=0.8,
                                     ub=0.999,
                                     value=0.99,
                                     round_to=4)
        self.parameters_box.add_widget(self.alpha)

        animate_button = Button(text="Animate")
        animate_button.bind(on_press=self.animate)
        self.parameters_box.add_widget(animate_button)

        def clear(_):
            p.clear()

        clear_button = Button(text="Clear")
        clear_button.bind(on_press=clear)
        self.parameters_box.add_widget(clear_button)

        self.add_widget(self.parameters_box)
Beispiel #17
0
    def draw(self):
        try:
            plt.clf()
        except:
            pass
        fig, ax1 = plt.subplots()
        ax1.set_xlabel('time')
        ax1.plot(plot_data_1, label='Exp1')
        ax1.plot(plot_data_2, label='Exp2')
        ax1.plot(plot_data_3, label='Exp3')
        ax1.plot(plot_data_4, label='Exp4')
        ax1.plot(plot_data_5, label='Exp5')
        ax1.plot(plot_data_6, label='Exp6')
        ax1.plot(plot_data_7, label='Exp7')
        ax1.plot(plot_data_8, label='Exp8')
        ax1.set_ylabel('c(CO2) / [ppm]')
        plt.legend(bbox_to_anchor=(1.15,1), loc="upper left", borderaxespad=0)

        ax2 = ax1.twinx()
        ax2.plot(plot_data_9, label='light')
        ax2.plot(plot_data_10, label='temperature')
        ax2.set_ylabel('light ; temperature / [C]')
        fig.tight_layout()
        fig.subplots_adjust(right=0.70)
        plt.legend(bbox_to_anchor=(1.15,0), loc="lower left", borderaxespad=0)

        print plot_data_9
        print plot_data_10

        popup_plt = Popup(title='Graphical representation of data', size_hint=(0.9,0.9), separator_color=(1,0,0,1))
        plt_box = BoxLayout(size_hint_y=0.95)
        plt_box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        box_btn = BoxLayout(orientation='horizontal', size_hint_y=0.05)
        cls_btn = Button(text='Close')
        box_btn.add_widget(cls_btn)
        cont_box=BoxLayout(orientation='vertical')
        cont_box.add_widget(plt_box)
        cont_box.add_widget(box_btn)
        popup_plt.add_widget(cont_box)

        popup_plt.open()

        cls_btn.bind(on_release=popup_plt.dismiss)
Beispiel #18
0
 def __init__(self, **kwargs):
     super(PlotBox_temp, self).__init__(**kwargs)
     # Set the animation update interval
     temp_anim_interval_ms = 200
     # Add figure to canvas
     self.add_widget(FigureCanvasKivyAgg(figure=fig_temp))
     # Add animation to figure
     self.anim = animation.FuncAnimation(fig_temp,
                                         func_animate_temp,
                                         interval=temp_anim_interval_ms)
     # Set axis variables
     ax1_temp.set_title("Temperature")
     ax1_temp.set_ylabel("\u00b0C")
     ax1_temp.set_xlabel("Time")
     ax1_temp.grid(which='both')
     # Hide x-axis labels at plot startup
     ax1_temp.set_xticklabels([])
     # First empty plot
     ax1_temp.plot_date(xs_temp, ys_temp, marker='o', linestyle='-')
Beispiel #19
0
    def makePlot(self, errorbar):
        target = App.get_running_app().root

        if not self.plotFitnessLog:
            return

        if (errorbar):
            target.ids.graphButton1.state = "down"
            target.ids.graphButton2.state = "normal"
            self.currentGraph = 1
        else:
            target.ids.graphButton1.state = "normal"
            target.ids.graphButton2.state = "down"
            self.currentGraph = 2

        plt.plotFitness(self.plotFitnessLog, self.task, self.nameList,
                        errorbar)
        target = App.get_running_app().root
        target.ids.image.clear_widgets()
        target.ids.image.add_widget(FigureCanvasKivyAgg(plt.pyplot.gcf()))
Beispiel #20
0
    def plotpopup(self):
        """This plotpopu show the energy plots on a popup when the giant 'Energy' button
        on the UI is pressed, this was originally and experiment and I ran out of time to 
        change it. It should be done like the histograms and embed the FigureCanvasKivyAgg in
        the UI directly"""
        self.eplot = Figure()
        t = np.arange(self.dt,self.T+self.dt,self.dt)
        ax = self.eplot.add_subplot(111)
        
        ax.plot(t,self.s.K,'r-',label = 'Kinetic Energy')
        ax.plot(t,self.s.U,'b-',label = 'Potential Energy')
        ax.plot(t,self.s.K+self.s.U,'g-',label = 'Total Energy')
#        plt.plot(t,self.s.Kmean,'g-',label = 'Mean Kinetic Energy')
        ax.legend(loc=1)
        ax.set_xlabel('t')
        
        self.ecanvas = FigureCanvasKivyAgg(self.eplot)
        content = self.ecanvas
        self._popup = Popup(title ='Energy conservation',content = content, size_hint=(0.9,0.9))
        self._popup.open()
Beispiel #21
0
    def candle_stick_plot(self, stock, table):
        """
        Display OHLC candlestick graph
        :param stock: stock symbol
        :param table: Stocks/Crypto
        :return: None
        """
        self.ids.graph.remove_plot(self.plot)
        points = DisplayGraphs().candle_stick(stock, table)
        # self.plot = mpf.plot(points, type='candle', title=stock, figsize=(1, 1), volume=True)

        fig, ax = plt.subplot()
        # fig.size = 0.75, 0.75

        # Setting labels & titles
        ax.set_xlabel('Date')
        self.plot.ylabel('Price')
        # sticks = mpf.plot(points, type='candle', title=stock, figsize=(1, 1), volume=True)
        # print(sticks.__sizeof__())
        # plot.points = sticks
        self.add_widget(FigureCanvasKivyAgg(figure=fig))
Beispiel #22
0
    def __init__(self, **kwargs):
        super(WellPlot, self).__init__(**kwargs)

        # load configs
        self.cwd = os.getcwd()
        self.config_path = os.path.join(self.cwd, "wellLitConfig.json")
        with open(self.config_path) as json_file:
            self.configs = json.load(json_file)
        A1_X = self.configs["A1_X"]
        A1_Y = self.configs["A1_Y"]
        WELL_SPACING = self.configs["WELL_SPACING"]
        SHAPE = self.configs["MARKER_SHAPE"]
        if SHAPE == 'circle':
            SIZE_PARAM = self.configs["CIRC_RADIUIS"]
            SHAPE = self.configs["MARKER_SHAPE"]
        elif SHAPE == 'square':
            SIZE_PARAM = self.configs["SQUARE_LENGTH"]

        # set up PlateLighting object
        self.pl = PlateLighting(A1_X, A1_Y, SHAPE, SIZE_PARAM, WELL_SPACING)
        self.add_widget(FigureCanvasKivyAgg(figure=self.pl.fig))
    def __init__(self, **kwargs):

        super(Results, self).__init__(**kwargs)

        # Get example user data...
        self.get_user_data()

        layout_box = BoxLayout(orientation='vertical')
        layout_box.add_widget(Label(text='Twoje wyniki', font_size='20sp'))
        plt.plot(self.user_data.get('dates'), self.user_data.get('scores'))
        plt.xlabel('Data')
        plt.ylabel('Wynik')
        layout_box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        back_button = Button(text="Powrót",
                             pos_hint={
                                 "center_x": 0.5,
                                 "center_y": 0.5
                             },
                             on_press=self.on_back)
        layout_box.add_widget(back_button)
        self.add_widget(layout_box)
    def draw_my_plot(self):
        self.figure_1 = Figure(figsize=(2, 2))
        self.figure_1.subplots_adjust(left=0.13, right=0.93, bottom=0.25,
                                      top=0.98)  # to expand and occupy full area around imshow
        #self.panel_col = (1,0,0)
        self.x_vals = np.arange(0, 10, 0.01)
        self.y_vals = np.zeros(len(self.x_vals))
        #self.figure_1.set_facecolor(self.rgb_to_hex(self.panel_col))
        self.axes = self.figure_1.add_subplot(111)
        self.canvas_speech = FigureCanvas(self.figure_1)
        self.axes.set_xlim(0, 10)
        self.axes.set_ylim(-1, 1)


        #self.axes.set_facecolor(self.rgb_to_hex(self.panel_col))
        self.axes.grid(True, color='lightgray')
        #self.axes.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
        self.axes.set_xlabel('Time (s)', fontsize=10, labelpad=0)
        self.axes.set_ylabel('Signal (norm)', fontsize=10, labelpad=0)
        self.line11, = self.axes.plot(self.x_vals, self.y_vals, "b", linewidth=0.5)



        self.axes.plot(self.x_vals, self.y_vals, "b", linewidth=0.5)
        self.canvas_speech.draw_idle()
        #self.canvas_speech.Refresh()

        # Draw 2 line on speech graph
        self.line_a = lines.Line2D((0.25, 0.25), (-1, 1), picker=5, color="r", linewidth=2)
        self.line_b = lines.Line2D((9.75, 9.75), (-1, 1), picker=5, color="r", linewidth=2)
        self.a_point = 0.25
        self.b_point = 9.75
        self.draggable_line_a(self.line_a, self.axes)
        self.draggable_line_b(self.line_b, self.axes)

        self.axes.add_line(self.line_a)
        self.axes.add_line(self.line_b)


        self.add_widget(self.canvas_speech, 1) #<==== This adds a graph above the first row (index=1)
Beispiel #25
0
    def initialize(self, config_path):
        # load configs
        with open(config_path) as json_file:
            configs = json.load(json_file)

        self.num_wells = configs['num_wells']

        if self.type == 'source_plate':
            A1_X = configs[self.num_wells]["A1_X_source"]
            A1_Y = configs[self.num_wells]["A1_Y_source"]

        if self.type == 'dest_plate':
            A1_X = configs[self.num_wells]["A1_X_dest"]
            A1_Y = configs[self.num_wells]["A1_Y_dest"]

        size_param = configs[self.num_wells]["size_param"]
        well_spacing = configs[self.num_wells]["well_spacing"]

        # set up PlateLighting object
        self.pl = PlateLighting(A1_X, A1_Y, self.shape, size_param,
                                well_spacing, self.num_wells)
        self.add_widget(FigureCanvasKivyAgg(figure=self.pl.fig))
def requirement_influence(json):
    if not json:
        json = test_json
    com_req = JSON.loads(json)['components']

    req_com = {}
    coms = set()

    for com in com_req:
        coms.add(com['name'])
        for req in com['requirements']:
            if req['desc'] not in req_com:
                req_com[req['desc']] = []
            req_com[req['desc']].append({'name':com['name'],'level':req['level']})

    com_count = len(coms)

    reqs = sorted([(req, get_requirement_score(coms)) for req,coms in req_com.items() ], key=itemgetter(1), reverse=True)

    labels = []
    values = list(map(lambda x: x[1] / com_count, reqs))

    table_data = [("'#'","'Component Coverage'")]
    for idx, val in enumerate(reqs, start=1):
        v = values[idx - 1]
        txt = '{}: {:.2%}'.format(val[0], v)
        table_data.append((str(idx), txt))
        labels.append(str(idx))
    # explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(values, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    plt.title('Requirement Influence(Levels are Weighted In)')
    return FigureCanvasKivyAgg(plt.gcf()), table_data, None
Beispiel #27
0
    def _reinit_graph(self, has_legend=True):
        # Clears graph.
        while len(self.plotbox.children) > 0:
            for widget in self.plotbox.children:
                if isinstance(widget, FigureCanvasKivyAgg):
                    self.plotbox.remove_widget(widget)
        
        fig, ax = plt.subplots()
        self.current_fig = fig
        self.current_ax = ax

        ax.xaxis.label.set_size(16)
        ax.yaxis.label.set_size(16)
        plt.rcParams.update({'font.size': 18, 'xtick.labelsize': 12, 'ytick.labelsize': 12,
                             'lines.linewidth': 2})
        plt.rc('legend', **{'fontsize': 10})

        if has_legend:
            box = ax.get_position()
            ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])

        plotbox = self.plotbox
        canvas = FigureCanvasKivyAgg(self.current_fig)
        plotbox.add_widget(canvas, index=0)
Beispiel #28
0
    def grafico_3d(self, r1, cnt1, r2, cnt2, r3, cnt3):
        plt.style.use('dark_background')  # tema escuro

        x1, y1 = self.pontos_circulo(r1, cnt1)  # dados de plotagem do circulo
        x2, y2 = self.pontos_circulo(r2, cnt2)  # dados de plotagem do circulo
        x3, y3 = self.pontos_circulo(r3, cnt3)  # dados de plotagem do circulo

        fig, grafico = plt.subplots()  # variavel que armazena o grafico

        grafico.plot(x1, y1)  # plot do círculo 1
        grafico.plot(x2, y2)  # plot do círculo 2
        grafico.plot(x3, y3)  # plot do círculo 3

        grafico.grid(True, linestyle='--')  # grade
        grafico.set(xlabel='Tensão Normal',
                    ylabel='Cisalhamento',
                    title='Círculo de Mohr',
                    aspect='equal')  # ajustes

        ylim1, ylim2 = plt.ylim()  # invertendo o eixo do grafico
        plt.ylim(ylim2, ylim1)  # invertendo o eixo do grafico

        self.clear_widgets()
        self.add_widget(FigureCanvasKivyAgg(plt.gcf()))
    def __init__(self, **kwargs):
        super(Classical, self).__init__(**kwargs)

        #Language:
        self.language = "CA"
        self.time_label = "Temps"
        self.but1 = "Sobre el pic"
        self.but2 = "En el pic"
        self.but3 = "Sota el pic"
        self.cabut.color = (0,0.75,1,1)
        self.esbut.color = (1,1,1,1)
        self.enbut.color = (1,1,1,1)

        "Classical definitions"
        self.time_cla = 0.
        self.height_cla = 0.3
        self.sigma_cla =  1./(np.sqrt(2*np.pi)*self.height_cla)
        self.mu_cla = 0
        rob.m = 5

        self.R = 0.2

        self.k_cla = 0.5
        self.tmax_cla = 10

        self.xo_cla = 1.5
        self.yin0 = np.array([self.xo_cla,0.0])  #Check if this is needed.
        self.timeslide_cla.disabled = True  #It is not allowed to move the time bar.

        self.xarr_cla = xarr_cla = np.arange(-20, 20 + (20 - (-20))/float(1000)*0.1, (20 - (-20))/float(1000)) #Why not?
        #It initially used xarr_qua. But since the programs were separated, it uses this. It is only for plotting purposes.

        #Flux controllers.
        self.oldtop2_cla = self.height_cla
        self.oldk2_cla = self.k_cla

        #Clock (Classical):
        self.time_cla = 0.
        self.dtime0_cla = 0.01 #Default time step (used by RK4 and as default playing velocity).

        self.dtime_cla = 1.2*self.dtime0_cla #Defines the playing velocity = 1.

        self.oldtime1_cla = self.time_cla + 1
        self.oldrow = -1

        #Plots (Classical):
        self.canvas_cla = FigureCanvasKivyAgg(fig_cla)
        self.panel1.add_widget(self.canvas_cla)

        acl.axis('scaled')
        acl.set_xlabel("x (m)")
        acl.set_ylabel("y (m)")
        acl.axis([-2.5, 2.5, 0 , 3])

        self.ground_cla, = acl.plot(self.xarr_cla, rob.fground(self.mu_cla, self.sigma_cla, self.k_cla, self.xarr_cla), 'k--')
        self.filled_cla = acl.fill_between(self.xarr_cla, 0, rob.fground(self.mu_cla, self.sigma_cla, self.k_cla, self.xarr_cla), color = (0.5,0.5,0.5,0.5))
        self.ballcm, = acl.plot([], [], 'ro', ms=1)
        self.ballperim, = acl.plot([], [], 'r-', lw=1)
        self.filled_ball_cla = acl.fill_between([], []) #Empty one. Needs to be here in order to use self.name.remove() later.
        self.balldots, = acl.plot([], [], 'ro', ms=1)
        self.E_cla, = acl.plot([],[], 'g-.', lw=1, label = "E")
        acl.legend(loc=1)

        #First computations:
        self.demo1_cla_btn()
        Clock.schedule_interval(self.ballupdate, self.dtime0_cla)
class Classical(BoxLayout):
    time_label = StringProperty()
    but1 = StringProperty()
    but2 = StringProperty()
    but3 = StringProperty()
    language = StringProperty()

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

        #Language:
        self.language = "CA"
        self.time_label = "Temps"
        self.but1 = "Sobre el pic"
        self.but2 = "En el pic"
        self.but3 = "Sota el pic"
        self.cabut.color = (0,0.75,1,1)
        self.esbut.color = (1,1,1,1)
        self.enbut.color = (1,1,1,1)

        "Classical definitions"
        self.time_cla = 0.
        self.height_cla = 0.3
        self.sigma_cla =  1./(np.sqrt(2*np.pi)*self.height_cla)
        self.mu_cla = 0
        rob.m = 5

        self.R = 0.2

        self.k_cla = 0.5
        self.tmax_cla = 10

        self.xo_cla = 1.5
        self.yin0 = np.array([self.xo_cla,0.0])  #Check if this is needed.
        self.timeslide_cla.disabled = True  #It is not allowed to move the time bar.

        self.xarr_cla = xarr_cla = np.arange(-20, 20 + (20 - (-20))/float(1000)*0.1, (20 - (-20))/float(1000)) #Why not?
        #It initially used xarr_qua. But since the programs were separated, it uses this. It is only for plotting purposes.

        #Flux controllers.
        self.oldtop2_cla = self.height_cla
        self.oldk2_cla = self.k_cla

        #Clock (Classical):
        self.time_cla = 0.
        self.dtime0_cla = 0.01 #Default time step (used by RK4 and as default playing velocity).

        self.dtime_cla = 1.2*self.dtime0_cla #Defines the playing velocity = 1.

        self.oldtime1_cla = self.time_cla + 1
        self.oldrow = -1

        #Plots (Classical):
        self.canvas_cla = FigureCanvasKivyAgg(fig_cla)
        self.panel1.add_widget(self.canvas_cla)

        acl.axis('scaled')
        acl.set_xlabel("x (m)")
        acl.set_ylabel("y (m)")
        acl.axis([-2.5, 2.5, 0 , 3])

        self.ground_cla, = acl.plot(self.xarr_cla, rob.fground(self.mu_cla, self.sigma_cla, self.k_cla, self.xarr_cla), 'k--')
        self.filled_cla = acl.fill_between(self.xarr_cla, 0, rob.fground(self.mu_cla, self.sigma_cla, self.k_cla, self.xarr_cla), color = (0.5,0.5,0.5,0.5))
        self.ballcm, = acl.plot([], [], 'ro', ms=1)
        self.ballperim, = acl.plot([], [], 'r-', lw=1)
        self.filled_ball_cla = acl.fill_between([], []) #Empty one. Needs to be here in order to use self.name.remove() later.
        self.balldots, = acl.plot([], [], 'ro', ms=1)
        self.E_cla, = acl.plot([],[], 'g-.', lw=1, label = "E")
        acl.legend(loc=1)

        #First computations:
        self.demo1_cla_btn()
        Clock.schedule_interval(self.ballupdate, self.dtime0_cla)

#Classical functions:
    #Changing parameters:
    def plotground(self):
        #It is only activated if some value changes.
        a = self.oldtop2_cla != self.height_cla
        b = self.oldk2_cla != self.k_cla

        if a or b:
            self.oldtop2_cla = self.height_cla
            self.oldk2_cla = self.k_cla

            #Changes and plots the new ground.
            self.ground_cla.set_data(self.xarr_cla, rob.fground(self.mu_cla, self.sigma_cla, self.k_cla, self.xarr_cla))
            self.filled_cla.remove()
            self.filled_cla = acl.fill_between(self.xarr_cla, 0, rob.fground(self.mu_cla, self.sigma_cla, self.k_cla, self.xarr_cla),
            color = (0.5,0.5,0.5,0.5))



    #Plotting.
    def plotball_0(self):
        x = self.supermatrix_cla[0, 1]
        XXcm = rob.xcm(self.R, self.mu_cla, self.sigma_cla, self.k_cla, x)
        YYcm = rob.ycm(self.R, self.mu_cla, self.sigma_cla, self.k_cla, x)

        gamma = np.arange(0, 2*np.pi + 0.5*0.02/self.R, 0.02/self.R)
        half_gamma = np.arange(0, np.pi, 0.02/self.R)
        XXr = XXcm + self.R*np.cos(gamma)
        YYr = YYcm + self.R*np.sin(gamma)

        Xdots = []
        Ydots = []
        for i in [-1./2., 0., 1./2., 1.]:
            Xdots.append(XXcm + self.R*np.sin(self.angle[0] + i*np.pi)/2.)
            Ydots.append(YYcm + self.R*np.cos(self.angle[0] + i*np.pi)/2.)

        self.ballperim.set_data(XXr, YYr)
        self.filled_ball_cla.remove()
        self.filled_ball_cla = acl.fill_between(XXcm + self.R*np.cos(half_gamma), YYcm - self.R*np.sin(half_gamma),
        YYcm + self.R*np.sin(half_gamma), color = (1,0,0,0.2))
        self.ballcm.set_data(XXcm, YYcm)
        self.balldots.set_data(Xdots, Ydots)
        self.canvas_cla.draw()


    def plotball(self, t):
        if self.oldtime1_cla != t:
            if t >= self.supermatrix_cla[-1,0]:
                row = - 1

            else:
                row = int(t/self.dtime0_cla)

            if self.oldrow != row:
                x = self.supermatrix_cla[row, 1]
                XXcm = rob.xcm(self.R, self.mu_cla, self.sigma_cla, self.k_cla, x)
                YYcm = rob.ycm(self.R, self.mu_cla, self.sigma_cla, self.k_cla, x)

                gamma = np.arange(0, 2*np.pi + 0.5*0.02/self.R, 0.02/self.R)
                half_gamma = np.arange(0, np.pi, 0.02/self.R)
                XXr = XXcm + self.R*np.cos(gamma)
                YYr = YYcm + self.R*np.sin(gamma)

                Xdots = []
                Ydots = []
                for i in [-1./2., 0., 1./2., 1.]:
                    Xdots.append(XXcm + self.R*np.sin(self.angle[row] + i*np.pi)/2.)
                    Ydots.append(YYcm + self.R*np.cos(self.angle[row] + i*np.pi)/2.)

                self.ballperim.set_data(XXr, YYr)
                self.filled_ball_cla.remove()
                self.filled_ball_cla = acl.fill_between(XXcm + self.R*np.cos(half_gamma), YYcm - self.R*np.sin(half_gamma),
                YYcm + self.R*np.sin(half_gamma), color = (1,0,0,0.2))
                self.ballcm.set_data(XXcm, YYcm)
                self.balldots.set_data(Xdots, Ydots)
                self.canvas_cla.draw()

                self.oldrow = row
            self.oldtime1_cla = t

    def plotE_cla(self):
        #Plots the initial energy as a height (maximum height).
        x = np.arange(-2.6, 2.6, 0.1)
        y = self.Eheight + 0*x
        self.E_cla.set_data(x,y)
        self.canvas_cla.draw()

    #Playing.
    def ballupdate(self, dt):
        self.time_cla = self.timeslide_cla.value + self.dtime_cla

        #It starts again if the time reaches the top.
        if self.time_cla >= self.tmax_cla:
            self.time_cla = 0

        self.timeslide_cla.value = self.time_cla
        self.plotball(self.time_cla)

    def reset_cla(self):
        #Sets time to 0
        self.timeslide_cla.value = 0
        self.time_cla = 0

    def demo1_cla_btn(self):
        self.reset_cla()

        self.height_cla = 0.8
        self.sigma_cla =  1./(np.sqrt(2*np.pi)*self.height_cla)
        self.k_cla = 0.8
        self.plotground()

        #This version does not compute anything. It just reads the precomputed matrices.
        self.supermatrix_cla = np.load("Demo1_cla/super.npy")
        self.angle = np.load("Demo1_cla/ang.npy")

        #Plots the maximum height:
        self.Eheight = np.load("Demo1_cla/ene.npy")
        self.plotE_cla()

        self.demo1_button_cla.color = (0,0.75,1,1)
        self.demo2_button_cla.color = (1,1,1,1)
        self.demo3_button_cla.color = (1,1,1,1)

    def demo2_cla_btn(self):
        self.reset_cla()

        self.height_cla = 0.9
        self.sigma_cla =  1./(np.sqrt(2*np.pi)*self.height_cla)
        self.k_cla = 0.8
        self.plotground()

        #This version does not compute anything. It just reads the precomputed matrices.
        self.supermatrix_cla = np.load("Demo2_cla/super.npy")
        self.angle = np.load("Demo2_cla/ang.npy")

        #Plots the maximum height:
        self.Eheight = np.load("Demo2_cla/ene.npy")
        self.plotE_cla()

        self.demo2_button_cla.color = (0,0.75,1,1)
        self.demo1_button_cla.color = (1,1,1,1)
        self.demo3_button_cla.color = (1,1,1,1)

    def demo3_cla_btn(self):
        self.reset_cla()

        self.height_cla = 1
        self.sigma_cla =  1./(np.sqrt(2*np.pi)*self.height_cla)
        self.k_cla = 0.8
        self.plotground()

        #This version does not compute anything. It just reads the precomputed matrices.
        self.supermatrix_cla = np.load("Demo3_cla/super.npy")
        self.angle = np.load("Demo3_cla/ang.npy")

        #Plots the maximum height:
        self.Eheight = np.load("Demo3_cla/ene.npy")
        self.plotE_cla()

        self.demo3_button_cla.color = (0,0.75,1,1)
        self.demo2_button_cla.color = (1,1,1,1)
        self.demo1_button_cla.color = (1,1,1,1)

    def changecat(self):
        if self.language != "CA":
            self.language = "CA"
            self.time_label = "Temps"
            self.but1 = "Sobre el pic"
            self.but2 = "En el pic"
            self.but3 = "Sota el pic"
            self.cabut.color = (0,0.75,1,1)
            self.esbut.color = (1,1,1,1)
            self.enbut.color = (1,1,1,1)

    def changeesp(self):
        if self.language != "ES":
            self.language = "ES"
            self.time_label = "Tiempo"
            self.but1 = "Sobre el pico"
            self.but2 = "En el pico"
            self.but3 = "Bajo el pico"
            self.esbut.color = (0,0.75,1,1)
            self.cabut.color = (1,1,1,1)
            self.enbut.color = (1,1,1,1)

    def changeeng(self):
        if self.language != "EN":
            self.language = "EN"
            self.time_label = "Time"
            self.but1 = "Above the peak"
            self.but2 = "On the peak"
            self.but3 = "Under the peak"
            self.enbut.color = (0,0.75,1,1)
            self.esbut.color = (1,1,1,1)
            self.cabut.color = (1,1,1,1)