def sample_sentences(section, n=1000):
    pair_list = array(list(alignment_pairs(section=section)))

    pair_len = len(pair_list)

    plagiarized_sample = []
    non_plagiarized_sample = []

    # draw plagiarized sentences
    for pair in pair_list[randint(0, high=pair_len, size=n)]:
        gold = pair.gold_alignments()

        if len(gold) > 0:
            susp_draw, src_draw = gold[randint(0, high=len(gold))]

            plagiarized_sample.append((pair.susp_fn, pair.src_fn, susp_draw, src_draw))
        else:
            logging.warn("Empty gold alignment for %s - %s" % (pair.susp_fn, pair.src_fn))

    # draw random non-plagiarized sentence pairs
    for pair in pair_list[randint(0, high=pair_len, size=n)]:
        gold = pair.gold_alignments()
        gold_susp_indexes = [x[0] for x in gold]
        gold_src_indexes = [x[1] for x in gold]

        susp_draw = choice([x for x in xrange(len(pair.susp_doc)) if x not in gold_susp_indexes])
        src_draw = choice([x for x in xrange(len(pair.src_doc)) if x not in gold_src_indexes])

        non_plagiarized_sample.append((pair.susp_fn, pair.src_fn, susp_draw, src_draw))

    return plagiarized_sample, non_plagiarized_sample
Exemplo n.º 2
0
    def reset(self):
        """Randomly throw the agent to a non-goal state

        """
        next_state = self.GOAL_STATE
        while next_state == self.GOAL_STATE:
            next_state = (randint(0, self.DIMS[0]), randint(0, self.DIMS[1]))
        self.state = next_state
def generate_new_data(t):
    returns = []
    for c, task_type in enumerate(data_series):
        last_val = 0 if t==0 else source.data[task_type][-1] - ( 0 if c == 0 else source.data[data_series[c-1]][-1])
        new_value = max(0, last_val + randint(-2,2))
        returns.append(new_value + (0 if len(returns) == 0 else returns[-1]))
    #datetime.datetime.fromtimestamp(time.time() + t*1000) doesn't work (axis seems to require something else, the timestamps are o.k.)
    return [t, returns[-1]] + returns
Exemplo n.º 4
0
def podskupovi(d, n, lambda1):
    list = []
    for i in range(d-n):
        random = nextPoisson(lambda1)
        print "\n\nPoasonov: ", random
        for j in range(random):
            list.insert(j, randint(1,100))
        for item in list:
            print " ", item,
        print '\n'
Exemplo n.º 5
0
 def update(self, im, values):
     index = 9
     if values[index] > 60:
         self.points.append(Point(randint(im.size[0]), 0, 10))
         
         
     for point in self.points:
         if point.isAlive() == False:
             self.points.remove(point)
         else:
             point.draw(values, im)
     
     return im
Exemplo n.º 6
0
def get_rdm_un_normalized_vector(dataflow, max_num=10):
    """Compute the smallest vector for un-normalized the graph.

    ------
    Return the the vector of coefficient for un-normalize the graph.
    """
    if not dataflow.is_normalized:
        return

    coef = {}
    for arc in dataflow.get_arc_list():
        random_num = randint(1, max_num)
        coef[arc] = Fraction(numerator=random_num, denominator=dataflow.get_gcd(arc))
    return coef
Exemplo n.º 7
0
    def gibbs_sampling(self, n_topics, alpha, n_iterations):
        seed(0)

        # randomly assign topics to words
        self.word_topic_map = {w: randint(0, n_topics-1) for w in self.vocab}
        n_dt = [{t: 0 for t in range(n_topics)} for _ in range(len(self.corpus))]
        n_tw = [{w: 0 for w in self.vocab} for _ in range(n_topics)]

        for d_index in range(len(self.corpus)):
            d = self.corpus[d_index]
            for w in d:
                t = self.word_topic_map[w]
                n_dt[d_index][t] += 1
                n_tw[t][w] += 1

        for i in range(n_iterations):
            print("Iteration %d/%d (%f%%)..." % (i, n_iterations, 100 * i / float(n_iterations)))
            for d_index in range(len(self.corpus)):
                print("Document %d/%d (%f%%)..." % (d_index, len(self.corpus), 100 * d_index / float(len(self.corpus))))
                d = self.corpus[d_index]
                for w in d:
                    # i. remove current word from counts
                    old_topic = self.word_topic_map[w]
                    # TODO
                    if n_dt[d_index][old_topic] == 0:
                        print("oops dt", d_index, old_topic)
                    else:
                        n_dt[d_index][old_topic] -= 1
                    n_tw[old_topic][w] -= 1

                    # ii. estimate probabilities using 5.6, 5.7
                    word_topic_probs = []
                    for t in range(n_topics):
                        p_t_d = float(n_dt[d_index][t] + alpha) / (sum(n_dt[d_index].values()) + n_topics * alpha)
                        p_w_t = float(n_tw[t][w] + alpha) / (sum(n_tw[t].values()) + len(self.vocab) * alpha)
                        word_topic_probs.append(p_w_t * p_t_d)

                    # iii. assign w to a topic randomly
                    word_topic_probs = [float(p) / sum(word_topic_probs) for p in word_topic_probs]
                    self.word_topic_map[w] = choice(range(n_topics), p=word_topic_probs)

                    # iv. increment counts accordingly
                    topic = self.word_topic_map[w]
                    n_tw[topic][w] += 1
                    n_dt[d_index][topic] += 1
Exemplo n.º 8
0
def random_Butter(n=(5, 10),
                  Wc=(0.1, 0.8),
                  W1=(0.1, 0.5),
                  W2=(0.5, 0.8),
                  form=None,
                  onlyEven=True,
                  seed=None):
    """
	Generate a n-th order Butterworh filters
	Parameters
		----------
		- n: (int) The order of the filter
		- Wc: used if btype is 'lowpass' or 'highpass'
			Wc is a tuple (min,max) for the cut frequency
		- W1 and W2: used if btype is ‘bandpass’, ‘bandstop’
			W1 and W2 are tuple (min,max) for the two start/stop frequencies
		- form: (string) {None, ‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Gives the type of filter. If None, the type is randomized
		- onlyEven: if True, only even order filter are generated
		- seed: if not None, indicates the seed toi use for the random part (in order to be reproductible, the seed is stored in the name of the filter)
	"""
    # change the seed if asked
    if seed:
        numpy_seed(seed)
    # choose a form if asked
    if form is None:
        form = choice(("lowpass", "highpass", "bandpass", "bandstop"))
    # choose Wn
    if form in ("bandpass", "bandstop"):
        # choose 2 frequencies
        if W2[1] <= W1[0]:
            raise ValueError("iter_random_Butter: W1 should be lower than W2")
        Wn1 = (W1[1] - W1[0]) * random_sample() + W1[0]
        Wn2 = (W2[1] - W2[0]) * random_sample() + W2[0]
        while Wn2 <= Wn1:
            Wn2 = (W2[1] - W2[0]) * random_sample() + W2[0]
        W = [Wn1, Wn2]
    else:
        # choose 1 frequency
        W = (Wc[1] - Wc[0]) * random_sample() + Wc[0]
    # choose order
    order = randint(*n)
    if onlyEven and order % 2 == 0:
        order += 1

    return Butter(order, W, form, name='Butterworth-random-%d' % seed)
Exemplo n.º 9
0
    def handle_ack_timeout(self):
        assert self.state == Transmitter.State.WAIT_ACK
        self.num_retries += 1
        self.cw = min(2 * self.cw, self.sim.params.cwmax)
        self.backoff = randint(0, self.cw)

        self.backoff_vector.append(self.backoff)

        self.sim.logger.debug(
            f'backoff={self.backoff}; CW={self.cw}, NR={self.num_retries})',
            src=self)

        if self.channel.is_busy:
            self.state = Transmitter.State.BUSY
        else:
            self.state = Transmitter.State.BACKOFF
            self.timeout = self.sim.schedule(self.sim.params.difs,
                                             self.handle_backoff_timeout)
Exemplo n.º 10
0
def sample_draw(count, size):
    """
    Return random sample (without replacement) of count integers between 0 and size.
    """
    
    if count == 0: return []
    elif count > size: raise AssertionError('count can not be > size')
    elif count < 0: raise AssertionError('count cannot be negative')
    if size < 1: raise AssertionError('size must be > 1')
    
    deck = range(size)
    for index in range(count):
        current = deck[index]
        swap_index = randint(index, size)
        deck[index] = deck[swap_index]
        deck[swap_index] = current
        
    return deck[:count]
Exemplo n.º 11
0
def random_TF(n=(5, 10), Wc=(0.1, 0.8), W1=(0.1, 0.5), W2=(0.5, 0.8)):
    """Generate one n-th order stable butterworth filter ((num, den) of the transfer function)"""
    # choose a form
    form = choice(['lowpass', 'highpass', 'bandpass', 'bandstop'])
    # choose Wn
    if form in ("bandpass", "bandstop"):
        # choose 2 frequencies such that Wn2<=Wn1
        Wn1 = (W1[1] - W1[0]) * random_sample() + W1[0]
        Wn2 = (W2[1] - W2[0]) * random_sample() + W2[0]
        while Wn2 <= Wn1:
            Wn2 = (W2[1] - W2[0]) * random_sample() + W2[0]
        W = [Wn1, Wn2]
    else:
        # choose 1 frequency
        W = (Wc[1] - Wc[0]) * random_sample() + Wc[0]
    # choose order
    order = randint(*n)
    num, den = butter(order, W, form)
    return num, den
Exemplo n.º 12
0
def test_collision_domain_saturated_network():
    num_clients = randint(1, 10)

    from pycsmaca.simulations.shortcuts import \
        collision_domain_saturated_network
    sr = collision_domain_saturated_network(
        num_clients=num_clients,
        payload_size=PAYLOAD_SIZE,
        ack_size=ACK_SIZE,
        mac_header_size=MAC_HEADER,
        phy_header_size=PHY_HEADER,
        preamble=PREAMBLE,
        bitrate=BITRATE,
        difs=DIFS,
        sifs=SIFS,
        slot=SLOT,
        cwmin=CWMIN,
        cwmax=CWMAX,
        connection_radius=CONNECTION_RADIUS,
        speed_of_light=SPEED_OF_LIGHT,
        sim_time_limit=SIM_TIME_LIMIT,
        log_level=Logger.Level.WARNING)

    for i in range(num_clients):
        cli = sr.clients[i]

        assert cli.service_time.mean() > 0
        assert cli.num_retries.mean() >= 0
        assert cli.queue_size.timeavg() == 0  # stations don't relay packets!
        assert cli.busy.timeavg() >= 0
        assert cli.num_packets_sent > 0

    srv = sr.server

    assert srv.arrival_intervals.mean() > 0
    if num_clients > 1:
        assert srv.num_rx_collided > 0
    else:
        assert srv.num_rx_collided == 0
    assert srv.num_rx_success > 0
    assert_allclose(srv.num_packets_received,
                    sum(cli.num_packets_sent for cli in sr.clients),
                    rtol=0.25)
 def test_randint_117(self):
     # GH 14189
     random.seed(0)
     expected = np.array(
         [
             2357136044,
             2546248239,
             3071714933,
             3626093760,
             2588848963,
             3684848379,
             2340255427,
             3638918503,
             1819583497,
             2678185683,
         ],
         dtype="int64",
     )
     actual = random.randint(2**32, size=10)
     assert_array_equal(actual, expected)
Exemplo n.º 14
0
def generate(num_seq, seq_length, alphabet, m_word_length, m_word_param, background_param):
	magic_thetas = [dirichlet(m_word_param) for j in range(m_word_length)]
	background_theta = dirichlet(background_param)
	sequences = []
	starts = []
	for k in range(num_seq):
		background_onehots = [multinomial(1, background_theta) for x in range(seq_length - m_word_length)]
		background = [alphabet[t] for t in [i.tolist().index(1) for i in background_onehots]]
		#background = [alphabet[t].lower() for t in [i.tolist().index(1) for i in background_onehots]]
		magic_onehots = [multinomial(1, theta) for theta in magic_thetas]
		magic_word = [alphabet[j] for j in [i.tolist().index(1) for i in magic_onehots]]
		start_pos = randint(seq_length - m_word_length)
		background[start_pos : start_pos] = magic_word
		sequences.append(background)
		starts.append(start_pos)
	#print starts
	ans = []
	ans.append(starts)
	ans.append(sequences)
	return ans
Exemplo n.º 15
0
def sample_where(data, count=None):
    """
    Get random sample of True elements from a multi-dimensional bool array, returning
    indices ala numpy.where(). Sampling is without replacement.

    If count is None, return random element's indices.
    If 0 < count < 1.0, return count fraction of True elements' indices.
    """

    true_indices = numpy.where(data)
    if count is None:
        random_slice = randint(len(true_indices[0]))
        return tuple([d[random_slice] for d in true_indices])
    elif count == 0: return None
    elif count < 1:
        count = int(count * numpy.sum(data))
        
    indicesT = []
    for random_slice in sample_draw(count, len(true_indices[0])):
        indicesT.append([d[random_slice] for d in true_indices])
    return tuple([d for d in numpy.array(indicesT).T])
Exemplo n.º 16
0
def iter_random_Elliptic(number,
                         n=(5, 10),
                         rp=(0, 10),
                         rs=(30, 80),
                         Wc=(0.1, 0.8),
                         W1=(0.1, 0.5),
                         W2=(0.5, 0.8),
                         form=None,
                         seeded=True,
                         quant=None):
    """
	Generate some n-th order Butterworh filters
	Parameters
		----------
		- number: number of Butterworth filters generated
		- n: (int) The order of the filter
		- Wc: used if btype is 'lowpass' or 'highpass'
			Wc is a tuple (min,max) for the cut frequency
		- W1 and W2: used if btype is ‘bandpass’, ‘bandstop’
			W1 and W2 are tuple (min,max) for the two start/stop frequencies
		- form: (string) {None, ‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Gives the type of filter. If None, the type is randomized
		- quant: quantized the coefficients with quant bits (None by default -> no quantization)
		- seeded: (boolean) indicates if the random  should be done with a particular seed or not (in order to be reproductible, the seed is stored in the name of the filter)

	"""
    seeds = [
        randint(0, 1e9) if seeded else None for _ in range(number)
    ]  # generate a particular seed for each random dSS, or None (if seeded is set to False)
    for s in seeds:
        yield random_Elliptic(n=n,
                              rp=rp,
                              rs=rs,
                              Wc=Wc,
                              W1=W1,
                              W2=W2,
                              form=form,
                              seed=s,
                              quant=quant)
def update(t):

    # new_series = []
    if t == 3: add_series("superseries")
    if t == 6: add_series("merge")
    if t == 6: add_series("project")
	#
    # for series in new_series:
    #     add_series(series)

    # generates new data
    new_data = generate_new_data(t)

    numMessages.text = infoBoxFormat("Log Messages", t)
    print("new_data: {0}".format(new_data))

    rollover = None #if interval.value == 0 else interval.value

    # Update the data by sending only the new data points
    if(randint(0,10)>-1):
        source.stream(pack_new_data(new_data), rollover)
    else:
        source.stream(pack_new_data(None), rollover)
Exemplo n.º 18
0
    def handle_message(self, packet, connection=None, sender=None):
        if connection.name == 'queue':
            assert self.state == Transmitter.State.IDLE

            self.cw = self.sim.params.cwmin
            self.backoff = randint(0, self.cw)
            self.num_retries = 1

            #
            # Create the PDU:
            #
            self.pdu = DataPDU(packet,
                               seqn=self.__seqn,
                               header_size=self.phy_header_size +
                               self.mac_header_size,
                               sender_address=self.address,
                               receiver_address=packet.receiver_address)
            self.__seqn += 1

            self.__start_service_time = self.sim.stime
            self.backoff_vector.append(self.backoff)
            self.__busy_trace.record(self.sim.stime, 1)

            self.sim.logger.debug(
                f'backoff={self.backoff}; CW={self.cw},NR={self.num_retries}',
                src=self)

            if self.channel.is_busy:
                self.state = Transmitter.State.BUSY
            else:
                self.state = Transmitter.State.BACKOFF
                self.timeout = self.sim.schedule(self.sim.params.difs,
                                                 self.handle_backoff_timeout)
        else:
            raise RuntimeError(
                f'unexpected handle_message({packet}, connection={connection}, '
                f'sender={sender}) call')
Exemplo n.º 19
0
def iter_random_dSSmp(number, stable=True, n=(5, 10), p=(1, 5), q=(1, 5), pRepeat=0.01, pReal=0.5, pBCmask=0.90, pDmask=0.8, pDzero=0.5):
	"""
	Generate some n-th order random (stable or not) state-spaces, with q inputs and p outputs
	copy/Adapted from control-python library (thanks guys): https://sourceforge.net/projects/python-control/
	possibly already adpated from Mathworks or Octave

	Parameters:
		- number: number of state-space to generate
		- stable: indicate if the state-spaces are stable or not
		- n: tuple (mini,maxi) number of states (default:  random between 5 and 10)
		- p: number of outputs (default: 1)
		- q: number of inputs (default: 1)

		- pRepeat: Probability of repeating a previous root (default: 0.01)
		- pReal: Probability of choosing a real root (default: 0.5). Note that when choosing a complex root, the conjugate gets chosen as well. So the expected proportion of real roots is pReal / (pReal + 2 * (1 - pReal))
		- pBCmask: Probability that an element in B or C will not be masked out (default: 0.9)
		- pDmask: Probability that an element in D will not be masked out (default: 0.8)
		- pDzero: Probability that D = 0 (default: 0.5)

	Returns:
		- returns a generator of dSS objects (to use in a for loop for example)

	"""
	for i in range(number):
		if stable:
			yield random_dSSmp(randint(*n), randint(*p), randint(*q), pRepeat, pReal, pBCmask, pDmask, pDzero)
		else:
			nn = randint(*n)
			pp = randint(*p)
			qq = randint(*q)
			A = numpy.matrix(rand(nn, nn))
			B = numpy.matrix(rand(nn, qq))
			C = numpy.matrix(rand(pp, nn))
			D = numpy.matrix(rand(pp, qq))

			yield dSSmp(A, B, C, D)
Exemplo n.º 20
0
    def generate_graph_nx(
            nodes: int,
            density,
            mode,
            directed,
            force=settings.force):  # graph generation using networkx
        bar = ProgBar(20, title='Generating graph', stream=sys.stdout)
        if directed:  # calculate edge count based on node count and density
            edges = nodes * (nodes - 1) * density
            if edges < nodes - 1 and not force:
                print(
                    "Minimum graph density for this problem is {:2.0%}. "
                    "To generate less dense graph anyway, set argument force to True."
                    .format(float(1 / nodes)),
                    file=sys.stderr)
                edges = nodes - 1
        else:
            edges = nodes * (nodes - 1) * density / 2
            if edges < nodes - 1 and not force:
                print(
                    "Minimum graph density for this problem is {:2.0%}. "
                    "To generate less dense graph anyway, set argument force to True."
                    .format(float(2 / nodes)),
                    file=sys.stderr)
                edges = nodes - 1
        bar.update()
        G = nx.generators.random_graphs.gnm_random_graph(
            nodes, edges, directed=directed)  # generate random graph
        bar.update()
        if not directed:  # check connectivity and generate new graph if failed
            while not nx.is_connected(G):
                G = nx.generators.random_graphs.gnm_random_graph(
                    nodes, edges, directed=directed)
        else:
            cont = False

            while not cont:
                cont = True
                for node in G.nodes:
                    if len([x for x in G.neighbors(node)]) == 0:
                        cont = False
                        G = nx.generators.random_graphs.gnm_random_graph(
                            nodes, edges, directed=directed)
                        break
        bar.update()
        if mode == 'matrix':  # convert generated networkx graph to own structure
            ret = Matrix(nodes)
            for x, y in G.edges:
                w = randint(1, nodes)
                ret.set(x, y, w)
                if directed and ret.get(y, x) == 0:
                    ret.set(y, x, 0)
                else:
                    ret.set(y, x, w)
                bar.update()
            return ret
        else:
            ret = ListGraph(nodes)
            for x, y in G.edges:
                w = randint(1, nodes)
                ret.add_connection(x, y, w)
                if not directed:
                    ret.add_connection(y, x, w)
                bar.update()
            return ret
Exemplo n.º 21
0
    def serial_test(self):  # bulk tests as specified in settings.py
        result_file = open('result.txt', 'a')
        for algorithm in settings.algorithms:
            print(algorithm.capitalize())
            result_file.write("%s\n" % algorithm.capitalize())
            alg_res = {}
            for representation in settings.representations:
                print(representation.capitalize())
                result_file.write("%s\n" % representation.capitalize())
                rep_res = {}
                for density in settings.densities:
                    print('Density: {}%'.format(density * 100))
                    result_file.write('Density: {}%\n'.format(density * 100))
                    den_res = {}
                    for serie in settings.series:
                        print('Graph size: %d' % serie)
                        result_file.write('Graph size: %d\n' % serie)
                        results = []
                        for i in range(settings.series_entries):
                            gc.disable()
                            graph = GraphGenerator.generate_graph_nx(
                                serie, density, representation, settings.
                                is_directed[algorithm])  # generate new graph
                            function = getattr(
                                algorithms, '%s_%s' %
                                (algorithm, representation))  # get function
                            args = ()
                            if algorithm == 'prim' or algorithm == 'kruskal':  # generate random arguments for function
                                args = tuple([randint(serie)])
                            elif algorithm == 'dijkstra' or algorithm == 'ford_bellman':
                                arg1 = randint(serie)
                                arg2 = randint(serie)
                                while arg2 == arg1:
                                    arg2 = randint(serie)
                                args = (arg1, arg2)
                            start = timer()
                            function(graph, args)  # time test
                            end = timer()
                            time = (end - start
                                    ) * 1000  # convert time to milliseconds
                            print(
                                'Entry %d | Execution time: %f milliseconds' %
                                (i + 1, time))
                            result_file.write(
                                'Entry %d | Execution time: %f milliseconds\n'
                                % (i + 1, time))
                            results.append(time)
                            del graph
                            gc.enable()

                        avg = average(results)
                        maxi = max(results)
                        mini = min(results)
                        print('Average time in series: %f' % avg)
                        result_file.write('Average time in series: %f\n' % avg)
                        print('Maximum execution time: %f' % maxi)
                        result_file.write('Maximum execution time: %f\n' %
                                          maxi)
                        print('Minimum execution time: %f' % mini)
                        result_file.write('Minimum execution time: %f\n' %
                                          mini)
                        print('-' * 30)
                        result_file.write('-' * 30)
                        result_file.write('\n')
                        den_res[serie] = results
                    rep_res[density] = den_res
                alg_res[representation] = rep_res
Exemplo n.º 22
0
    def generate_graph(nodes, density, mode, directed, force=settings.force):
        """
        graph generated via algorithm:
        1. calculate edge count
        2. build a tree
        3. add random edges to meet edge count
        """
        connected = []
        disconnected = [i for i in range(nodes)]
        if directed:  # calculate edge count based on node count and density
            edge_list = [(x, y) for x in range(nodes) for y in range(nodes)
                         if x != y]
            edges = nodes * (nodes - 1) * density
            if edges < nodes - 1 and not force:
                print(
                    "Minimum graph density for this problem is {:2.0%}. "
                    "To generate less dense graph anyway, set argument force to True."
                    .format(float(1 / nodes)),
                    file=sys.stderr)
                edges = nodes - 1
        else:
            edge_list = [(x, y) for x in range(nodes) for y in range(nodes)
                         if x != y]
            edges = nodes * (nodes - 1) * density / 2
            if edges < nodes - 1 and not force:
                print(
                    "Minimum graph density for this problem is {:2.0%}. "
                    "To generate less dense graph anyway, set argument force to True."
                    .format(float(2 / nodes)),
                    file=sys.stderr)
                edges = nodes - 1
        bar = ProgBar(edges, title='Generating graph', stream=sys.stdout)
        if mode == 'list':
            graph = ListGraph(nodes)
            while len(disconnected) > 0:  # build a tree

                if len(connected) == 0:
                    s = randint(nodes)
                    e = randint(nodes)
                    connected.append(s)
                    disconnected.remove(s)
                else:
                    s = connected[randint(
                        len(connected)
                    )]  # get starting vertex randomly from already connected nodes
                    e = disconnected[randint(
                        len(disconnected)
                    )]  # get ending vertex randomly from not yet connected

                disconnected.remove(e)
                w = randint(1, nodes)
                graph.add_connection(s, e, w)  # add connection
                if not directed:
                    graph.add_connection(e, s, w)
                connected.append(e)
                edge_list.remove((s, e))  # remove edge from the pool
                if not directed:
                    edge_list.remove((e, s))
                edges -= 1
                bar.update()

            while edges > 0:  # add remaining edges at random
                s, e = edge_list[randint(len(edge_list))]

                edge_list.remove((s, e))
                w = randint(nodes)
                graph.add_connection(s, e, w)
                if not directed:
                    edge_list.remove((e, s))
                    graph.add_connection(e, s, w)
                edges -= 1
                bar.update()

        elif mode == 'matrix':
            graph = Matrix(nodes)
            while len(disconnected) > 0:  # build a tree
                if len(connected) == 0:
                    s = randint(nodes)
                    e = randint(nodes)
                    connected.append(s)
                    disconnected.remove(s)
                else:
                    s = connected[randint(
                        len(connected)
                    )]  # get starting vertex randomly from already connected nodes
                    e = disconnected[randint(
                        len(disconnected)
                    )]  # get ending vertex randomly from not yet connected

                disconnected.remove(e)
                w = randint(1, nodes)
                graph.set(s, e, w)  # add connection
                if not directed:
                    graph.set(e, s, w)
                connected.append(e)
                edge_list.remove((s, e))  # remove edge from the pool
                if not directed:
                    edge_list.remove((e, s))
                edges -= 1
                bar.update()

            bar = ProgBar(20, stream=sys.stdout)
            while edges > 0:  # add remaining edges at random
                s, e = edge_list[randint(len(edge_list))]
                edge_list.remove((s, e))
                w = randint(nodes)
                graph.set(s, e, w)
                if not directed:
                    edge_list.remove((e, s))
                    graph.set(e, s, w)
                edges -= 1
                bar.update()
        print("Generated graph")
        return graph
    def createGraph(self,
                    nodeNum,
                    arcNum,
                    snode,
                    dnode,
                    totalDemand,
                    balanced=False):
        #Determining the per dnode and per snode b's for balanced version
        demval = int(math.floor(totalDemand / dnode))
        supmval = int(math.floor(totalDemand / snode))

        #Adding desired amount of nodes
        for i in range(0, nodeNum):
            self.addNode()

        #Supply Node Determination
        dt = deepcopy(totalDemand)
        t = 0
        supplyIds = []
        while t < snode:
            index = randint(0, nodeNum - 1)
            if self.nodes[index].b is None:
                if t is not snode - 1:
                    if balanced is True:
                        k = randint(math.floor(3 * supmval / 4),
                                    math.floor(supmval))
                    else:
                        k = randint(1, math.floor(dt - (snode - t)))
                    supplyIds.append(index)
                    self.nodes[index].b = k
                    dt = dt - k
                    t = t + 1
                else:
                    self.nodes[index].b = dt
                    supplyIds.append(index)
                    t = t + 1
            else:
                continue

        #Demand Node Determination
        dt = deepcopy(totalDemand)
        t = 0
        demandIds = []
        while t < dnode:
            index = randint(0, nodeNum - 1)
            if self.nodes[index].b is None:
                if t is not dnode - 1:
                    if balanced is True:
                        k = randint(math.floor(3 * demval / 4),
                                    math.floor(demval))
                    else:
                        k = randint(1, math.floor(dt - (dnode - t)))
                    self.nodes[index].b = k * -1
                    demandIds.append(index)
                    dt = dt - k
                    t = t + 1
                else:
                    self.nodes[index].b = dt * -1
                    demandIds.append(index)
                    t = t + 1
            else:
                continue
        #Adding Edges From Each Supply Node to Each Demand Node to Guarantee the Connectivity
        arc = 0
        for s in supplyIds:
            for d in demandIds:
                self.addEdge(self.nodes[s], self.nodes[d], 50, self.nodes[s].b)
                arc = arc + 1

        #Adding remaining arcs
        while arc < arcNum:
            index1 = randint(0, nodeNum - 1)
            index2 = randint(0, nodeNum - 1)
            if self.getEdge(index1, index2) is None:
                if index1 is not index2:
                    self.addEdge(self.nodes[index1], self.nodes[index2],
                                 randint(1, 20), randint(0, totalDemand))
                    arc = arc + 1
            else:
                continue
        #Adding dummy node and connecting all nodes to this node (Otherwise it may be problematic for capacity scaling due to possible loss of strong connectivity)
        self.addNode(0)
        dummy = self.nodes[len(self.nodes) - 1]
        for i in self.nodes:
            if i is not dummy:
                self.addEdge(i, dummy, 2000, 1000000000000)
                self.addEdge(dummy, i, 2000, 1000000000000)
        #Setting remaining b's to 0 other than supply and demand nodes
        for n in self.nodes:
            if n.b is None:
                n.b = 0
Exemplo n.º 24
0
def genereer_getal(bereik):
    return randint(1, bereik)
Exemplo n.º 25
0
'''
Created on Jan 2, 2019

@author: vkhoday
'''

from numpy.random import rand
from numpy.random.mtrand import randint
import pandas

from selenium import webdriver

dr =webdriver.Chrome(executable_path='C:/Users/DELL/git/Pyunit_Selenium/WebDriver/chromedriver_235')

dr.get("https://www.google.com")
y =dr.execute_script("return document.body.scrollHeight")
x =dr.execute_script("return document.body.scrollWidth")
print(x,y)

for i in range(0,10):
    r =randint(26,size=(5,10))
    print (r)
    
pd = pandas.Series(randint.random.randn(50))
Exemplo n.º 26
0
 def test_warns_byteorder(self):
     # GH 13159
     other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
     with pytest.deprecated_call(match='non-native byteorder is not'):
         random.randint(0, 200, size=10, dtype=other_byteord_dt)
Exemplo n.º 27
0
# are separately analysed posteriors.
mode = 'replace'

# Calculate entropy numbers with surprise
rel_ent, exp_rel_ent, S, sD, p = sc(sample1, sample2, mode = mode)

print('Entropy estimates for two standard normal distributions.')
print('Relative entropy D: %f'%rel_ent)
print('Expected relative entropy <D>: %f'%exp_rel_ent)
print('Surprise S: %f'%S)
print('Expected fluctuations of relative entropy sigma(D): %f'%sD)
print('p-value of Surprise: %f'%p)

# Draw random weights for the samples.
mini = 1
maxi = 10
weights1 = randint(mini, maxi, n)
weights2 = randint(mini, maxi, n)

# Calculate entropy numbers with surprise using the random weights
rel_ent, exp_rel_ent, S, sD, p = sc(sample1, sample2, mode = mode,
                                    weights1 = weights1, weights2 = weights2)

print('Entropy estimates for two standard normal distributions.')
print('(with random weights)')
print('Relative entropy D: %f'%rel_ent)
print('Expected relative entropy <D>: %f'%exp_rel_ent)
print('Surprise S: %f'%S)
print('Expected fluctuations of relative entropy sigma(D): %f'%sD)
print('p-value of Surprise: %f'%p)
Exemplo n.º 28
0
def main():
    seed = 1
    number_of_samples = 20000
    dbd4 = DBD4(size=number_of_samples, ratio=1, thresh=6, seed=seed)
    SecondaryStructureExtractor(dbd4).extract_feature()

    for complex_name in dbd4.complexes:
        print_info(complex_name)
        c = dbd4.complexes[complex_name]
        b_ligand, b_receptor = (c.bound_formation.ligand, c.bound_formation.receptor)
        u_ligand, u_receptor = (c.unbound_formation.ligand, c.unbound_formation.receptor)
        b_ligand_bio_residues, b_receptor_bio_residues = b_ligand.biopython_residues, b_receptor.biopython_residues
        # b_l_ns, b_r_ns = NeighborSearch(b_ligand.atoms), NeighborSearch(b_receptor.atoms)
        u_l_ns, u_r_ns = NeighborSearch(u_ligand.atoms), NeighborSearch(u_receptor.atoms)
        index = randint(1, 30)
        positives = 0
        negatives = 0
        lb2u = c.ligand_bound_to_unbound
        rb2u = c.receptor_bound_to_unbound
        p = False
        n = False
        with PdfPages('{0}/geometry/figures/{1}.pdf'.format(reports_directory, complex_name)) as pdf:
            try:
                for i in range(len(b_ligand_bio_residues)):
                    for j in range(len(b_receptor_bio_residues)):
                        if b_ligand.residues[i] not in lb2u or b_receptor.residues[j] not in rb2u:
                            continue
                        l_atoms = b_ligand_bio_residues[i].get_list()
                        r_atoms = b_receptor_bio_residues[j].get_list()
                        dist_mat = cdist([atom.get_coord() for atom in l_atoms], [atom.get_coord() for atom in r_atoms])
                        if p and n:
                            print "getting out of loop..."
                            raise GetOutOfLoop
                        if dist_mat.min() < dbd4.interaction_threshold:
                            if p:
                                continue
                            positives += 1
                            if positives != index:
                                continue
                            # b_l_points, b_l_dist = get_coords(b_l_ns, b_ligand, b_ligand.residues[i], 0.5, False)
                            # b_r_points, b_r_dist = get_coords(b_r_ns, b_receptor, b_receptor.residues[j], 0.5, False)

                            b_l_points, b_l_dist = get_coords(u_l_ns, u_ligand, lb2u[b_ligand.residues[i]], 0.5, False)
                            b_r_points, b_r_dist = get_coords(u_r_ns, u_receptor, rb2u[b_receptor.residues[j]], 0.5,
                                                              False)

                            u_l_points, u_l_dist = get_coords(u_l_ns, u_ligand, lb2u[b_ligand.residues[i]], 0.5, True)
                            u_r_points, u_r_dist = get_coords(u_r_ns, u_receptor, rb2u[b_receptor.residues[j]], 0.5,
                                                              True)

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(b_l_points[:, 0], b_l_points[:, 1], b_l_points[:, 2], c='r')
                            ax.scatter(b_r_points[:, 0], b_r_points[:, 1], b_r_points[:, 2], c='b')
                            plt.title("Interacting Residues Bound Conformation")
                            pdf.savefig()
                            plt.close()

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(u_l_points[:, 0], u_l_points[:, 1], u_l_points[:, 2], c='r')
                            ax.scatter(u_r_points[:, 0], u_r_points[:, 1], u_r_points[:, 2], c='b')
                            plt.title("Interacting Surface Residues Bound Conformation")
                            pdf.savefig()
                            plt.close()

                            plt.figure()
                            plt.plot(u_l_dist)
                            plt.plot(u_r_dist)
                            plt.legend(["bound ligand {0}".format(i), "bound receptor {0}".format(j), "unbound ligand",
                                        "unbound receptor"])
                            pdf.savefig()
                            plt.close()
                            p = True
                        else:
                            if n:
                                continue
                            lb2u = c.ligand_bound_to_unbound
                            rb2u = c.receptor_bound_to_unbound

                            b_l_points, b_l_dist = get_coords(u_l_ns, u_ligand, lb2u[b_ligand.residues[i]], 0.5, False)
                            b_r_points, b_r_dist = get_coords(u_r_ns, u_receptor, rb2u[b_receptor.residues[j]], 0.5,
                                                              False)

                            u_l_points, u_l_dist = get_coords(u_l_ns, u_ligand, lb2u[b_ligand.residues[i]], 0.5, True)
                            u_r_points, u_r_dist = get_coords(u_r_ns, u_receptor, rb2u[b_receptor.residues[j]], 0.5,
                                                              True)

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(b_l_points[:, 0], b_l_points[:, 1], b_l_points[:, 2], c='r')
                            ax.scatter(b_r_points[:, 0], b_r_points[:, 1], b_r_points[:, 2], c='b')
                            plt.title("Non-Interacting Residues Bound Conformation")
                            pdf.savefig()
                            plt.close()

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(u_l_points[:, 0], u_l_points[:, 1], u_l_points[:, 2], c='r')
                            ax.scatter(u_r_points[:, 0], u_r_points[:, 1], u_r_points[:, 2], c='b')
                            plt.title("Non-Interacting Surface Residues Bound Conformation")
                            pdf.savefig()
                            plt.close()

                            plt.figure()
                            plt.plot(u_l_dist)
                            plt.plot(u_r_dist)
                            plt.legend(["bound ligand {0}".format(i), "bound receptor {0}".format(j), "unbound ligand",
                                        "unbound receptor"])
                            pdf.savefig()
                            plt.close()
                            n = True

            except GetOutOfLoop:
                pass
Exemplo n.º 29
0
def run():

    #sets useful variables and gets window size
    black = [0, 0, 0]
    w, h = display1.get_size()

    pygame.mouse.set_visible(False)  #hides the mouse for the game

    x = int(w / 2)
    y = int(h / 2) + 200
    # x, y refer to pygame coordinates of player

    score = 0

    flagy = -263
    flagx = randint(0, scr_width - 500)
    #pygame coordinates of the obstacle, the x value is randomly generated

    intro()
    #introduction screen displayed if it is firsttime is true

    pygame.mixer.music.play(-1)
    #plays the background music during gameplay

    while (True):
        scorefont = myfont.render('Score: %d' % score, False, (0, 0, 0))
        #text that shows current score in upper left corner

        if (flagy > scr_height + 270):
            #detects for an obstacle successfully avoided (off the bottom of screen)
            flagy = -270
            flagx = randint(0, scr_width - 500)
            #obstacle moved to new position above player, with random x value

            score += 1

        color = [randint(0, 255), randint(0, 255), randint(0, 255)]
        #randomly generates a color for the background

        flagy = flagy + 12
        #this is the speed that the obstacle falls down

        #detects for user input from keyboard (escape button only)
        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                sys.exit()
            elif (event.type == pygame.KEYDOWN):
                if (event.key == pygame.K_ESCAPE):
                    sys.exit()

        #detects user controlling player (this method must be used or else
        #holding a button only renders one click, and the player will not
        #continuously move. It is also checked that the player will not go
        #off the screen after moving
        keys = pygame.key.get_pressed()
        if (keys[pygame.K_RIGHT]):
            if (x + 10 in range(0, scr_width - 121)):
                x = x + 10
        if (keys[pygame.K_LEFT]):
            if (x - 10 in range(0, scr_width)):
                x = x - 10

        if (not Intersection(Interval(y, y + 140), Interval(
                flagy, flagy + 150)).is_EmptySet):
            #checks if the intervals of y coordinates of the obstacle and player overlap

            if (not Intersection(Interval(x, x + 121),
                                 Interval(flagx, flagx + 500)).is_EmptySet):
                #given that the y coordinates overlap, check if the x coordinates overlap

                display1.fill(black)

                global highscore  #defined global because variable is in function

                if (score > highscore):
                    #check if score this round is higher than highscore, update highscore if needed
                    highscore = score
                    savehighscore(highscore)

                #this is the text on the death screen
                text = myfont.render('you have died.', False, (255, 255, 255))
                scoretext = myfont.render(
                    'Score: %d   Highscore: %d' % (score, highscore), False,
                    (255, 255, 255))
                text2 = myfont.render('press space to restart', False,
                                      (255, 255, 255))

                while (True):

                    #while on death screen, checks for user input
                    for event in pygame.event.get():
                        if (event.type == pygame.QUIT):
                            sys.exit()
                        elif (event.type == pygame.KEYDOWN):
                            if (event.key == pygame.K_ESCAPE):
                                sys.exit()
                            if (event.key == pygame.K_SPACE):
                                #restart the game
                                global firsttime
                                pygame.mixer.music.stop()
                                #stops music so it can be replayed

                                firsttime = False
                                #prevents the intro screen from showing

                                run()

                    #draws the text onto death screen
                    display1.blit(text, (int(scr_width / 2) - 500, 200))
                    display1.blit(scoretext, (int(scr_width / 2) - 500, 300))
                    display1.blit(text2, (int(scr_width / 2) - 500, 400))
                    pygame.display.update()

        #clears game window, moves all objects, and redraws them. Also draws on score.
        display1.fill(color)
        display1.blit(player, (x, y))
        display1.blit(flag, (flagx, flagy))
        display1.blit(scorefont, (40, 50))

        pygame.display.update()
Exemplo n.º 30
0
def gibbssample(num_iters, pos_sequences, alphabet, m_word_length, m_word_param, background_param):
	#print sequences
	sequences = pos_sequences[1]
	M = len(alphabet) # Alphabet size
	K = len(sequences) # Num sequences
	N = len(sequences[0]) # Seq length
	alph_map = {alphabet[m] : m for m in range(M)}
	iter_logpost = [[] for x in range(2)]

	# Initialize hidden word starting locations
	R = randint(0, N - m_word_length, K).tolist()

	# Calculate sum of alphas for magic word and background distributions
	A = float(sum(m_word_param))
	A_back = float(sum(background_param))

	# Get magic word and background symbol counts
	N_m = [[0.0] * m_word_length for x in range(M)]
	bg_m = [0.0] * M
	for i in range(K):
		for x in range(N):
			if x >= R[i] and x < R[i] + m_word_length:
				N_m[alph_map[sequences[i][x].upper()]][x-R[i]] += 1
			else:
				bg_m[alph_map[sequences[i][x].upper()]] += 1

	# Begin iterations
	for l in range(num_iters):
		to_exclude = range(K)
		for s in range(K):
			# Select sequence to exclude
			exclude_indx = randint(len(to_exclude))
			z = to_exclude[exclude_indx]
			del to_exclude[exclude_indx]

			# Update counts for excluding excluded sequence
			for x in range(N):
				if x >= R[z] and x < R[z] + m_word_length:
					N_m[alph_map[sequences[z][x].upper()]][x-R[z]] -= 1
				else:
					bg_m[alph_map[sequences[z][x].upper()]] -= 1

			P = [[0.0] * m_word_length for x in range(M)]
			P_bg = [0.0] * M

			# Calculate log conditional P(s_(z,j) = m | s_(j,-z), alpha) for each symbol and m_word pos
			for m in range(M):
				P_bg[m] = log((bg_m[m] + background_param[m]) / (A_back + K*(N-m_word_length) - 1))
				for j in range(m_word_length):
					P[m][j] = log((N_m[m][j] + m_word_param[m]) / (A + K - 1))

			# Calculate posterior over each starting position in s_z
			r_bg_z = sum([P_bg[alph_map[m.upper()]] for m in sequences[z]])
			r = [r_bg_z] * (N - m_word_length)

			for s_pos in range(N - m_word_length):
				for j in range(m_word_length):
					idx = s_pos + j
					r[s_pos] -= P_bg[alph_map[sequences[z][idx].upper()]]
					r[s_pos] += P[alph_map[sequences[z][idx].upper()]][j]

			# Normalize conditionals
			probs = [exp(x) for x in r]
			normalizer = sum(probs)
			probs = [x/normalizer for x in probs]

			# Update starting position for s_z
			R[z] = multinomial(1,probs).tolist().index(1)

			# Update counts for updating starting position of excluded sequence
			for x in range(N):
				if x >= R[z] and x < R[z] + m_word_length:
					N_m[alph_map[sequences[z][x].upper()]][x-R[z]] += 1
				else:
					bg_m[alph_map[sequences[z][x].upper()]] += 1

		# Calculate posterior
		log_post = lgamma(A_back) - lgamma(K*(N - m_word_length) + A_back)
		for m in range(M):
			log_post += lgamma(bg_m[m] + background_param[m]) - lgamma(background_param[m])
		for j in range(m_word_length):
			log_post += lgamma(A) - lgamma(K + A)
			for m in range(M):
				log_post += lgamma(N_m[m][j] + m_word_param[m]) - lgamma(m_word_param[m])

		iter_logpost[0].append(l)
		iter_logpost[1].append(log_post)

	#print[abs(pos_sequences[0][i] - R[i]) < 1 for i in range(len(R))]
	#print R

	return [R,iter_logpost]
Exemplo n.º 31
0
with tf.Session() as sess:
    sess.run(init)

    for epoch in range( training_epochs ):
        avg_cost = 0.
        total_batch = int( mnist.train.num_examples/batch_size)
        
        for i in range( total_batch ):
            batch_xs, batch_ys = mnist.train.next_batch( batch_size )
            sess.run( optimizer, feed_dict={x: batch_xs, y:batch_ys} )
            avg_cost += sess.run( cost, feed_dict={x: batch_xs, y:batch_ys} ) / total_batch
            
        if epoch % display_step == 0:
            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
    print "Optimization Finished!"
    
    # Get one and predict
    r = randint( 0, mnist.test.num_examples -1 )
    print "Label: ", sess.run( tf.arg_max(mnist.test.labels[r:r+1], 1) )
    print "Prediction: ", sess.run( tf.arg_max(activation, 1), {x: mnist.test.images[r:r+1]} )
    
    # Test model
    correct_prediction = tf.equal( tf.arg_max(activation, 1), tf.arg_max(y, 1) )
    # Calculate accuracy
    accuracy = tf.reduce_mean( tf.cast(correct_prediction, "float") )
    print "Accuracy:", accuracy.eval( {x: mnist.test.images, y: mnist.test.labels} )
    
    #Show the img
#     plt.imshow( mnist.test.images[r:r+1], reshape(28, 28), cmap="Greys", interpolation='nearest' )
#     plt.show()
Exemplo n.º 32
0
def generateNewValue(lim1, lim2):
    return randint(lim1, lim2)
Exemplo n.º 33
0
def MonteCarlo_Meals(data, epsilon, episodes, alpha, plan_goals):
    breakfast_meals = data[data['breakfast'] == 1]
    lunch_dinner = data[data['main_dish'] == 1]
    inbetween_meals = data[(data['breakfast'] == 0) & (data['main_dish'] == 0)]
    meal_types = [
        'breakfast', 'lunch', 'dinner', 'inbetweener_1', 'inbetweener_2',
        'inbetweener_3'
    ]
    nutrition_Val = ['calories', 'fats', 'proteins', 'carbs']
    good_episodes = []
    counter = 0

    ### Generate Servings table for the number of meals

    serv_table = servingsTable(plan_goals.meals)

    while counter == 0:
        print('Trial')
        for k in range(0, episodes):
            print(k)
            episode_run = []

            for i in range(0, plan_goals.meals):

                if i == 0:
                    meals = breakfast_meals
                elif i < 2:
                    meals = lunch_dinner
                else:
                    meals = inbetween_meals

                greedyselection = randint(1, 10)

                if greedyselection <= epsilon:
                    rand_selection = randint(low=0, high=len(meals.index))
                    episode_run = np.append(
                        episode_run, meals.iloc[rand_selection]['index'])
                else:
                    maxOfV = meals[meals['avg_val'] ==
                                   meals['avg_val'].max()]['index']
                    # If multiple max values, take first
                    maxOfV = maxOfV.values[0]
                    episode_run = np.append(episode_run, maxOfV)

                episode_run = episode_run.astype(int)

            for i in range(2, serv_table.shape[0]):

                episode = pd.DataFrame({
                    'meal_type':
                    meal_types[:len(episode_run)],
                    'meal_index':
                    episode_run,
                    'serving':
                    serv_table[i]
                })

                episode['meal_index'] = (episode['meal_index']).astype(int)
                data['index'] = (data['index']).astype(int)

                detailed_episode = episode.merge(
                    data[['index', 'name', 'value_ser1', 'value_ser2'] +
                         nutrition_Val],
                    left_on='meal_index',
                    right_on='index',
                    how='inner')

                for col in nutrition_Val:
                    detailed_episode[col] = detailed_episode[
                        col] * detailed_episode['serving']

                result = 0
                reward = -1
                # Total nutritional value in the entire plan

                total_protein = detailed_episode['proteins'].sum()
                total_fats = detailed_episode['fats'].sum()
                total_calories = detailed_episode['calories'].sum()
                total_carbs = detailed_episode['carbs'].sum()

                if (plan_goals.needed_proteins[0] < total_protein) & (
                        plan_goals.needed_proteins[1] > total_protein):
                    result += 1
                if (plan_goals.needed_carbs[0] < total_carbs) & (
                        plan_goals.needed_carbs[1] > total_carbs):
                    result += 1
                if (plan_goals.needed_fats[0] <
                        total_fats) & (plan_goals.needed_fats[1] > total_fats):
                    result += 1
                if abs(plan_goals.needed_calories - total_calories) < 100:
                    result += 1

                if result == 4:
                    counter += 1
                    reward = 1
                    good_episodes.append(detailed_episode)

                detailed_episode['return'] = reward

                for v in range(0, len(detailed_episode)):
                    serv = detailed_episode.iloc[v]['serving']
                    int(serv)
                    if detailed_episode.iloc[v]['return'] != 0:
                        update = data[data['index'] == detailed_episode.iloc[v]['meal_index']][
                                     'value_ser' + str(serv)[0]] + alpha * \
                                 ((detailed_episode.iloc[v]['return'] / plan_goals.meals) -
                                  data[data['index'] == detailed_episode.iloc[v]['meal_index']][
                                      'value_ser' + str(serv)[0]])

                        data.loc[(data['index'] ==
                                  detailed_episode.iloc[v]['meal_index']),
                                 ('value_ser' + str(serv)[0])] = update

                data['avg_val'] = data[['value_ser2',
                                        'value_ser1']].values.max(1)

    return good_episodes[0]
Exemplo n.º 34
0
mode = 'replace'

# Calculate entropy numbers with surprise
rel_ent, exp_rel_ent, S, sD, p = sc(sample1, sample2, mode=mode)

print('Entropy estimates for two standard normal distributions.')
print('Relative entropy D: %f' % rel_ent)
print('Expected relative entropy <D>: %f' % exp_rel_ent)
print('Surprise S: %f' % S)
print('Expected fluctuations of relative entropy sigma(D): %f' % sD)
print('p-value of Surprise: %f' % p)

# Draw random weights for the samples.
mini = 1
maxi = 10
weights1 = randint(mini, maxi, n)
weights2 = randint(mini, maxi, n)

# Calculate entropy numbers with surprise using the random weights
rel_ent, exp_rel_ent, S, sD, p = sc(sample1,
                                    sample2,
                                    mode=mode,
                                    weights1=weights1,
                                    weights2=weights2)

print('Entropy estimates for two standard normal distributions.')
print('(with random weights)')
print('Relative entropy D: %f' % rel_ent)
print('Expected relative entropy <D>: %f' % exp_rel_ent)
print('Surprise S: %f' % S)
print('Expected fluctuations of relative entropy sigma(D): %f' % sD)
Exemplo n.º 35
0
twentylstmaccdata = []
twentylstmstddata = []
twentylstmstderror = []

predictedBLLabels = []
predictedBRLabels = []
predictedBRLLabels = []
predictedBRRLabels = []
predictedBRPLabels = []
predictedRWLabels = []

offset = 100
accuracyOverall = []
for testnumber in range(30):
    start = randint(7999, 9799)
    end = start + offset
    timestep = range(start, end)
    LSTMClassificationNet.reset()
    for i in timestep:
        x = LSTMClassificationNet.activate(BallLiftJoint[i])
    predictedBLLabels.append(argmax(x))

    start = randint(7999, 9799)
    end = start + offset
    timestep = range(start, end)
    LSTMClassificationNet.reset()
    for i in timestep:
        x = LSTMClassificationNet.activate(BallRollJoint[i])
    predictedBRLabels.append(argmax(x))
Exemplo n.º 36
0
def main():
    seed = 1
    number_of_samples = 20000
    dbd4 = DBD4(size=number_of_samples, ratio=1, thresh=6, seed=seed)
    SecondaryStructureExtractor(dbd4).extract_feature()

    for complex_name in dbd4.complexes:
        print_info(complex_name)
        c = dbd4.complexes[complex_name]
        b_ligand, b_receptor = (c.bound_formation.ligand,
                                c.bound_formation.receptor)
        u_ligand, u_receptor = (c.unbound_formation.ligand,
                                c.unbound_formation.receptor)
        b_ligand_bio_residues, b_receptor_bio_residues = b_ligand.biopython_residues, b_receptor.biopython_residues
        # b_l_ns, b_r_ns = NeighborSearch(b_ligand.atoms), NeighborSearch(b_receptor.atoms)
        u_l_ns, u_r_ns = NeighborSearch(u_ligand.atoms), NeighborSearch(
            u_receptor.atoms)
        index = randint(1, 30)
        positives = 0
        negatives = 0
        lb2u = c.ligand_bound_to_unbound
        rb2u = c.receptor_bound_to_unbound
        p = False
        n = False
        with PdfPages('{0}/geometry/figures/{1}.pdf'.format(
                reports_directory, complex_name)) as pdf:
            try:
                for i in range(len(b_ligand_bio_residues)):
                    for j in range(len(b_receptor_bio_residues)):
                        if b_ligand.residues[
                                i] not in lb2u or b_receptor.residues[
                                    j] not in rb2u:
                            continue
                        l_atoms = b_ligand_bio_residues[i].get_list()
                        r_atoms = b_receptor_bio_residues[j].get_list()
                        dist_mat = cdist(
                            [atom.get_coord() for atom in l_atoms],
                            [atom.get_coord() for atom in r_atoms])
                        if p and n:
                            print "getting out of loop..."
                            raise GetOutOfLoop
                        if dist_mat.min() < dbd4.interaction_threshold:
                            if p:
                                continue
                            positives += 1
                            if positives != index:
                                continue
                            # b_l_points, b_l_dist = get_coords(b_l_ns, b_ligand, b_ligand.residues[i], 0.5, False)
                            # b_r_points, b_r_dist = get_coords(b_r_ns, b_receptor, b_receptor.residues[j], 0.5, False)

                            b_l_points, b_l_dist = get_coords(
                                u_l_ns, u_ligand, lb2u[b_ligand.residues[i]],
                                0.5, False)
                            b_r_points, b_r_dist = get_coords(
                                u_r_ns, u_receptor,
                                rb2u[b_receptor.residues[j]], 0.5, False)

                            u_l_points, u_l_dist = get_coords(
                                u_l_ns, u_ligand, lb2u[b_ligand.residues[i]],
                                0.5, True)
                            u_r_points, u_r_dist = get_coords(
                                u_r_ns, u_receptor,
                                rb2u[b_receptor.residues[j]], 0.5, True)

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(b_l_points[:, 0],
                                       b_l_points[:, 1],
                                       b_l_points[:, 2],
                                       c='r')
                            ax.scatter(b_r_points[:, 0],
                                       b_r_points[:, 1],
                                       b_r_points[:, 2],
                                       c='b')
                            plt.title(
                                "Interacting Residues Bound Conformation")
                            pdf.savefig()
                            plt.close()

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(u_l_points[:, 0],
                                       u_l_points[:, 1],
                                       u_l_points[:, 2],
                                       c='r')
                            ax.scatter(u_r_points[:, 0],
                                       u_r_points[:, 1],
                                       u_r_points[:, 2],
                                       c='b')
                            plt.title(
                                "Interacting Surface Residues Bound Conformation"
                            )
                            pdf.savefig()
                            plt.close()

                            plt.figure()
                            plt.plot(u_l_dist)
                            plt.plot(u_r_dist)
                            plt.legend([
                                "bound ligand {0}".format(i),
                                "bound receptor {0}".format(j),
                                "unbound ligand", "unbound receptor"
                            ])
                            pdf.savefig()
                            plt.close()
                            p = True
                        else:
                            if n:
                                continue
                            lb2u = c.ligand_bound_to_unbound
                            rb2u = c.receptor_bound_to_unbound

                            b_l_points, b_l_dist = get_coords(
                                u_l_ns, u_ligand, lb2u[b_ligand.residues[i]],
                                0.5, False)
                            b_r_points, b_r_dist = get_coords(
                                u_r_ns, u_receptor,
                                rb2u[b_receptor.residues[j]], 0.5, False)

                            u_l_points, u_l_dist = get_coords(
                                u_l_ns, u_ligand, lb2u[b_ligand.residues[i]],
                                0.5, True)
                            u_r_points, u_r_dist = get_coords(
                                u_r_ns, u_receptor,
                                rb2u[b_receptor.residues[j]], 0.5, True)

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(b_l_points[:, 0],
                                       b_l_points[:, 1],
                                       b_l_points[:, 2],
                                       c='r')
                            ax.scatter(b_r_points[:, 0],
                                       b_r_points[:, 1],
                                       b_r_points[:, 2],
                                       c='b')
                            plt.title(
                                "Non-Interacting Residues Bound Conformation")
                            pdf.savefig()
                            plt.close()

                            fig = plt.figure()
                            ax = fig.add_subplot(111, projection='3d')
                            ax.scatter(u_l_points[:, 0],
                                       u_l_points[:, 1],
                                       u_l_points[:, 2],
                                       c='r')
                            ax.scatter(u_r_points[:, 0],
                                       u_r_points[:, 1],
                                       u_r_points[:, 2],
                                       c='b')
                            plt.title(
                                "Non-Interacting Surface Residues Bound Conformation"
                            )
                            pdf.savefig()
                            plt.close()

                            plt.figure()
                            plt.plot(u_l_dist)
                            plt.plot(u_r_dist)
                            plt.legend([
                                "bound ligand {0}".format(i),
                                "bound receptor {0}".format(j),
                                "unbound ligand", "unbound receptor"
                            ])
                            pdf.savefig()
                            plt.close()
                            n = True

            except GetOutOfLoop:
                pass
Exemplo n.º 37
0
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
            avg_cost += sess.run(cost, feed_dict={
                x: batch_xs,
                y: batch_ys
            }) / total_batch

        if epoch % display_step == 0:
            print "Epoch:", '%04d' % (epoch +
                                      1), "cost=", "{:.9f}".format(avg_cost)
    print "Optimization Finished!"

    # Get one and predict
    r = randint(0, mnist.test.num_examples - 1)
    print "Label: ", sess.run(tf.arg_max(mnist.test.labels[r:r + 1], 1))
    print "Prediction: ", sess.run(tf.arg_max(activation, 1),
                                   {x: mnist.test.images[r:r + 1]})

    # Test model
    correct_prediction = tf.equal(tf.arg_max(activation, 1), tf.arg_max(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print "Accuracy:", accuracy.eval({
        x: mnist.test.images,
        y: mnist.test.labels
    })

    #Show the img
#     plt.imshow( mnist.test.images[r:r+1], reshape(28, 28), cmap="Greys", interpolation='nearest' )
Exemplo n.º 38
0
 def get_random_tile():
     return SPAWN_CHANCE_LIST[randint(0, len(SPAWN_CHANCE_LIST))]
 def fill(self):
     for i in range(0, self.x):
         for j in range(0, self.y):
             self.matrix[i, j] = randint(100)
     print(self.matrix)
     return (self.matrix)
Exemplo n.º 40
0
def model(df):
    # tfidfconverter = TfidfVectorizer(max_features=1, min_df=1, max_df=0.7, stop_words=stopwords.words('english'))
    # job_id = tfidfconverter.fit_transform(df["job_id"]).toarray()
    df.drop(["job_id"],inplace=True,axis=1)
      # [randint(1, 4) for i in range(0,df["file_size"].count())]
    df.drop(["operation"],inplace=True,axis=1)
    where_are_NaNs = np.isnan(df)
    df[where_are_NaNs] = 592
    df2= pd.DataFrame();
    df2["file_size"]=[randint(500, 1000) for i in range(0,80)]
    df2["output_size"]=[randint(5, 10000) for i in range(0,80)]
    df2["file_size"]=[randint(400,1300) for i in range(0,80)]

    df.append(df2,ignore_index=True)


    pso_optimization(df)
    y = df["output"]
    df.drop(["output"],inplace=True,axis=1)

    X =df;

    names = ["Nearest Neighbors", "Linear SVM", "RBF SVM","Gaussian Process",
             "Decision Tree", "Random Forest", "Neural Net", "AdaBoost",
             "Naive Bayes"]
    classifiers = [
        KNeighborsClassifier(3),
        SVC(kernel="linear", C=0.025),
        SVC(gamma=2, C=1),
        GaussianProcessClassifier(1.0 * RBF(1.0)),

        DecisionTreeClassifier(max_depth=5),
        RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
        MLPClassifier(alpha=1, max_iter=1000),
        AdaBoostClassifier(),
        GaussianNB()

        ]

    # Splitting the dataset into the Training set and Test set

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
    sc = StandardScaler()
    X_train = sc.fit_transform(X_train)
    X_test = sc.transform(X_test)
    print("##################Without PCA####################")
    # iterate over classifiers
    score=[]
    time_withoutPCA = []
    for name, clf in zip(names, classifiers):
        start = time.clock()
        clf.fit(X_train, y_train)
        y_score=clf.score(X_test, y_test)
        score.append(y_score)
        time_withoutPCA.append(time.clock() - start)
        # print("time_withoutPCA: ", time_withoutPCA)
        print(name,y_score)

    print("time_withoutPCA: ", time_withoutPCA)

    plot_bar_x(names, score, titlle="Various Algorithm without PCA")
    plot_bar_x_execution_time(names, time_withoutPCA, titlle="Excution time without PCA")

    print("#################WITH PCA#########################")

    #########PCA 1#############
    # pca = PCA()
    # X_train = pca.fit_transform(X_train)
    # X_test = pca.transform(X_test)
    ##############PCA 2###########
    pca = PCA(n_components=3)
    X_train = pca.fit_transform(X_train)
    X_test = pca.transform(X_test)
    score_withPCA = []
    time_withPCA=[]
    for name, clf in zip(names, classifiers):
        start=time.clock()
        clf.fit(X_train, y_train)
        y_hat= clf.predict(X_test)
        y_score_pca=clf.score(X_test, y_test)
        # plt.plot(list(y_hat),'ro',linewidth=7.0)
        # plt.plot(list(y_test), 'g^', linewidth=7.0)
        # plt.show()
        score_withPCA.append(y_score_pca)
        print(name,y_score_pca)
        time_withPCA.append(time.clock() - start)
    print("time_withPCA: ", time_withPCA)

    plot_bar_x(names, score_withPCA, titlle="Various Algorithm with PCA")
    plot_bar_x_execution_time(names, time_withPCA, titlle="Excution time with PCA")
Exemplo n.º 41
0
def get_random_mover():
    i = randint(0, 4)
    movers = ['8', '9', '10', '11']
    return movers[i]
Exemplo n.º 42
0
    def gibbs_sampling(self, alpha, n_iterations):
        n_topics = self.n_topics

        # initialize all counts to 0
        n_d_t = [[0 for _ in range(n_topics)] for _ in range(len(self.corpus))]
        n_t_w = {w: [0 for _ in range(n_topics)] for w in self.vocab}

        # store intermediate values for estimating parameters
        doc_sums = [float(len(d) + n_topics * alpha) for d in self.corpus]
        topic_sums = [len(self.vocab) * alpha for _ in range(n_topics)]

        word_topic_map = [[None for _ in d] for d in self.corpus]

        # randomly assign topics to words, and set up initial counts
        for di in range(len(self.corpus)):
            d = self.corpus[di]
            for wi in range(len(d)):
                w = d[wi]
                t = randint(0, n_topics)
                word_topic_map[di][wi] = t
                n_t_w[w][t] += 1
                n_d_t[di][t] += 1
                topic_sums[t] += 1

        for i in range(n_iterations):
            for di in range(len(self.corpus)):
                pct_done = 100 * (i * len(self.corpus) + di) / float(len(self.corpus) * n_iterations)
                print("Iteration %d/%d, Document %d/%d.... (%2.2f%%)" % \
                      (i, n_iterations, di, len(self.corpus), pct_done))

                d = self.corpus[di]

                for wi in range(len(d)):
                    w = d[wi]
                    # i. remove current word from counts
                    old_topic = word_topic_map[di][wi]
                    n_d_t[di][old_topic] -= 1
                    n_t_w[w][old_topic] -= 1
                    topic_sums[old_topic] -= 1

                    # ii. estimate probabilities using 5.6, 5.7
                    word_topic_probs = []
                    for t1 in range(n_topics):
                        p_t_d = (n_d_t[di][t1] + alpha) / doc_sums[di]
                        p_w_t = (n_t_w[w][t1] + alpha) / topic_sums[t1]
                        word_topic_probs.append(p_t_d * p_w_t)
                    s = float(sum(word_topic_probs))
                    word_topic_probs = [p/s for p in word_topic_probs]
                    # iii. assign w to a topic randomly
                    new_topic = choice(list(range(n_topics)), p=word_topic_probs)
                    word_topic_map[di][wi] = new_topic

                    # iv. increment counts accordingly
                    n_d_t[di][new_topic] += 1
                    n_t_w[w][new_topic] += 1
                    topic_sums[new_topic] += 1

        # finalize parameters
        for di in range(len(self.corpus)):
            self.p_t_d.append([(n_d_t[di][t1] + alpha) / doc_sums[di] for t1 in range(n_topics)])
        for w in self.vocab:
            self.p_w_t[w] = [(n_t_w[w][t1] + alpha) / topic_sums[t1] for t1 in range(n_topics)]

        # also store counts
        self.n_t_w = n_t_w
Exemplo n.º 43
0
def get_tile_code_for_buffer():
    i = randint(0, len(SPAWN_CHANCE_LIST))
    return str(SPAWN_CHANCE_LIST[i])
Exemplo n.º 44
0
twentylstmaccdata = []
twentylstmstddata = []
twentylstmstderror = []

predictedBLLabels = []
predictedBRLabels = []
predictedBRLLabels = []
predictedBRRLabels = []
predictedBRPLabels = []
predictedRWLabels = []
print "1st Iteration, noiseless test data"
offset = 100
accuracyOverall = []
for testnumber in range(30):    
    start = randint(8000,9980)
    x = tdnnclassifier.activate(BallLiftJoint[start:start+10].flatten())
    predictedBLLabels.append(argmax(x))
    
    start = randint(8000,9980)
    x = tdnnclassifier.activate(BallRollJoint[start:start+10].flatten())
    predictedBRLabels.append(argmax(x))
    
    start = randint(8000,9980)
    x = tdnnclassifier.activate(BellRingLJoint[start:start+10].flatten())
    predictedBRLLabels.append(argmax(x))
    
    start = randint(8000,9980)
    x = tdnnclassifier.activate(BellRingRJoint[start:start+10].flatten())
    predictedBRRLabels.append(argmax(x))
    
Exemplo n.º 45
0
def spawn_tile():
    return SPAWN_CHANCE_LIST[randint(0, len(SPAWN_CHANCE_LIST))]
Exemplo n.º 46
0
    def __init__(self, input=None, n_visible=784, n_hidden=500, no_bias=False, non_linearity="sigmoid"):
        """
        Initialize the dA class by specifying the number of visible units (the
        dimension d of the input ), the number of hidden units ( the dimension
        d' of the latent or hidden space ) and the corruption level. The
        constructor also receives symbolic variables for the input, weights and
        bias. Such a symbolic variables are useful when, for example the input
        is the result of some computations, or when weights are shared between
        the dA and an MLP layer. When dealing with SdAs this always happens,
        the dA on layer 2 gets as input the output of the dA on layer 1,
        and the weights of the dA are used in the second stage of training
        to construct an MLP.

        :type input: theano.tensor.TensorType
        :param input: a symbolic description of the input or None for
                      standalone dA

        :type n_visible: int
        :param n_visible: number of visible units

        :type n_hidden: int
        :param n_hidden:  number of hidden units

        :type continuous_corruption: bool
        :param continuous_corruption: instead of just zeroing out randomly-chosen elements, scale all the
            1-valued inputs randomly to floats chosen uniformly in the range (1-corruption_level) to 1.

        """
        self.n_visible = n_visible
        self.num_features = n_visible  # Alias
        self.n_hidden = n_hidden
        self.non_linearity = non_linearity

        if non_linearity == "sigmoid":
            self.activation_fn = T.nnet.sigmoid
            self.inverse_activation_fn = lambda x: T.log(x / (1-x))
        elif non_linearity == "tanh":
            self.activation_fn = T.tanh
            self.inverse_activation_fn = T.arctanh
        else:
            raise ValueError("unkown non-linearity '%s'. Must be 'sigmoid' or 'tanh'" % non_linearity)

        # create a Theano random generator that gives symbolic random values
        theano_rng = RandomStreams(randint(2 ** 30))

        # note : W' was written as `W_prime` and b' as `b_prime`
        # W is initialized with `initial_W` which is uniformely sampled
        # from -4*sqrt(6./(n_visible+n_hidden)) and
        # 4*sqrt(6./(n_hidden+n_visible))the output of uniform if
        # converted using asarray to dtype
        # theano.config.floatX so that the code is runable on GPU
        initial_W = numpy.asarray(
            uniform(
                low=-numpy.sqrt(6. / (n_hidden + n_visible)),
                high=numpy.sqrt(6. / (n_hidden + n_visible)),
                size=(n_visible, n_hidden),
            ),
            dtype=theano.config.floatX
        )
        W = theano.shared(value=initial_W, name='W', borrow=True)

        bvis = theano.shared(
            value=numpy.zeros(
                n_visible,
                dtype=theano.config.floatX
            ),
            borrow=True
        )

        bhid = theano.shared(
            value=numpy.zeros(
                n_hidden,
                dtype=theano.config.floatX
            ),
            name='b',
            borrow=True
        )

        self.W = W
        # b corresponds to the bias of the hidden
        self.b = bhid
        # b_prime corresponds to the bias of the visible
        self.b_prime = bvis
        # tied weights, therefore W_prime is W transpose
        self.W_prime = self.W.T
        self.theano_rng = theano_rng
        # if no input is given, generate a variable representing the input
        if input is None:
            # we use a matrix because we expect a minibatch of several
            # examples, each example being a row
            self.x = T.dmatrix(name='input')
        else:
            self.x = input
        self.x_as_int = T.cast(self.x, "int8")

        if no_bias:
            # Don't include a bias in the network
            # The bias still features in the equations, but isn't include among the params, so doesn't get updated
            # It therefore retains its initial values: 0
            self.params = [self.W]
        else:
            self.params = [self.W, self.b, self.b_prime]

        self.hidden_layer = self.get_hidden_values(self.x)

        self._b_copy = None
        self._b_prime_copy = None
        self._hidden_fn = None
        self._probs_fn = None
Exemplo n.º 47
0
def can_spawn_crafting_chest():
    return randint(0, CHUNK_SIZE * CHUNK_SIZE) < 5
Exemplo n.º 48
0
import Queue
import unittest
from main.model.Game import Game
from main.model.Robot import Robot
import mock
from main.states.NearResistanceState import NearResistanceState
from main.states.NearLetterBoardState import NearLetterBoardState
from numpy.random.mtrand import randint
from main.model.Puck import Puck

RANDOM_COLOR_CODE = randint(0,9)

class NearLetterBoardStateTest(unittest.TestCase):

    def setUp(self):
        Robot.initHardwareDevices = mock.Mock(return_value="")
        Robot.rotateToAngle = mock.Mock(return_value="")
        Robot.findLetterInLetterBoard = mock.Mock(return_value="D")
        Robot.setCamMiddle = mock.Mock(return_value="")
        Robot.setCamUp = mock.Mock(return_value="")
        NearResistanceState.fetchResistance = mock.Mock(return_value="")
        self.robot = Robot(Queue.Queue())
        self.aGame = Game(self.robot, Queue.Queue())
        self.aGame.currentState = NearLetterBoardState(self.aGame)
        self.aGame.listOfPucks = [Puck(RANDOM_COLOR_CODE), Puck(RANDOM_COLOR_CODE), Puck(RANDOM_COLOR_CODE)]
        self.aGame.setPositionToReadInLetterBoard(2)

    def test_whenGameDoAnActionStateGameStateShouldChangeAtTheEnd(self):
        self.aGame.doAction()
        self.assertTrue(self.aGame.getCurrentStateName() == "HasReadLetterBoardState")
        
Exemplo n.º 49
0
 def __init__(self, x=50, y=50, ttl=10):
     self.x = x
     self.y = y
     self.lastUpdate = time.time() * 1000
     self.endTime = time.time() * 1000 + (ttl * 1000)
     self.color = (randint(255), randint(255), randint(255))