Exemple #1
0
    def __init__(self, fig: plt.Figure, directed=False):
        fig.clear()
        self.fig = fig
        self.can = fig.canvas
        self.ax = fig.add_subplot(aspect="equal")

        self.directed = directed
        self.ui_nodes: List[NodeUi] = []
        self.selected = None
        return
Exemple #2
0
    def visualize(
        self,
        fig: plt.Figure,
        X: np.ndarray,
        energy: Callable[[np.ndarray], np.ndarray] = None,
    ):
        """
        Visualize a set of samples, returning a figure.

        Args:
            X (tensor ~ (n_samples, n_features):

        Returns:
            Figure
        """
        fig.clear()
        ax = fig.subplots(1, 1)
        if X.shape[1] == 1:
            ax.hist(X.reshape([-1]), density=True, label="Data")
            x_min = X.min()
            x_max = X.max()
            xs = np.linspace(x_min, x_max, 100)
            if hasattr(self, "logpdf"):
                ys_ = np.exp(self.logpdf(xs.reshape([-1, 1])))
                ys = ys_.reshape(-1)
                ax.plot(xs, ys, label="Actual")
            if energy is not None:
                ys_ = np.exp(-energy(xs.reshape([-1, 1])))
                ys = ys_.reshape(-1)
                Z = ys_.mean() * (x_max - x_min)
                ax.plot(xs, ys / Z, label="Energy", color="red")
            ax.legend()
        elif X.shape[1] == 2:
            ax.scatter(X[:, 0], X[:, 1], label="Data")
            x_min, x_max = X[:, 0].min(), X[:, 0].max()
            y_min, y_max = X[:, 1].min(), X[:, 1].max()
            x_support = np.linspace(x_min, x_max, 100)
            y_support = np.linspace(y_min, y_max, 100)
            xx, yy = np.meshgrid(x_support, y_support)
            XY = np.hstack([xx.reshape([-1, 1]), yy.reshape([-1, 1])])
            if hasattr(self, "logpdf"):
                z_ = np.exp(self.logpdf(XY))
                z = z_.reshape(xx.shape)
                ax.contour(xx, yy, z, 10)
            if energy is not None:
                z_ = np.exp(-energy(XY))
                z = z_.reshape(xx.shape)
                ax.contour(xx, yy, z, 10, cmap="Reds")
            ax.legend()
        else:
            from sklearn.manifold import TSNE

            tsne = TSNE(n_components=2)
            emb = tsne.fit_transform(X)
            ax.scatter(emb[:, 0], emb[:, 1])
Exemple #3
0
def plot_image_samples(im_size: Tuple[int, ...],
                       binarize,
                       fig: plt.Figure,
                       X: np.ndarray,
                       energy=None):
    """Plots model samples on the given figure."""
    fig.clear()
    if binarize:
        X = X > 0.5
    n = min(int(sqrt(X.shape[0])), 7)

    ax = fig.subplots(ncols=n, nrows=n)
    for i in range(n):
        for j in range(n):
            ax[i, j].imshow(X[i + n * j, :].reshape(im_size),
                            cmap="gray",
                            vmin=-1,
                            vmax=1)
            ax[i, j].axis("off")
Exemple #4
0
class Matplotlib(FigureCanvasKivyAgg):
    control_points = ListProperty([])
    contour = ObjectProperty(None, allownone=True, force_dispatch=True)
    initial = ObjectProperty(None, allownone=True, force_dispatch=True)
    controls = ObjectProperty(None)
    diameter = 30.0

    def __init__(self, **kwargs):
        from skimage.io import imread

        self.figure = Figure(tight_layout=True)

        super().__init__(self.figure, **kwargs)
        self.figure.patch.set_visible(False)
        self.image_data = imread(str(Path(__file__).parent / "insects.jpg"),
                                 as_gray=True)

        def add_control_point(event):
            if self.contour is not None:
                self.remove_all()

            if event.inaxes is not None:
                self.control_points.append((event.xdata, event.ydata))

        self.bind(control_points=lambda *args: self.draw(),
                  contour=lambda *args: self.draw())
        self.mpl_connect("button_release_event", add_control_point)

    def draw(self):
        from matplotlib import pyplot as plt

        self.figure.clear()
        axes = self.figure.add_subplot()
        axes.imshow(self.image_data, cmap=plt.get_cmap("binary_r"))
        axes.set_title("Left click to add a control node.\n"
                       "At least 3 are needed to perform a segmentation.")
        axes.get_xaxis().set_visible(False)
        axes.get_yaxis().set_visible(False)
        self.draw_control_points(axes)
        self.draw_contour(axes)
        return super().draw()

    def remove_all(self):
        """Removes all control points and segments."""
        self.initial = None
        self.contour = None
        self.control_points = []

    def draw_control_points(self, axes):
        if len(self.control_points) == 0:
            return

        xy = np.array(self.control_points + [self.control_points[0]])
        axes.plot(*xy.T, "ro-")

    def draw_contour(self, axes):
        if self.contour is None:
            return

        axes.plot(*self.initial.T, color="blue", label="Initial")
        axes.plot(*self.contour.T, color="orange", label="Segmented")

    def on_segment(self, degree, resolution, sigma):
        from model import segment_one_image
        from kivy.clock import Clock

        degree = int(degree)
        resolution = int(getattr(resolution, "text", resolution))
        sigma = int(getattr(sigma, "value", sigma))

        self.controls.disabled = True
        self.disabled = True

        def reenable(*args):
            """Enables controls.

            In order to ensure that clicks which happen during the computation are not
            taken into account, we have to make sure the fields are disabled while these
            clicks are processed. That means the computation will schedule un-disabling
            for the frame after it is itself completed.
            """
            self.controls.disabled = False
            self.disabled = False

        def computation(*args):
            """Performs contour computations.

            Computations are started in the next frame, *after* disabling the fields
            becomes visible.

            Note: async/await has landed in kivy dev. Eventually, computations should be
            performed asynchronously, rather than through a chain of calls to
            schedule_once.
            """
            contour, initial = segment_one_image(
                nodes=self.control_points,
                image=self.image_data,
                degree=degree,
                resolution=resolution,
                sigma=sigma,
            )
            self.initial = initial
            self.contour = contour
            Clock.schedule_once(reenable, 0)

        Clock.schedule_once(computation, 0)
Exemple #5
0
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0)
        self.hex_color = '#0000ff'
        self.color_list = ["red","blue","green","orange","purple"]
        self.parent = parent
        print "Loading model..."
        self.lux = Lux()
        fp = open(curdir+"/gauss_model.pkl"); self.gm = pickle.load(fp); fp.close()
        fp = open(curdir+"/memoized_binomial_data.pkl"); self.curve_data = pickle.load(fp); fp.close()
        fp = open(curdir+"/sampling_normalizer.pkl"); self.normalizer = pickle.load(fp); fp.close()
        print "Creating UI"
        self.initUI()
        self.update_output()
        self.replot()

    def update_output(self):
        (h, s, v) = self.hsv_color
        self.hsv_var.set("Hue: \t %2.1f \nSat:\t %2.1f \nValue:\t %2.1f" % (h*360,s*100,v*100))
        items = self.lux.full_posterior((h * 360, s * 100, v * 100))
        self.current_post = items
        desc = [ '{:<25} ({:.3f})\n'.format(items[i][0], items[i][1]) for i in range(25) ]
        self.display.config(state=NORMAL)
        self.display.delete(0, END)

        for i in range(25): self.display.insert(END, '{:<20} ({:.3f})'.format(items[i][0], items[i][1]))

        self.display.select_set(0, 0)

    def plot_lux_model(self, params,ax1,label,support,dim):
        cur_color='black'
        mu1,sh1,sc1,mu2,sh2,sc2 = params
        left_stach=gam_dist(sh1,scale=sc1); lbounds=left_stach.interval(0.99)
        right_stach=gam_dist(sh2,scale=sc2); rbounds=right_stach.interval(0.99)
        lx=np.linspace(mu1,-180); rx=np.linspace(mu2,360)
        s=3;
        ax1.plot(rx, [right_stach.sf(abs(y-mu2)) for y in rx],linewidth=s,c=cur_color);
        ax1.plot([1.01*mu1,0.99*mu2], [1.,1.], linewidth=s,c=cur_color)
        return ax1.plot(lx,[left_stach.sf(abs(y-mu1)) for y in lx],c=cur_color, linewidth=s);

    def plot_gm_model(self, params, ax, label, support):
        s=3
        x = np.linspace(support[0],support[1],360)

        return ax.plot(x,norm.pdf(x,params[0],params[1]),c='red', linewidth=s), norm.pdf([params[0]],params[0],[params[1]])[0]


    def initUI(self):

        self.parent.title("Interactive LUX visualization")
        self.pack(fill=BOTH, expand=1)

        self.color_frame = Frame(self, border=1)
        self.color_frame.pack(side=LEFT)

        probe_title_var = StringVar(); probe_title_label = Label(self.color_frame, textvariable=probe_title_var, justify=CENTER,  font = "Helvetica 16 bold italic")
        probe_title_var.set("Color Probe X"); probe_title_label.pack(side=TOP)

        self.hsv_var = StringVar()
        self.hsv_label = Label(self.color_frame, textvariable=self.hsv_var,justify=LEFT)
        h,s,v = self.hsv_color
        self.hsv_var.set("Hue: %2.1f \nSaturation: %2.1f \nValue: %2.1f" % (h*360,s*100,v*100))
        self.hsv_label.pack(side=TOP)

        self.frame = Frame(self.color_frame, border=1,
            relief=SUNKEN, width=200, height=200)

        self.frame.pack(side=TOP)
        self.frame.config(bg=self.hex_color)
        self.frame.bind("<Button-1>",self.onChoose)


        self.btn = Button(self.color_frame, text="Select Color",
            command=self.onChoose)
        self.btn.pack(side=TOP)

        posterior_title_var = StringVar(); posterior_title_label = Label(self.color_frame, textvariable=posterior_title_var, justify=CENTER, font = "Helvetica 16 bold italic")
        posterior_title_var.set("\n\nLUX's Posterior"); posterior_title_label.pack(side=TOP)

        Label(self.color_frame, text="Double click to show details \n(Wait time dependent on computer)").pack(side=TOP)



        my_font = tkFont.Font(family="Courier", size=10)
        self.display = Listbox(self.color_frame, border=1,
            relief=SUNKEN, width=30, height=25, font=my_font)
        self.display.pack(side=TOP,fill=Y,expand=1)
        self.display.bind("<Double-Button-1>",self.onSelect)
        self.display_btn = Button(self.color_frame, text="Show details", command=self.onSelect)
        self.display_btn.pack(side=TOP)

        self.update_output()



        self.fig = Figure(figsize=(10,4), dpi=100)

        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)
        self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)

    def replot(self):

        def gb(x,i,t):
            #t is max value, i in number of bins, x is the thing to be binned
            if x==t:
                return i-1
            elif x==0.0:
                return 0
            return int(floor(float(x)*i/t))
        hsv_title = []
        j=self.display.curselection()[0]
        name = self.current_post[j][0]
        mult = lambda x: reduce(operator.mul, x)
        g_labels = []; lux_labels=[]; all_g_params=[]
        for i in range(3):

            def align_yaxis(ax1, v1, ax2, v2):
                """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
                _, y1 = ax1.transData.transform((0, v1))
                _, y2 = ax2.transData.transform((0, v2))
                inv = ax2.transData.inverted()
                _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
                miny, maxy = ax2.get_ylim()

                ax2.set_ylim(miny, maxy+dy)

            subplot = self.fig.add_subplot(4,1,i+1)
            dim_label = ["H", "S","V"][i]
            subplot.set_ylabel(r"$P(k^{true}_{%s}|x)$" % ["H", "S","V"][i] )

            curve_data = self.curve_data[name][i]

            scale = lambda x,a=0.3,b=0.9: (b-a)*(x)+a
            p_x = lambda x: self.normalizer[i][gb(x,len(self.normalizer[i]),[360,100,100][i])]
            max_p_x = max(self.normalizer[i])
            #1 is white, 0 is black. so we want highly probable thigns to be black..


            if self.lux.get_adj(self.current_post[j][0]):
                support = [[-180,180], [0,100],[0,100]][i]
                pp = lambda x,i: x-360 if i==0 and x>180 else x
                hacky_solution = [360,100,100][i]
                w = 1.5 if i==0 else 1

                conv = lambda x: x*support[1]/len(curve_data)
                bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))]
                bar1 = subplot.bar([pp(atan2(sin((x*hacky_solution/len(curve_data))*pi/180),cos((x*hacky_solution/len(curve_data))*pi/180))*180/pi,i) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % j,ec="black",width=w,linewidth=0,color=bar_colors)
            else:
                support = [[0,360], [0,100],[0,100]][i]
                w = 1.5 if i==0 else 1
                conv = lambda x: x*support[1]/len(curve_data)
                bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))]
                bar1 = subplot.bar([x*support[1]/len(curve_data) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % name[0],ec="black",width=w,linewidth=0,color=bar_colors)
                pp = lambda x,*args: x

            point = pp(self.hsv_color[i]*[360,100,100][i],i)
            hsv_title.append(point)
            probeplot = subplot.plot([point,point], [0,1],linewidth=3,c='blue',label="Probe")

            #for j in range(5):
            lux_plot = self.plot_lux_model(self.lux.get_params(self.current_post[j][0])[i], subplot, self.current_post[j][0],support, i)
            subplot2 = subplot.twinx()
            gm_plot,gm_height = self.plot_gm_model([pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]], subplot2, self.current_post[j][0], support)
            extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)

            subplot.legend([extra], [["Hue", "Saturation", "Value"][i]],loc=2,frameon=False)


            if i==0: legend_set=lux_plot+[extra,extra,extra]+gm_plot+[extra,extra,extra]
            lux_params = self.lux.get_params(self.current_post[j][0])[i]
            g_params = [pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]]
            all_g_params.append(g_params)

            g_labels.append(r"$\mu^{%s}=$%2.2f, $\sigma^{%s}$=%2.2f" % (dim_label, g_params[0],dim_label,g_params[1]))
            #lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, (lux_params[0]-lux_params[1]*lux_params[2]),dim_label,lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,(lux_params[3]+lux_params[4]*lux_params[5]),dim_label, lux_params[4],dim_label,lux_params[5]))
            lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f,  $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,lux_params[4],dim_label,lux_params[5]))

            subplot.set_xlim(support[0],support[1])
            subplot.set_ylim(0,1.05)
            subplot2.set_xlim(support[0],support[1])
            subplot2.set_ylabel(r"$P(x|Gaussian_{%s})$" % ["H", "S","V"][i])
            align_yaxis(subplot, 1., subplot2, gm_height)


        leg_loc =(0.9,0.2)

        datum = [x*[360,100,100][i] for i,x in enumerate(self.hsv_color)];  phi_value = self.lux.get_phi(datum,self.current_post[j][0])
        #gauss_value = mult([norm.pdf(datum[i],all_g_params[i][0],all_g_params[i][1]) for i in range(3)])
        leg=self.fig.legend(probeplot+legend_set, ["Probe X"]+ [r"$\mathbf{\phi}_{%s}(X)=\mathbf{%2.5f}$; $\mathbf{\alpha}=\mathbf{%2.4f}$" % (self.current_post[j][0],phi_value,self.lux.get_avail(self.current_post[j][0]))]+lux_labels+
                                     [r"$Normal^{Hue}_{%s}$; $prior(%s)=%2.4f$" % (self.current_post[j][0],self.current_post[j][0], self.gm[self.current_post[j][0]][2])]+[g_labels[0]+"; "+g_labels[1]+"; "+g_labels[2]]
                                     , loc=8, handletextpad=4,labelspacing=0.1)


        self.fig.suptitle("%s" % name, size=30)

        print "done replotting"

    def onChoose(self, *args):
        try:
            ((red,green,blue), hx) = tkColorChooser.askcolor()
        except:
            print "I think you hit cancel"
            return
        self.hex_color = hx
        self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0)
        self.frame.config(bg=hx)
        self.update_output()
        self.fig.clear()
        self.replot()
        self.canvas.draw()

    def onSelect(self, *args):
        self.fig.clear()
        self.replot()
        self.canvas.draw()
Exemple #6
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setupUI()

        self.accounts = {}
        self.records = {}
        self.dm = dataManager('database.dat')
        self.initAccounts()

    # 레이아웃 설정 #
    def setupUI(self):
        self.layoutDialog = QVBoxLayout()

        self.setRow1UI()
        self.setRow2UI()
        self.setRow3UI()
        self.setSystemAlertUI()

        self.setLayout(self.layoutDialog)
        self.setWindowTitle("나만의 자산관리 프로그램")

    # 첫 번째 줄 레이아웃 #
    def setRow1UI(self):
        # 계좌 목록
        self.twAccountInfo = QTableWidget()
        self.twAccountInfo.setColumnCount(2)
        self.twAccountInfo.setHorizontalHeaderLabels(['계좌 번호', '총 자산'])
        self.twAccountInfo.resizeColumnsToContents()

        # 입출금
        self.cbDnW = QComboBox()
        self.cbDnW.addItems(['입금', '출금'])
        self.cbDnW.setCurrentIndex(0)
        self.leAmount = QLineEdit()
        pbSaveCash = QPushButton('현금 저장')
        pbSaveCash.clicked.connect(self.submitDnW)

        layoutInputAmount = QHBoxLayout()
        layoutInputAmount.addWidget(QLabel('액수:'))
        layoutInputAmount.addWidget(self.leAmount)

        # 주식
        self.leAmountStock = QLineEdit()
        self.leStockName = QLineEdit()
        pbSaveStock = QPushButton('주식 저장')
        pbSaveStock.clicked.connect(self.submitSaveStock)

        layoutInputAmountStock = QHBoxLayout()
        layoutInputAmountStock.addWidget(QLabel('변동주:'))
        layoutInputAmountStock.addWidget(self.leAmountStock)

        layoutInputStockName = QHBoxLayout()
        layoutInputStockName.addWidget(QLabel('주식명:'))
        layoutInputStockName.addWidget(self.leStockName)

        # 계좌 추가
        self.leNewAccountName = QLineEdit()
        self.leNewAccountBaseMoney = QLineEdit()
        pbSubmitNewAccount = QPushButton('계좌 등록')
        pbSubmitNewAccount.clicked.connect(self.submitNewAccount)

        layoutInputNewAccountName = QHBoxLayout()
        layoutInputNewAccountName.addWidget(QLabel('계좌 번호:'))
        layoutInputNewAccountName.addWidget(self.leNewAccountName)

        layoutInputNewAccountBaseMoney = QHBoxLayout()
        layoutInputNewAccountBaseMoney.addWidget(QLabel('예수금:'))
        layoutInputNewAccountBaseMoney.addWidget(self.leNewAccountBaseMoney)

        # 계좌 선택
        self.cbAccounts = QComboBox()
        self.cbAccounts.setFixedWidth(150)
        self.cbAccounts.addItem('---------------')
        self.cbAccounts.currentIndexChanged.connect(self.displayBreakdownList)

        layoutChoiceAccount = QHBoxLayout()
        layoutChoiceAccount.addStretch()
        layoutChoiceAccount.addWidget(QLabel('선택 계좌:'))
        layoutChoiceAccount.addWidget(self.cbAccounts)

        # 배치
        layoutRow = QGridLayout()
        layoutRow.addWidget(QLabel('계좌 목록'), 0, 0, alignment=Qt.AlignCenter)
        layoutRow.addWidget(self.twAccountInfo, 1, 0, -1, 1)
        layoutRow.addWidget(QLabel('현금'), 0, 1, alignment=Qt.AlignCenter)
        layoutRow.addWidget(self.cbDnW, 1, 1)
        layoutRow.addLayout(layoutInputAmount, 2, 1)
        layoutRow.addWidget(pbSaveCash, 3, 1)
        layoutRow.addWidget(QLabel('주식'), 0, 2, alignment=Qt.AlignCenter)
        layoutRow.addLayout(layoutInputAmountStock, 1, 2)
        layoutRow.addLayout(layoutInputStockName, 2, 2)
        layoutRow.addWidget(pbSaveStock, 3, 2)
        layoutRow.addWidget(QLabel('새 계좌 등록'), 0, 3, alignment=Qt.AlignCenter)
        layoutRow.addLayout(layoutInputNewAccountName, 1, 3)
        layoutRow.addLayout(layoutInputNewAccountBaseMoney, 2, 3)
        layoutRow.addWidget(pbSubmitNewAccount, 3, 3)
        layoutRow.addLayout(layoutChoiceAccount,
                            4,
                            1,
                            1,
                            -1,
                            alignment=Qt.AlignRight)

        self.layoutDialog.addLayout(layoutRow)

    # 두 번째 줄 레이아웃 #
    def setRow2UI(self):
        # 거래 내역 목록
        self.twBreakdown = QTableWidget()
        self.twBreakdown.setColumnCount(4)
        self.twBreakdown.setHorizontalHeaderLabels(['유형', '변동 내용', '잔고', '날짜'])
        self.twBreakdown.setColumnWidth(0, 110)
        self.twBreakdown.setColumnWidth(1, 200)
        self.twBreakdown.setColumnWidth(2, 300)
        self.twBreakdown.setColumnWidth(3, 230)
        self.layoutDialog.addWidget(self.twBreakdown)

    # 세 번째 줄 레이아웃 #
    def setRow3UI(self):
        # 그래프
        self.fig = Figure()
        self.canvas = FigureCanvasQTAgg(self.fig)
        # 날짜 선택
        self.cbStartDate = QComboBox()
        self.cbStartDate.setFixedWidth(120)
        self.cbStartDate.addItem('---------------')
        self.cbEndDate = QComboBox()
        self.cbEndDate.setFixedWidth(120)
        self.cbEndDate.addItem('---------------')
        pbCalc = QPushButton('계산')
        pbCalc.clicked.connect(self.displayGraph)
        # 배치
        layoutSelectDate = QVBoxLayout()
        layoutSelectDate.addStretch()
        layoutSelectDate.addWidget(self.cbStartDate)
        layoutSelectDate.addWidget(self.cbEndDate)
        layoutSelectDate.addWidget(pbCalc)
        layoutSelectDate.addStretch()

        layoutRow = QHBoxLayout()
        layoutRow.addWidget(self.canvas, stretch=1)
        layoutRow.addLayout(layoutSelectDate)

        self.layoutDialog.addLayout(layoutRow)

    # 시스템 알림 레이아웃 #
    def setSystemAlertUI(self):
        self.lbSystemAlert = QLabel('시스템 알림')
        self.lbSystemAlert.setAlignment(Qt.AlignCenter)

        self.layoutDialog.addWidget(self.lbSystemAlert)

    # 현금 입출금 #
    def submitDnW(self):
        cmd = self.cbDnW.currentText()
        amount = self.leAmount.text()
        account = self.cbAccounts.currentText()
        if not amount:
            self.showWarningMsgBox(f'{cmd}할 액수를 작성해 주세요.')
        elif not amount.isdecimal():
            self.showWarningMsgBox('액수에는 숫자만 입력해 주세요.')
        elif not self.cbAccounts.currentIndex():
            self.showWarningMsgBox(f'{cmd}할 계좌를 선택해 주세요.')
        else:
            curAccount = self.accounts[account]
            curRecord = self.records[account]
            if cmd == '입금':
                curAccount.addMoney(int(amount))
                curRecord.recordBalanceChange(int(amount), curAccount.money)
            else:
                if curAccount.money >= int(amount):
                    curAccount.delMoney(int(amount))
                    curRecord.recordBalanceChange(-int(amount),
                                                  curAccount.money)
                else:
                    self.showWarningMsgBox('계좌 잔고가 부족합니다.')
                    return
            self.refreshAccountsList('MODIFY')
            self.leAmount.clear()
            self.showInfoMsgBox(f'{cmd}이 완료되었습니다.')

    # 주식 저장 #
    def submitSaveStock(self):
        amount = self.leAmountStock.text()
        stockName = self.leStockName.text()
        account = self.cbAccounts.currentText()
        if not amount or not stockName:
            self.showWarningMsgBox('변동주와 주식명 모두 입력해 주세요.')
        elif not (('-' in amount and amount[1:].isdecimal())
                  or amount.isdecimal()):
            self.showWarningMsgBox('변동주에는 양이나 음의 정수만 입력해 주세요.')
        elif not self.cbAccounts.currentIndex():
            self.showWarningMsgBox('주식을 저장할 계좌를 선택해 주세요.')
        else:
            amount = int(amount)
            curAccount = self.accounts[account]
            curRecord = self.records[account]
            price = int(
                curAccount.showStockPrice(
                    curAccount.showStockCode(stockName))) * amount
            if amount >= 0:
                if curAccount.money >= price:
                    curAccount.addStock(stockName, amount)
                    curRecord.recordStockChange(amount, curAccount.money)
                else:
                    self.showWarningMsgBox('계좌 잔액이 부족합니다.')
                    return
            else:
                amount = abs(amount)
                if stockName not in curAccount.stockList.keys():
                    self.showWarningMsgBox('해당 계좌는 해당 주식을 보유하고 있지 않습니다.')
                    return
                elif amount > curAccount.stockList[stockName]:
                    self.showWarningMsgBox('입력값이 해당 계좌의 해당 주식 보유량을 초과하였습니다.')
                    return
                else:
                    curAccount.delStock(stockName, amount)
                    curRecord.recordStockChange(-amount, curAccount.money)
            self.refreshAccountsList('MODIFY')
            self.leAmountStock.clear()
            self.leStockName.clear()
            self.showInfoMsgBox('주식 저장이 완료되었습니다.')

    # 계좌 생성 #
    def submitNewAccount(self):
        account = self.leNewAccountName.text()
        baseMoney = self.leNewAccountBaseMoney.text()
        if not account or not baseMoney:
            self.showWarningMsgBox('계좌 번호와 기초 자금 모두 입력해 주세요.')
        elif account in self.accounts.keys():
            self.showWarningMsgBox('이미 존재하는 계좌입니다.')
        elif not baseMoney.isdecimal():
            self.showWarningMsgBox('기초 자금에는 숫자만 입력해 주세요.')
        else:
            self.accounts[account] = balance(account, int(baseMoney))
            self.records[account] = record(account)
            self.records[account].recordBalanceChange(
                int(baseMoney), self.accounts[account].money)
            self.refreshAccountsList('ADD')
            self.leNewAccountName.clear()
            self.leNewAccountBaseMoney.clear()
            self.showInfoMsgBox('새 계좌가 추가되었습니다.')

    # 거래 내역 출력 #
    def displayBreakdownList(self):
        if self.cbAccounts.currentIndex():
            self.twBreakdown.clearContents()
            self.twBreakdown.setRowCount(0)
            self.twBreakdown.setColumnWidth(0, 110)
            self.twBreakdown.setColumnWidth(1, 200)
            self.twBreakdown.setColumnWidth(2, 300)
            self.twBreakdown.setColumnWidth(3, 230)

            curRecord = self.records[self.cbAccounts.currentText()]
            datas = [{
                'type': '입출금',
                'changed': data[0],
                'balance': data[2],
                'time': data[1]
            } for data in curRecord.readBalanceChange()] + [{
                'type': '주식',
                'changed': data[0],
                'balance': data[2],
                'time': data[1]
            } for data in curRecord.readStockChange()]
            datas = sorted(datas, key=lambda x: x['time'], reverse=True)

            for data in datas:
                row = self.twBreakdown.rowCount()
                self.twBreakdown.setRowCount(row + 1)
                item = QTableWidgetItem(data['type'])
                item.setTextAlignment(Qt.AlignCenter)
                self.twBreakdown.setItem(row, 0,
                                         QTableWidgetItem(data['type']))
                item = QTableWidgetItem(f"{int(data['changed']):,}")
                item.setTextAlignment(Qt.AlignCenter)
                self.twBreakdown.setItem(row, 1, item)
                item = QTableWidgetItem(f"{int(data['balance']):,}")
                item.setTextAlignment(Qt.AlignCenter)
                self.twBreakdown.setItem(row, 2, item)
                item = QTableWidgetItem(data['time'])
                item.setTextAlignment(Qt.AlignCenter)
                self.twBreakdown.setItem(row, 3, item)
            #self.setBreakdownHeaderWidth()

            dates = [data['time'].split()[0] for data in datas]
            dates = sorted(list(set(dates)))
            self.cbStartDate.clear()
            self.cbStartDate.addItem('---------------')
            self.cbStartDate.addItems(dates)
            dates.reverse()
            self.cbEndDate.clear()
            self.cbEndDate.addItem('---------------')
            self.cbEndDate.addItems(dates)
        else:
            self.twBreakdown.clearContents()
            self.twBreakdown.setRowCount(0)

    # 그래프 출력 #
    def displayGraph(self):
        if self.cbStartDate.currentIndex() and self.cbEndDate.currentIndex():
            gr = graphrecord('', self.cbAccounts.currentText())
            self.fig.clear()
            gr.showMoneyStockGraph(self.fig, self.cbStartDate.currentText(),
                                   self.cbEndDate.currentText())
            self.canvas.draw()
        else:
            self.showWarningMsgBox('날짜를 모두 선택해 주세요.')

    # 경고 메시지 박스 #
    def showWarningMsgBox(self, msg):
        QMessageBox.warning(self, '알림', msg)

    # 완료 메시지 박스 #
    def showInfoMsgBox(self, msg):
        QMessageBox.information(self, '알림', msg)

    # 계좌 목록 초기화 #
    def initAccounts(self):
        accountDatas = self.dm.dataRead()
        if len(accountDatas):
            self.refreshAccountsList('INIT', accountDatas=accountDatas)
            for data in accountDatas:
                account = data['AccountName']
                money = data['Money']
                stock = data['Stock']

                self.accounts[account] = balance(account, money)
                self.accounts[account].stockList = stock
                self.accounts[account].saveAccount()
                self.records[account] = record(account)

    # 계좌 목록 갱신 #
    def refreshAccountsList(self, cmd, accountDatas=None):
        if accountDatas is None:
            accountDatas = self.dm.dataRead()
        if not len(accountDatas):
            return
        if cmd == 'INIT':
            for data in accountDatas:
                self.cbAccounts.addItem(data['AccountName'])
                row = self.twAccountInfo.rowCount()
                self.twAccountInfo.setRowCount(row + 1)
                self.twAccountInfo.setItem(
                    row, 0, QTableWidgetItem(data['AccountName']))
                self.twAccountInfo.setItem(
                    row, 1, QTableWidgetItem(f"{data['Money']:,}"))
        elif cmd == 'ADD':
            self.cbAccounts.addItem(self.leNewAccountName.text())
            row = self.twAccountInfo.rowCount()
            self.twAccountInfo.setRowCount(row + 1)
            self.twAccountInfo.setItem(
                row, 0, QTableWidgetItem(self.leNewAccountName.text()))
            self.twAccountInfo.setItem(
                row, 1,
                QTableWidgetItem(
                    f"{int(self.leNewAccountBaseMoney.text()):,}"))
        elif cmd == 'MODIFY':
            row = self.twAccountInfo.findItems(self.cbAccounts.currentText(),
                                               Qt.MatchExactly)[0].row()
            self.twAccountInfo.setItem(
                row, 1,
                QTableWidgetItem(
                    f"{self.accounts[self.cbAccounts.currentText()].money:,}"))
        self.setAccountInfoHeaderWidth()

    # 계좌 목록 컬럼 너비 설정 #
    def setAccountInfoHeaderWidth(self):
        header = self.twAccountInfo.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)

    # 거래 내역 컬럼 너비 설정 #
    def setBreakdownHeaderWidth(self):
        header = self.twBreakdown.horizontalHeader()
        for i in range(4):
            header.setSectionResizeMode(i, QHeaderView.ResizeToContents)
Exemple #7
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0)
        self.hex_color = '#0000ff'
        self.color_list = ["red","blue","green","orange","purple"]
        self.parent = parent        
        print "Getting Model"
        self.lux = lux.LUX("lux.xml")
        print "Creating UI"
        self.initUI()
        self.update_output()

    def update_output(self):
        (h, s, v) = self.hsv_color
        items = self.lux.full_posterior((h * 360, s * 100, v * 100))
        self.current_post = items
        desc = [ '{} ({:.3f})\n'.format(items[i][0], items[i][1]) for i in range(25) ]
        self.display.config(state=NORMAL)
        self.display.delete(1.0, END)
        self.display.insert(END, ''.join(desc))
        self.display.config(state=DISABLED)        
    
    def make_plotter(self, params,ax1,label,cur_color,support):
        mu1,sh1,sc1,mu2,sh2,sc2 = params
        left_stach=gam_dist(sh1,scale=sc1); lbounds=left_stach.interval(0.99)
        right_stach=gam_dist(sh2,scale=sc2); rbounds=right_stach.interval(0.99)
        lx=np.linspace(mu1,-180); rx=np.linspace(mu2,360)
        s=3; #cur_color='black'
        ax1.plot(rx, [1-right_stach.cdf(abs(y-mu2)) for y in rx],linewidth=s,c=cur_color);
        ax1.plot([1.01*mu1,0.99*mu2], [1,1], linewidth=s,c=cur_color)
        return ax1.plot(lx,[1-left_stach.cdf(abs(y-mu1)) for y in lx],c=cur_color, label=r"$\phi^{Hue}_{%s}$" % label,linewidth=s);
        
        
        
    def initUI(self):
      
        self.parent.title("Interactive LUX visualization")      
        self.pack(fill=BOTH, expand=1)
        
        self.color_frame = Frame(self, border=1)
        self.color_frame.pack(side=LEFT)
        
        
        self.frame = Frame(self.color_frame, border=1, 
            relief=SUNKEN, width=100, height=100)
        #self.frame.place(x=160, y=30)
        self.frame.pack(side=TOP)
        self.frame.config(bg=self.hex_color)
                
        
        self.btn = Button(self.color_frame, text="Select Color", 
            command=self.onChoose)
        self.btn.pack(side=TOP)
        #self.btn.place(x=30, y=30)
        

        self.display = Text(self, border=1, 
            relief=SUNKEN, width=30, height=5)
        #self.display.place(x=280, y=30)
        self.display.pack(side=LEFT,fill=Y,expand=1)
        self.update_output()
        
        self.fig = Figure(figsize=(10,4), dpi=100)
        self.replot()
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)
        self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)

    def replot(self):
        hsv_title = []
        for i in range(3):
            if self.lux.get_adj(self.current_post[0][0]): 
                support = [[-180,180], [0,100],[0,100]][i]
                pp = lambda x,i: x-360 if i==0 and x>180 else x
            else: 
                support = [[0,360], [0,100],[0,100]][i]
                pp = lambda x,*args: x
            subplot = self.fig.add_subplot(3,1,i+1) 
            subplot.set_xlim(support[0],support[1])   
            subplot.set_ylabel("%s" % ["Hue", "Saturation","Value"][i])
            point = pp(self.hsv_color[i]*[360,100,100][i],i)
            hsv_title.append(point)
            probeplot = subplot.plot([point,point], [0,1],linewidth=3,c='black',label="Probe")
            legend_set = []
            for j in range(5):
                test = self.make_plotter(self.lux.get_params(self.current_post[j][0])[i], subplot, self.current_post[j][0],self.color_list[j],support)
                if type(test)==type([]): legend_set+=test
                else: legend_set.append(test)
        
        self.fig.legend(legend_set, [r"$\phi_{%s}$; $\alpha=%2.4f$" % (x[0],self.lux.get_avail(x[0])) for x in self.current_post[:5]], loc=1)
        self.fig.suptitle("HSV (%2.2f,%2.2f,%2.2f) top 5 Phi curves" % (hsv_title[0],hsv_title[1],hsv_title[2]))

    def onChoose(self):
      
        ((red,green,blue), hx) = tkColorChooser.askcolor()
        self.hex_color = hx
        self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0)
        self.frame.config(bg=hx)
        self.update_output()
        self.fig.clear()
        self.replot()
        self.canvas.draw()
Exemple #8
0
def hot_map(time_counter: int, fig: plt.Figure, p: parameter.Parameter,
            uav_swarm: uav.Uav_Swarm, target_swarm: target.Target_Swarm):
    fig.clear()
    ax1 = fig.add_subplot(1, 3, 1)
    x_pix = 4
    y_pix = 4
    xticks = [
        p.pixel_length_x * x_pix * i
        for i in range(math.ceil((p.nx + 1) / x_pix))
    ]
    xtick_labes = [
        str(x_pix * i) for i in range(math.ceil((p.nx + 1) / x_pix))
    ]
    plt.xticks(xticks, xtick_labes)
    yticks = [
        p.pixel_length_y * y_pix * i
        for i in range(math.ceil((p.ny + 1) / y_pix))
    ]
    ytick_labes = [
        str(y_pix * i) for i in range(math.ceil((p.ny + 1) / y_pix))
    ]
    plt.yticks(yticks, ytick_labes)
    plt.xlim(-5, p.nx * p.pixel_length_x)
    plt.ylim(-5, p.ny * p.pixel_length_y)
    plt.xlabel("x", fontsize=14)
    plt.ylabel("y", fontsize=14)
    plt.title('time_counter = ' + str(time_counter) + ' find_count = ' +
              str(p.found_counter))
    # 目标散点
    targets_xlist = [
        i.path[time_counter, 0] * p.pixel_length_x + 1 for i in target_swarm
        if i.path[time_counter, 0] > -1
    ]
    targets_ylist = [
        i.path[time_counter, 1] * p.pixel_length_y + 1 for i in target_swarm
        if i.path[time_counter, 1] > -1
    ]
    plt.scatter(targets_xlist,
                targets_ylist,
                s=20,
                c='blue',
                marker='s',
                zorder=3,
                label="targets")
    # uav散点
    uavs_xlist = [
        i.path[time_counter, 0] * p.pixel_length_x + 1 for i in uav_swarm
        if i.path[time_counter, 0] > -1
    ]
    uavs_ylist = [
        i.path[time_counter, 1] * p.pixel_length_y + 1 for i in uav_swarm
        if i.path[time_counter, 1] > -1
    ]

    plt.scatter(uavs_xlist,
                uavs_ylist,
                s=20,
                c='red',
                marker='s',
                zorder=3,
                label="uavs")
    # grid_map散点
    grid_xlist = [
        i * p.pixel_length_x + 1 for i in np.arange(0, p.nx, dtype=int)
        if i % (p.ox + 1) != 0
    ]
    grid_xlist = [i for i in grid_xlist for _ in range(p.ny)]
    grid_ylist = [
        i * p.pixel_length_y + 1
        for i in np.arange(0, p.ny, dtype=int) if i % (p.oy + 1) != 0
    ] * p.nx
    plt.scatter(grid_xlist,
                grid_ylist,
                s=20,
                c='yellow',
                marker='s',
                zorder=2,
                label="grid")
    # 标签位置
    plt.legend(bbox_to_anchor=(1.05, 0), loc=3, borderaxespad=0)
    # 已探索的范围
    ax2 = fig.add_subplot(1, 3, 2)
    plt.plot(range(time_counter), p.detect_list[0:time_counter])
    plt.ylim(0, 1)
    plt.xlim(0, p.time_limit)
    plt.title('time_counter = ' + str(time_counter) + ' detect_list')
    # 找到的目标个数
    ax3 = fig.add_subplot(1, 3, 3)
    plt.plot(range(time_counter), p.fd_ct_list[0:time_counter])
    plt.ylim(0, p.nt)
    plt.xlim(0, p.time_limit)
    plt.title('time_counter = ' + str(time_counter) + ' fd_ct_list')

    plt.pause(0.1)
    plt.draw()
Exemple #9
0
class Ui(QMainWindow):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('gui.ui', self)
        self.show()
        # self.initWorker()
        self.initMatplotlib()
        self.tbCalculate.clicked.connect(self.runAlgorithm)
        self.working = False

    def startProgress(self):
        self.progressBar = QProgressBar()
        self.progressBar.setRange(0, 0)
        self.statusbar.addPermanentWidget(self.progressBar)
        self.statusbar.showMessage('Obliczam entropię...')

    def initMatplotlib(self):
        self.fig = Figure(figsize=(9, 7))
        self.canvas = FigureCanvas(self.fig)
        self.mapLayout.addWidget(self.canvas)

    def runAlgorithm(self):
        if self.working:
            return
        self.statusbar.clearMessage()
        classes = self.sbClasses.value()
        expected_entropy = self.dsbEntropy.value()
        expected_diff = self.dsbAccuracy.value()
        x, y = self.sbX.value(), self.sbY.value()
        size = x * y
        #Obsługa przypadku gdzie classes == 1:
        if classes == 1:
            if expected_entropy == 0.:
                values = np.asarray([1])
                self.statusbar.showMessage("Cały obrazek w jednym kolorze")
                self.generateRaster(values)
                return
            else:
                self.statusbar.showMessage("Wartość niemożliwa do osiągnięcia")
                return
        max_entropy_case = np.asarray([1 / classes] * classes)
        if expected_entropy > calculate_entropy(
                max_entropy_case) or expected_entropy < 0:
            self.statusbar.showMessage("Wartość niemożliwa do osiągnięcia")
            return
        if expected_entropy == 0:
            self.statusbar.showMessage("Wartość niemożliwa do osiągnięcia")
            return
        min_entropy_case = [0] * size
        for class_ in range(classes):
            min_entropy_case[class_] = class_
        min_entropy = array_to_entropy(min_entropy_case)
        if min_entropy > expected_entropy:
            self.statusbar.showMessage("Minimalna entropia dla " +
                                       str(classes) +
                                       " klas w macierzy o wielkości " +
                                       str(size) + " to " + str(min_entropy))
            return
        self.startProgress()
        init_cases = random_results(200, classes, size)
        classes = list(set(init_cases[0]))
        best_cases = selection(init_cases, expected_entropy, 30, expected_diff)
        if len(best_cases) == 1:
            self.generateRaster(np.array(best_cases[0]))
            return
        #Async
        self.worker = Worker(best_cases, classes, expected_entropy,
                             expected_diff)
        self.worker.finished.connect(self.generateRaster)
        self.worker.start()
        self.working = True

    def generateRaster(self, result):
        x, y = self.sbX.value(), self.sbY.value()
        self.fig.clear()
        self.ax = self.fig.add_subplot(111)
        found_ent = array_to_entropy(result)
        result = result.reshape(x, y)
        values = np.unique(result.ravel())
        im = self.ax.imshow(result, extent=[0, x, 0, y])
        colors = [im.cmap(im.norm(value)) for value in values]
        patches = [
            mpatches.Patch(color=colors[i],
                           label="Class {l}".format(l=values[i] + 1))
            for i in range(len(values))
        ]
        self.ax.legend(handles=patches,
                       bbox_to_anchor=(1.05, 1),
                       loc=2,
                       borderaxespad=0.)
        self.canvas.draw()
        self.statusbar.removeWidget(self.progressBar)
        self.statusbar.showMessage(f"Obliczona entropia: {found_ent}")
        self.working = False
        try:
            del self.worker
        except AttributeError:
            pass
Exemple #10
0
class classGetQuote(Toplevel):
    def __init__(self,
                 master=None,
                 argkey=None,
                 argscript="",
                 argoutputtree=None,
                 argIsTest=False,
                 argDataFolder=None):
        Toplevel.__init__(self, master=master)
        #self.wm_state(newstate='zoomed')
        self.wm_state(newstate='normal')
        #self.wm_resizable(width=False, height=False)
        self.key = argkey
        self.script = argscript
        self.output_tree = argoutputtree
        self.bool_test = argIsTest
        self.datafolderpath = argDataFolder
        #graph filter params
        self.pastdate = str(date.today())
        self.graphctr = 1

        if (len(self.script) <= 0):
            self.wm_title("Get Quote")
        else:
            self.wm_title("Get Quote: " + self.script)
            self.search_symbol_combo_text.set(argscript)
        #self.configure(padx=5, pady=10)

        self.wm_protocol("WM_DELETE_WINDOW", self.OnClose)

        self.iscancel = False

        #check box buttons
        self.bdaily = BooleanVar()
        self.bintra = BooleanVar()
        self.bsma = BooleanVar()
        self.bema = BooleanVar()
        self.bvwap = BooleanVar()
        self.bmacd = BooleanVar()
        self.brsi = BooleanVar()
        self.badx = BooleanVar()
        self.baroon = BooleanVar()
        self.brsi = BooleanVar()

        self.bdaily.set(False)
        self.bintra.set(False)
        self.bsma.set(False)
        self.bema.set(False)
        self.bvwap.set(False)
        self.bmacd.set(False)
        self.brsi.set(False)
        self.badx.set(False)
        self.baroon.set(False)
        self.brsi.set(False)

        self.frame1 = ttk.Frame(self, borderwidth=5,
                                relief="sunken")  #, width=200, height=100)
        self.frame2 = ttk.Frame(self, borderwidth=5,
                                relief="sunken")  #, width=200, height=100)

        self.search_symbol_label = ttk.Label(self, text='*Search Symbol: ')
        self.search_symbol_combo_text = StringVar()
        #self.search_symbol_combo = ttk.Combobox(self, textvariable=self.search_symbol_combo_text,state='normal', postcommand=self.commandSearchSymbol)
        self.search_symbol_combo = ttk.Combobox(
            self,
            width=60,
            textvariable=self.search_symbol_combo_text,
            state='normal')
        self.search_symbol_combo.bind('<Return>', self.commandEnterKey)

        self.open_label = ttk.Label(self.frame2, text='Open: ')
        self.open_val_label = ttk.Label(self.frame2, text='ABCD')
        self.high_label = ttk.Label(self.frame2, text='High: ')
        self.high_val_label = ttk.Label(self.frame2, text='ABCD')
        self.low_label = ttk.Label(self.frame2, text='Low: ')
        self.low_val_label = ttk.Label(self.frame2, text='ABCD')
        self.price_label = ttk.Label(self.frame2, text='Price: ')
        self.price_val_label = ttk.Label(self.frame2, text='ABCD')
        self.volume_label = ttk.Label(self.frame2, text='Volume: ')
        self.volume_val_label = ttk.Label(self.frame2, text='ABCD')
        self.latesttradingday_label = ttk.Label(self.frame2,
                                                text='Latest Trading Day: ')
        self.latesttradingday_val_label = ttk.Label(self.frame2, text='ABCD')
        self.prevclose_label = ttk.Label(self.frame2, text='Previous Close: ')
        self.prevclose_val_label = ttk.Label(self.frame2, text='ABCD')
        self.change_label = ttk.Label(self.frame2, text='Change: ')
        self.change_val_label = ttk.Label(self.frame2, text='ABCD')
        self.changepct_label = ttk.Label(self.frame2, text='Change %: ')
        self.changepct_val_label = ttk.Label(self.frame2, text='ABCD')

        self.f = Figure(figsize=(12.6, 8.55),
                        dpi=100,
                        facecolor='w',
                        edgecolor='k',
                        tight_layout=True,
                        linewidth=0.5)
        self.output_canvas = FigureCanvasTkAgg(self.f, master=self)
        self.toolbar_frame = Frame(master=self)
        self.toolbar = NavigationToolbar2Tk(self.output_canvas,
                                            self.toolbar_frame)

        self.btn_search_script = ttk.Button(self,
                                            text="Search Script",
                                            command=self.btnSearchScript)
        self.btn_get_quote = ttk.Button(self,
                                        text="Get Quote",
                                        command=self.btnGetQuote)
        self.btn_get_daily_close = ttk.Button(self,
                                              text="Show selected graphs",
                                              command=self.btnGetDailyClose)
        self.btn_cancel = ttk.Button(self,
                                     text="Close",
                                     command=self.btnCancel)
        self.btn_add_script = ttk.Button(self,
                                         text="Add script",
                                         command=self.btnAddScript)

        self.checkdaily = ttk.Checkbutton(self.frame1,
                                          text="Daily close",
                                          variable=self.bdaily,
                                          onvalue=True)
        self.checkintra = ttk.Checkbutton(self.frame1,
                                          text="Intra day",
                                          variable=self.bintra,
                                          onvalue=True)
        self.checksma = ttk.Checkbutton(self.frame1,
                                        text="SMA",
                                        variable=self.bsma,
                                        onvalue=True)
        self.checkema = ttk.Checkbutton(self.frame1,
                                        text="EMA",
                                        variable=self.bema,
                                        onvalue=True)
        self.checkvwap = ttk.Checkbutton(self.frame1,
                                         text="VWAP",
                                         variable=self.bvwap,
                                         onvalue=True)
        self.checkmacd = ttk.Checkbutton(self.frame1,
                                         text="MACD",
                                         variable=self.bmacd,
                                         onvalue=True)
        self.checkrsi = ttk.Checkbutton(self.frame1,
                                        text="RSI",
                                        variable=self.brsi,
                                        onvalue=True)
        self.checkadx = ttk.Checkbutton(self.frame1,
                                        text="ADX",
                                        variable=self.badx,
                                        onvalue=True)
        self.checkaroon = ttk.Checkbutton(self.frame1,
                                          text="AROON",
                                          variable=self.baroon,
                                          onvalue=True)

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.search_symbol_label.grid_configure(row=0,
                                                column=0,
                                                sticky=(N, E),
                                                padx=5,
                                                pady=5)
        self.search_symbol_combo.grid_configure(row=0,
                                                column=1,
                                                sticky=(N, S, E, W),
                                                columnspan=3,
                                                padx=5,
                                                pady=5)
        self.btn_search_script.grid_configure(row=0, column=4, padx=5, pady=5)
        self.btn_get_quote.grid_configure(row=0, column=5, pady=5)
        self.btn_add_script.grid_configure(row=0, column=6, pady=5)

        self.frame1.grid_configure(row=0,
                                   column=7,
                                   columnspan=8,
                                   rowspan=4,
                                   sticky=(N, S, E, W),
                                   padx=5,
                                   pady=5)
        self.checkdaily.grid_configure(row=0, column=0, sticky=(W))
        self.checkintra.grid_configure(row=0, column=1, sticky=(W))
        self.checksma.grid_configure(row=0, column=2, sticky=(W))
        self.checkema.grid_configure(row=1, column=0, sticky=(W))
        self.checkvwap.grid_configure(row=1, column=1, sticky=(W))
        self.checkmacd.grid_configure(row=1, column=2, sticky=(W))
        self.checkrsi.grid_configure(row=2, column=0, sticky=(W))
        self.checkadx.grid_configure(row=2, column=1, sticky=(W))
        self.checkaroon.grid_configure(row=2, column=2, sticky=(W))

        self.btn_get_daily_close.grid_configure(row=0,
                                                column=15,
                                                padx=5,
                                                pady=5)
        self.btn_cancel.grid_configure(row=2, column=15, padx=5, pady=5)

        self.frame2.grid_configure(row=1,
                                   column=0,
                                   columnspan=7,
                                   rowspan=3,
                                   sticky=(N, S, E, W),
                                   padx=5,
                                   pady=5)
        self.open_label.grid_configure(row=1, column=0, sticky='E')
        self.open_val_label.grid_configure(
            row=1, column=1, padx=35,
            sticky='W')  #, columnspan=2, sticky='NW')
        self.high_label.grid_configure(row=1, column=3,
                                       sticky='E')  #, columnspan=2)
        self.high_val_label.grid_configure(row=1,
                                           column=4,
                                           padx=35,
                                           sticky='W')  #, sticky='NW')
        self.low_label.grid_configure(
            row=1, column=6, sticky='E')  #, columnspan=2, sticky='NE')
        self.low_val_label.grid_configure(row=1, column=7, padx=35,
                                          sticky='W')  #,sticky='NW')
        self.price_label.grid_configure(row=2, column=0,
                                        sticky='E')  #, sticky='NE')
        self.price_val_label.grid_configure(
            row=2, column=1, padx=35,
            sticky='W')  #, columnspan=2, sticky='NW')
        self.volume_label.grid_configure(
            row=2, column=3, sticky='E')  #, columnspan=2, sticky='NE')
        self.volume_val_label.grid_configure(row=2,
                                             column=4,
                                             padx=35,
                                             sticky='W')  #, sticky='NW')
        self.latesttradingday_label.grid_configure(
            row=2, column=6, sticky='E')  #,columnspan=2, sticky='NE')
        self.latesttradingday_val_label.grid_configure(
            row=2, column=7, padx=35, sticky='W')  #, sticky='NW')
        self.prevclose_label.grid_configure(row=3, column=0,
                                            sticky='E')  #, sticky='NE')
        self.prevclose_val_label.grid_configure(
            row=3, column=1, padx=35,
            sticky='W')  #, columnspan=2, sticky='NW')
        self.change_label.grid_configure(
            row=3, column=3, sticky='E')  #, columnspan=2, sticky='NE')
        self.change_val_label.grid_configure(row=3,
                                             column=4,
                                             padx=35,
                                             sticky='W')  #, sticky='NW')
        self.changepct_label.grid_configure(
            row=3, column=6, sticky='E')  #, columnspan=2, sticky='NE')
        self.changepct_val_label.grid_configure(row=3,
                                                column=7,
                                                padx=35,
                                                sticky='W')  #, sticky='NW')

        self.output_canvas.get_tk_widget().grid(row=5,
                                                column=0,
                                                columnspan=17,
                                                sticky=(N, E, W, S))
        self.toolbar_frame.grid(row=6,
                                column=0,
                                columnspan=17,
                                rowspan=1,
                                sticky=(N, E, W, S))
        self.toolbar.grid(row=0, column=2, sticky=(N, W))

    """ self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.grid_columnconfigure(2, weight=1)
        self.grid_columnconfigure(3, weight=1)
        self.grid_rowconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)
        self.grid_rowconfigure(2, weight=1)
    """

    def OnClose(self):
        self.destroy()

    def btnGetQuote(self):
        self.getQuoteFromMarket()

        #if (len(self.exchange_text.get()) > 0 and len(self.symbol_text.get()) > 0):
        #    self.getQuoteFromMarket()
        #    #self.iscancel = False
        #    #self.destroy()
        #else:
        #    msgbx.showerror("Error", "Please select Exchange & Symbol")

    def btnCancel(self):
        self.iscancel = True
        self.destroy()

    def show(self):
        self.wm_deiconify()
        self.search_symbol_combo.focus_force()
        self.wait_window()

    def getQuoteFromMarket(self):
        #ti = TechIndicators(self.key, output_format='pandas')
        try:
            #self.script = self.exchange_text.get() + ":" + self.symbol_text.get()
            curr_selection = self.search_symbol_combo.current()
            if (curr_selection >= 0):
                self.script = self.searchTuple[0].values[curr_selection][0]
            else:
                msgbx.showerror('Get Quote', 'No script selected')
                self.search_symbol_combo.focus_force()
                return
            ts = TimeSeries(self.key, output_format='pandas')
            quote_tuple = ts.get_quote_endpoint(symbol=self.script)
            #quote_tuple[0].values[0][1]
            #for i in range(1, 1, quote_tuple[0].size):
            self.open_val_label.configure(text=quote_tuple[0].values[0][1])
            self.high_val_label.configure(text=quote_tuple[0].values[0][2])
            self.low_val_label.configure(text=quote_tuple[0].values[0][3])
            self.price_val_label.configure(text=quote_tuple[0].values[0][4])
            self.volume_val_label.configure(text=quote_tuple[0].values[0][5])
            self.latesttradingday_val_label.configure(
                text=quote_tuple[0].values[0][6])
            self.prevclose_val_label.configure(
                text=quote_tuple[0].values[0][7])
            self.change_val_label.configure(text=quote_tuple[0].values[0][8])
            self.changepct_val_label.configure(
                text=quote_tuple[0].values[0][9])
        except Exception as e:
            msgbx.showerror("Get Quote Error", str(e))
            self.search_symbol_combo.focus_force()
            return

    #def commandSearchSymbol(self):
    def btnSearchScript(self):
        try:
            ts = TimeSeries(self.key, output_format='pandas')

            self.searchTuple = ts.get_symbol_search(
                self.search_symbol_combo.get())

            #print(searchTuple[0].columns)
            #print(searchTuple[0].values)

            search_values_list = list()
            self.search_symbol_combo['values'] = search_values_list
            for i in range(len(self.searchTuple[0].values)):
                search_values_list.append(self.searchTuple[0].values[i][0] +
                                          "--" +
                                          self.searchTuple[0].values[i][1])

            self.search_symbol_combo['values'] = search_values_list
            self.search_symbol_combo.focus_force()
            self.search_symbol_combo.event_generate('<Down>')

        except Exception as e:
            msgbx.showerror("Search Symbol Error", str(e))
            self.search_symbol_combo.focus_force()
            return

    def commandEnterKey(self, event):
        #self.commandSearchSymbol()
        self.btnSearchScript()

    def btnAddScript(self):

        curr_selection = self.search_symbol_combo.current()
        if (curr_selection >= 0):
            self.script = self.searchTuple[0].values[curr_selection][0]
            dnewscript = dict()
            dnewscript = classAddNewModifyScript(
                master=self,
                argisadd=True,
                argscript=self.script,
                argPurchasePrice=self.price_val_label.cget('text'),
                argkey=self.key).show()
            # returns dictionary - {'Symbol': 'LT.BSE', 'Price': '1000', 'Date': '2020-02-22', 'Quantity': '10', 'Commission': '1', 'Cost': '10001.0'}
            if ((dnewscript != None) and (len(dnewscript['Symbol']) > 0)):
                stock_name = dnewscript['Symbol']
                listnewscript = list(dnewscript.items())
                #argHoldingIID="", argStockName=stock_name, argPriceDf=DataFrame()
                self.output_tree.get_stock_quote(
                    "", stock_name, DataFrame(),
                    listnewscript[1][0] + '=' + listnewscript[1][1],
                    listnewscript[2][0] + '=' + listnewscript[2][1],
                    listnewscript[3][0] + '=' + listnewscript[3][1],
                    listnewscript[4][0] + '=' + listnewscript[4][1],
                    listnewscript[5][0] + '=' + listnewscript[5][1])
                #dnewscript['Price'], dnewscript['Date'],
                #   dnewscript['Quantity'], dnewscript['Commission'], dnewscript['Cost'])
        else:
            msgbx.showerror('Get Quote', 'No script selected')
        self.btn_add_script.focus_force()

    def btnGetDailyClose(self):
        self.dateFilter(1)
        self.drawPastData()
        return

    """ method - dateFilter(self, argYears):
        argYears - indicates no of years from todays date 
    """

    def dateFilter(self, argYears):
        try:
            dt = date.today()
            dt = dt.replace(year=dt.year - argYears)
        except ValueError:
            dt = dt.replace(year=dt.year - argYears, day=dt.day - 1)
        self.pastdate = str(dt)
        """strtoday = date.today()
        self.pastdate = date(strtoday.year-argYears, strtoday.month, strtoday.day)
        self.pastdate = str(self.pastdate)"""

    def setAxesCommonConfig(self, argAxes, argTitle):
        argAxes.tick_params(direction='out',
                            length=6,
                            width=2,
                            colors='black',
                            grid_color='black',
                            grid_alpha=0.5,
                            labelsize='xx-small')
        argAxes.tick_params(axis='x', labelrotation=30)

        argAxes.grid(True)
        argAxes.set_title(argTitle, size='xx-small')
        argAxes.legend(fontsize='xx-small')

    def drawPastData(self):
        try:
            curr_selection = self.search_symbol_combo.current()
            if (curr_selection >= 0):
                self.script = self.searchTuple[0].values[curr_selection][0]
                self.f.clear()
            else:
                msgbx.showerror('Get Quote', 'No script selected')
                self.focus_force()
                return

            if (self.bool_test == False):
                ts = TimeSeries(self.key, output_format='pandas')
                ti = TechIndicators(self.key, output_format='pandas')

            self.graphctr = 1
            self.f.clear()
            #daily
            if (self.bdaily.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath,
                                              argOutputSize='full')
                    dfdata = testobj.loadDaily(self.script)
                else:
                    dfdata, dfmetadata = ts.get_daily(symbol=self.script,
                                                      outputsize='full')
                #self.changeColNameTypeofDailyTS()
                #self.f.add_subplot(3, 3, graphctr, label='Daily closing price',
                #    xlabel='Date', ylabel='Closing price').plot(self.dfdailyts['Close'], label='Daily closing price')
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax1 = self.f.add_subplot(3,
                                         3,
                                         self.graphctr,
                                         label='Daily closing price')
                #ylabel='Close',
                ax1.plot(dfdata.loc[dfdata.index[:] >= self.pastdate,
                                    '4. close'],
                         label='Daily close')
                self.setAxesCommonConfig(ax1, 'Daily closing price')
                self.graphctr += 1

            #intraday
            if (self.bintra.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath,
                                              argOutputSize='full')
                    dfdata = testobj.loadIntra(self.script)
                else:
                    dfdata, dfmetadata = ts.get_intraday(symbol=self.script,
                                                         outputsize='full')
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax2 = self.f.add_subplot(3,
                                         3,
                                         self.graphctr,
                                         label='Intra-day close')
                ax2.plot(dfdata.loc[dfdata.index[:] >= self.pastdate,
                                    '4. close'],
                         label='Intra-day close')
                self.setAxesCommonConfig(ax2, 'Intra-day close')
                self.graphctr += 1
            #sma
            if (self.bsma.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadSMA(self.script)
                else:
                    dfdata, dfmetadata = ti.get_sma(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]

                ax3 = self.f.add_subplot(3,
                                         3,
                                         self.graphctr,
                                         label='Simple moving avg')
                ax3.plot(dfdata.loc[dfdata.index[:] >= self.pastdate, 'SMA'],
                         label='SMA')
                self.setAxesCommonConfig(ax3, 'Simple moving avg')
                self.graphctr += 1

            #ema
            if (self.bema.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadEMA(self.script)
                else:
                    dfdata, dfmetadata = ti.get_ema(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax4 = self.f.add_subplot(3,
                                         3,
                                         self.graphctr,
                                         label='Exponential moving avg')
                ax4.plot(dfdata.loc[dfdata.index[:] >= self.pastdate, 'EMA'],
                         label='EMA')
                self.setAxesCommonConfig(ax4, 'Exponential moving avg')
                self.graphctr += 1

            #vwap returns one col = VWAP
            if (self.bvwap.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadVWMP(self.script)
                else:
                    dfdata, dfmetadata = ti.get_vwap(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax5 = self.f.add_subplot(3,
                                         3,
                                         self.graphctr,
                                         label='Vol weighted avg price')
                ax5.plot(dfdata.loc[dfdata.index[:] >= self.pastdate, 'VWAP'],
                         label='VWAP')
                self.setAxesCommonConfig(ax5, 'Volume weighted avg price')
                self.graphctr += 1

            #macd returns 3 cols. For ex, "MACD_Signal": "-4.7394", "MACD": "-7.7800", "MACD_Hist": "-3.0406"
            if (self.bmacd.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadMACD(self.script)
                else:
                    dfdata, dfmetadata = ti.get_macd(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax6 = self.f.add_subplot(3, 3, self.graphctr, label='MACD')
                ax6.plot(dfdata.loc[dfdata.index[:] >= self.pastdate,
                                    'MACD_Signal'],
                         'b-',
                         label='MACD Signal')
                ax6.plot(dfdata.loc[dfdata.index[:] >= self.pastdate, 'MACD'],
                         'y-',
                         label='MACD')
                ax6.plot(dfdata.loc[dfdata.index[:] >= self.pastdate,
                                    'MACD_Hist'],
                         'r-',
                         label='MACD Hist')
                self.setAxesCommonConfig(ax6,
                                         'Moving avg convergence/divergence')
                self.graphctr += 1

            #rsi returns one col RSI
            if (self.brsi.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadRSI(self.script)
                else:
                    dfdata, dfmetadata = ti.get_rsi(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax7 = self.f.add_subplot(3, 3, self.graphctr, label='RSI')
                ax7.plot(dfdata.loc[dfdata.index[:] >= self.pastdate, 'RSI'],
                         label='RSI')
                self.setAxesCommonConfig(ax7, 'Relative strength index')
                self.graphctr += 1

            #adx returns one col ADX
            if (self.badx.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadADX(self.script)
                else:
                    dfdata, dfmetadata = ti.get_adx(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax8 = self.f.add_subplot(3, 3, self.graphctr, label='ADX')
                ax8.plot(dfdata.loc[dfdata.index[:] >= self.pastdate, 'ADX'],
                         label='ADX')
                self.setAxesCommonConfig(ax8,
                                         'Average directional moving index')
                self.graphctr += 1

            #aroon returns two cols for ex "Aroon Up": "28.5714", "Aroon Down": "100.0000"
            if (self.baroon.get() == True):
                if (self.bool_test):
                    testobj = PrepareTestData(argFolder=self.datafolderpath)
                    dfdata = testobj.loadAROON(self.script)
                else:
                    dfdata, dfmetadata = ti.get_aroon(symbol=self.script)
                dfdata = dfdata.sort_index(axis=0, ascending=False)
                #dfdata=dfdata[dfdata.index[:] >= self.pastdate]
                ax9 = self.f.add_subplot(3, 3, self.graphctr, label='AROON')
                ax9.plot(dfdata.loc[dfdata.index[:] >= self.pastdate,
                                    'Aroon Up'],
                         'b-',
                         label='Aroon Up')
                ax9.plot(dfdata.loc[dfdata.index[:] >= self.pastdate,
                                    'Aroon Down'],
                         'r-',
                         label='Aroon Down')
                self.setAxesCommonConfig(ax9, 'AROON')
                self.graphctr += 1

            #self.f.legend() #(loc='upper right')
            self.output_canvas.set_window_title(self.script)
            self.output_canvas.draw()
            self.toolbar.update()

        except Exception as e:
            msgbx.showerror("Graph error", str(e))

        self.btn_get_daily_close.focus_force()

    def changeColNameTypeofDailyTS(self):
        #rename columns
        self.dfdailyts = self.dfdailyts.rename(
            columns={
                '1. open': 'Open',
                '2. high': 'High',
                '3. low': 'Low',
                '4. close': 'Close',
                '5. volume': 'Volume'
            })
Exemple #11
0
class Graph(tk.Frame):
    ax, original_xlim, original_ylim, coll, pick_id = None, None, None, None, None
    start_end_bool = -1  # 0 is start, 1 is end, -1 is None
    start_index, end_index, move_index, remove_index = 0, None, None, None
    max_time, max_speed, max_height, min_height = 0, 0, 0, 0
    data = []
    connect_ids, move_ids = [], []
    current_color_scheme = 'd'

    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.fig = Figure(figsize=(10, 7), dpi=100, tight_layout=True)
        self.fig.set_facecolor('#f0f0ed')

        self.zoom_pan = GraphInteractions.ZoomPan()
        self.master_string = tk.StringVar()

        self.canvas = FigureCanvasTkAgg(self.fig, self)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def redraw(self, input_file_location):
        x, y, c = zip(*self.read_data(input_file_location))
        self.fig.clear()
        self.ax = self.fig.add_subplot(111, frameon=False)
        self.coll = self.ax.scatter(x, y, color=c, picker=True)
        self.end_index = len(self.data) - 1
        self.connect_ids.append(
            GraphInteractions.ZoomPan.zoom_factory(self.zoom_pan,
                                                   self.ax,
                                                   base_scale=1.3))
        self.connect_ids.extend(
            GraphInteractions.ZoomPan.pan_factory(self.zoom_pan, self.ax))
        self.original_xlim = self.ax.get_xlim()
        self.original_ylim = self.ax.get_ylim()
        self.canvas.draw()

    def redraw_color(self, x, y, c):
        self.fig.clear()
        self.ax = self.fig.add_subplot(111, frameon=False)
        self.coll = self.ax.scatter(x, y, color=c, picker=True)
        self.ax.set_xlim(self.zoom_pan.cur_xlim)
        self.ax.set_ylim(self.zoom_pan.cur_ylim)
        self.connect_ids.append(
            GraphInteractions.ZoomPan.zoom_factory(self.zoom_pan,
                                                   self.ax,
                                                   base_scale=1.3))
        self.connect_ids.extend(
            GraphInteractions.ZoomPan.pan_factory(self.zoom_pan, self.ax))
        self.canvas.draw()

    def reset_zoom(self):
        self.ax.set_xlim(self.original_xlim)
        self.ax.set_ylim(self.original_ylim)
        self.ax.figure.canvas.draw()  # force re-draw

    def reset_start(self, master_string):
        self.start_index = 0
        master_string.set("")
        self.redraw_ext()

    def reset_end(self, master_string):
        self.end_index = len(self.data) - 1
        master_string.set("")
        self.redraw_ext()

    def read_data(self, input_file_location):
        x_array = []
        y_array = []
        color_array = []
        self.data.clear()
        json_file = open(input_file_location, "r")
        file_data = json.load(json_file)
        json_file.close()
        old_time, old_x, old_y = 0, file_data['recording']['path'][0][
            'x'], file_data['recording']['path'][0]['y']
        self.max_time, self.max_speed, self.max_height, self.min_height = 0, 0, 0, file_data[
            'recording']['path'][0]['z']
        speed = 0
        for time in file_data['recording']['path']:
            x_array.append(time['x'])
            y_array.append(time['y'])
            time_div = time['t'] - old_time
            if time['t'] > self.max_time:
                self.max_time = time['t']
            if time_div != 0:
                speed = distance(time['x'], old_x, time['y'], old_y) / time_div
            if speed > self.max_speed:
                self.max_speed = speed
            if time['z'] > self.max_height:
                self.max_height = time['z']
            elif time['z'] < self.min_height:
                self.min_height = time['z']
            self.data.append(
                [time['x'], time['y'], time['t'], speed, time['z']])
            color_array.append('tab:blue')
            old_time = time['t']
            old_x, old_y = time['x'], time['y']
        return zip(x_array, y_array, color_array)

    def redraw_ext(self):
        for cid in self.connect_ids:
            self.canvas.mpl_disconnect(cid)
        self.connect_ids.clear()
        x = []
        y = []
        c = []
        for idx, row in enumerate(self.data):
            x.append(row[0])
            y.append(row[1])
            if idx == self.start_index or idx == self.end_index or idx == self.remove_index:
                c.append('tab:red')
            elif idx < self.start_index or idx > self.end_index or\
                    (self.start_index == 0 and self.end_index == len(self.data) - 1):
                c.append('tab:blue')
            elif self.start_index < idx < self.end_index:
                c.append('c')

        self.redraw_color(x, y, c)

    def redraw_simp(self):
        for cid in self.connect_ids:
            self.canvas.mpl_disconnect(cid)
        self.connect_ids.clear()
        x = []
        y = []
        c = []
        for idx, row in enumerate(self.data):
            x.append(row[0])
            y.append(row[1])
            if idx == self.move_index:
                c.append('tab:red')
            else:
                c.append('tab:blue')
        self.redraw_color(x, y, c)

    def change_color(self, event):
        if event.mouseevent.button != 1: return
        if self.start_end_bool == 0:
            self.start_index = event.ind[0]
        elif self.start_end_bool == 1:
            self.end_index = event.ind[0]
        elif self.start_end_bool == 2:
            self.remove_index = event.ind[0]
        self.redraw_ext()
        self.master_string.set(
            'x: %.4f, y: %.4f' %
            (self.data[event.ind[0]][0], self.data[event.ind[0]][1]))

    def show_time(self):
        self.current_color_scheme = 't'
        for cid in self.connect_ids:
            self.canvas.mpl_disconnect(cid)
        self.connect_ids.clear()
        x = []
        y = []
        c = []
        for idx, row in enumerate(self.data):
            x.append(row[0])
            y.append(row[1])
            gradient = row[2] / self.max_time
            c.append((0, 1 - gradient, gradient))
        self.redraw_color(x, y, c)

    def show_speed(self):
        self.current_color_scheme = 's'
        for cid in self.connect_ids:
            self.canvas.mpl_disconnect(cid)
        self.connect_ids.clear()
        x = []
        y = []
        c = []
        for idx, row in enumerate(self.data):
            x.append(row[0])
            y.append(row[1])
            gradient = row[3] / self.max_speed
            c.append((1 - gradient, gradient, 0))
        self.redraw_color(x, y, c)

    def show_height(self):
        self.current_color_scheme = 'h'
        for cid in self.connect_ids:
            self.canvas.mpl_disconnect(cid)
        self.connect_ids.clear()
        x = []
        y = []
        c = []
        for idx, row in enumerate(self.data):
            x.append(row[0])
            y.append(row[1])
            gradient = (row[4] - self.min_height) / (self.max_height -
                                                     self.min_height)
            c.append((gradient * 0.5 + 0.5, gradient * 0.8, gradient * 0.8))
        self.redraw_color(x, y, c)

    def reset_color(self):
        self.current_color_scheme = 'd'
        for cid in self.connect_ids:
            self.canvas.mpl_disconnect(cid)
        self.connect_ids.clear()
        x = []
        y = []
        c = []
        for idx, row in enumerate(self.data):
            x.append(row[0])
            y.append(row[1])
            c.append('tab:blue')
        self.redraw_color(x, y, c)

    def attach_start_stop(self, master_string_var, start_end):
        self.detach_start_stop()
        self.start_end_bool = start_end
        self.master_string = master_string_var
        self.pick_id = self.canvas.mpl_connect('pick_event', self.change_color)

    def detach_start_stop(self):
        if self.pick_id is None: return
        self.start_end_bool = -1
        self.canvas.mpl_disconnect(self.pick_id)
        for move_id in self.move_ids:
            self.canvas.mpl_disconnect(move_id)

    def attach_move_node(self):
        def on_press(event):
            if event.mouseevent.button != 1: return
            self.move_index = event.ind[0]
            self.master.move_node_location.set(
                'x: %.4f, y: %.4f' %
                (self.data[self.move_index][0], self.data[self.move_index][1]))

        def on_release(event):
            self.redraw_simp()

        def on_motion(event):
            if event.button != 1: return
            self.data[self.move_index][0] = event.xdata
            self.data[self.move_index][1] = event.ydata
            self.master.move_node_location.set(
                'x: %.4f, y: %.4f' %
                (self.data[self.move_index][0], self.data[self.move_index][1]))

            self.redraw_simp()

        self.detach_start_stop()
        self.pick_id = self.canvas.mpl_connect('pick_event', on_press)
        self.move_ids.append(
            self.canvas.mpl_connect('key_press_event', self.move_node_button))
        self.move_ids.append(
            self.canvas.mpl_connect('button_release_event', on_release))
        self.move_ids.append(
            self.canvas.mpl_connect('motion_notify_event', on_motion))

    def attach_remove_node(self, master_string):
        self.detach_start_stop()
        self.start_end_bool = 2
        self.master_string = master_string
        self.pick_id = self.canvas.mpl_connect('pick_event', self.change_color)

    def next_start(self, master_string, diff):
        self.start_index += diff
        if self.start_index < 0:
            self.start_index = 0
        self.redraw_ext()
        master_string.set(
            'x: %.4f, y: %.4f' %
            (self.data[self.start_index][0], self.data[self.start_index][1]))

    def next_end(self, master_string, diff):
        self.end_index += diff
        if self.end_index > len(self.data) - 1:
            self.end_index = len(self.data) - 1
        self.redraw_ext()
        master_string.set(
            'x: %.4f, y: %.4f' %
            (self.data[self.end_index][0], self.data[self.end_index][1]))

    def move_node_button(self, event):
        direction = ""
        if event.key == "up":
            direction = "N"
        elif event.key == "right":
            direction = "E"
        elif event.key == "down":
            direction = "S"
        elif event.key == "left":
            direction = "W"
        if direction != "":
            self.move_node(direction, float(self.master.move_entry.get()))

    def move_node(self, direction, move_distance):
        if direction == "N":
            self.data[self.move_index][1] += move_distance
        elif direction == "E":
            self.data[self.move_index][0] += move_distance
        elif direction == "S":
            self.data[self.move_index][1] -= move_distance
        elif direction == "W":
            self.data[self.move_index][0] -= move_distance
        self.master.move_node_location.set(
            'x: %.4f, y: %.4f' %
            (self.data[self.move_index][0], self.data[self.move_index][1]))
        self.redraw_simp()

    def remove_node(self):
        del self.data[self.remove_index]
        self.end_index = len(self.data) - 1
        self.redraw_ext()
        self.master_string.set(
            'x: %.4f, y: %.4f' %
            (self.data[self.remove_index][0], self.data[self.remove_index][1]))

    def apply_local_speedup(self, value):
        speedup = 1
        speed = 0
        previous_time = 0
        previous_old_time = 0
        old_x, old_y = self.data[0][0], self.data[0][1]
        for idx, row in enumerate(self.data):
            if self.start_index == idx:
                speedup = 1 - float(value) / 100
            elif self.end_index == idx:
                speedup = 1
            old_time = row[2]
            if old_time < previous_old_time:
                previous_old_time = old_time / 2
            row[2] = previous_time + (min(old_time - previous_old_time, 2) *
                                      speedup)
            time_div = row[2] - previous_time
            if row[2] > self.max_time:
                self.max_time = row[2]
            if time_div != 0:
                speed = distance(row[0], old_x, row[1], old_y) / time_div
            if speed > self.max_speed:
                self.max_speed = speed
            row[3] = speed
            previous_time = row[2]
            previous_old_time = old_time
            old_x, old_y = row[0], row[1]
            self.update_unknown()

    def update_unknown(self):
        if self.current_color_scheme == 'h':
            self.show_height()
        elif self.current_color_scheme == 's':
            self.show_speed()
        elif self.current_color_scheme == 't':
            self.show_time()
        else:
            self.reset_color()