Пример #1
0
 def __init__(self, context):
     self._context = context
     self._writer = Writer(context.tag)
     self._prepare = Prepare(context)
     self._event = Event(context)
     self._postprocessing = PostProcessing(context, self._writer)
     self._system_monitor = Sysmon(
         self._context.args.tick_duration,
         self._context.args.amount_of_ticks,
     )
Пример #2
0
class Runner:
    """ Prepare and execute the simulation and post process the data"""
    def __init__(self, context):
        self._context = context
        self._writer = Writer(context.tag)
        self._prepare = Prepare(context)
        self._event = Event(context)
        self._postprocessing = PostProcessing(context, self._writer)
        self._system_monitor = Sysmon(
            self._context.args.tick_duration,
            self._context.args.amount_of_ticks,
        )

    def run(self):

        try:
            self._prepare.create_folder()
            StepTimes().add(
                'preparation_start'
            )  # TODO writes to old directory because does not exist yet
            Info().status = "preperation_start"
            self._prepare.execute()
            logging.info('End of Preparation')

            #StepTimes().add('preparation_start')
            StepTimes().add('simulation_start')
            logging.info('Start of simulation')
            self._system_monitor.start()
            self._event.execute(
                timeout=25)  # TODO check if timeout works as expected
            self._system_monitor.exit()
            logging.info('End of simulation')

            StepTimes().add('postprocessing_start')
            self._postprocessing.execute()
            StepTimes().add('postprocessing_end')

        except Exception as exce:
            Info().status = f"failed with {exce}"
            self._postprocessing.clean_up_docker_safe()
            raise exce
Пример #3
0
    def _build(self, ai):
        print '========== Found AI to be build: <', ai['user'].encode('utf-8'), ',', ai['idOfUser'], '>, upload date: ', ai['uploadDate']
        p = Prepare(ai).Run()

        ID = str(ai['_id'])
        if p['status'] == 'failure':
            status = 'Unavailable'
            info = p['error']
        else:
            status = 'Available'
            info = p['info']
        self._uploadAI(ID, status, info, path.join(const.AI_SAVE_DIRECTORY, 'ai_' + ID))
        print '      Done!'
Пример #4
0
def move():

    winner_player = Prepare.verify_rule()
    next_player, hand, palette = Prepare.next_player(Helper.players,
                                                     winner_player)

    if winner_player != next_player:

        print('Następny jest gracz ' + str(next_player))
        print("Na ręce:")
        print(hand)
        print("W palecie")
        print(palette)
        option = input("Co zagrywasz? \n"
                       "1. Kartę na tło \n"
                       "2. Kartę na paletę \n"
                       "3. Kartę na paletę i tło \n"
                       "4. Poddaje się \n")

        if option == "1":
            result = Prepare.add_card(hand, palette, False, False)
        elif option == "2":
            result = Prepare.add_card(hand, palette, True, False)
        elif option == "3":
            result = Prepare.add_card(hand, palette, True, True)
        elif option == "4":
            print("Przegrałeś")
            result = False
        else:
            print("Wrong number")
            result = False

        if result:
            move()
        else:
            print("Nadal przegrywasz")

    else:
        print("Nadal przegrywasz")
Пример #5
0
def hello():
    print("Witajcie w Red7 \n ************")
    players = input("Proszę podać ilu będzie graczy ")
    players = int(players)

    Helper.players = players

    # if 4 >= int(players) >= 2:

    # player1 = input("Podaj imię pierwszego gracza: ")
    # player2 = input("Podaj imię drugiego gracza: ")
    #
    # if int(players) == 3:
    #     player3 = input("Podaj imię trzeciego gracza: ")
    # elif int(players) == 4:
    #     player3 = input("Podaj imię trzeciego gracza: ")
    #     player4 = input("Podaj imię czwartego gracza: ")

    if Prepare.generate_start_cards(players):
        move()
Пример #6
0
def run(unknown_arguments=False):
    for file in [config.ticks_csv, config.network_csv, config.nodes_csv]:
        utils.check_for_file(file)

    parser = _create_parser()
    if unknown_arguments:
        args = parser.parse_known_args(sys.argv[2:])[0]
    else:
        args = parser.parse_args(sys.argv[2:])
    logging.info("Parsed arguments in {}: {}".format(__name__, args))
    utils.update_args(args)

    _check_skip_ticks(args.skip_ticks)

    context = Context()

    logging.info(config.log_line_run_start + context.run_name)

    tag = context.args.tag
    if hasattr(context.args, 'tag_appendix'):
        tag += context.args.tag_appendix
    writer = Writer(tag)
    runner = Runner(context, writer)

    prepare = Prepare(context)
    runner._prepare = prepare

    postprocessing = PostProcessing(context, writer)
    runner._postprocessing = postprocessing

    event = Event(context)
    runner._event = event

    start = time.time()

    runner.run()

    logging.info("The duration of the run was {} seconds".format(
        str(time.time() - start)))
Пример #7
0
    def setUp(self):
        self.context = Mock()
        self.prepare = Prepare(self.context)

        bitcoin.SelectParams('regtest')
Пример #8
0
class TestPrepare(TestCase):
    def setUp(self):
        self.context = Mock()
        self.prepare = Prepare(self.context)

        bitcoin.SelectParams('regtest')

    @patch('node.wait_until_height_reached', lambda node, height: None)
    @patch('utils.sleep', lambda time: None)
    @patch('prepare._calc_number_of_tx_chains',
           lambda txs_per_tick, block_per_tick, amount_of_nodes: 5)
    def test_warmup_block_generation(self):
        node_0 = MagicMock()
        node_1 = MagicMock()
        nodes = [node_0, node_1]
        self.context.nodes.values.return_value = nodes

        self.prepare._pool = MagicMock()
        self.prepare._give_nodes_spendable_coins()

        self.assertEqual(node_0.execute_rpc.call_count, 2)
        self.assertEqual(node_1.execute_rpc.call_count, 2)

    @patch('os.path.exists')
    @patch('os.path.islink')
    @patch('os.makedirs')
    @patch('bash.check_output')
    @patch('builtins.open', new_callable=mock_open)
    def test_prepare_simulation_dir(self, m_open, m_check_output, m_makedirs,
                                    m_islink, m_exists):
        m_exists.return_value = False
        self.prepare._pool = MagicMock()

        self.prepare._prepare_simulation_dir()

        self.assertEqual(m_makedirs.call_count, 3)
        self.assertEqual(m_check_output.call_count, 10)

    @patch('bash.check_output')
    def test_remove_old_containers_if_exists(self, m_check_output):
        m_check_output.return_value = ['container1', 'container2']

        prepare._remove_old_containers_if_exists()

        self.assertEqual(m_check_output.call_count, 2)

    @patch('bash.check_output')
    def test_remove_old_containers_if_exists_no_old_containers(
            self, m_check_output):
        m_check_output.return_value = []

        prepare._remove_old_containers_if_exists()

        self.assertEqual(m_check_output.call_count, 1)

    @patch('utils.sleep', lambda t: None)
    @patch('bash.call_silent')
    @patch('bash.check_output')
    def test_recreate_network(self, m_check_output, m_call_silent):
        m_call_silent.return_value = 0

        prepare._recreate_network()

        self.assertEqual(m_check_output.call_count, 2)
        self.assertEqual(m_call_silent.call_count, 1)

    @patch('utils.sleep', lambda t: None)
    @patch('bash.call_silent')
    @patch('bash.check_output')
    def test_recreate_network_no_network(self, m_check_output, m_call_silent):
        m_call_silent.return_value = -1

        prepare._recreate_network()

        self.assertEqual(m_check_output.call_count, 1)

    def test_calc_number_of_tx_chains(self):
        config.max_in_mempool_ancestors = 25
        amount = prepare._calc_number_of_tx_chains(2, 1 / 600, 10)

        self.assertEqual(amount, 51)
Пример #9
0
def sendPrepare():
    global bNum
    bNum = BallotNum(bNum.getDepth(), bNum.getSeqNum() + 1, bNum.getPid())
    prepMsg = Prepare('prepare', bNum, MY_PORT)
    print("Sending prepare messages.")
    broadcastMsg(pickle.dumps(prepMsg))
Пример #10
0
def gwas(start_snp, end_snp, individuals, ants_number, update_times, factor, threshold):
    """
     individuals: sum of cases and control.
     factor:  0<factor<1 user-adjustable distribution.if factor is near 1,snps with high scores are only slightly
              more likely to be selected.
     threshold <-> P-Value: 26.12<->0.001;20.09<->0.01;15.51<->.0.05
    """
    snps_number = end_snp - start_snp + 1
    dict_pair = Prepare.dict_pair(start_snp, end_snp)
    print('dict_pair done')

    n = 0
    for order in range(1, 101):
        dict_prob = Prepare.dict_prob1(start_snp, end_snp + 1)
        print('dict_prob done')
        label, data_set = Prepare.data_matrix(order, individuals, snps_number)
        dict_weka = Prepare.load_weka_ranking(order)
        snps_sequence = Prepare.snps_sequence1(start_snp, end_snp)
        snps_scores = [0] * snps_number
        # Rank dict on weight,return a list of tuples
        list_weka = sorted(dict_weka.items(), key=lambda weka: weka[1], reverse=True)
        rank = Prepare.scaling_rank(factor, snps_number)
        for snp_weight_tuple, new_weight in zip(list_weka, rank):
            # allocate scaling rank weight to corresponding snp
            snps_scores[snp_weight_tuple[0] - start_snp] = new_weight
        selected_pairs = {}
        for x in range(update_times):
            list_k1_threshold = []  # 存储chi2_statistics > 阈值的pair在dict_prob[first_snp]中的索引位置
            list_k2_threshold = []  # 存储chi2_statistics > 阈值的pair在dict_prob[second_snp]中的索引位置
            list_chi2_statistics = []  # 存储chi2_statistics > 阈值的pair的卡方值,在update的时候使用
            list_k1 = []  # 存储chi2_statistics < 阈值的pair在dict_prob[first_snp]中的索引位置
            list_k2 = []  # 存储chi2_statistics < 阈值的pair在dict_prob[second_snp]中的索引位置
            list_first_snp_threshold = []  # 存储chi2_statistics > 阈值的first_snp
            list_second_snp_threshold = []  # 存储chi2_statistics > 阈值的second_snp
            list_first_snp = []  # 存储chi2_statistics < 阈值的first_snp
            list_second_snp = []  # 存储chi2_statistics < 阈值的second_snp
            for y in range(ants_number):
                first_snp = Ant.ant_first_snp(snps_sequence, snps_scores)
                second_snp = Ant.ant_second_snp(first_snp, dict_pair, dict_prob)
                # print(first_snp, second_snp)
                if second_snp > first_snp:
                    k1 = second_snp - start_snp - 1
                    k2 = first_snp - start_snp
                else:
                    k1 = second_snp - start_snp
                    k2 = first_snp - start_snp - 1
                case_row, control_row = ChiSquareTest.chi2_table(data_set, label, first_snp, second_snp, individuals)
                sum_colum, A2_NcNr, chi2_statistics = ChiSquareTest.chi2_test(case_row, control_row, individuals)
                if chi2_statistics > threshold:
                    list_k1_threshold.append(k1)
                    list_k2_threshold.append(k2)
                    list_chi2_statistics.append(chi2_statistics)
                    list_first_snp_threshold.append(first_snp)
                    list_second_snp_threshold.append(second_snp)
                else:
                    list_k1.append(k1)
                    list_k2.append(k2)
                    list_first_snp.append(first_snp)
                    list_second_snp.append(second_snp)
            # 更新条件概率和snps_scores.
            # 除以 10 的目的是将卡方值转换到和weight同样的量级.snps_score_original[x]引入expert information
            for m, i, j in zip(list_first_snp_threshold, list_k1_threshold, list_chi2_statistics):
                dict_prob[m][i] += (int(j) / 10)
            for m, i, j in zip(list_second_snp_threshold, list_k2_threshold, list_chi2_statistics):
                dict_prob[m][i] += (int(j) / 10)
            for m, i in zip(list_first_snp, list_k1):
                dict_prob[m][i] = 0
            for m, i in zip(list_second_snp, list_k2):
                dict_prob[m][i] = 0
            for first, second, i in zip(list_first_snp_threshold, list_second_snp_threshold, list_k1_threshold):
                selected_pairs[(first, second)] = dict_prob[first][i]
            print(selected_pairs)
        result = sorted(selected_pairs.items(), key=lambda x: x[1], reverse=True)
        for x in result[0:20]:
            if x[0] == (999, 988) or x[0] == (998, 999):
                n += 1
                break
        f = open('result_conProb-H0.1-{ants}_{updates}-fac={factor}.txt'.format(
            ants=ants_number, updates=update_times, factor=factor), 'a')
        f.writelines('\n')
        f.writelines(str(x[0]) + '\t' + str(x[1]) + '\n' for x in result[0:20])
        f.writelines('----------------------------------')
        f.close()
    f = open('result_conProb-H0.1-{ants}_{updates}-fac={factor}.txt'.format(
        ants=ants_number, updates=update_times, factor=factor), 'a')
    f.writelines('\nThe pow of this ACO algorithm is ' + str(n) + '%')
    f.close()