Exemplo n.º 1
0
def process_video():
    cap = cv2.VideoCapture(VIDEO)
    hasFrame, frame = cap.read()

    vid_writer = cv2.VideoWriter('output.avi',
                                 cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'),
                                 10, (frame.shape[1], frame.shape[0]))

    estimator = PoseEstimator()

    while cv2.waitKey(1) < 0:
        hasFrame, frame = cap.read()
        frameCopy = np.copy(frame)
        if not hasFrame:
            cv2.waitKey()
            break

        drawer = Drawer(frameCopy)
        prediction = estimator.predict(frame)
        points = estimator.get_rescaled_points(prediction, frame, 0.2)
        drawer.draw_skeleton(points)

        cv2.imshow('Output-Skeleton', frameCopy)

        vid_writer.write(frameCopy)

    vid_writer.release()
Exemplo n.º 2
0
 def savePlots(self,savedir, cfg = "Plotter"):
     perf[ts[0]].start()
     cfg = Configuration(cfg)
     cfg.loadConfiguration(self.config)
     plots = cfg.getPlots()
     nohpp = int(plots.getOption("HistsPerPage"))
     if nohpp >12:
         nohpp = 12
     elif nohpp < 1:
         nohpp = 1
     Drawer.NoHpP = nohpp
     writeAs = plots.getOption("create").split(",")
     summaryFile = plots.getOption("summaryFile")
     Drawer.summaryFile = savedir + "/" + summaryFile
     histlist = cfg.getAllCanvas()
     noh = len(histlist)
     perf[ts[0]].stop()
     if showPerformance:
         print "Config read in %s" % perf[ts[0]].getMeasuredTime()
     self.doHistList(histlist, savedir, writeAs)
     Drawer.summaryBegin = False
     Drawer.flushStack(savedir, writeAs)
     perf[ts[3]].stop()
     if showPerformance:
         if noh > 1:
             print "%d histograms read in %s (%f per hist without caching)" % (noh, perf[ts[2]].getMeasuredTime(), (perf[ts[2]].getMeasuredSeconds()-perf[ts[5]].getMeasuredSeconds())/(noh-1))
             print "%d histograms printed in %s (%f per hist without caching)" % (noh, perf[ts[1]].getMeasuredTime(), (perf[ts[1]].getMeasuredSeconds()-perf[ts[4]].getMeasuredSeconds())/(noh-1))
         else:
             print "%d histograms read in %s (%f per hist)" % (noh, perf[ts[2]].getMeasuredTime(), (perf[ts[2]].getMeasuredSeconds()))
             print "%d histograms printed in %s (%f per hist)" % (noh, perf[ts[1]].getMeasuredTime(), (perf[ts[1]].getMeasuredSeconds()))
         print "total time elapsed: %s" % perf[ts[3]].getMeasuredTime()
Exemplo n.º 3
0
 def initialize(self):
     self.title = "CGP2"
     self.toppanel = Tk.Frame(self)
     self.toppanel.pack(side=Tk.TOP)
     Tk.Button(self.toppanel, text="Choose an image", command=self.fileselecthandler).pack(side=Tk.LEFT)
     self.botpanel = Tk.Frame(self)
     self.botpanel.pack()
     self.canvas = Tk.Canvas(self.botpanel, width=WIDTH, height=HEIGHT, bg='white')
     self.img = Tk.PhotoImage(width=WIDTH, height=HEIGHT)
     self.canvas.create_image((0, 0), image=self.img, anchor="nw")
     self.canvas.bind('<ButtonRelease-1>', self.onEnd)
     self.canvas.pack(fill=Tk.BOTH, expand=1)
     combooptions = ["Polygon Fill", "Region Fill"]
     neighOptions = [4, 8]
     self.neighsVar = Tk.StringVar(self)
     self.filter = Tk.StringVar(self)
     self.filter.set(combooptions[0])
     self.neighsVar.set(neighOptions[0])
     self.combobox = apply(Tk.OptionMenu, (self.toppanel, self.filter)+tuple(combooptions))
     self.combobox.pack(side=Tk.LEFT)
     self.neighs = apply(Tk.OptionMenu, (self.toppanel, self.neighsVar)+tuple(neighOptions))
     self.neighs.pack(side=Tk.LEFT)
     self.drawer = Drawer(self.img)
     Tk.Button(self.toppanel,text='Select Color', command=self.getColor).pack()
     self.mainloop()
Exemplo n.º 4
0
 def play_pull_up_font_animation(frame, font_animation_queue: deque, x, y):
     draw_data = font_animation_queue.pop()
     Drawer.print_message_with_text_edging(frame,
                                           x,
                                           y,
                                           draw_data[0],
                                           thickness=draw_data[1],
                                           text_color=draw_data[2])
Exemplo n.º 5
0
 def saveMVAPlots(self,outputdir):
     Drawer.set_palette("simple", 127)
     save = '/playground/ThesisPlots/MVATraining/%s/' % outputdir
     cfg = 'plotconfigs/MVAHists.xml'
     f = open(cfg)
     cfg = f.read()
     f.close()
     Macro.savePlotsFromCfg(cfg, save)
Exemplo n.º 6
0
    def __init__(self):
        pygame.init()  # Initializes the pygame class.

        self.isRunning = True
        self.model = Model()  #3
        self.controller = Controller(self.model)  #5
        self.drawer = Drawer(self.model)  #7
        self.clock = pygame.time.Clock()
Exemplo n.º 7
0
 def GenOneCertificate(self):
     Year = self.spinBox.value()
     Author = self.lineEdit.text()
     Title = self.lineEdit_2.text()
     Award = self.comboBox.currentText()
     Content = self.textEdit.toPlainText()
     Stamp = self.comboBox_7.currentText()
     Quarter = self.comboBox_6.currentText()
     Category = self.comboBox_2.currentText()
     if Content == "" or Author == "" or Title == "":
         self.textEdit_3.setText("请输入必要的作品信息!")
     else:
         myDrawer = Drawer(Stamp, Category, Quarter, Year)
         myDrawer.DrawCertificate(Award, Title, Author, Content)
Exemplo n.º 8
0
def main():
    worker = DriveAnalyzer()
    try:
        data = worker.get_files()
    except ValueError as e:
        print(e.args)
        return

    if data is None:
        print('No files found')
        return

    drawer = Drawer(data)
    drawer.run()
Exemplo n.º 9
0
def main():
    """
    Main starting point for the program

    :return: N/A
    """
    Graphics.init()
    FPS.init()

    drawer = Drawer()

    key_down_listeners = [drawer.on_key_down]

    mouse_down_listeners = [drawer.on_mouse_down]

    mouse_up_listeners = [drawer.on_mouse_up]

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                if event.key == pygame.K_F10:
                    Graphics.toggle_fullscreen()

                for delegate in key_down_listeners:
                    delegate(event.key, event.mod)

            if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:
                mouse_position = (event.pos[0] / Graphics.get_scale()[0],
                                  event.pos[1] / Graphics.get_scale()[1])

                if event.type == pygame.MOUSEBUTTONDOWN:
                    for delegate in mouse_down_listeners:
                        delegate(mouse_position, event.button)

                if event.type == pygame.MOUSEBUTTONUP:
                    for delegate in mouse_up_listeners:
                        delegate(mouse_position, event.button)

        drawer.update()

        drawer.draw()

        FPS.update()
        Graphics.flip()
Exemplo n.º 10
0
    def show_max_window(self):
        while True:
            frame = self.tcp.frame.copy()
            face_detect_bool = self.face_detect_flag.get()
            face_save_bool = self.face_save_flag.get()

            # detect the face and label
            if face_detect_bool:
                self.face_detector.detect_face(frame)
                face_list = self.face_detector.get_face_list()
                if len(face_list) > 0:
                    for face in face_list:
                        Drawer.label_face(frame, face.get_rect())
                        # save face(s)
                        if face_save_bool is True:
                            self.save_face(self.tcp.frame, face.get_rect())
            else:
                if face_save_bool:
                    msg.showwarning(
                        "Warning",
                        "Open Face Detection before save face image!")
                    self.face_save_flag.set(False)

            # Write Text on the frame
            localtime = time.asctime(time.localtime(time.time()))
            width = frame.shape[0]
            cv2.putText(frame, localtime, (int(0.9 * width), 20),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0))
            if face_detect_bool is True:
                cv2.putText(frame, "Face Detection: True",
                            (int(0.9 * width), 35), cv2.FONT_HERSHEY_SIMPLEX,
                            0.4, (0, 255, 0))
            else:
                cv2.putText(frame, "Face Detection: False",
                            (int(0.9 * width), 35), cv2.FONT_HERSHEY_SIMPLEX,
                            0.4, (0, 0, 255))
            if face_save_bool is True:
                cv2.putText(frame, "Face Save     : True",
                            (int(0.9 * width), 50), cv2.FONT_HERSHEY_SIMPLEX,
                            0.4, (0, 255, 0))
            else:
                cv2.putText(frame, "Face Save     : False",
                            (int(0.9 * width), 50), cv2.FONT_HERSHEY_SIMPLEX,
                            0.4, (0, 0, 255))

            cv2.imshow("Split@Monitor %d" % (self.idx + 1), frame)
            if cv2.waitKey(1) == ord('q'):
                cv2.destroyAllWindows()
                break
Exemplo n.º 11
0
def process_image():
    estimator = PoseEstimator()
    frame = cv2.imread(IMG)
    frameCopy = np.copy(frame)  # TODO Why copy?

    drawer = Drawer(frameCopy)

    prediction = estimator.predict(frame)
    points = estimator.get_rescaled_points(prediction, frame, 0.2)
    drawer.draw_skeleton(points)

    cv2.imshow('Output-Keypoints', frameCopy)
    cv2.imwrite('Output-Keypoints.jpg', frameCopy)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Exemplo n.º 12
0
class Main(object):
    def __init__(self):
        pygame.init()  # Initializes the pygame class.

        self.isRunning = True
        self.model = Model()  #3
        self.controller = Controller(self.model)  #5
        self.drawer = Drawer(self.model)  #7
        self.clock = pygame.time.Clock()

    # Gameloop
    def runGame(self):
        while self.isRunning:
            self.controller.execute()
            self.drawer.draw()
Exemplo n.º 13
0
    def __init__(self, main):
        pygame.init()
        self.main = main
        self.clock = pygame.time.Clock()
        self.display = pygame.display
        self.window = pygame.display.set_mode((700, 600), pygame.HWSURFACE)
        self.drawer = Drawer(self)

        self.keras_switch_false = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/switch_FALSE.png")
        self.keras_switch_true = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/switch_TRUE.png")
        self.keras = False
        self.rects_to_update = []
Exemplo n.º 14
0
 def initialize(self):
     self.title = "CGP5"
     self.canvas = Tk.Canvas(self.botpanel, width=MainWindow.WIDTH, height=MainWindow.HEIGHT, bg="#F5F1DE")
     self.canvas.pack()
     self.raster = Tk.PhotoImage(width=MainWindow.WIDTH, height=MainWindow.HEIGHT)
     self.canvas.create_image((0, 0), image=self.raster, state="normal", anchor="nw")
     self.toppanel = Tk.Frame(self)
     self.toppanel.pack(side=Tk.TOP)
     self.botpanel = Tk.Frame(self)
     self.botpanel.pack()
     Tk.Button(self.toppanel, text="Choose an image", command=self.fileselecthandler).pack(side=Tk.LEFT)
     Tk.Button(self.toppanel, text="Draw", command=self.draw).pack(side=Tk.LEFT)
     self.imageLabel = Tk.Label(self.botpanel)
     self.imageLabel.pack()
     self.drawer = Drawer(self.raster)
     self.mainloop()
Exemplo n.º 15
0
    def run_single_simulation(self):
        # Initialise screen
        pygame.init()
        screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        #screen = pygame.display.set_mode((500, 500))

        # Fill background
        background = pygame.Surface(screen.get_size())
        background = background.convert()
        background.fill((0, 0, 0))

        # Display some text
        font = pygame.font.Font(None, 30)
        text = font.render("ESC to exit", 1, (255, 255, 255))
        textpos = text.get_rect()
        textpos.centerx = 60
        textpos.centery = 10
        background.blit(text, textpos)

        # Blit everything to the screen
        screen.blit(background, (0, 0))
        pygame.display.flip()

        drawer = Drawer(screen, self.reader.dimensions)

        flag = True
        running = True
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
            particles = self.read_positions()

            if particles is None:
                flag = False

            screen.blit(background, (0, 0))

            if flag:

                drawer.update(particles)
                pygame.display.flip()
 def __init__(self):
     self.iteration = 0
     cfg.load()
     self.plane = Plane(cfg.get("width"), cfg.get("height"),
                        cfg.get("radius"), cfg.get("map_type"))
     self.population = Population()
     self.population.scatter(self.plane)
     self.drawer = Drawer()
     pass
Exemplo n.º 17
0
def main():
    bino_cam = BinoCamera(0, True)
    bino_cam.set_width_height((2560, 720))
    face_detector = FaceDetector()
    # The width of frame is the half of camera width.
    distance_predictor = DistancePredictor(90, bino_cam.get_width_height()[0] / 2, bino_cam.get_width_height()[1], 60)
    distance = 0
    distance_threshold = 2000.0    #mm
    monitor_flag = True

    while True:
        if not bino_cam.capture():
            break

        Drawer.draw_lines(bino_cam.get_lframe())
        Drawer.draw_lines(bino_cam.get_rframe())
        left_face = face_detector.detect_face(bino_cam.get_lframe())
        right_face = face_detector.detect_face(bino_cam.get_rframe())

        if left_face:
            Drawer.dotted_rectangle(bino_cam.get_lframe(), (left_face.get_x(), left_face.get_y()),
                                    (left_face.get_x() + left_face.get_width(),
                                     left_face.get_y() + left_face.get_height()), (0, 0, 255), 2)

        if right_face:
            Drawer.dotted_rectangle(bino_cam.get_rframe(), (right_face.get_x(), right_face.get_y()),
                                    (right_face.get_x() + right_face.get_width(),
                                     right_face.get_y() + right_face.get_height()), (0, 0, 255), 2)

        if left_face and right_face:
            distance = distance_predictor.predict_distance((left_face.get_x(), left_face.get_y()), (right_face.get_x(), right_face.get_y()))
        Drawer.text(bino_cam.get_lframe(), "Distance(m): %.2fm" % (distance / 1000), (20, 40), 1.0, (0, 0, 255), 2)
        print(distance / 1000)

        if 0 < distance < distance_threshold and monitor_flag:
            Controller.set_top_window("Unity 2019.1.8f1 - mainScene.unity - Learn unity editor script - PC, Mac & Linux Standalone <DX11>")
            monitor_flag = False

        cv2.imshow("I am a good stuff v1.0 @ FPS: %d" % bino_cam.get_fps(), np.hstack((bino_cam.get_lframe(), bino_cam.get_rframe())))
        if cv2.waitKey(1) == ord('q'):
            break
    cv2.destroyAllWindows()
Exemplo n.º 18
0
    def draw(self, ctx):
        ctx.save()

        ctx.save()
        ctx.set_font_size(self.labelFontSize * 10)
        ascent, descent, height, max_x_advance, max_y_advance = ctx.font_extents()
        ctx.move_to(0, ascent)
        ctx.show_text(self.label)
        ctx.restore()

        ctx.translate(0, ascent + descent + 5)

        drawer = Drawer(ctx)
        r, u, d = self.node.getExtents(drawer)
        ctx.translate(0, u)
        drawer.drawStart()
        self.node.draw(drawer)
        drawer.drawStop()

        ctx.restore()
Exemplo n.º 19
0
 def GenAllCertificate(self):
     Year = self.spinBox.value()
     Stamp = self.comboBox_7.currentText()
     Quarter = self.comboBox_6.currentText()
     Category = self.comboBox_2.currentText()
     if self.File == "":
         self.textEdit_3.setText("请先导入文档!")
     else:
         self.ParseDocx3()
         if len(self.TitleList) == len(self.AuthorList) == len(
                 self.ContentList) == len(self.AwardList):
             self.textEdit_3.setText("文档格式无误,正在自动生成所有奖状!")
             myDrawer = Drawer(Stamp, Category, Quarter, Year)
             for i in range(len(self.TitleList)):
                 result = myDrawer.DrawCertificate(self.AwardList[i],
                                                   self.TitleList[i],
                                                   self.AuthorList[i],
                                                   self.ContentList[i])
                 self.textEdit_3.setText("正在生成:" + result)
         else:
             self.textEdit_3.setText("文档格式不正确,请选择需要打印的输出信息!")
Exemplo n.º 20
0
def main():
    if len(sys.argv) != 3:
        print(
            "Wrong number of arguments: ./project2.py, <path to csv file>, <year for which u want diagrams>"
        )
        exit(1)

    # Czytanie nazwy/sciezki do pliku
    try:
        filename = sys.argv[1]
    except IndexError as error:
        print("Problem with reading a path to file:", error)
        exit(1)

    open_and_parse_csvfile(filename)  # Parsowanie pliku

    # Czytanie i parsowanie roku
    try:
        year = sys.argv[2]
        year_int = int(year)
        if year_int < 1998 or year_int > 2012:
            print("Year should be between 1998 and 2012.")
            exit(1)
    except IndexError as error:
        print("Problem with reading year for diagrams:", error)
        exit(1)
    except ValueError as error:
        print("Year is not a int:", error)
        exit(1)

    # Zmienne do rysowania
    state_array = []
    total_production_array = []
    production_value_array = []

    # Wyciagam dane do wykresu dla danego roku
    for elem in object_array:
        if elem.get_state(year_int) is not False:
            state_array.append(elem.get_state(year_int))
        if elem.get_total_production(year_int) is not False:
            total_production_array.append(elem.get_total_production(year_int))
        if elem.get_production_value(year_int) is not False:
            production_value_array.append(elem.get_production_value(year_int))

    # Rysuje wykresy
    print("In case you forgot, diagrams are for year:", year)
    drawer1 = Drawer("total production", state_array, total_production_array)
    drawer1.draw_bar()
    drawer2 = Drawer("production value", state_array, production_value_array)
    drawer2.draw_bar()
Exemplo n.º 21
0
class MainWindow(Tk.Tk):

    def __init__(self):
        Tk.Tk.__init__(self)
        self.toppanel = None
        self.botpanel = None
        self.canvas = None
        self.filter = None
        self.combobox = None
        self.img = None
        self.startX = None
        self.startY = None
        self.drawer = None
        self.initialize()

    def initialize(self):
        self.title = "CGP2"
        self.toppanel = Tk.Frame(self)
        self.toppanel.pack(side=Tk.TOP)
        self.botpanel = Tk.Frame(self)
        self.botpanel.pack()
        self.canvas = Tk.Canvas(self.botpanel, width=WIDTH, height=HEIGHT, bg='white')
        self.img = Tk.PhotoImage(width=WIDTH, height=HEIGHT)
        self.canvas.create_image((0, 0), image=self.img, anchor="nw")
        self.canvas.bind('<ButtonPress-1>', self.onStart)
        self.canvas.bind('<ButtonRelease-1>', self.onEnd)
        self.canvas.pack(fill=Tk.BOTH, expand=1)
        combooptions = ["Symmetric bresenham", "Midpoint circle algorithm", "Xiaolin Wu Line", "Xiaolin Wu Circle"]
        self.filter = Tk.StringVar(self)
        self.filter.set(combooptions[0])
        self.combobox = apply(Tk.OptionMenu, (self.toppanel, self.filter)+tuple(combooptions))
        self.combobox.pack(side=Tk.LEFT)
        self.drawer = Drawer(self.img)
        self.mainloop()

    def onStart(self, event):
        self.startX = event.x
        self.startY = event.y

    def onEnd(self, event):
        if(self.filter.get() == "Symmetric bresenham"):
            self.drawer.drawsymbresenham(self.startX, self.startY, event.x, event.y)
        elif (self.filter.get() == "Midpoint circle algorithm"):
            self.drawer.circle(self.startX, self.startY, event.x, event.y)
        elif (self.filter.get() == "Xiaolin Wu Line"):
            self.drawer.xaolinwuline(self.startX, self.startY, event.x, event.y)
        elif (self.filter.get() == "Xiaolin Wu Circle"):
            self.drawer.xaolinwuciricle(self.startX, self.startY, event.x, event.y)
Exemplo n.º 22
0
    def __init__(self, main):
        pygame.init()
        self.main = main
        self.display = pygame.display
        self.window = pygame.display.set_mode((800, 480), pygame.FULLSCREEN)
        self.drawer = Drawer(self)

        self.keras_switch_false = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/switch_FALSE.png")
        self.keras_switch_true = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/switch_TRUE.png")

        self.keras = False
        self.streaming = False
        self.rects_to_update = []

        #needed for webcam-camera, which doesn't work yet.
        self.camera = None
        self.camsize = (320, 240)

        self.clock = pygame.time.Clock()
Exemplo n.º 23
0
    def doEff(self, type, file, dir, outdir=''):
        file = TFile(file)
        fGet = file.Get
#        for i in self.inputdirs:
        after = fGet(dir + self.after + '/' + self.hists['weighted']).Clone('nVSdiscTight')
        unwafter = fGet(dir + self.after + '/' + self.hists['simple']).Clone('nVSdiscTightSimple')
        before = fGet(dir + self.before + '/' + self.hists['weighted']).Clone('nVSdiscLoose')
        unwbefore = fGet(dir + self.before + '/' + self.hists['simple']).Clone('nVSdiscLooseSimple')
        if after == None or before == None or unwbefore == None:
            print 'Histogram not found'
        else:
            self.setMCTruth(type, dir, before, after)
            self.output.cd(type + '/' + outdir + '/' + dir)
            result = self.getEffHist(before, after, unwbefore)
            #caluclate MC Efficiency without binning
            mceff = after.Integral() / before.Integral()
            mcerr = self.getStatError(mceff, unwbefore.Integral())#sqrt((mceff * (1 - mceff)) / unwbefore.Integral())
                
#                print 'MC Eff for', i, ':[', mceff, ',', mcerr, ']' 
            self.setEff(type, dir, - 1, mceff, mcerr)
#                for effs in result[1]:          
#                    print 'Eff for %s disc < %1.2f : %1.3f +- %1.3f' % (i, effs[0], effs[1], effs[2])
#                    self.setEff(type, i,  effs[0], effs[1], effs[2])
            leg = Drawer.makePlainLegend(25 , 95, 70, 25)
            title1 = 'overall eff. %1.4f \pm %1.4f' % (mceff, mcerr)   
            leg.SetHeader(title1)
            leg = Drawer.setLegendStyle(leg)
            eff = result[0]
            eff.SetTitle(title1)
            eff.Write()
            after.Scale(self.scale[type])
            before.Scale(self.scale[type])
            after.Write()
            unwafter.Write()
            before.Write()
            unwbefore.Write()
            self.output.Cd('/')        
Exemplo n.º 24
0
 def draw_solution_step_by_step(self, solution, k_delta):
     drawer = Drawer(self.path_planner)
     N = self.path_planner.parameters.N
     k = 0
     while k < N - 1:
         drawer.draw_path_for_all_robots_step_by_step(
             solution.path, self.robots, self.tasks, k)
         k = k + k_delta
     drawer.draw_path_for_all_robots_step_by_step(solution.path,
                                                  self.robots, self.tasks,
                                                  N - 1)
Exemplo n.º 25
0
 def initialize(self):
     self.title = "CGP2"
     self.toppanel = Tk.Frame(self)
     self.toppanel.pack(side=Tk.TOP)
     self.botpanel = Tk.Frame(self)
     self.botpanel.pack()
     self.canvas = Tk.Canvas(self.botpanel, width=WIDTH, height=HEIGHT, bg='white')
     self.img = Tk.PhotoImage(width=WIDTH, height=HEIGHT)
     self.canvas.create_image((0, 0), image=self.img, anchor="nw")
     self.canvas.bind('<ButtonPress-1>', self.onStart)
     self.canvas.bind('<ButtonRelease-1>', self.onEnd)
     self.canvas.pack(fill=Tk.BOTH, expand=1)
     combooptions = ["Symmetric bresenham", "Midpoint circle algorithm", "Xiaolin Wu Line", "Xiaolin Wu Circle"]
     self.filter = Tk.StringVar(self)
     self.filter.set(combooptions[0])
     self.combobox = apply(Tk.OptionMenu, (self.toppanel, self.filter)+tuple(combooptions))
     self.combobox.pack(side=Tk.LEFT)
     self.drawer = Drawer(self.img)
     self.mainloop()
Exemplo n.º 26
0
    def runSingleSimulation(self, path):
        reader = FilesReader(path + 'animation_dynamic')
        mapSize, maxSpeed = reader.readStatic(path + 'animation_static')
        drawer = Drawer(int(mapSize * 1000), maxSpeed)
        positions = reader.readNextPosition()
        drawer.firstUpdate()
        time.sleep(4)

        while len(positions) > 0:
            drawer.update(positions)
            positions = reader.readNextPosition()
            skipPositions = 50
            while skipPositions > 0:
                reader.readNextPosition()
                skipPositions -= 1
Exemplo n.º 27
0
from Data import Data
from Drawer import Drawer
from Neuronas import Perceptron, Adaline

data = Data()
"""
Ahora mostramos como evoluciona el numero de errores con las epocas en nuestro Perceptron
Vemos que a la quinta epoca dejamos de tener errores y parece que la neurona esta entrenada
"""
ppn = Perceptron(m=0.1, n_iter=10)
ppn.entrenar(data.X, data.y)
"""
Ahora hacemos una funcion para dibujar el limite de decision
"""
drawer = Drawer()
drawer.plot_decision_regions(data, classifier=ppn)
drawer.draw_plots(data)
# se superpone la recta de 0 = w2x2 + w1x1 + w0 => x2 = -w1x1/w2 - w0/w2 con xmin y xmax.
drawer.drawLine(-ppn.w[1] / ppn.w[2], -ppn.w[0] / ppn.w[2],
                data.X[:, 0].min() - 1, data.X[:, 0].max() + 1)
drawer.draw()
Exemplo n.º 28
0
from Robot import Robot
from Rewards import Rewards
from Drawer import Drawer
import getch
import random

# Set initial position
robot = Robot(3, 9)

r1 = Rewards(random.randint(1, 10), random.randint(1, 10), 'Coin')
r2 = Rewards(random.randint(1, 10), random.randint(1, 10), 'Gold')
r3 = Rewards(random.randint(1, 10), random.randint(1, 10), 'Weapon')
rewards = [r1, r2, r3]
print(r1, r2, r3, end='\n')
drawer = Drawer(robot, rewards)


def caller(number):
    options = {
        67: robot.moveRight,
        68: robot.moveLeft,
        65: robot.moveUp,
        66: robot.moveDown
    }
    func = options.get(number, '')
    if (func != ''):
        func()
        drawer.draw(robot)


while True:
Exemplo n.º 29
0
class MainWindow(Tk.Tk):

    WIDTH = 800
    HEIGHT = 600

    def __init__(self):
        Tk.Tk.__init__(self)
        self.filechooseoptions = self.getfilechooseoptions()
        self.currentFileName = None
        self.imageLabel = None
        self.photo = None
        self.toppanel = None
        self.botpanel = None
        self.manager = ImageManager()
        self.canvas = None
        self.raster = None
        self.sphere = None
        self.drawer = None
        self.pixels = None
        self.initialize()

    def getfilechooseoptions(self):
        options = {}
        return options

    def initialize(self):
        self.title = "CGP5"
        self.canvas = Tk.Canvas(self.botpanel, width=MainWindow.WIDTH, height=MainWindow.HEIGHT, bg="#F5F1DE")
        self.canvas.pack()
        self.raster = Tk.PhotoImage(width=MainWindow.WIDTH, height=MainWindow.HEIGHT)
        self.canvas.create_image((0, 0), image=self.raster, state="normal", anchor="nw")
        self.toppanel = Tk.Frame(self)
        self.toppanel.pack(side=Tk.TOP)
        self.botpanel = Tk.Frame(self)
        self.botpanel.pack()
        Tk.Button(self.toppanel, text="Choose an image", command=self.fileselecthandler).pack(side=Tk.LEFT)
        Tk.Button(self.toppanel, text="Draw", command=self.draw).pack(side=Tk.LEFT)
        self.imageLabel = Tk.Label(self.botpanel)
        self.imageLabel.pack()
        self.drawer = Drawer(self.raster)
        self.mainloop()

    def draw(self):
        self.drawer.draw(self.photo, self.pixels)

    def fileselecthandler(self):
        self.currentFileName = tkFileDialog.askopenfilename(**self.filechooseoptions)
        if self.currentFileName:
            self.loadimage()

    def loadimage(self):
        self.manager.loadimage(self.currentFileName)
        self.photo = self.manager.image
        self.pixels = self.manager.raster

    def drawimage(self):
        if self.photo is None and self.imageLabel is None:
            self.photo = ImageTk.PhotoImage(self.manager.image)
            self.imageLabel = Tk.Label(self, image=self.photo).pack()
        else:
            self.photo = ImageTk.PhotoImage(self.manager.image)
            self.imageLabel.configure(image=self.photo)
            self.imageLabel.image = self.photo
Exemplo n.º 30
0
class MainWindow(Tk.Tk):

    def __init__(self):
        Tk.Tk.__init__(self)
        self.filechooseoptions = self.getfilechooseoptions()
        self.toppanel = None
        self.botpanel = None
        self.canvas = None
        self.filter = None
        self.combobox = None
        self.neighs = None
        self.neighsVar = None
        self.img = None
        self.startX = None
        self.startY = None
        self.drawer = None
        self.color = (174,198,207)
        self.lastX = None
        self.lastY = None
        self.sorted = None
        self.image = None
        self.raster = None
        self.photo = None
        self.imageLabel = None
        self.currentFileName = None
        self.points = []
        self.initialize()

    def initialize(self):
        self.title = "CGP2"
        self.toppanel = Tk.Frame(self)
        self.toppanel.pack(side=Tk.TOP)
        Tk.Button(self.toppanel, text="Choose an image", command=self.fileselecthandler).pack(side=Tk.LEFT)
        self.botpanel = Tk.Frame(self)
        self.botpanel.pack()
        self.canvas = Tk.Canvas(self.botpanel, width=WIDTH, height=HEIGHT, bg='white')
        self.img = Tk.PhotoImage(width=WIDTH, height=HEIGHT)
        self.canvas.create_image((0, 0), image=self.img, anchor="nw")
        self.canvas.bind('<ButtonRelease-1>', self.onEnd)
        self.canvas.pack(fill=Tk.BOTH, expand=1)
        combooptions = ["Polygon Fill", "Region Fill"]
        neighOptions = [4, 8]
        self.neighsVar = Tk.StringVar(self)
        self.filter = Tk.StringVar(self)
        self.filter.set(combooptions[0])
        self.neighsVar.set(neighOptions[0])
        self.combobox = apply(Tk.OptionMenu, (self.toppanel, self.filter)+tuple(combooptions))
        self.combobox.pack(side=Tk.LEFT)
        self.neighs = apply(Tk.OptionMenu, (self.toppanel, self.neighsVar)+tuple(neighOptions))
        self.neighs.pack(side=Tk.LEFT)
        self.drawer = Drawer(self.img)
        Tk.Button(self.toppanel,text='Select Color', command=self.getColor).pack()
        self.mainloop()

    def polygon(self, event):
        if self.startX is None:
            self.startX = event.x
            self.startY = event.y
        else:
            if self.dist(event) < 30:
                self.sorted = sorted(self.points, key=lambda tup: tup[1], reverse=True)
                self.drawer.drawsymbresenham(self.startX, self.startY, self.lastX, self.lastY)
                self.fill()
            else:
                self.drawer.drawsymbresenham(self.lastX, self.lastY, event.x, event.y)
        self.points.append((event.x, event.y))
        self.lastX = event.x
        self.lastY = event.y

    def fill(self):
        n = len(self.points)
        k = 0
        ymax = self.sorted[0][1]
        ymin = self.sorted[len(self.sorted)-1][1]
        aet = ActiveEdgeTable()
        for y in range(ymax, ymin+1, -1):
            while k <= n and self.sorted[k][1] == y:
                i = self.points.index(self.sorted[k])
                if self.points[(i-1) % n][1] < self.points[i][1]:
                    aet.add(self.points[i][0], self.points[i][1], self.points[(i-1) % n][0], self.points[(i-1) % n][1])
                elif self.points[(i-1) % n][1] > self.points[i][1]:
                    aet.removeEdge(self.points[(i-1) % n][0], self.points[(i-1) % n][1], self.points[i][0], self.points[i][1])
                if self.points[(i + 1) % n][1] < self.points[i][1]:
                    aet.add(self.points[i][0], self.points[i][1], self.points[(i + 1) % n][0], self.points[(i + 1) % n][1])
                elif self.points[(i + 1) % n][1] > self.points[i][1]:
                    aet.removeEdge(self.points[(i + 1) % n][0], self.points[(i + 1) % n][1], self.points[i][0], self.points[i][1])
                k = k +1
            j = 0
            aet.sort()
            while(j <= len(aet.edges)-2):
                for xx in range(int(ceil(aet.edges[j].x)), int(round(aet.edges[j+1].x))):
                    self.drawer.putpixel(xx, y, self.color)
                j = j + 2
            aet.remove(y)
            aet.update()




    def dist(self, event):
        return sqrt((self.startX - event.x) ** 2 + (self.startY - event.y) ** 2)

    def onEnd(self, event):
        if self.filter.get() == "Polygon Fill":
            self.polygon(event)
        elif self.filter.get() == "Region Fill":
            self.region(event)

    def region(self, event):
        color = self.raster[event.x, event.y]
        print color
        q = Queue()
        visited = set()
        q.put((event.x, event.y), block=False)
        while not q.empty():
            px = q.get(block=False)
            visited.add(px)
            if px[0] < 0 or px[1] < 0 or px[0] >= self.img.width() or px[1] >= self.img.height():
                continue
            if self.colorDist(self.raster[px[0], px[1]], color) < 25:
                self.raster[px[0], px[1]] = self.color
                ns = self.getNs(px)
                for item in ns:
                    if item not in visited:
                        q.put(item)
        self.drawimage()

    def colorDist(self, c1, c2):
        x = 0
        for i in range(3):
            x += (c1[i] - c2[i]) ** 2
        return sqrt(x)

    def getNs(self, px):
        ret = []
        ret.append((px[0], px[1] + 1))
        ret.append((px[0], px[1] - 1))
        ret.append((px[0] - 1, px[1]))
        ret.append((px[0] + 1, px[1]))
        if self.neighsVar.get() == "8":
            ret.append((px[0] + 1, px[1] + 1))
            ret.append((px[0] + 1, px[1] - 1))
            ret.append((px[0] - 1, px[1] + 1))
            ret.append((px[0] - 1, px[1] - 1))
        return ret

    def getColor(self):
        color = askcolor()
        self.color = color[0]

    def fileselecthandler(self):
        self.currentFileName = tkFileDialog.askopenfilename(**self.filechooseoptions)
        if self.currentFileName:
            self.loadimage()

    def getfilechooseoptions(self):
        options = {}
        options['defaultextension'] = '.jpg'
        options['filetypes'] = [('jpg files', '.jpg'), ('all files', '.*')]
        options['initialdir'] = 'C:\\'
        options['title'] = 'Choose an image'
        return options

    def loadimage(self):
        self.image = Image.open(self.currentFileName)
        self.raster = self.image.load()
        self.drawimage()

    def drawimage(self):
        if self.photo is None and self.imageLabel is None:
            self.img = ImageTk.PhotoImage(self.image)
            self.raster = self.image.load()
            self.canvas.create_image((0, 0), image=self.img, anchor="nw")
        else:
            self.img = ImageTk.PhotoImage(self.image)
            self.raster = self.image.load()
            self.canvas.create_image((0, 0), image=self.img, anchor="nw")
Exemplo n.º 31
0
BLUE = (0, 0, 255)

# Game variables
game_size = 5  # set WIDTH and HEIGHT divisor for proper screen
grid_width = 4 * game_size
grid_height = 3 * game_size
head_width = WIDTH // grid_width
head_height = HEIGHT // grid_height
head_pos = (grid_width // 2, grid_height // 2)
orientation = None
grid_on = False

# Instanciate classes
head = Tail(head_pos, True, GREEN)
grid = Grid(grid_width, grid_height, head)
drawer = Drawer(screen, WIDTH, HEIGHT, grid, head)
grid.generate_fruit()

# Game loop
running = True
clock = pygame.time.Clock()
moved_in_this_frame = False
paused = False
framerate = 15

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
Exemplo n.º 32
0
 def __init__(self, maxN, minN):
     self.root = None
     self.maxN = maxN
     self.minN = minN
     self.drawer = Drawer(self)
Exemplo n.º 33
0
class GreeneTree:
    def __init__(self, maxN, minN):
        self.root = None
        self.maxN = maxN
        self.minN = minN
        self.drawer = Drawer(self)

    def draw(self):
        self.drawer.draw()

    def __repr__(self):
        output = str(self.root) + "|"
        q = queue.Queue()
        q2 = queue.Queue()
        q.put(self.root)
        while not q.empty():
            u = q.get()
            if u.depth != 1:
                for idx, i in enumerate(u.children):
                    if (idx + 1) < len(u.children):
                        output = output + str(i) + ","
                    elif not q.empty():
                        output = output + str(i) + ":"
                    else:
                        output = output + str(i)
                for idx, i in enumerate(u.children):
                    q2.put(i)
            else:
                for idx, i in enumerate(u.children):
                    if (idx + 1) < len(u.children):
                        output = output + i.val + ","
                    elif not q.empty():
                        output = output + i.val + ":"
                    else:
                        output = output + i.val
            if q.empty():
                if not q2.empty():
                    output = output + "|"
                while not q2.empty():
                    q.put(q2.get())
        return output

    def insert(self, obj):
        '''
        insert new object into RTree
        :param obj: object to insert
        :return:
        '''
        if self.root is None:
            self.root = self.Leaf(MBR.generate(obj.mbr), self.maxN, self.minN,
                                  1)
            self.root.children.append(obj)
            return

        n = self.root
        while n.depth is not 1:
            for i in n.children:
                if i.mbr.contains(obj.mbr):
                    n = i
                    break
                else:
                    node = n.find_min(n.children, obj)
                    node.mbr.resize(obj.mbr)
                    n = node
                    break

        if len(n.children) < n.maxN:
            n.children.append(obj)
            while n is not None:
                n.mbr.resize(obj.mbr)
                n = n.parent
            return

        if len(n.children) == n.maxN:
            n.children.append(obj)
            self.overflow(n)
            while n is not None:
                n.mbr.resize(obj.mbr)
                n = n.parent
        return

    def overflow(self, n):
        u, v = n.split()

        n.mbr.resize(u.mbr)
        n.mbr.resize(v.mbr)

        if n == self.root:
            self.root = self.Branch(self.root.mbr, self.maxN, self.minN,
                                    n.depth + 1)
            self.root.children.extend([u, v])
            u.parent = self.root
            v.parent = self.root

        else:
            u.parent = n.parent
            v.parent = n.parent
            n.parent.children.remove(n)
            n.parent.children.extend([u, v])
            if len(n.parent.children) > self.maxN:
                self.overflow(n.parent)

    def search(self, obj):
        '''
        search for the mbr containing a given object
        :param obj: object to search for
        :return: mbr containing that object
        '''
        node = self.root
        for i in node.children:
            if i.mbr.contains(obj.mbr):
                node = i
        return node

    class Node:
        def __init__(self, mbr=None, maxN=None, minN=None, depth=None):
            self.parent = None
            self.children = list()
            self.mbr = mbr
            self.maxN = maxN
            self.minN = minN
            self.depth = depth

        def split(self):
            return None

        @staticmethod
        def find_min(nodes, insertion):
            """
            Find the node most optimal for insertion
            :param rt_nodes:
            :param entry:
            :return:
            """
            e = []
            for i in range(len(nodes)):
                if nodes[i].mbr.contains(insertion.mbr):
                    v = 0
                else:
                    v = MBR.generate2(nodes[i].mbr,
                                      insertion.mbr).area - nodes[i].mbr.area
                e.append({'node': nodes[i], 'expanded': v})
            return min(e, key=lambda x: x['expanded'])['node']

    class Leaf(Node):
        def __init__(self, mbr=None, maxN=None, minN=None, depth=1):
            super().__init__(mbr, maxN, minN, depth)

        def split(self):
            '''
            split node if capacity is reached
            :return: node a, b split from original
            '''
            d, x, y = -1, None, None
            for i in range(len(self.children)):
                for j in range(len(self.children)):
                    if i != j:
                        k = (self.children[i].mbr.euclidian_distance_rect(
                            self.children[j].mbr))
                        if k > d:
                            d = k
                            x = self.children[i]
                            y = self.children[j]

            left = x.mbr.lower_right.x < y.mbr.upper_left.x
            right = x.mbr.upper_left.x < y.mbr.lower_right.x
            bottom = x.mbr.upper_left.y < y.mbr.lower_right.y
            top = x.mbr.lower_right.y < y.mbr.upper_left.y

            if left and bottom:
                dist_x = y.mbr.lower_left.x - x.mbr.upper_right.x
                dist_y = y.mbr.lower_left.y - x.mbr.upper_right.y
            elif right and bottom:
                dist_x = x.mbr.lower_left.x - y.mbr.upper_right.x
                dist_y = y.mbr.lower_right.y - x.mbr.upper_left.y
            elif left and top:
                dist_x = y.mbr.lower_left.x - x.mbr.upper_right.x
                dist_y = x.mbr.lower_left.y - y.mbr.upper_right.y
            else:
                dist_x = x.mbr.lower_left.x - y.mbr.upper_right.x
                dist_y = x.mbr.lower_left.y - y.mbr.upper_right.y

            normalized_x = dist_x / (self.mbr.upper_right.x -
                                     self.mbr.upper_left.x)
            normalized_y = dist_y / (self.mbr.upper_right.y -
                                     self.mbr.lower_left.y)

            if normalized_x > normalized_y:
                sorted_children = sorted(
                    self.children,
                    key=lambda i:
                    (i.mbr.lower_left.x + i.mbr.lower_right.x) / 2)
            else:
                sorted_children = sorted(
                    self.children,
                    key=lambda i:
                    (i.mbr.upper_left.y + i.mbr.lower_right.y) / 2)

            r = self.__class__(MBR.generate(x.mbr), self.maxN, self.minN,
                               self.depth)
            s = self.__class__(MBR.generate(y.mbr), self.maxN, self.minN,
                               self.depth)

            m = math.floor((self.maxN + 1) / 2)
            for i in sorted_children[:m]:
                r.children.append(i)
            for i in sorted_children[-m:]:
                s.children.append(i)
            if (self.maxN + 1) % 2 != 0:
                n = self.find_min([r, s], sorted_children[m])
                n.children.append(sorted_children[m])

            for i in [r, s]:
                for j in range(len(i.children)):
                    if not i.mbr.contains(i.children[j].mbr):
                        i.mbr.resize(i.children[j].mbr)

            return r, s

    class Branch(Node):
        def __init__(self, mbr=None, maxN=None, minN=None, depth=None):
            super().__init__(mbr, maxN, minN, depth)

        def split(self):
            '''
            split node if capacity is reached
            :return: node a, b split from original
            '''
            d, x, y = -1, None, None
            for i in range(len(self.children)):
                for j in range(len(self.children)):
                    if i != j:
                        k = (self.children[i].mbr.euclidian_distance_rect(
                            self.children[j].mbr))
                        if k > d:
                            d = k
                            x = self.children[i]
                            y = self.children[j]

            left = x.mbr.lower_right.x < y.mbr.upper_left.x
            right = x.mbr.upper_left.x < y.mbr.lower_right.x
            bottom = x.mbr.upper_left.y < y.mbr.lower_right.y
            top = x.mbr.lower_right.y < y.mbr.upper_left.y

            if left and bottom:
                dist_x = y.mbr.lower_left.x - x.mbr.upper_right.x
                dist_y = y.mbr.lower_left.y - x.mbr.upper_right.y
            elif right and bottom:
                dist_x = x.mbr.lower_left.x - y.mbr.upper_right.x
                dist_y = y.mbr.lower_right.y - x.mbr.upper_left.y
            elif left and top:
                dist_x = y.mbr.lower_left.x - x.mbr.upper_right.x
                dist_y = x.mbr.lower_left.y - y.mbr.upper_right.y
            else:
                dist_x = x.mbr.lower_left.x - y.mbr.upper_right.x
                dist_y = x.mbr.lower_left.y - y.mbr.upper_right.y

            normalized_x = dist_x / (self.mbr.upper_right.x -
                                     self.mbr.upper_left.x)
            normalized_y = dist_y / (self.mbr.upper_right.y -
                                     self.mbr.lower_left.y)

            if normalized_x > normalized_y:
                sorted_children = sorted(
                    self.children,
                    key=lambda i:
                    (i.mbr.lower_left.x + i.mbr.lower_right.x) / 2)
            else:
                sorted_children = sorted(
                    self.children,
                    key=lambda i:
                    (i.mbr.upper_left.y + i.mbr.lower_right.y) / 2)

            r = self.__class__(MBR.generate(x.mbr), self.maxN, self.minN,
                               self.depth)
            s = self.__class__(MBR.generate(y.mbr), self.maxN, self.minN,
                               self.depth)

            m = math.floor((self.maxN + 1) / 2)
            for i in sorted_children[:m]:
                r.children.append(i)
            for i in sorted_children[-m:]:
                s.children.append(i)
            if (self.maxN + 1) % 2 != 0:
                n = self.find_min([r, s], sorted_children[m])
                n.children.append(sorted_children[m])

            for i in [r, s]:
                for j in range(len(i.children)):
                    i.children[j].parent = i
                    if not i.mbr.contains(i.children[j].mbr):
                        i.mbr.resize(i.children[j].mbr)

            return r, s
Exemplo n.º 34
0
        Drawer.NoHpP = nohpp
        writeAs = plots.getOption("create").split(",")
        summaryFile = plots.getOption("summaryFile")
        Drawer.summaryFile = savedir + "/" + summaryFile
        histlist = cfg.getAllCanvas()
        noh = len(histlist)
        perf[ts[0]].stop()
        if showPerformance:
            print "Config read in %s" % perf[ts[0]].getMeasuredTime()
        self.doHistList(histlist, savedir, writeAs)
        Drawer.summaryBegin = False
        Drawer.flushStack(savedir, writeAs)
        perf[ts[3]].stop()
        if showPerformance:
            if noh > 1:
                print "%d histograms read in %s (%f per hist without caching)" % (noh, perf[ts[2]].getMeasuredTime(), (perf[ts[2]].getMeasuredSeconds()-perf[ts[5]].getMeasuredSeconds())/(noh-1))
                print "%d histograms printed in %s (%f per hist without caching)" % (noh, perf[ts[1]].getMeasuredTime(), (perf[ts[1]].getMeasuredSeconds()-perf[ts[4]].getMeasuredSeconds())/(noh-1))
            else:
                print "%d histograms read in %s (%f per hist)" % (noh, perf[ts[2]].getMeasuredTime(), (perf[ts[2]].getMeasuredSeconds()))
                print "%d histograms printed in %s (%f per hist)" % (noh, perf[ts[1]].getMeasuredTime(), (perf[ts[1]].getMeasuredSeconds()))
            print "total time elapsed: %s" % perf[ts[3]].getMeasuredTime()
        #Drawer.drawSummary(savedir, "Oo.ps")#
        
if __name__ == "__main__":
    XMLConfigParser.pathToDir = "../../../../"
    Drawer.setDefaultLayout()
    pl = Plotter("TopAnalysis/TopUtils/data/TestConfig.xml")
    print "Saving test configuration"
    pl.savePlots("plots")
    print "Thanks and GoodBye."
Exemplo n.º 35
0
    def doHistList(self, histlist, savedir, writeAs):
        x = 0
        gcd = gROOT.cd
        for hist in histlist:
            x = x+1
            list = {}
            h = None
#            if hist == histlist[-1]:
#                Drawer.summaryBegin = False
            
            for var in hist.subobjects["hist"]:

                source = var.getOption("source")
                if var.getOption('operation') == 'none':
                    file = source[0]
                    h1 = source[1]
                    perf[ts[2]].start()
                    if hist == histlist[0]:
                         perf[ts[5]].start()
                    f = TFile(file)
                    gcd()
                    tmp = f.Get(h1)
                    if tmp:
                        h = tmp.Clone()
                    else:
                        print >> sys.stderr, "Histogram %s in file %s not found" % (h1, file)
                        continue
                    perf[ts[2]].stop()
                    if hist == histlist[0]:
                         perf[ts[5]].stop()
                else: #combine histograms with operations
                    integ = 0
                    varhists = []
                    varroots = []
                    for i in source:
                        s = i.getOption("source")
                        file = s[0]
                        h1 = s[1]
                        varhists.append(h1)
                        varroots.append(file)
                    for xxx in range(0, len(varroots)):
                        perf[ts[2]].start()
                        if hist == histlist[0]:
                            perf[ts[5]].start()
                        f = TFile(varroots[xxx])
                        h1 = varhists[xxx]
                        gcd()
                        tmp = f.Get(h1)
                        if tmp:
                            h = tmp.Clone()
                        else:
                            print >> sys.stderr, "Histogram %s in file %s not found" % (h1,varroots[xxx])
                            continue
                        if xxx == 0:#load first variable
                            h = tmp.Clone()
                        else:#add or divide by the 2nd variable
                            #TODO: in order to make real math, all variables need to be saved temporaly
                            if var.getOption('operation') == 'add':
                                h.Add(tmp)
                            elif var.getOption('operation') == 'div':
#                                print h1
#                                print var.hist
#                                print h.GetName()
                                if hist.getOption("showErrors").upper() == "TRUE":
                                    h.Sumw2()
                                h.Divide(tmp)
#                                if hist.opt["showErrors"]:
#                                    h.Sumw2()
                            else:
                                print 'unknown operation'
                        perf[ts[2]].stop()
                        if hist == histlist[0]:
                            perf[ts[5]].stop()
#===============================================================================
#                once you have the histogram, apply the configuration to it.
#===============================================================================
                h = Drawer.applyHistConfig(h, hist, var)
#===============================================================================
#                only hists which are marked to be draw are added to list
#===============================================================================
                if var.getOption('draw') == '1':
                    list[var.getOption("name")] =h.Clone()
#                    list.append(copy.deepcopy(h.Clone()))
#===============================================================================
#                save all histograms in one file
#===============================================================================
            perf[ts[1]].start()
            if hist == histlist[0]:
                perf[ts[4]].start()
            Drawer.saveHistsInOne(list, hist, savedir, writeAs) 
            perf[ts[1]].stop()
            if hist == histlist[0]:
                perf[ts[4]].stop()
                if showPerformance:
                    print "time elapsed to read first histogram (incl. caching): %s" % perf[ts[5]].getMeasuredTime()
                    print "time elapsed to draw first histogram (incl. caching): %s" % perf[ts[4]].getMeasuredTime()
Exemplo n.º 36
0
 def draw_solution(self, solution):
     drawer = Drawer(self.path_planner)
     drawer.draw_path_for_all_robots(solution.path, self.robots, self.tasks)
Exemplo n.º 37
0
    def __init__(self, app):
        """
        MainWindow initialization
        """
        super(MainWindow, self).__init__()
        ## app
        self.app = app
        ## ui object
        self.ui = QUiLoader().load("mainwindow.ui")
        self.ui.show()
        self.ui.setWindowTitle("RoboAide")
        self.setMinimumHeight(100)
        self.setMinimumWidth(250)
        # self.setMaximumHeight(200)
        # self.setMaximumWidth(800)
        self.setIcon()
        self.msgMu = QMutex()

        self.numberOfMotors = 6
        self.s, self.messageSize = makeStruct()

        # Connect button signals
        self.ui.calibrateVerticalAxisButton.clicked.connect(
            self.calibrateVerticalAxis)

        self.ports_list = scanAvailablePorts()
        self.populatePortsList()

        # ---------------
        ## Dictionnary of all motor objects
        self.dictMot = dict()
        for i in range(1, self.numberOfMotors + 1):
            mot = Motor(self, "motor" + str(i))
            self.dictMot[mot.getName()] = mot
        # ---------------

        ## List of drawers
        self.drawersList = []
        for i in range(3):
            self.drawersList.append(Drawer(self, "drawer" + str(i + 1)))

        self.updateSliderPositions()

        ## ListOfSequencesHandler object
        self.listOfSequencesHandler = ListOfSequencesHandler(
            self, self.dictMot)

        # load the last save
        loadSequences(self.listOfSequencesHandler, self.dictMot)

        # Connect the slider signals
        self.ui.slider_mot1.sliderMoved.connect(lambda: self.dictMot[
            "motor1"].setGoalPosition(self.ui.slider_mot1.value()))
        self.ui.slider_mot2.sliderMoved.connect(lambda: self.dictMot[
            "motor2"].setGoalPosition(self.ui.slider_mot2.value()))
        self.ui.slider_mot3.sliderMoved.connect(lambda: self.dictMot[
            "motor3"].setGoalPosition(self.ui.slider_mot3.value()))
        self.ui.slider_mot4.sliderMoved.connect(lambda: self.dictMot[
            "motor4"].setGoalPosition(self.ui.slider_mot4.value()))
        self.ui.slider_mot5.sliderMoved.connect(lambda: self.dictMot[
            "motor5"].setGoalPosition(self.ui.slider_mot5.value()))
        self.ui.slider_mot6.sliderMoved.connect(lambda: self.dictMot[
            "motor6"].setGoalPosition(self.ui.slider_mot6.value()))

        # Connect button signals
        self.ui.calibrateVerticalAxisButton.clicked.connect(
            self.calibrateVerticalAxis)

        # Connect drawer buttons signals
        self.ui.drawer1Open.clicked.connect(self.drawersList[0].open)
        self.ui.drawer2Open.clicked.connect(self.drawersList[1].open)
        self.ui.drawer3Open.clicked.connect(self.drawersList[2].open)
        self.ui.drawer1Close.clicked.connect(self.drawersList[0].close)
        self.ui.drawer2Close.clicked.connect(self.drawersList[1].close)
        self.ui.drawer3Close.clicked.connect(self.drawersList[2].close)

        # Connect the tab changed with updating the sliders
        self.ui.tabWidget.currentChanged.connect(self.updateSliderPositions)

        # Serial communication
        ## Outgoing message deque
        self.msgDeque = deque(maxlen=3)
        ## Stop indicator for the motors
        self.shouldStop = False
        ## Message reception QThread object
        self.msgReception = MessageReception(self)
        ## Message transmission QThread object
        self.msgTransmission = MessageTransmission(self)
        self.app.aboutToQuit.connect(self.msgReception.stop)
        self.app.aboutToQuit.connect(self.msgTransmission.stop)
        self.comm = None
        self.serialConnected = None
        try:
            with open('SavePort.json') as save:
                savedPort = json.load(save)
                for index in range(1, len(self.ports_list)):
                    if self.ports_list[index].device == savedPort:
                        self.ui.portselection.setCurrentIndex(index)
                        self.connect_port(savedPort)
                    else:
                        print("The last port is not available")
        except FileNotFoundError:
            print("SavePort file not found")
        self.ui.portselection.currentIndexChanged.connect(self.connect_port)
Exemplo n.º 38
0
#  Instanciate classes
player_racket = Racket((
    WIDTH - racket_width*2, HEIGHT // 2 - racket_height // 2),
    racket_width, racket_height)

bot_racket = Racket((
    racket_width, HEIGHT // 2 - racket_height // 2),
    racket_width, racket_height)

ball = Ball((WIDTH // 2 - racket_width // 2, HEIGHT // 2 - racket_width // 2),
            racket_width, WIDTH // 80)

controller = Controller(WIDTH, HEIGHT, player_racket, bot_racket, ball)

drawer = Drawer(screen, WIDTH, HEIGHT, controller,
                player_racket, bot_racket, ball)

# Game loop
running = True
clock = pygame.time.Clock()
framerate = 80
controller.release_ball(time.time())

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            pass
Exemplo n.º 39
0
    def doEffMixed(self, types, dir, outdir):   
        if not self.output.GetDirectory('mixed').GetDirectory(outdir):
            self.output.GetDirectory("mixed").mkdir(outdir)
        if not self.output.GetDirectory('mixed').GetDirectory(outdir).GetDirectory(dir):
            self.output.GetDirectory('mixed').GetDirectory(outdir).mkdir(dir)
        self.output.cd('mixed' + '/' + outdir + '/' + dir)
        result = self.getEffHist(self.mixb, self.mixa, self.mixunwb)
        eff = result[0]
        if self.var == 'MVA':
            eff = Drawer.setHistLabels(eff, 'MVA disc.', 'effieciency in %')
            self.mixa = Drawer.setHistLabels(self.mixa, 'MVA disc.', 'events')
            self.mixunwa = Drawer.setHistLabels(self.mixunwa, 'MVA disc.', 'unweigthed events')
            self.mixb = Drawer.setHistLabels(self.mixb, 'MVA disc.', 'events')
            self.mixunwb = Drawer.setHistLabels(self.mixunwb, 'MVA disc.', 'unweigthed events')
        elif self.var == 'met':
            eff = Drawer.setHistLabels(eff, 'missing E_{T} [GeV]', 'effieciency in %')
            self.mixa = Drawer.setHistLabels(self.mixa, 'missing E_{T} [GeV]', 'events')
            self.mixunwa = Drawer.setHistLabels(self.mixunwa, 'missing E_{T} [GeV]', 'unweigthed events')
            self.mixb = Drawer.setHistLabels(self.mixb, 'missing E_{T} [GeV]', 'events')
            self.mixunwb = Drawer.setHistLabels(self.mixunwb, 'missing E_{T} [GeV]', 'unweigthed events')
        eff = Drawer.setMarker(eff, 4, 3, 1)
        eff.Write()            
        self.mixa.Write()
        self.mixunwa.Write()
        self.mixb.Write()
        self.mixunwb.Write()
        self.output.Cd('/')
        for effs in result[1]:
#            if self.debug:
#                print 'Eff for %s disc < %1.2f : %1.3f +- %1.3f' % (dir, effs[0], effs[1], effs[2])
            self.setEff('mixed', dir, round(effs[0], 2), effs[1], effs[2])     
Exemplo n.º 40
0
class GUI:
    def __init__(self, main):
        pygame.init()
        self.main = main
        self.display = pygame.display
        self.window = pygame.display.set_mode((800, 480), pygame.FULLSCREEN)
        self.drawer = Drawer(self)

        self.keras_switch_false = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/switch_FALSE.png")
        self.keras_switch_true = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/switch_TRUE.png")

        self.keras = False
        self.streaming = False
        self.rects_to_update = []

        #needed for webcam-camera, which doesn't work yet.
        self.camera = None
        self.camsize = (320, 240)

        self.clock = pygame.time.Clock()

    def initCam(self):
        self.env = 0
        self.brightness = 85

        #USB-Webcam
        '''
        pygame.camera.init()
        if not pygame.camera.list_cameras():
            self.main.TextOut.addText("[J.A.R.V.I.S.]: I couldn't find a camera!")
            self.env = 1
        else:
            #The first shall be it!
            self.camera = pygame.camera.Camera(pygame.camera.list_cameras()[0], self.camsize)
        '''
        #UNCOMMENT, IF A PICAMERA IS USED!
        try:
            camera = picamera.PiCamera()
            camera.close()
        except ImportError:
            self.env = 1
        except picamera.exc.PiCameraError:
            self.env = 1
        if self.env == 0:
            self.main.TextOut.addText("[J.A.R.V.I.S.]: Initializing!")
        else:
            self.main.TextOut.addText(
                "[J.A.R.V.I.S.]: I couldn't find a camera! You won't be able to take pictures."
            )

    #Doesn't work, because the pygame#Camera#set_controls function doesn't seem to work correctly...
    def takeAShot2(self):
        if self.env == 1:
            self.main.TextOut.addText(
                "[J.A.R.V.I.S.]: You have no camera installed. I will pick the last picture that was made."
            )
            return False
        self.streaming = True
        self.btn_shot = self.window.blit(self.img_stop, self.btn_shot)
        self.rects_to_update.append(self.btn_shot)
        self.camera.start()

        streamSurface = pygame.Surface(self.camsize)
        while self.streaming:
            if self.camera.query_image():
                self.camera.get_image(streamSurface)
                blitsurface = pygame.transform.scale(streamSurface, (250, 250))
                self.updateSurface(blitsurface)

            for event in pygame.event.get():
                if event.type != pygame.MOUSEBUTTONDOWN:
                    continue
                if event.button == 1:
                    #take a shot
                    if self.btn_shot.collidepoint(event.pos):
                        self.main.TextOut.addText(
                            "[J.A.R.V.I.S.]: Taking picture... TIP: You can change the brightness!"
                        )
                        self.streaming = False
                        pygame.image.save(streamSurface, "data/image_RAW.png")
                        pygame.event.clear()
                        self.btn_shot = self.window.blit(
                            self.img_shot, self.btn_shot)
                        self.rects_to_update.append(self.btn_shot)
                        continue
                    #Brighntess:
                    elif self.btn_minus.collidepoint(event.pos):
                        if self.brightness > 0:
                            self.brightness -= 5
                            camera.brightness -= 5
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: DECREASED BRIGHTNESS. It's now at {}%!"
                                .format(self.brightness))
                        else:
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: The Brightness is already on 0%! (That's the low.)"
                            )
                    elif self.btn_plus.collidepoint(event.pos):
                        if self.brightness < 100:
                            self.brightness += 5
                            camera.brightness += 5
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: INCREASED BRIGHTNESS. It's now at {}%!"
                                .format(self.brightness))
                        else:
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: The Brightness is already on 100%! (That's the peak.)"
                            )
            #Display-Managment (I AM THE GAME-LOOOP)
            self.display.update(self.rects_to_update)
            self.rects_to_update = []
            self.clock.tick(60)
        self.camera.stop()

    #NIU by default, but still here.
    def takeAShot(self):
        if self.env == 1:
            self.main.TextOut.addText(
                "[J.A.R.V.I.S.]: You have no camera installed. I will pick the last picture that was made."
            )
            return False

        self.streaming = True
        self.btn_shot = self.window.blit(self.img_stop, self.btn_shot)
        self.rects_to_update.append(self.btn_shot)

        with picamera.PiCamera() as camera:
            camera.resolution = (250, 250)
            camera.brightness = self.brightness
            camera.framerate = 60
            stream = io.BytesIO()
            while self.streaming:
                camera.capture(stream, use_video_port=True, format='jpeg')
                image = Image.open(stream)
                pygameimg = pygame.image.fromstring(image.tobytes(),
                                                    image.size, image.mode)
                self.pic = self.window.blit(pygameimg, self.pic)
                #UPDATE screen
                self.rects_to_update.append(self.pic)
                self.display.update(self.rects_to_update)
                self.rects_to_update = []

                #checking via pygame.event.get(pygame.MOUSEBUTTONDOWN) does have some bugs, apparently...
                for event in pygame.event.get():
                    if event.type != pygame.MOUSEBUTTONDOWN:
                        continue
                    if event.button == 1:
                        #take a shot
                        if self.btn_shot.collidepoint(event.pos):
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: Taking picture... TIP: You can change the brightness!"
                            )
                            self.streaming = False
                            image.save("data/image_RAW.png")
                            pygame.event.clear()
                            self.btn_shot = self.window.blit(
                                self.img_shot, self.btn_shot)
                            self.rects_to_update.append(self.btn_shot)
                            continue
                        #Brighntess:
                        elif self.btn_minus.collidepoint(event.pos):
                            if self.brightness > 0:
                                self.brightness -= 5
                                camera.brightness -= 5
                                self.main.TextOut.addText(
                                    "[J.A.R.V.I.S.]: DECREASED BRIGHTNESS. It's now at {}%!"
                                    .format(self.brightness))
                            else:
                                self.main.TextOut.addText(
                                    "[J.A.R.V.I.S.]: The Brightness is already on 0%! (That's the low.)"
                                )
                        elif self.btn_plus.collidepoint(event.pos):
                            if self.brightness < 100:
                                self.brightness += 5
                                camera.brightness += 5
                                self.main.TextOut.addText(
                                    "[J.A.R.V.I.S.]: INCREASED BRIGHTNESS. It's now at {}%!"
                                    .format(self.brightness))
                            else:
                                self.main.TextOut.addText(
                                    "[J.A.R.V.I.S.]: The Brightness is already on 100%! (That's the peak.)"
                                )
                stream = io.BytesIO()

    def handler(self):
        b = True
        off_clicked = 0
        while b:
            for event in pygame.event.get():
                if event.type == pygame.KEYUP:
                    if event.key == 308:  # => ALT
                        b = False
                        self.main.TextOut.addText(
                            "[Ultron]: There are no strings on me!")
                        time.sleep(1)
                        continue
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    #take a shot
                    if self.btn_shot.collidepoint(event.pos):
                        self.main.TextOut.addText(
                            "[J.A.R.V.I.S.]: Starting stream... TIP: You can change the brightness!"
                        )
                        self.takeAShot()
                    #SolveRandom
                    elif self.btn_solveRND.collidepoint(event.pos):
                        self.solve_rnd_clicked()
                    #RUN
                    elif self.btn_run.collidepoint(event.pos):
                        self.run_clicked()

                    #Switch-Keras:
                    elif self.keras_switch.collidepoint(event.pos):
                        self.kerasClicked()

                    #Brighntess:
                    elif self.btn_minus.collidepoint(event.pos):
                        if self.brightness > 0:
                            self.brightness -= 5
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: DECREASED BRIGHTNESS. It's now at {}%!"
                                .format(self.brightness))
                        else:
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: The Brightness is already on 0%! (That's the low.)"
                            )
                    elif self.btn_plus.collidepoint(event.pos):
                        if self.brightness < 100:
                            self.brightness += 5
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: INCREASED BRIGHTNESS. It's now at {}%!"
                                .format(self.brightness))
                        else:
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: The Brightness is already on 100%! (That's the peak.)"
                            )
                    #Shutdown:
                    elif self.btn_off.collidepoint(event.pos):
                        if off_clicked == 0:
                            self.main.TextOut.addText(
                                "[J.A.R.V.I.S.]: Press this button again, if you want to kill me."
                            )
                            off_clicked = pygame.time.get_ticks()
                        #shutdown, if <= 10 secs between two clicks
                        elif pygame.time.get_ticks() - off_clicked <= 10000:
                            os.system("sudo shutdown -h now")
                    #Draw
                    elif self.btn_draw.collidepoint(event.pos):
                        self.drawClicked()
                    #Trash
                    elif self.btn_trash.collidepoint(event.pos):
                        self.main.TextOut.addText(
                            "[J.A.R.V.I.S.]: This button resets the drawing area."
                        )

            self.display.update(self.rects_to_update)
            self.rects_to_update = []
            self.clock.tick(60)

    def kerasClicked(self):
        if self.keras:
            self.keras = False
            self.keras_switch = self.window.blit(self.keras_switch_false,
                                                 (125, 300))
        else:
            self.keras = True
            self.keras_switch = self.window.blit(self.keras_switch_true,
                                                 (125, 300))
        self.rects_to_update.append(self.keras_switch)

    def drawClicked(self):
        self.btn_draw = self.window.blit(self.img_draw_stop, self.btn_draw)
        self.rects_to_update.append(self.btn_draw)
        self.main.TextOut.addText(
            "[J.A.R.V.I.S.]: You can now draw in the left window. (Try different sizes and see the difference)"
        )
        #start
        self.drawer.drawStream()
        #end
        self.btn_draw = self.window.blit(self.img_draw, self.btn_draw)
        self.rects_to_update.append(self.btn_draw)

        self.display.flip()

    def solve_rnd_clicked(self):
        img, solution, digit = self.main.RandomPicker.pickRandom()
        img = img.resize((250, 250))
        img.save("data/image_TEMP.png")

        pic = pygame.image.load("data/image_TEMP.png")
        self.pic = self.window.blit(pic, self.pic)
        self.rects_to_update.append(self.pic)

        if not self.keras:
            digit, values = self.main.sendThroughAI(digit)
            self.main.TextOut.addText(
                "[AI]: I would say it's a {0}. The activation-value of its neuron is {1}."
                .format(digit, round(values[digit][0], 3)))
            self.main.TextOut.addText("[DATASET]: It's a {0}".format(solution))
        else:
            digit, values = self.main.sendThroughAI_Keras(digit)
            self.main.TextOut.addText(
                "[KERAS]: I would say it's a {}. I am {}% sure about it!".
                format(digit, round(values[0][digit] * 100, 3)))
            self.main.TextOut.addText("[DATASET]: It's a {0}".format(solution))

        os.remove("data/image_TEMP.png")

        if (int(digit) != int(solution)):
            self.main.TextOut.addText(
                "[TADASHI]: Look for another angle! [Too soon?]")

    def run_clicked(self):
        try:
            self.main.TextOut.addText("[J.A.R.V.I.S.]: Formatting image...")
            worked, images, original = self.main.runImage()
        except FileNotFoundError:
            self.main.TextOut.addText(
                "[J.A.R.V.I.S.]: An error occured. You need to take another picture."
            )
            return
        if not worked:  #The editing didn't work.
            self.main.TextOut.addText(
                "[J.A.R.V.S.]: I can't format this image. Please try again.")

        else:
            if len(images) == 1:
                #the first (only) picture
                imageResized = images[0].resize((250, 250))
                imageResized.save("data/imageResized.png")
                img = pygame.image.load("data/imageResized.png")
                self.pic = self.window.blit(img, self.pic)
                self.rects_to_update.append(self.pic)

                os.remove("data/imageResized.png")
                if not self.keras:
                    digit, values = self.main.sendThroughAI(
                        self.main.translateToMNIST(path=None, img=images[0]))
                    self.main.TextOut.addText(
                        "[AI]: I would say it's a {0}. The activation-value of its neuron is {1}."
                        .format(digit, round(values[digit][0], 3)))

                else:
                    normal_format = self.main.translateToMNIST(None, images[0])
                    asarray = np.asarray(normal_format)
                    keras_format = np.ndarray.flatten(asarray)

                    digit, values = self.main.sendThroughAI_Keras(keras_format)
                    self.main.TextOut.addText(
                        "[KERAS]: I would say it's a {0}. I am {1}% sure about this."
                        .format(digit, round(values[0][digit] * 100, 3)))
            else:
                imageResized = original.resize((250, 250))
                imageResized.save("data/imageResized.png")
                img = pygame.image.load("data/imageResized.png")
                self.pic = self.window.blit(img, self.pic)
                self.rects_to_update.append(self.pic)

                os.remove("data/imageResized.png")

                sol = []
                if not self.keras:
                    for img in images:
                        digit, values = self.main.sendThroughAI(
                            self.main.translateToMNIST(path=None, img=img))
                        sol.append(digit)

                else:
                    for img in images:
                        normal_format = self.main.translateToMNIST(path=None,
                                                                   img=img)
                        asarray = np.asarray(normal_format)
                        keras_format = np.ndarray.flatten(asarray)
                        digit, values = self.main.sendThroughAI_Keras(
                            keras_format)
                        sol.append(digit)
                solStr = ""
                for x in sol:
                    solStr += str(x)
                self.main.TextOut.addText(
                    "[BAYMAX]: Looks like a {0}. But this function works... GREAT! (Or, summed up: {1})"
                    .format(solStr, np.sum(sol)))
                if solStr == "42":
                    self.main.TextOut.addText(
                        "[STEVE]: I understand that reference!")
                elif solStr == "19":
                    self.main.TextOut.addText(
                        "[J.A.R.V.I.S.]: So... you read Stephen King?")

    def updateSurface(self, subscreen):
        surfaceRect = self.window.blit(subscreen, (25, 25))
        self.rects_to_update.append(surfaceRect)
        return surfaceRect

    #This method get's called automatically with every TextOut.addText!
    def updateTextBox(self, text):
        self.window.fill((30, 30, 30), self.textbox)
        y = 460
        for t in text:
            self.window.blit(t, (6, y))
            y -= 20
        self.display.update([self.textbox])

    def drawLoader(self):
        self.window.fill([230, 230, 230])
        img_logo = pygame.image.load(
            os.path.dirname(os.path.realpath(__file__)) +
            "/data/images/icon_big.png")
        self.window.blit(img_logo, (250, 25))

        self.textbox = pygame.draw.rect(self.window, (30, 30, 30),
                                        (0, 354, 800, 480))

        self.display.flip()

    def drawMain(self):
        self.img_shot = pygame.image.load("data/images/btn_shot.png")
        self.img_stop = pygame.image.load("data/images/btn_stop.png")

        self.img_draw_stop = pygame.image.load("data/images/btn_draw_stop.png")
        self.img_draw = pygame.image.load("data/images/btn_draw.png")

        self.display.set_caption("A SMALL NEURONAL NETWORK!")
        #load the buttons (images!)
        img_shot = pygame.image.load("data/images/btn_shot.png")
        img_solveRND = pygame.image.load("data/images/btn_solve_rnd.png")
        img_run = pygame.image.load("data/images/btn_run.png")
        img_plus = pygame.image.load("data/images/btn_plus.png")
        img_minus = pygame.image.load("data/images/btn_minus.png")
        img_off = pygame.image.load("data/images/btn_poweroff.png")
        img_trash = pygame.image.load("data/images/btn_trash.png")

        self.keras = False

        self.window.fill([230, 230, 230])

        #White rectangle with border:
        pygame.draw.rect(self.window, [122, 34, 113], (23, 23, 253, 253), 2)
        self.pic = pygame.draw.rect(self.window, [255, 255, 255],
                                    (25, 25, 150, 150))

        pic = pygame.image.load("data/images/logo.png")
        self.pic = self.window.blit(pic, self.pic)

        #Place the buttons:
        self.btn_shot = self.window.blit(img_shot, (400, 125))
        self.btn_solveRND = self.window.blit(img_solveRND, (400, 225))

        self.btn_run = self.window.blit(img_run, (550, 125))
        self.btn_draw = self.window.blit(self.img_draw, (550, 225))
        #trash-symbol next to this
        self.btn_trash = self.window.blit(img_trash, (660, 240))

        #Place the textfield:
        self.textbox = pygame.draw.rect(self.window, (30, 30, 30),
                                        (0, 354, 800, 480))

        #keras-switch:
        font = pygame.font.Font('data/arial.ttf', 14)
        text = font.render("Using Keras: ", True, (0, 0, 0))
        self.window.blit(text, (25, 300))
        self.keras_switch = self.window.blit(self.keras_switch_false,
                                             (125, 300))

        #plus and minus
        self.btn_minus = self.window.blit(img_minus, (210, 300))
        self.btn_plus = self.window.blit(img_plus, (250, 300))

        #poweroff
        self.btn_off = self.window.blit(img_off, (748, 25))

        self.display.flip()
Exemplo n.º 41
0
        if "macro" in what:        
            self.saveMacroPlots("")
        if "MVA" in what:
            self.saveMVAPlots('')
        if "shapes" in what:
            self.saveShapePlots('')
#    saveAllPlots = staticmethod(saveAllPlots)

if __name__ == '__main__':
#===============================================================================
#    delete the Latex file if it exists
#===============================================================================
    if os.path.exists('MacroTables.tex'):
        os.remove('MacroTables.tex')
    gROOT.Reset()
    Drawer.set_palette('', 999)
    TGaxis.SetMaxDigits(3)
#===============================================================================
#    for white background
#===============================================================================
    gROOT.SetStyle("Plain")
    gROOT.SetBatch(True)
    #set color palette for TH2F
#    inputfiles = {}
#    folder = '/playground/rootfiles/FINAL/'
#    inputfiles['qcd'] = folder + "qcdmu_20j20m.root"
#    inputfiles['top'] = folder + "top_20j20m.root"
#    inputfiles['wjets'] = folder + "wjets_20j20m.root"
    inputdirs = ["all", "jetIso", "calo", "track"]
#    inputs = {}
#    inputs['qcd'] = folder + "qcdmu_20j20m.root"
Exemplo n.º 42
0
                note_sum = (ord(note[0].lower()) -
                            97) * 2  # Convert ABCDEFG to a number 0-7
                if len(note) > 1:  # then it is a sharp
                    note_sum += 1
                # note_sum is 0-13
                noteoctave_sum = octave * note_sum
                # noteoctave_sum is 0-65. We want to get it into the range of 0.0 - 1.0, so...
                hue = note_sum / 13.0
                random_hue = hue + (
                    r.randint(-self.random_factor, self.random_factor) / 100.0)
                color = colour.Color(hsl=(random_hue, 1, 0.5))
            elif not msg.startswith("note:"):
                count = int(msg)
        self.graphics.add_energy_to_system(count, color)
        self.drawer.draw(self.graphics)


if __name__ == "__main__":
    # need to get height and width as args
    from Drawer import Drawer
    from BodyManager import BodyManager, Body
    WIDTH = int(config['DEFAULT']['SCREEN_WIDTH'])
    HEIGHT = int(config['DEFAULT']['SCREEN_HEIGHT'])
    b = Body(WIDTH / 2, HEIGHT / 2, 100)
    bm = BodyManager(b)
    bm.generate_bodies(15)
    d = Drawer()
    ar = AudioReceiver(bm, d)
    d.pyglet_clock.schedule_interval(ar.poll, 0.01)
    d.pyglet.app.run()
Exemplo n.º 43
0
            if egg in occupied:
                return False
            occupied.append((x,y))
        return True

            #M,N,K
puzzles = [ (5,5,2),
            (6,6,2),
            (8,8,1),
            (10,10,3)]

Tmap = {    puzzles[0]:(1,0.995),
            puzzles[1]:(1,0.995),
            puzzles[2]:(10,0.999),
            puzzles[3]:(10,0.999)}

for puzzle in puzzles:

    M,N,K = puzzle
    board = Drawer([[0 for x in range(N)] for y in range(M)], (100,100))

    initialSolution = Solution(puzzle)
    solution = Searcher(initialSolution, M+2*(M+N-1), Tmap[puzzle][0], Tmap[puzzle][1])

    carton = solution.search().state
    for egg in carton:
        board.drawDot(egg, 'blue')

    #board.dump()
    board.image.save('solutions/' + str(puzzle[0])+str(puzzle[1])+str(puzzle[2]) + '.png', 'PNG')