Ejemplo n.º 1
0
    def create_filter_message_from_descriptor(descriptor):
        filter = ros_vision.msg.Filter()
        filter.name = descriptor.get_name()
        filter.type = descriptor.get_name()
        filter.description = descriptor.description

        for i in descriptor.get_inputs():
            d = ros_vision.msg.IODescriptor()
            name = i.get_name()
            d.name = name
            d.type = str(i.get_io_type().get_ros_type()._type)
            d.topic = IOManager().format_topic_name(filter.name + "/" + name)
            filter.inputs.append(d)

        for o in descriptor.get_outputs():
            d = ros_vision.msg.IODescriptor()
            name = o.get_name()
            d.name = name
            d.type = str(o.get_io_type().get_ros_type()._type)
            d.topic = IOManager().format_topic_name(filter.name + "/" + name)
            filter.outputs.append(d)

        for p in descriptor.get_parameters():
            parameter = ros_vision.msg.Parameter()
            parameter.name = p.get_name()
            parameter.description = p.get_description()
            parameter.type = p.get_type().__name__
            parameter.default = str(p.get_default_value())
            parameter.min = str(p.get_min_value())
            parameter.max = str(p.get_max_value())
            filter.parameters.append(parameter)

        return filter
Ejemplo n.º 2
0
 def __init__(self, deck: Deck = None, player: BlackJackPlayer = None):
     if deck is None:
         deck = Deck(shuffled=True, n_decks=8)
     if player is None:
         player = BlackJackPlayer()
     self.__deck = deck
     self._dealer = BlackJackDealer()
     self.player = player
     self._io_manager = IOManager()
Ejemplo n.º 3
0
    def create_filter_message_from_filter(f):
        filter = MessageFactory.create_filter_message_from_descriptor(
            f.descriptor)
        filter.name = f.name

        for idx, i in enumerate(f.descriptor.get_inputs()):
            filter.inputs[idx].topic = IOManager().format_topic_name(
                f.get_io_name(filter.inputs[idx].name))

        for idx, o in enumerate(f.descriptor.get_outputs()):
            filter.outputs[idx].topic = IOManager().format_topic_name(
                f.get_io_name(filter.outputs[idx].name))

        return filter
Ejemplo n.º 4
0
    def __init__(self, verbose=False):

        self.verbose = verbose

        capture = cv2.VideoCapture(0)
        capture.set(cv2.CAP_PROP_FRAME_WIDTH, 960)
        capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 500)
        capture.set(cv2.CAP_PROP_BUFFERSIZE, 3)
        capture.set(cv2.CAP_PROP_FPS, 60)
        self.__capture_manager = CaptureManager(capture, 10)

        self.__io_manager = IOManager(IO_PINS, verbose)

        self.__image_analyzer = ImageAnalyzer(self.__capture_manager.current_frame_color, verbose)

        self.__coordinates_translator = CoordinatesTranslator(self.__image_analyzer, CONVEYOR_WIDTH)

        self.__packager = Packager(TRAY_SIZE, PADDING, verbose)

        self.__item_movement_motor = Motor(MOTOR_PINS['item_movement_control'],
                                           MOTOR_PINS['item_movement_direction'],
                                           ITEM_MOVEMENT_CONVEYOR_STEP_INTERVAL,
                                           ITEM_MOVEMENT_CONVEYOR_STEP_LIMIT,
                                           MOTOR_PINS['item_movement_limit_switch'],
                                           0.15,
                                           10,
                                           0.15,
                                           10,
                                           self.__io_manager,
                                           verbose)

        self.__io_manager.protect_pin(MOTOR_PINS['item_movement_control'])
        self.__io_manager.protect_pin(MOTOR_PINS['item_movement_direction'])
        self.__io_manager.protect_pin(MOTOR_PINS['item_movement_limit_switch'])

        self.__tray_movement_motor = Motor(MOTOR_PINS['tray_movement_control'],
                                           MOTOR_PINS['tray_movement_direction'],
                                           TRAY_MOVEMENT_CONVEYOR_STEP_INTERVAL,
                                           None,
                                           MOTOR_PINS['tray_movement_limit_switch'],
                                           0.15,
                                           10,
                                           0.15,
                                           10,
                                           self.__io_manager,
                                           verbose)

        self.__io_manager.protect_pin(MOTOR_PINS['tray_movement_control'])
        self.__io_manager.protect_pin(MOTOR_PINS['tray_movement_direction'])
        self.__io_manager.protect_pin(MOTOR_PINS['tray_movement_limit_switch'])

	self.current_loop_done = 1
	self.__calibrate_motors()
Ejemplo n.º 5
0
def main():
    point_file_manager = IOManager('sample_input_4_4.tsv')

    points = point_file_manager.read_points_from_file()
    dimension = point_file_manager.get_element_per_line()

    n_dim_points = Point(points)
    n_dim_points.dimension = dimension

    calculator = SimpleCalculator()
    min_dist_pairs = calculator.get_minimum_distance_pair(
        n_dim_points.points, n_dim_points.dimension)

    pair_values = n_dim_points.get_point_pairs(min_dist_pairs)

    result = point_file_manager.get_formatted_result(min_dist_pairs,
                                                     pair_values)
    point_file_manager.write_result_to_file(result)
    print result
Ejemplo n.º 6
0
class Game:
    # noinspection PyShadowingNames
    def __init__(self, deck: Deck = None, player: BlackJackPlayer = None):
        if deck is None:
            deck = Deck(shuffled=True, n_decks=8)
        if player is None:
            player = BlackJackPlayer()
        self.__deck = deck
        self._dealer = BlackJackDealer()
        self.player = player
        self._io_manager = IOManager()

    def play_round(self):
        self._dealer.hand = self.deal_new_hand()
        self.player.hands = [self.deal_new_hand()]
        self._get_bet_from_user()
        for hand in self.player.hands:
            self.play_hand(hand)
        if not (self.player.all_bust() or self.player.all_blackjack()):
            self._dealer.play_turn()
        self._io_manager.show_dealer_hand_to_user(self._dealer.hand, upcard_only=False)
        self._process_winnings(self.player.hands, self._dealer.hand)

    def play_hand(self, hand: BlackJackHand):
        choice = 0
        while choice != 2 and hand.sum < 21:
            self._io_manager.print_turn_status(self.player, hand, self._dealer)
            if hand.is_blackjack():
                return
            self._io_manager.show_player_options(hand)
            choice = self._io_manager.get_player_choice()
            if choice == 1:
                self._dealer.deal_to(hand)
            if choice == 4:
                return self.double_down(hand)
            if choice == 3:
                self.split_hand(hand)
        self._io_manager.print_end_turn_message(hand)

    def deal_new_hand(self):
        new_hand = BlackJackHand()
        self._dealer.deal_to(new_hand, 2)
        return new_hand

    def _get_bet_from_user(self):
        bet = self._io_manager.get_player_bet()
        self.player.bank -= bet
        self.player.hands[0].bet_size = bet

    def split_hand(self, hand: BlackJackHand):
        new_hand = BlackJackHand()
        self.player.bank -= hand.bet_size
        new_hand.bet_size = hand.bet_size
        hand.transfer_last_card_to(new_hand)
        self.player.hands.append(new_hand)
        self._dealer.deal_to(hand)
        self._dealer.deal_to(new_hand)

    def double_down(self, hand: BlackJackHand):
        self.player.bank -= hand.bet_size
        hand.bet_size *= 2
        self._dealer.deal_to(hand)
        return

    def is_winning(self, player_hand: BlackJackHand):
        return player_hand.sum <= 21 and (player_hand.sum < self._dealer.hand.sum or self._dealer.hand.sum > 21)

    def _process_winnings(self, player_hands: typing.List[BlackJackHand], dealer_hand: BlackJackHand):
        for hand in player_hands:
            if hand.is_blackjack():
                winnings_sum = hand.bet_size * 2.5
                winnings_status = WinStatus.BLACKJACK
            elif hand.sum <= 21 and (dealer_hand.sum < hand.sum or dealer_hand.sum > 21):
                winnings_sum = hand.bet_size * 2
                winnings_status = WinStatus.WIN
            elif dealer_hand.sum == hand.sum <= 21:
                winnings_sum = hand.bet_size
                winnings_status = WinStatus.PUSH
            else:
                winnings_sum = 0
                winnings_status = WinStatus.BUST if hand.sum > 21 else WinStatus.LOSS
            self._io_manager.print_winnings_to_player(winnings_sum, winnings_status.value)
            self.player.bank += winnings_sum
Ejemplo n.º 7
0
""" Implementa a abstração de gerenciamento de filas, ou escalonador de processos, do pseudo-SO."""
from process_manager import Process
from io_manager import IOManager

io = IOManager()


class QueueManager:
    """ O Gerenciador de filas é a entidade responsável por alocar
        os processos prontos na CPU da forma mais eficiente.
        O algoritmo usado é o de múltiplas filas de prioridade,
        onde a fila mais prioritária é não-preemptiva e as outras são preemptivas.
    """
    def __init__(self):
        self.queues = [[], [], [],
                       []]  # inicializa as 4 filas, ordenadas por prioridade
        self.blocked = []  # inicializa lista de processos bloqueados

    def len(self):
        """ Retorna o tamanho somado de todas as filas de execução."""
        return sum([len(q) for q in self.queues])

    def schedule(self, proc: Process):
        """ Escala um processo para ser executado na CPU, após sua criação.
            Coloca o processo na fila correspondente à sua prioridade.
            Caso a prioridade seja maior que 3, ele entrará na fila 3.
        """
        # Testa se consegue alocar os recursos do processo. Se sim, insere na fila de execução
        if io.open(proc):
            # Se o limite máximo de processos foi atingido, não insere
            if self.len() >= 1000:
Ejemplo n.º 8
0
class Depowdering:
    def __init__(self, verbose=False):

        self.verbose = verbose

        capture = cv2.VideoCapture(0)
        capture.set(cv2.CAP_PROP_FRAME_WIDTH, 960)
        capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 500)
        capture.set(cv2.CAP_PROP_BUFFERSIZE, 3)
        capture.set(cv2.CAP_PROP_FPS, 60)
        self.__capture_manager = CaptureManager(capture, 10)

        self.__io_manager = IOManager(IO_PINS, verbose)

        self.__image_analyzer = ImageAnalyzer(self.__capture_manager.current_frame_color, verbose)

        self.__coordinates_translator = CoordinatesTranslator(self.__image_analyzer, CONVEYOR_WIDTH)

        self.__packager = Packager(TRAY_SIZE, PADDING, verbose)

        self.__item_movement_motor = Motor(MOTOR_PINS['item_movement_control'],
                                           MOTOR_PINS['item_movement_direction'],
                                           ITEM_MOVEMENT_CONVEYOR_STEP_INTERVAL,
                                           ITEM_MOVEMENT_CONVEYOR_STEP_LIMIT,
                                           MOTOR_PINS['item_movement_limit_switch'],
                                           0.15,
                                           10,
                                           0.15,
                                           10,
                                           self.__io_manager,
                                           verbose)

        self.__io_manager.protect_pin(MOTOR_PINS['item_movement_control'])
        self.__io_manager.protect_pin(MOTOR_PINS['item_movement_direction'])
        self.__io_manager.protect_pin(MOTOR_PINS['item_movement_limit_switch'])

        self.__tray_movement_motor = Motor(MOTOR_PINS['tray_movement_control'],
                                           MOTOR_PINS['tray_movement_direction'],
                                           TRAY_MOVEMENT_CONVEYOR_STEP_INTERVAL,
                                           None,
                                           MOTOR_PINS['tray_movement_limit_switch'],
                                           0.15,
                                           10,
                                           0.15,
                                           10,
                                           self.__io_manager,
                                           verbose)

        self.__io_manager.protect_pin(MOTOR_PINS['tray_movement_control'])
        self.__io_manager.protect_pin(MOTOR_PINS['tray_movement_direction'])
        self.__io_manager.protect_pin(MOTOR_PINS['tray_movement_limit_switch'])

	self.current_loop_done = 1
	self.__calibrate_motors()

    def main_cycle(self):
        self.__wait_for_closed_door()
        if not self.current_loop_done:
            self.__io_manager.output('lock_door', IOManager.HIGH)  # Lock door
            item_list = self.__generate_item_list()
            if not item_list:
                self.__log('No item detected.')
                return
            translated_item_list = self.__translate_item_list(item_list)
            if not self.__packager.next_item_will_fit_row(translated_item_list):
                self.__log('Starting new row')
                self.__push_item(translated_item_list)
                if not self.__packager.next_row_will_fit_tray():
                    self.__log('Requesting new tray')
                    self.__load_new_tray()
            else:
                self.__make_room_for_next_item(translated_item_list)
            self.__io_manager.output('lock_door', IOManager.LOW)  # Unlock door
            self.current_loop_done = 1

    def __wait_for_closed_door(self):
        while not self.__io_manager.input('door_is_closed'):  # Wait while door is open
            self.current_loop_done = 0
            time.sleep(0.1)
        return

    def __generate_item_list(self):
        new_frame = self.__capture_manager.current_frame
        self.__image_analyzer.update(new_frame)
        return self.__image_analyzer.analyze_image()

    def __translate_item_list(self, item_list):
        return [self.__coordinates_translator.translate_values(item) for item in item_list]

    def __make_room_for_next_item(self, translated_item_list):
        target_position = self.__packager.item_size[0] + PADDING[0]
        current_position = translated_item_list[0][0]
        horizontal_distance_to_move = target_position - current_position
        self.__item_movement_motor.move(horizontal_distance_to_move * ITEM_MOVEMENT_CONVEYOR_STEPS_PER_CENTIMETER, True)

    def __push_item(self, translated_item_list):
        target_position = BUFFER_WIDTH
        current_position = translated_item_list[0][0]
        horizontal_distance_to_move = target_position - current_position
        vertical_distance_to_move = self.__packager.item_size[1] + PADDING[1]
        self.__item_movement_motor.move_to(horizontal_distance_to_move * ITEM_MOVEMENT_CONVEYOR_STEPS_PER_CENTIMETER, True)
        self.__io_manager.output('push_items', IOManager.HIGH)  # Request piston push from PLC
        time.sleep(TRAY_MOVEMENT_CONVEYOR_DELAY_DURING_PUSH)
        self.__io_manager.output('push_items', IOManager.LOW)
        self.__tray_movement_motor.move(vertical_distance_to_move * TRAY_MOVEMENT_CONVEYOR_STEPS_PER_CENTIMETER)
        while not self.__io_manager.input('push_completed'):  # Wait while piston operates
            time.sleep(0.1)
        self.__item_movement_motor.move_to(ITEM_MOVEMENT_CONVEYOR_REST_POSITION, True)
        return

    def __load_new_tray(self):
        self.__tray_movement_motor.loop_back_home()
        self.__io_manager.output('load_new_tray', IOManager.HIGH)  # Request a new tray from the loader
        time.sleep(0.5)
        self.__io_manager.output('load_new_tray', IOManager.LOW)
        while not self.__io_manager.input('load_completed'):  # Wait while the
            time.sleep(0.1)
        self.__tray_movement_motor.move(STEPS_FROM_LOADER_TO_ITEM_CONVEYOR)
        return

    def __calibrate_motors(self):
        self.__item_movement_motor.find_home()
        self.__tray_movement_motor.find_home(True)

    def __log(self, message):
        if self.verbose:
            print(message)
Ejemplo n.º 9
0
 def set_io_manager(self):
     self.io_manager = IOManager(self.argv, self.vocab_word, self.vocab_label)
Ejemplo n.º 10
0
class ModelAPI(object):

    def __init__(self, argv):
        self.argv = argv
        self.emb = None
        self.vocab_word = None
        self.vocab_label = None

        self.model = None
        self.decoder = None
        self.io_manager = None

        self.train = None
        self.predict = None

    def compile(self, vocab_word, vocab_label, init_emb=None):
        say('\n\nBuilding a model API...\n')
        self.emb = init_emb
        self.vocab_word = vocab_word
        self.vocab_label = vocab_label
        self.set_model()
        self.set_decoder()
        self.set_io_manager()

    def set_model(self):
        self.model = Model(argv=self.argv,
                           emb=self.emb,
                           n_vocab=self.vocab_word.size(),
                           n_labels=self.vocab_label.size())
        self.compile_model()

    def compile_model(self):
        self.model.compile(self._get_input_tensor_variables())

    @staticmethod
    def _get_input_tensor_variables():
        # x_w: 1D: batch, 2D: n_words, 3D: 5 + window; word id
        # x_p: 1D: batch, 2D: n_words; posit id
        # y: 1D: batch, 2D: n_words; label id
        return T.itensor3('x_w'), T.imatrix('x_p'), T.imatrix('y')

    def set_decoder(self):
        self.decoder = Decoder(self.argv)

    def set_io_manager(self):
        self.io_manager = IOManager(self.argv, self.vocab_word, self.vocab_label)

    def set_train_f(self):
        model = self.model
        self.train = theano.function(inputs=model.inputs,
                                     outputs=[model.y_pred, model.y_gold, model.nll],
                                     updates=model.update
                                     )

    def set_predict_f(self):
        model = self.model
        outputs = self._select_outputs(self.argv, model)
        self.predict = theano.function(inputs=model.x,
                                       outputs=outputs,
                                       )

    @staticmethod
    def _select_outputs(argv, model):
        outputs = [model.y_prob]
        if argv.output == 'pretrain':
            outputs.append(model.hidden_reps)
        return outputs

    def train_one_epoch(self, batch):
        train_eval = Eval(self.vocab_label)
        start = time.time()
        batch.shuffle_batches()

        for index, batch in enumerate(batch.batches):
            if index != 0 and index % 1000 == 0:
                print index,
                sys.stdout.flush()

            result_sys, result_gold, nll = self.train(*batch)
            assert not math.isnan(nll), 'NLL is NAN: Index: %d' % index

            train_eval.update_results(result_sys, result_gold)
            train_eval.nll += nll

        print '\tTime: %f' % (time.time() - start)
        train_eval.show_results()

    def predict_one_epoch(self, samples):
        results = Results(self.argv)
        start = time.time()

        for index, sample in enumerate(samples):
            if index != 0 and index % 1000 == 0:
                print index,
                sys.stdout.flush()

            if sample.n_prds == 0:
                model_outputs = []
                decoder_outputs = []
            else:
                model_outputs = self.predict(*self.create_input_variables(sample))
                decoder_outputs = self.decode(prob_lists=model_outputs[0], prd_indices=sample.prd_indices)

            results.add([sample, model_outputs, decoder_outputs])

        print '\tTime: %f' % (time.time() - start)
        return results

    @staticmethod
    def create_input_variables(sample):
        return sample.x

    def decode(self, prob_lists, prd_indices):
        assert len(prob_lists) == len(prd_indices)
        return self.decoder.decode(prob_lists, prd_indices)

    def eval_one_epoch(self, batch_y_hat, samples):
        pred_eval = Eval(self.vocab_label)
        assert len(batch_y_hat) == len(samples)
        for result, sample in zip(batch_y_hat, samples):
            if len(result) == 0:
                continue
            pred_eval.update_results(y_hat_batch=result, y_batch=sample.y)
        pred_eval.show_results()
        return pred_eval.all_f1

    def save_model(self):
        self.io_manager.save_model(self.model)

    def save_pas_results(self, results, samples):
        self.io_manager.save_pas_results(results, samples)

    def save_outputs(self, results):
        self.io_manager.save_outputs(results)

    def load_params(self, fn):
        self.model = self.io_manager.load_params(self.model, fn)