Пример #1
0
    def __init__(self):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(SystemdHandler())
        self.logger.info("Starting up. Alarm status is normal.")

        self.alarm_status = "normal"
        self.alarm_last_fire = datetime.datetime(1970, 1, 1, 0, 0, 0)
        self.display = Display(self.logger)
        self.alarm_manager = AlarmManager(self.logger)
        self.time_keeper = TimeKeeper(self.logger)
        self.weather_manager = WeatherManager(self.logger)
Пример #2
0
    def __init__(self):
        pygame.init()
        pygame.mixer.init()

        self.score = 0
        self.timeKeeper = TimeKeeper(self)

        self.player = None
        self.playerGroup = None
        self.candies = pygame.sprite.Group()
        self.toothbrushes = pygame.sprite.Group()

        self.score = 0

        self.screen = None
        self.clock = None

        self.handlersToRemove = []

        self.pressedKeys = None
        self.screen = pygame.display.set_mode(SCREEN_SIZE, pygame.DOUBLEBUF, 32)
        self.clock = pygame.time.Clock()

        self.player = Molarr(self)
        self.allCandies = [pygame.image.load(img).convert_alpha() for img in CANDY_FILES]

        impactSound = pygame.mixer.Sound(SOUND_IMPACT_FILE)
        ductTapeSound = pygame.mixer.Sound(SOUND_DUCT_TAPE_FILE)
        toothbrushSound = pygame.mixer.Sound(SOUND_TOOTHBRUSH)

        self.sounds = {
            "impact": impactSound,
            "ductTape": ductTapeSound,
            "toothbrush": toothbrushSound
        }

        self.baseMolarrImage = pygame.image.load(MOLARR_IMG).convert_alpha()
        self.baseHammerImage = pygame.image.load(HAMMER_IMG).convert_alpha()

        self.loadEnemyTimer = 0
        self.loadToothbrushTimer = 0

        self.scenes = {
            "opening": OpeningCutScene,
            "mainMenu": MainMenuScene,
            "playGame": GameScene,
            "gameOver": GameOverScene
        }

        self.currentScene = self.scenes["opening"](self)
Пример #3
0
def getStationData():
    return {
        'LAB': 6,
        'XRAY': 12,
        'LAB_VISIT_1': 10,
        'BREAKFAST': 20
    }


def initializeStation():
    stationWithTimeMap = getStationData()

    stationQueue = {}
    for station in stationWithTimeMap:
        stationQueue[station] = Queue()
    return stationQueue, stationWithTimeMap


if __name__ == "__main__":
    # dataset = getDataSet()
    # filteredData = filterDataSet(dataset)

    filteredData = getDataSetTest()
    stationQueueInit, stationTimeMap = initializeStation()
    stationQueue, patientList = InputParser().processPatientList(stationQueueInit,
                                                                 filteredData)
    patientManager = PatientManager(stationQueue, patientList, stationTimeMap)
    timeKeeper = TimeKeeper(patientManager)

    predictTime = timeKeeper.predictTime()
Пример #4
0
def iterall(files_list, match_thresh=1.5):

    timekeeper = TimeKeeper()
    timekeeper.time_now('start', True)

    detector = cv2.SIFT()
    all_descriptors = {}
    descriptor_distances = {}
    desc_strings = {}
    weighted_strings = {}

    desc_man = ImageDescriptorManager(match_threshold=match_thresh, detector=detector)

    wrote_sift = 0
    for img_idx in files_list:
        img_path = files_list[img_idx]
        # print str(img_idx) + ' : ' + img_path

        # if os.path.isfile(img_path + '.sift'):
        #     print 'Found sift file : ' + img_path + '.sift'
        #     # print '.',
        #     # with open(img_path + '.sift', 'rb') as f:
        #     #     keypoints, descriptors = unpickle_keypoints( cPickle.load(f) )
        # else:
        #     print 'Creating sift : ' + img_path + '.sift'
        #     img = cv2.imread(img_path)
        #     img_gray = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY )
        #     keypoints, descriptors = detector.detectAndCompute(img_gray, None)
        #
        #     key_desc_temp = pickle_keypoints(keypoints, descriptors)
        #
        #     with open(img_path + '.sift', 'wb') as f:
        #         cPickle.dump(key_desc_temp, f, protocol=cPickle.HIGHEST_PROTOCOL)
        #     del keypoints
        #     del descriptors
        #     wrote_sift += 1
        already_existed = touch_descriptor(img_path, detector)
        if not already_existed:
            wrote_sift += 1

                # all_descriptors[idx] = descriptors
    print 'Had to create ' + str(wrote_sift) + ' .sift files.'

    timekeeper.time_now('After check SIFT')

    for filea in files_list:
        img_desc = ImageDescriptor(filea, files_list[filea])
        desc_man.add_descriptor(img_desc)

    time_delta = timekeeper.time_now('After create ImageDescriptors', True)
    print '\nAvg ' + str(float(time_delta) / len(files_list)) + ' secs per img load'

    for man_img_idx in desc_man.image_descriptors:
        man_img = desc_man.image_descriptors[man_img_idx]
        print '***\n'
        print 'img sig : ' + man_img.get_image_signature()
        print man_img.get_weighted_signature()
        print 'Image ' + man_img.img_path + ' is most similar to ' + files_list[list(man_img.get_sorted_weights())[0]]
        for i in files_list:
            if files_list[i] == man_img.img_path:
                print str(man_img.img_path) + ' : ' + str(i)

        for j in files_list:
            if files_list[j] == files_list[list(man_img.get_sorted_weights())[0]]:
                print 'Similar to image : ' + str(j)

        print '\n'

    print timekeeper.time_now('After similarities', True)



    # for file_a in files_list:
    #     print '\nComparing file ' + str(file_a) + ' to : '
    #
    #     descriptor_orders = {}
    #     weighted_orders = {}
    #     with open(files_list[file_a] + '.sift', 'rb') as fa:
    #         keypoints_a, descriptors_a = unpickle_keypoints( cPickle.load(fa) )
    #
    #     for file_b in files_list:
    #         print file_b,
    #         if file_a != file_b:
    #             with open(files_list[file_b] + '.sift', 'rb') as fb:
    #                 keypoints_b, descriptors_b = unpickle_keypoints( cPickle.load(fb) )
    #
    #             matches_size = find_matches(str(file_a) + ',' + str(file_b),
    #                                         descriptors_a,
    #                                         descriptors_b,
    #                                         match_thresh)
    #             descriptor_orders[str(file_b)] = matches_size
    #
    #             weighted_orders[str(file_b)] = (str(file_b) + '=' + str(matches_size)) + ':'
    #             # weighted_orders[str(file_b)] = (str(file_b) * matches_size)
    #
    #             descriptor_distances[str(file_a) + ':' + str(file_b)] = matches_size
    #
    #     print '\nImage ' + files_list[file_a] + ' is most similar to ' \
    #           + files_list[int(list(sorted(descriptor_orders, key=descriptor_orders.get, reverse=True))[0])] + '\n'
    #
    #     desc_arr = list(sorted(descriptor_orders, key=descriptor_orders.get, reverse=True))
    #
    #     item_string = ''
    #     for item in desc_arr:
    #         item_string += str(weighted_orders[item])
    #     weighted_strings[file_a] = item_string

        # desc_strings[file_a] = ' '.join(desc_arr)
        # print 'Array of img_idx for file ' + str(file_a) + ', closest match first : \n' + desc_strings[file_a]

    # print '\n****\nArray of distances between images : \n' + str(descriptor_distances)




    # for ws in weighted_strings:
    #     print str(ws) + ' : ' + weighted_strings[ws]

    # print '\n****\nAll images description strings : \n' + str(desc_strings)
    # for s in desc_strings:
    #     for st in desc_strings:
    #         dist = nltk.metrics.edit_distance(
    #             desc_strings[s],
    #             desc_strings[st])
    #         if (len(files_list) * 0.3) < dist < (len(files_list) * 0.8):
    #             print '\n****\nClosest image pair signatures within 0.8 of each other:'
    #             print str(s) + ' : ' + desc_strings[s]
    #             print str(st) + ' : ' + desc_strings[st]
    #             print 'Deviation of sigs (lower is better) : ' + str(dist)
    #             print files_list[s]
    #             print files_list[st]
    #             print '\n'

    print '\n****\nAll images description strings : \n' + str(desc_strings)
    sigs = desc_man.get_all_image_signatures()
    for s in sigs:
        for st in sigs:
            dist = nltk.metrics.edit_distance(
                sigs[s],
                sigs[st])
            print sigs[s] + '\n' + sigs[st] + '\n' + str(dist)
            if (len(files_list) * 0.3) < dist < (len(files_list) * 0.8):
                print '\n****\nClosest image pair signatures within 0.8 of each other:'
                print str(s) + ' : ' + sigs[s]
                print str(st) + ' : ' + sigs[st]
                print 'Deviation of sigs (lower is better) : ' + str(dist)
                print files_list[s]
                print files_list[st]
                print '\n'

    print timekeeper.time_now('After description strings', True)

    # new_desc = ImageDescriptor(len(files_list), './portrait/11040852736_83cc5c2155_z.jpg')
    # desc_man.quick_init(new_desc)
    # print '\n' + new_desc.get_image_signature()
    # print new_desc.get_weighted_signature()
    timekeeper.time_now('Finish', True)
Пример #5
0
# python doesn't have enums
tags = {
    'READY': 1,
    'DONE': 2,
    'EXIT': 3,
    'START': 4,
    'START_2': 5,
    'DONE_2': 6,
    'WAIT': 7
}

status = MPI.Status()   # get MPI status object

if rank == 0:

    timekeeper = TimeKeeper()
    timekeeper.time_now('start', True)

    session = DatabaseAccessor().session

    files = []
    tasks = []
    # Master process executes code below

    # Find files
    # For the moment skip any clever filtering of existing descriptor existance
    # TODO come back and add this in

    if DO_TASKS['find_files']:

        if DO_FILTER_DESCRIPTORS:
Пример #6
0
            weights = [1, 2, 4, 8, 16, 32, 64, 128]
            res = 0
            for a in range(0, len(values)):
                res += weights[a] * values[a]

            transformed_img.itemset((x,y), res)

    return transformed_img
    # print x


def np_hist_to_cv(np_histogram_output):
    counts, bin_edges = np_histogram_output
    return counts.ravel().astype('float32')

tk = TimeKeeper()
tk.time_now('start')

filename = 'animals/11175682543_4db70a7f6f_z.jpg'

img = cv2.imread(filename, 0)
transformed_img = cv2.imread(filename, 0)

tk.time_now('read img')

transformed_img = calculate_lbp(img, transformed_img)

tk.time_now('lpb')

# cv2.imshow('image', img)
# cv2.imshow('thresholded image', transformed_img)
Пример #7
0
class TimeMachine:
    def __init__(self):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(SystemdHandler())
        self.logger.info("Starting up. Alarm status is normal.")

        self.alarm_status = "normal"
        self.alarm_last_fire = datetime.datetime(1970, 1, 1, 0, 0, 0)
        self.display = Display(self.logger)
        self.alarm_manager = AlarmManager(self.logger)
        self.time_keeper = TimeKeeper(self.logger)
        self.weather_manager = WeatherManager(self.logger)

    def second_ticked(self, hour, minute, second):
        if self.alarm_status != "normal":
            self.logger.info("{:02}:{:02}:{:02} - Alarm Status {}".format(
                hour, minute, second, self.alarm_status))

    def minute_ticked(self, hour, minute, second):
        self.display.set_new_time(hour, minute, second)
        self.display.set_appropriate_brightness(hour)

    def button_pressed(self):
        if self.alarm_status == "normal":
            self.logger.info("Button pressed during normal status.")
            next_alarm = self.alarm_manager.get_next_alarm()
            if type(next_alarm) is not None:
                self.display.set_new_time(next_alarm.hour, next_alarm.minute,
                                          next_alarm.second)
                sleep(5)
                # reset back to normal
                self.display.set_new_time(self.time_keeper.hour,
                                          self.time_keeper.minute,
                                          self.time_keeper.second)
        else:
            self.logger.info("Button pressed while alarm is sounding.")
            self.alarm_status = "normal"
            self.stop_music()
            self.logger.info("Alarm turned off.")

    def button_double_pressed(self):
        self.logger.info("Button double tapped.")
        current_temp = self.weather_manager.get_temp_from_file()
        self.display.set_temp(current_temp)
        sleep(5)
        # reset back to normal
        self.display.set_new_time(self.time_keeper.hour,
                                  self.time_keeper.minute,
                                  self.time_keeper.second)

    def alarm_fired(self, alarm):
        if self.alarm_last_fire is None or self.alarm_last_fire <= datetime.datetime.now(
        ) + datetime.timedelta(minutes=-1):
            self.logger.info("Alarm fired!")
            self.alarm_last_fire = datetime.datetime.now()
            self.alarm_status = "alarm_fired"
            self.music_thread = threading.Thread(target=self.start_music)
            self.music_thread.start()

    def start_music(self):
        subprocess.call("shell/play_music.sh", shell=True)

    def stop_music(self):
        subprocess.call("shell/stop_music.sh", shell=True)

    def run(self):
        button_manager = ButtonManager(self.logger)

        # Add any listeners
        self.time_keeper.on_tick(self.second_ticked)
        self.time_keeper.on_tick(self.alarm_manager.check_new_time)
        self.time_keeper.on_minute_tick(self.minute_ticked)

        button_manager.on_button_press(self.button_pressed)
        button_manager.on_button_double_press(self.button_double_pressed)

        self.alarm_manager.on_alarm_fired(self.alarm_fired)

        # Start processes

        time_thread = threading.Thread(target=self.time_keeper.run_time)
        time_thread.start()

        button_thread = threading.Thread(target=button_manager.watch)
        button_thread.start()

        alarm_caching_thread = threading.Thread(
            target=self.alarm_manager.cache_alarms_to_file)
        alarm_caching_thread.start()

        weather_caching_thread = threading.Thread(
            target=self.weather_manager.cache_weather_to_file)
        weather_caching_thread.start()
Пример #8
0
class Engine(object):

    def __init__(self):
        pygame.init()
        pygame.mixer.init()

        self.score = 0
        self.timeKeeper = TimeKeeper(self)

        self.player = None
        self.playerGroup = None
        self.candies = pygame.sprite.Group()
        self.toothbrushes = pygame.sprite.Group()

        self.score = 0

        self.screen = None
        self.clock = None

        self.handlersToRemove = []

        self.pressedKeys = None
        self.screen = pygame.display.set_mode(SCREEN_SIZE, pygame.DOUBLEBUF, 32)
        self.clock = pygame.time.Clock()

        self.player = Molarr(self)
        self.allCandies = [pygame.image.load(img).convert_alpha() for img in CANDY_FILES]

        impactSound = pygame.mixer.Sound(SOUND_IMPACT_FILE)
        ductTapeSound = pygame.mixer.Sound(SOUND_DUCT_TAPE_FILE)
        toothbrushSound = pygame.mixer.Sound(SOUND_TOOTHBRUSH)

        self.sounds = {
            "impact": impactSound,
            "ductTape": ductTapeSound,
            "toothbrush": toothbrushSound
        }

        self.baseMolarrImage = pygame.image.load(MOLARR_IMG).convert_alpha()
        self.baseHammerImage = pygame.image.load(HAMMER_IMG).convert_alpha()

        self.loadEnemyTimer = 0
        self.loadToothbrushTimer = 0

        self.scenes = {
            "opening": OpeningCutScene,
            "mainMenu": MainMenuScene,
            "playGame": GameScene,
            "gameOver": GameOverScene
        }

        self.currentScene = self.scenes["opening"](self)

    def resetGame(self):
        self.score = 0
        self.timeKeeper.resetTimer()
        self.player.health = 100
        self.changeScene("playGame")

    def changeScene(self, sceneName):
        self.handlersToRemove.append(self.currentScene.handleEvents)

        self.currentScene = self.scenes[sceneName](self)

    def playSound(self, soundName):
        sound = self.sounds[soundName]
        sound.stop()
        sound.play()

    def loadEnemies(self):

        numCandies = self.timeKeeper.numCandies()

        while len(self.candies) < numCandies:
            self.candies.add(Candy(self))

    def loadToothbrushes(self):

        numBrushes = self.timeKeeper.numToothbrushes()

        while len(self.toothbrushes) < numBrushes:
            self.toothbrushes.add(Toothbrush(self))

    def startGame(self):

        while True:
            self.clock.tick(MAX_FPS)

            self.timeKeeper.timer += self.clock.get_time()

            self.pressedKeys = pygame.key.get_pressed()

            self.screen.blit(BACKGROUND, (0, 0))

            events = pygame.event.get()

            for event in events:
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit(0)

            self.currentScene.handleEvents(events)

            self.currentScene.update()

            self.currentScene.render()

            pygame.display.update()

    # Blarg...too lazy to create a Util class for just one function...
    def msToHMS(self, n):
        n //= 1000

        if n < 60:
            return str(int(round(n, 0)))
        elif n < 3600:
            numMin = n // 60
            numLeftOverSec = n - 60 * numMin
            secStr = str(numLeftOverSec)
            if numLeftOverSec < 10:
                secStr = "0" + secStr
            return str(numMin) + ":" + secStr
        else:
            # If you can make it through an entire hour, I salute you...
            numHours = n // 3600
            numLeftOverMinutes = n - numHours // 60
            numLeftOverSec = n - 60 * numLeftOverMinutes

            minStr = str(numLeftOverMinutes)
            if numLeftOverMinutes < 10:
                minStr = "0" + minStr

            secStr = str(numLeftOverSec)
            if numLeftOverSec < 10:
                secStr = "0" + secStr

            return str(numHours) + ":" + minStr + ":" + secStr