Пример #1
0
def generate_Heart(period, i, decay):
    x_0 = np.randint(0, 1)
    y_0 = np.randint(0, 1)
    d = np.uniform(0.01, 0.1)
    t = i
    dd = list()
    zz = list()
    for t in range(1000):
        t = t / 1000.0
        t = 2 * pi * t / period
        x = 16 * pow(np.sin(t), 3)
        y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(
            4 * t)
        dd.append(y)
        zz.append(x)
    miy = min(dd)
    mix = min(zz)
    may = max(dd)
    maxx = max(zz)

    i = 2 * pi * i / period
    x = 16 * pow(np.sin(i), 3)
    y = 13 * np.cos(i) - 5 * np.cos(2 * i) - 2 * np.cos(3 * i) - np.cos(4 * i)

    x = (x - mix) / (maxx - mix)
    y = (y - miy) / (may - miy)

    return [x, y]
Пример #2
0
def make_fibrous_image(shape,
                       nfibers=300,
                       l=300,
                       a=0.2,
                       stepsize=0.5,
                       limits=(0.1, 1.0),
                       blur=1.0):
    h, w = shape
    lo, hi = limits
    result = np.zeros(shape)
    for i in range(nfibers):
        v = pylab.rand() * (hi - lo) + lo
        fiber = make_fiber(l, a, stepsize=stepsize)
        y, x = np.randint(0, h - 1), np.randint(0, w - 1)
        fiber[:, 0] += y
        fiber[:, 0] = np.clip(fiber[:, 0], 0, h - .1)
        fiber[:, 1] += x
        fiber[:, 1] = np.clip(fiber[:, 1], 0, w - .1)
        for y, x in fiber:
            result[int(y), int(x)] = v
    result = ndi.gaussian_filter(result, blur)
    result -= np.amin(result)
    result /= np.amax(result)
    result *= (hi - lo)
    result += lo
    return result
Пример #3
0
 def eval_pos(self, state):
     win = 0
     tot = 10
     for qq in range(tot):
         cur_state = state[:]
         moves = self.get_moves(cur_state, self.tag)
         moves_op = self.get_moves(cur_state, self.op_tag)
         while not moves_op.empty() and not moves.empty():
             ind = np.randint(len(moves_op))
             i, j, dr = moves_op[ind]
             game_won = 0
             while not self.valid_move(cur_state, i, j, dr, self.op_tag):
                 del moves_op[ind]
                 if moves_op.empty():
                     game_won = 1
                     break
                 ind = np.randint(len(moves_op))
                 i, j, dr = moves_op[ind]
             if game_won == 1:
                 win += 1
                 break
             cur_state = self.make_move(cur_state, self.op_tag)
             ind = np.randint(len(moves))
             i, j, dr = moves[ind]
             while not self.valid_move(cur_state, i, j, dr, self.tag):
                 del moves[ind]
                 if moves.empty():
                     break
                 ind = np.randint(len(moves))
                 i, j, dr = moves[ind]
     return win/tot
Пример #4
0
 def rand_state(self, xrange, yrange):
     """在指定范围内随机设置潜艇位置,重置速度、加速度"""
     self.__position.x = np.randint(*xrange)
     self.__position.y = np.randint(*yrange)
     self.velocity = (0, 0)
     self.acceleration = (0, 0)
     return self.__position
def sample_params(k1=None, k2=None, d1=None, d2=None):
    '''
    Samples random parameters, with the possibility of keeping certain ones
    fixed.
    '''

    k1 = k1 or np.randint(16, 32)
    k2 = k2 or np.randint(16, 64)
    d1 = d1 or np.randint(32, 128)
    d2 = d2 or np.randint(32, 64)
Пример #6
0
def game_init():
    if CONFIG_PLAYER_ENABLE:
        inst = instance(0, 1, 1, True)
        instances.append(inst)
        for i in range(CONFIG_INSTANCE_COUNT - 1):
            inst = instance(i + 1, np.randint(area_w), np.randint(area_h))
            instances.append(inst)
    else:
        for i in range(CONFIG_INSTANCE_COUNT):
            inst = instance(i, np.randint(area_w), np.randint(area_h))
            instances.append(inst)
Пример #7
0
def sample_data(data_dir, n_speaker, n_frame):
    # TODO
    f_speaker = os.listdir(data_dir)
    rand_list = get_rand_list(n_speaker, len(f_speaker))
    chosen_speakers = [f_speaker[idx] for idx in rand_list]
    wave_files = []
    for speaker in chosen_speakers:
        now_path = os.path.join(data_dir, speaker)
        total_frame = []
        for (root, dirs, files) in os.walk(now_path):
            total_frame += [root + f for f in files]
        rand_list = get_rand_list(n_frame, len(total_frame))
        frame_list = [total_frame[i] for i in rand_list]
        wave_files += frame_list

    data = []
    for name in wave_files:
        wav = scipy.io.wavfile.read(name)  #read the waveform
        #TODO
        frames = mfcc(wav)  #turn waveform to spectrogram

        frame = frames[np.randint(len(frames))]  #select a frame in spectrogram
        data.append(frame)

    data = np.array(data)
    #label = np.array(label)
    label = np.repeat(range(n_speaker), n_frame)
    return data, label
Пример #8
0
def npc_turn():
    #Empty list for coterie matchup
    global battle_queue
    battle_queue = []

    #Iterate through NPCs
    for i in range(0, len(player_list - 1)):
        while player_list[i].actions > 0:
            #If NPC is playing as Red Queen
            if player_list[i].hand[0].card_id == 11:
                action = numpy.randint(1, 5)
                npc_action(action)
            #If NPC is playing as anyone else
            elif True:
                action = numpy.randint(0, 2)
                npc_action(action)
Пример #9
0
def gen_fake_graph(n_entities, n_edges_approx):
    from numpy.random import randint
    edges1 = numpy.randint(0, n_entities, n_edges_approx)
    edges2 = numpy.oneslike(edges1)
    for i in range(len(edges2)):
        edges2[i] = randint(edges1[i] + 1, n_entities)
    return [edges1, edges2]
Пример #10
0
    def __init__(self, n_trees=1, max_leaf_size=10, max_labels_per_leaf=20,
            re_split=0, n_jobs=1, alpha=1e-4, n_epochs=2, bias=True,
            subsample=1, loss='log', sparse_multiple=25, leaf_classifiers=False,
            gamma=30, blend=0.8, leaf_eps=1e-5, verbose=False, seed=2016):

        self.n_trees = n_trees
        self.max_leaf_size = max_leaf_size
        self.max_labels_per_leaf = max_labels_per_leaf
        self.re_split = re_split
        self.n_jobs = n_jobs if n_jobs > 0 else (multiprocessing.cpu_count() + 1 + n_jobs)
        self.alpha = alpha

        if isinstance(seed, np.random.RandomState):
            seed = np.randint(0, np.iinfo(np.int32).max)

        self.seed = seed
        self.n_epochs = n_epochs
        self.verbose = verbose
        self.bias = bias
        self.subsample = subsample
        self.loss = loss
        self.sparse_multiple = sparse_multiple
        self.leaf_classifiers = leaf_classifiers
        self.gamma = gamma
        self.blend = blend
        self.leaf_eps = leaf_eps
        self.roots = []
Пример #11
0
 def masked_gen(self, mode='train'):
     while True:
         posgen = self.pos_training_gen(mode=mode)
         for p in posgen:
             start_index = np.randint(len(p) - FLAGS.mutmask_size)
             p[start_index:start_index + FLAGS.mutmask_size] = 'x'
             yield p
def incrementPitchset(startPitchset, endPitchset, numsteps):
	extraPitches = np.array([])
	pitchesAtStart = False # tracks where our extra pitches are
	# make sure they're the same length
	while len(endPitchset) > len(startPitchset):
		i = np.randint(0,len(endPitchset))
		extraPitches.append(endPitchset[i])
		endPitchset = np.delete(endPitchset, i)
	while len(startPitchset) > len(endPitchset):
		i = np.random.randint(0,len(startPitchset))
		np.append(extraPitches, startPitchset[i])
		startPitchset = np.delete(startPitchset, i)
		pitchesAtStart = True
	# create the list of pitchsets
	retval = np.empty((numsteps, len(startPitchset)))
	retval[0] = startPitchset
	retval[-1] = endPitchset
	# fill them in
	for i in range(1, len(startPitchset)-1):
		retval[:,i]=interpolateNumbers(startPitchset[i],endPitchset[i], numsteps)
	# insert back in the extra pitches
	for i in range(len(extraPitches)):
		if pitchesAtStart:
			n = int(np.absolute(np.random.normal(0, 1)))
			np.append(retval[0:n],extraPitches[i])
		else:
			n = len(retval)-int(np.absolute(np.random.normal(0,1)))
			np.append(retval[n:],extraPitches[i])
	return retval
Пример #13
0
def randomized(file,links,trait_dict,node_gens,focus,coloring, colors='red',traits = None):
    node_list = []
    edge_list = []

    for tup in links:
        x = random()
        if x <= .12:
            if isinstance(colors,dict):
                # random color
                color_keys = colors.keys()
                i = np.randint(len(color_keys))
                trait = color_keys[i]
            else:
                trait = None

            if focus == 'nodes' or focus == 'both':
                string = coloring(tup,trait,colors,'nodes')
                node_list.append(string)
           
            # don't color the edge  
            if focus == 'nodes':
                string = color_edges(tup,'grey')
                edge_list.append(string)
            
            # also color the edge
            if focus == 'edges' or focus == 'both':
                string = coloring(tup,trait,colors,'edges')
                edge_list.append(string)

        # base edge
        else:
            string = color_edges(tup,'grey')
            edge_list.append(string)

    write_nedges(file,node_list,edge_list)
Пример #14
0
def layerModes():
    N = mypaintlib.TILE_SIZE

    dst = np.zeros((N, N, 4), 'uint16')  # rgbu
    dst_values = []
    r1 = range(0, 20)
    r2 = range((1 << 15)/2-10, (1 << 15)/2+10)
    r3 = range((1 << 15)-19, (1 << 15)+1)
    dst_values = r1 + r2 + r3

    src = np.zeros((N, N, 4), 'int64')
    alphas = np.hstack((
        np.arange(N/4),                     # low alpha
        (1 << 15)/2 - np.arange(N/4),       # 50% alpha
        (1 << 15) - np.arange(N/4),         # high alpha
        np.randint((1 << 15)+1, size=N/4),  # random alpha
        ))
    #plot(alphas); show()
    src[:, :, 3] = alphas.reshape(N, 1)  # alpha changes along y axis

    src[:, :, 0] = alphas  # red
    src[:, N*0/4:N*1/4, 0] = np.arange(N/4)  # dark colors
    src[:, N*1/4:N*2/4, 0] = alphas[N*1/4:N*2/4]/2 + np.arange(N/4) - N/2  # 50% lightness
    src[:, N*2/4:N*3/4, 0] = alphas[N*2/4:N*3/4] - np.arange(N/4)  # bright colors
    src[:, N*3/4:N*4/4, 0] = alphas[N*3/4:N*4/4] * np.random(N/4)  # random colors
    # clip away colors that are not possible due to low alpha
    src[:, :, 0] = np.minimum(src[:, :, 0], src[:, :, 3]).clip(0, 1 << 15)
    src = src.astype('uint16')

    #figure(1)
    #imshow(src[:,:,3], interpolation='nearest')
    #colorbar()
    #figure(2)
    #imshow(src[:,:,0], interpolation='nearest')
    #colorbar()
    #show()

    src[:, :, 1] = src[:, :, 0]  # green
    src[:, :, 2] = src[:, :, 0]  # blue

    for name in dir(mypaintlib):
        if not name.startswith('tile_composite_'):
            continue
        junk1, junk2, mode = name.split('_', 2)
        print('testing', name, 'for invalid output')
        f = getattr(mypaintlib, name)
        for dst_value in dst_values:
            for alpha in [1.0, 0.999, 0.99, 0.90, 0.51, 0.50, 0.49, 0.01, 0.001, 0.0]:
                dst[:] = dst_value
                dst_has_alpha = False
                src_opacity = alpha
                f(src, dst, dst_has_alpha, src_opacity)
                #imshow(dst[:,:,0], interpolation='nearest')
                #gray()
                #colorbar()
                #show()
                errors = dst > (1 << 15)
                assert not errors.any()
        print('passed')
Пример #15
0
 def mutant_gen(self, mode='train'):
     while True:
         posgen = self.pos_training_gen(mode=mode)
         for p in posgen:
             rand_indecies = [np.randint(len(p)) for i in FLAGS.num_mutations]
             for index in rand_indecies:
                 p[index] = np.random.choice(['a', 'c', 'g', 't'])
             yield p 
Пример #16
0
 def act(self, environment=self.envir):
     action = self.Q.argmax() if np.random.uniform(
         0, 1) > self.epsilon else np.randint(len(self.Q))
     reward, optimal = environment.feedback(action)
     self.visit[action] += 1
     self.Q[action] += 1.0 / self.visit[action] * (reward - self.Q[action])
     super().update(action, reward, optimal)
     return self.avg_reward, self.optimal_rate, action, optimal
Пример #17
0
 def sample_batch(self):
     move_sum = float(sum(len(g.history) for g in self.buffer))
     games = np.random.choice(
         self.buffer,
         size=self.batch_size,
         p=[len(g.history) / move_sum for g in self.buffer])
     game_pos = [(g, np.randint(len(g.history))) for g in games]
     return [(g.make_image(i), g.make_target(i)) for (g, i) in game_pos]
Пример #18
0
 def __init__(self, name, price=10, weight=20,
              flammability=0.5,
              identifier=randint(1000000, 10000000)):
     self.name = str(name)
     self.price = int(price)
     self.weight = int(weight)
     self.flammability = float(flammability)
     self.identifier = identifier
Пример #19
0
def preprocess_for_train(image,height,width,bbox):
    if bbox is None:#标注框没定义的话就取全图片
        bbox = tf.constant([0.0,0.0,1.0,1.0],dtype=tf.float32,shape=[1,1,4])
    if image.dtype != tf.float32#转换图像像素值类型
        image = tf.convert_image_dtype(image, dtype=tf.float32)
    bbox_begin,bbox_size,_ = tf.image.sample_distorted_bounding_box(tf.shape(image),bounding_boxes=bbox)#随机截取图像
	
    distort_image = tf.slice(image, bbox_begin, bbox_size)
	distorted_image = tf.image.resize_images(distort_image,[height,width],method=np.randint(4))#调整图像大小为神经网络的输入大小
Пример #20
0
def Createdataset(number=1):
    Output = []

    for i in range(number):
        rng = pd.date_range(start='1/1/2016', end='12/31/2016', freq='W-MON')
        data = np.randint(low=25, high=1000, size=len(rng))
        status = [1, 2, 3]
        random_status = [
            status[np.randint(low=0, high=len(status))]
            for i in range(len(rng))
        ]
        states = ['GA', 'FL', 'fl', 'NY', 'NJ', 'TX']
        random_states = [
            states[np.randint(low=0, high=len(states))]
            for i in range(len(rng))
        ]
        Output.extend(zip(random_states, random_status, data, rng))
    return Output
Пример #21
0
def _crossover(parent, otherParent, grid, get_fitness):
    childGenes = parent[:]

    if len(parent) <= 2 or len(otherParent) < 2:
        childGenes[1] = otherParent[1]
    else:
        length = np.randint(1, high=len(parent) - 2)
        start = np.randint(0, high=len(parent) - length)
        childGenes[start:start + length] = otherParent[start:start + length]

    fitness = get_fitness(childGenes)
    x, y, grid = create_coordinates(grid)

    if x != -1 and y != -1:
        # print("crossover")
        return Chromosome(childGenes, fitness, x, y, 0), grid
    else:
        return None, grid
Пример #22
0
def generate_real_samples(dataset, n_samples):
    # split into images and labels
    images, labels = dataset
    # choose random instances
    ix = np.randint(0, images.shape[0], n_samples)
    # select images and labels
    X, labels = images[ix], labels[ix]
    # generate class labels
    y = np.ones((n_samples, 1))
    return [X, labels], y
Пример #23
0
 def get_mock_data(self):
     signals = np.linspace(0, 4*np.pi, 10000)
     rand_idx = np.randint(6000)
     lgth = np.randint(1000, 3000)
     signals = signals[rand_idx:rand_idx+lgth]
     # ttd[-100:] = 1
     signals = np.vstack([signals]*8)
     signals = signals.T
     signals[:, 0] = 0.5 + 0.5*np.sin(signals[:, 0])
     signals[:, 1] = 0.5  # + 0.5*cos(signals[:,1])
     signals[:, 2] = 0.5 + 0.5*np.sin(2*signals[:, 2])
     signals[:, 3:] *= 0
     offset = 100
     ttd = 0.0*signals[:, 0]
     ttd[offset:] = 1.0*signals[:-offset, 0]
     mask = ttd > np.mean(ttd)
     ttd[~mask] = 0
     # mean(signals[:,:2],1)
     return signals, ttd
Пример #24
0
def generate_latent_points(latent_dim, n_samples, n_attributes):
    # generate points in the latent space
    x_input = np.randn(latent_dim * n_samples)
    # reshape into a batch of inputs for the network
    z_input = x_input.reshape(n_samples, latent_dim)
    # generate labels
    labels = []
    for _ in range(n_samples):
        labels.append(np.randint(0, 2, n_attributes))
    return [z_input, labels]
Пример #25
0
def next_frame(last_step, last_frame, column):
    # define the scope of the next step
    lower = max(0, last_step - 1)
    upper = min(last_frame.shape[0] - 1, last_step + 1)
    # choose the row index for the next step
    step = np.randint(lower, upper)
    # copy the prior frame
    frame = last_frame.copy()
    # add the new step
    frame[step, column] = 1
    return frame, step
Пример #26
0
    def generate_trial(self, generation, donor_vector):
        list_of_trialvectors = []
        random_index_j = np.randint(0, len(generation))

        #once for every target vector
        for i in generation:
            if np.random(
            ) <= self.Cr or random_index_j == i:  #we take the donor vector
                list_of_trialvectors.append(donor_vector[i])
            else:  # we just take the old vector
                list_of_trialvectors.append(generation[i])
Пример #27
0
def crit_outflow_degruyter():
    """
    Specify the conditions for eruptions according to Degruyter 2014 model
    Pc = critical overpressure
    eta_x = crystal volume fraction
    M_out_rate is the mass outflow rate
    """
    delta_Pc = np.randint(10,50) # assume a critical overpressure btw 10 - 50 MPa
    eta_x = 0.5 # based on cystal locking above 50 % packing ..
    M_out_rate = 1e4 # kg/s
    return delta_Pc,eta_x,M_out_rate
Пример #28
0
def generate_examplesX(length, n_patterns, output):
    X, y = list(), list()
    for _ in range(n_patterns):
        p = np.randint(10, 20)
        d = np.uniform(0.01, 0.1)
        sequence = [0, 1]  # generate_sequenceDampedSin(length + output, p, d)
        X.append(sequence[:-output])
        y.append(sequence[-output:])
    X = np.array(X).reshape(n_patterns, length, 1)
    y = np.array(y).reshape(n_patterns, output)
    return X, y
Пример #29
0
def nomad_tweet(handle):
    config = ConfigParser.ConfigParser()
    sect = "twitter"
    print("Posting to twitter...")
    auth = tweepy.OAuthHandler(client_key, client_secret)
    auth.set_access_token(user_key, user_secret)
    api = tweepy.API(auth)
    trolls = np.genfromtxt("trollolol.txt", dtype=str)
    sent = "%s %s" % (handle, trolls[np.randint(0, len(trolls))])
    print sent
#     time.sleep(5*60)
    api.update_status(sent)
Пример #30
0
def basic_sketch(epsilon, M, datastream):
	# Initialize 
	k = 3/(epsilon**2)
	C = [0] * k
	p = find_next_prime(M)
	p2 = 3
	a = numpy.randint(0, M, 1) % p
	b = numpy.randint(0, 2, 1) % p
	# Choose a random hash function h : [n] -> [k], 2-universal 
	h = lambda x: ((a * x) % p) % M
	# Choose a random hash function g : [n] ->  {-1,1}, 2-universal 
	g = lambda x: ((b * x) % p) % M
	# Process
	# Because we're considering ints, the count of a token is always one
	_c = 1
	
	for data in datastream:
		C[h(j)] = C[h(j)] + _c * g(j)
	# Output 
	# One query a, report f_hat_a = g(a)C[h(a)] 
	return C, g, h
Пример #31
0
def _with_replace(origin_list, output_dir, req_num):
    labels = set([])
    for path_label in origin_list:
        path, label = path_label
        labels.add(label)
    for label in labels:
        os.makedirs(osp.join(output_dir,label))
    inds = np.randint(0,len(origin_list),size = req_num)
    for num, ind in enumerate(inds):
        src, label = origin_list[ind]
        dst = osp.join( osp.join(output_dir,label) , '{}'.format(num))
        shutil.copyfile(src,dst)
Пример #32
0
def backtrap(matrix, len_read, len_gen, read, genome) :
    score = max(matrix[len_read])
    score_index = np.nonzero(matrix[len_read] == score)[0]
    len_score = len(score_index)
    op = []

    i = len_read
    
    # Si plusieurs max
    if (len_score > 1) :
        j = score_index[np.randint(1, len_score-1)] 
    else :
        j = score_index
    print "SCORE %d" % score
    print "BACKTRAP : "
    print("score_index : %d"%score_index)
    tmp = len_gen

    while (tmp > j) :
        op.append(INS)
        tmp -= 1

    while (i!=0 and j!=0) :
        if ((matrix[i][j]-match == matrix[i-1][j-1]) and (genome[j-1] == read[i-1])):
            i -= 1
            j-= 1
            op.append(MATCH)
            print("MATCH")
        elif (matrix[i][j]-mis == matrix[i-1][j-1]) :
            i -= 1
            j -= 1
            op.append(MIS)
            print("MIS")
        elif (matrix[i][j]-indel == matrix[i-1][j]) :
            i -= 1
            op.append(DEL)
            print("DEL")
        elif (matrix[i][j]-indel == matrix[i][j-1]) :
            j -= 1
            op.append(INS)
            print("INS")
        else : 
            print("OTHER %d "% i) 
            return
        print("%d - %d : %d" % (i, j, matrix[i][j]))
    '''
    if j > 0 :
        while j > 0 :
            op.append(INS)
            j -= 1
    '''
    return op
Пример #33
0
    def is_prime(n):
        """
            Checks whether n is prime.
        :param n:   Value to check primality.
        :type n:    int
        :return:    False  if n is composite, otherwise
                    True   (probably prime).
        :rtype:     bool
        Notes
            May return True even though n is composite.
            Probability of such event is not greater than 1 / n**2.
        Time complexity
            O(log(n)**3)
        References
            https://en.wikipedia.org/wiki/Miller–Rabin_primality_test
        """

        if n == 2 or n == 3:
            return True
        elif n == 1 or n % 2 == 0:
            return False

        d = n - 1
        r = 0
        while d % 2 == 0:  # n - 1 = d * 2**r, d - odd
            r += 1
            d >>= 1

        for i in range(r):
            a = np.randint(2, n)

            x = pow(a, d, n)  # x = (a**d) % n

            if x == 1 or x == n - 1:
                continue

            stop = False
            j = 0
            while j < r - 1 and not stop:
                x = pow(x, 2, n)

                if x == 1:
                    return False
                if x == n - 1:
                    stop = True

                j += 1

            if not stop:
                return False

        return True
Пример #34
0
def tileConversions():
    # fully transparent tile stays fully transparent (without noise)
    N = mypaintlib.TILE_SIZE
    src = np.zeros((N, N, 4), 'uint16')
    dst = np.ones((N, N, 4), 'uint8')
    mypaintlib.tile_convert_rgba16_to_rgba8(src, dst)
    assert not dst.any()
    # fully opaque tile stays fully opaque
    src[:, :, 3] = 1 << 15
    src[:, :, :3] = np.randint(0, 1 << 15, (N, N, 3))
    dst = np.zeros((N, N, 4), 'uint8')
    mypaintlib.tile_convert_rgba16_to_rgba8(src, dst)
    assert (dst[:, :, 3] == 255).all()
Пример #35
0
def mutation(q, K, F, N):

    from extras import get_limits

    n = len(q[0])
    qNew = np.zeros(q.shape)
    f = min(F)
    for j in range(1, q.shape[1] + 1):
        # To do the mutation, the task MUST BE DISCOVERED and
        # NOT BE the BEST.
        if K[j] and (not F[j] == f):
            # Select the number of tasks to swap
            M = np.randint(n)
            for m in range(1, M + 1):
                # Select the task to swap
                Q = q[j]
                i = np.randint(max(Q))
                idxI = buscar(Q == i)
                [Pred, Sucs] = get_limits(N, i, Q)
                idxPos = search_index(Pred, Sucs, Q)
                # NOTA: Esta operacion no genera soluciones inviables
                if idxPos > idxI:
                    qNew[j] = [
                        q[j][:idxI - 1], q[j][idxPos],
                        q[j][idxI + 1:idxPos - 1], q[j][idxI],
                        q[j][idxPos + 1:]
                    ]
                elif idxPos < idxI:
                    qNew[j] = [
                        q[j][:idxPos - 1], q[j][idxI],
                        q[j][idxPos + 1:idxI - 1], q[j][idxPos],
                        q[j][idxI + 1:]
                    ]
                else:
                    qNew[j] = q[j]
        else:
            qNew[j] = q[j]

    return qNew
Пример #36
0
def tileConversions():
    # fully transparent tile stays fully transparent (without noise)
    N = mypaintlib.TILE_SIZE
    src = np.zeros((N, N, 4), 'uint16')
    dst = np.ones((N, N, 4), 'uint8')
    mypaintlib.tile_convert_rgba16_to_rgba8(src, dst)
    assert not dst.any()
    # fully opaque tile stays fully opaque
    src[:, :, 3] = 1 << 15
    src[:, :, :3] = np.randint(0, 1 << 15, (N, N, 3))
    dst = np.zeros((N, N, 4), 'uint8')
    mypaintlib.tile_convert_rgba16_to_rgba8(src, dst)
    assert (dst[:, :, 3] == 255).all()
Пример #37
0
def jackknife_variance(func,data,N=None,args=()):
    estimate = func(data,*args)
    
    if N is None:
        N = data.size
        omit_points = np.arange(N)
    else:
        omit_points = np.randint(0,data.size,N)
    
    other_estimates = np.empty(N)    
    
    for i in range(N):
        other_estimates[i] = func(np.delete(data,i),*args)
        
    return (data.size-1)/N * np.sum((estimate-other_estimates)**2)
Пример #38
0
def sample(elements, n, replace=False):    
    n_elem = len(elements)

    if n > n_elem and replace == False:
        raise ValueError("cannot sample %d elements "
                         "without replacement from list of "
                         "%d elements" % (n, n_elem))

    if replace:
        # get random indices into list of elements(repeated values allowed)
        idx = np.randint(0, n_elem, n)
    else:
        # get randomly permuted indices into list of elements
        idx = np.random.permutation(n_elem)
    
    # take elements corresponding to first n permutted indices
    return [elements[i] for i in idx[0:n]]
Пример #39
0
 def random_position(self):
     return [np.randint(0, self.size[0]), np.randint(0, self.size[1])]
Пример #40
0
                if isinstance(l1, list) and isinstance(l2, list):
                    res = cmp_sort(l1,l2)
                elif isinstance(l1, types) and isinstance(l2, types):
                    res = swap_cmp(l1, l2)
                tmp_list.append(res)
            elif isinstance(l1, list):
                tmp_list.append(l1)
            elif isinstance(l1, types):
                tmp_list.append([l1])
        l = tmp_list
        ln = len(l)
        #print "after merge iteration: {}".format(l)
    #del tmp_list, res, l1, l2, ln, levels
    return l[0], grand_count*it_count

if __name__ == "__main__":

    tmp = []
    for _ in xrange(20):
        l=[randint(1,100) for _ in xrange(randint(1,20))]
        ln = len(l)
        res = merge_sort(l)
        #cmp nlogn VS. actual levels * counts time.
        tmp.append((ln, ln*log(ln,2), res[1]))
    print tmp
    tmp_arr = np.array(tmp).transpose()
    #cmp with nlogn
    plot(map(sorted, (tmp_arr[0], tmp_arr[1])))
    #cmp with the above solution iterations
    plot(map(sorted, (tmp_arr[0], tmp_arr[2])))
Пример #41
0
def random_site( seq_length, model_length ):
    return Site(
            start = numpy.randint( seq_length - model_length ),
            rev_comp = numpy.uniform() > 0.5,
            length = model_length
    )
def gnss_observations(t, XS_tx, VS_tx, Xr_M, Vr_M, Xr_R, Vr_R):
    Xb0 = Xr_M - Xr_R
    nsat = len(global_gpsConfig.sign_set_prnmat)
    gnss_obs = GNSSObservations(np.zeros((nsat, global_gpsConfig.sign_set_data_length)))
    for i in range(nsat):
        for j in range(global_gpsConfig.sign_set_data_length):
            gnss_obs.R1_M[i, j] = np.sqrt(
                (XS_tx[i, :].T - Xr_M).T * (XS_tx[i, :].T - Xr_M))
            gnss_obs.e1_M[i, :, j] = (XS_tx[i, :] - Xr_M.T) / gnss_obs.R1_M(i, j)
            gnss_obs.pr1_M[i, j] = gnss_obs.R1_M[
                                       i, j] + global_gpsConfig.sign_set_phase * global_gpsConfig.sign_set_code * np.random.randint()
            gnss_obs.pr2_M[i, j] = gnss_obs.pr1_M(i, j)

            gnss_obs.ph1_M[i, j] = gnss_obs.R1_M[i, j] / global_gpsConfig.sign_set_g_bo1 - math.floor[
                gnss_obs.R1_M[
                    i, j] / global_gpsConfig.sign_set_g_bo1] + global_gpsConfig.sign_set_phase * global_gpsConfig.sign_set_g_bo1 * np.randint()

            gnss_obs.N1_M[i, j] = floor[
                gnss_obs.R1_M[i, j] / global_gpsConfig.sign_set_g_bo1]  # L1频点 整周模糊度
            gnss_obs.N2_M[i, j] = floor[
                gnss_obs.R1_M[i, j] / global_gpsConfig.sign_set_g_bo2]  # L2频点 整周模糊度

            gnss_obs.dop1_M[i, j] = np.matrix([Vr_M.T, -VS_tx[i, :]]) * gnss_obs.e1_M[i, :,
                                                                        j].T / global_gpsConfig.sign_set_c * global_gpsConfig.sign_set_l1  # 当卫星与接收机相对远离时,多普勒频移为负,载波相位测量值变大
            gnss_obs.dop2_M[i, j] = np.matrix([Vr_M.T - VS_tx[i, :]]) * gnss_obs.e1_M[i, :,
                                                                        j].T / global_gpsConfig.sign_set_c * global_gpsConfig.sign_set_l2
            gnss_obs.e1_Mx[i, j] = [XS_tx[i, 1] - Xr_M[1]] / gnss_obs.R1_M[i, j]
            gnss_obs.e1_My[i, j] = [XS_tx[i, 2] - Xr_M[2]] / gnss_obs.R1_M[i, j]
            gnss_obs.e1_Mz[i, j] = [XS_tx[i, 3] - Xr_M[3]] / gnss_obs.R1_M[i, j]
            # Rover 的L1、L2、L5频点伪距、载波相位观测值和整周模糊度、多普勒频移观测量
            gnss_obs.R1_R[i, j] = np.sqrt[
                [XS_tx[i, :].T - Xr_R].T * [XS_tx[i, :].T - Xr_R]]  # 卫星到流动站的距离
            gnss_obs.e1_R[i, :, j] = [XS_tx[i, :] - Xr_R.T] / gnss_obs.R1_R[
                i, j]  # 卫星到流动站的方向余弦
            gnss_obs.pr1_R[i, j] = gnss_obs.R1_R[
                                       i, j] + global_gpsConfig.sign_set_phase * global_gpsConfig.sign_set_code * np.randint()  # 流动站伪距观测量    ???
            gnss_obs.pr2_R[i, j] = gnss_obs.pr1_R[i, j]

            gnss_obs.ph1_R[i, j] = gnss_obs.R1_R[i, j] / global_gpsConfig.sign_set_g_bo1 - floor[
                gnss_obs.R1_R[
                    i, j] / global_gpsConfig.sign_set_g_bo1] + global_gpsConfig.sign_set_phase * global_gpsConfig.sign_set_g_bo1 * np.randint()  # L1频点 载波相位观测值
            gnss_obs.ph2_R[i, j] = gnss_obs.R1_R[i, j] / global_gpsConfig.sign_set_l2 - floor[
                gnss_obs.R1_R[
                    i, j] / global_gpsConfig.sign_set_l2] + global_gpsConfig.sign_set_phase * global_gpsConfig.sign_set_l2 * np.randint()  # L2频点 载波相位观测值
            # ph5_R[i,j]  = R1_R[i,j]/sign_set.G_bo5 - floor[R1_R[i,j]/sign_set.G_bo5] + global_gpsConfig.sign_set_phase*sign_set.G_bo5*np.randint()    #L5频点 载波相位观测值

            gnss_obs.N1_R[i, j] = floor[
                gnss_obs.R1_R[i, j] / global_gpsConfig.sign_set_g_bo1]  # L1频点 整周模糊度
            gnss_obs.N2_R[i, j] = floor[
                gnss_obs.R1_R[i, j] / global_gpsConfig.sign_set_l2]  # L2频点 整周模糊度
            # N5_R[i,j]  =floor[R1_R[i,j]/sign_set.G_bo5]         #L5频点 整周模糊度

            gnss_obs.dop1_R[i, j] = np.matrix([Vr_R.T, -VS_tx[i, :]]) * gnss_obs.e1_R[i, :,
                                                                        j].T / global_gpsConfig.sign_set_c * global_gpsConfig.sign_set_l1  # 当卫星与接收机相对远离时,多普勒频移为负,载波相位测量值变大
            gnss_obs.dop2_R[i, j] = np.matrix([Vr_R.T, -VS_tx[i, :]]) * gnss_obs.e1_R[i, :,
                                                                        j].T / global_gpsConfig.sign_set_c * global_gpsConfig.sign_set_l2
            # dop5_R[i,j] = [Vr' -VS_tx[i,:]]*e1_R[i,j]/global_gpsConfig.sign_set_c*sign_set.L5
            gnss_obs.e1_Rx[i, j] = [XS_tx[i, 1] - Xr_R[1]] / gnss_obs.R1_R[i, j]
            gnss_obs.e1_Ry[i, j] = [XS_tx[i, 2] - Xr_R[2]] / gnss_obs.R1_R[i, j]
            gnss_obs.e1_Rz[i, j] = [XS_tx[i, 3] - Xr_R[3]] / gnss_obs.R1_R[i, j]
    return gnss_obs
Пример #43
0
import numpy as np
import scipy.misc

q_1 = np.zeros(8)
q_2 = np.ones(7)
q_3 = 5*np.ones(6)

r_1 = np.arange(6)
r_2 = np.arange(0,6,0.5)
r_3 = np.arange(5,-1,-1)

s_1 = []

t_1 = np.linspace(0,5,90)
t_2 = np.linspace(5,0,80)

u_1 = np.logspace(-2,2,9)
u_2 = np.log10(u_1)

v_1 = np.exp(np.arange(-2,4))
v_2 = np.log(v_1)

w_1 = 2**np.arange(0,11)
w_2 = 1 / 2**np.arange(0,6)

x_1 = scipy.misc.factorial(np.arange(0,7))

y_1 = np.rand(10)
y_2 = np.randn(10)
y_3 = np.randint(5,15, size = 10)