Пример #1
0
    def generate_random_objects(cls, count):
        rand_1 = random.randint(140, size=count)
        rand_2 = random.randint(140, size=count)
        rand_3 = random.randint(1100000000, 1100999999, size=count)
        rand_4 = random.randint(3, size=count)

        user_pk = User.objects.latest('pk').pk + 1
        generated_count = 0
        for i in range(0, count):
            first_name = first_names[rand_1.item(i)]
            last_name = last_names[rand_2.item(i)]
            student_id = rand_3.item(i)
            grade_level = rand_4.item(i)
            user = User.objects.create_user(
                username=user_pk,
                password=user_pk,
                first_name=first_name,
                last_name=last_name,
            )
            user_profile = UserProfile.objects.create(
                user=user,
                mobile='6787901506',
                is_student=True,
            )
            student_profile= StudentProfile.objects.create(
                user_profile=user_profile,
                student_id = student_id,
                grade_level=grade_level,
            )
            user_pk += 1
            generated_count += 1
            print('Generated StudentProfile %d (UserProfile %d User %d)' %(student_profile.pk, user_profile.pk, user.pk))
        return generated_count
Пример #2
0
 def setUp(self):
     self.ntime = 2048
     self.nfreq = 10
     self.data = sp.zeros((self.ntime, 4, self.nfreq))
     self.n_bins_cal = 64
     # Set channel dependant gain.
     self.level = 0.1*(self.nfreq + sp.arange(self.nfreq))
     # Add noise.
     self.data[:,:,:] += (0.1 * self.level
                          * rand.randn(self.ntime, 4, self.nfreq))
     # Add DC level.
     self.dc = 10 * self.level
     self.data += self.dc
     # First can transition.
     self.first_trans = rand.randint(0, self.n_bins_cal // 2)
     # The following randomly assigns self.neg to -1 or 1.
     self.neg = 0
     while not self.neg: self.neg = rand.randint(-1, 2)
     # First upward edge:
     if self.neg == 1:
         self.offset = self.first_trans
     else:
         self.offset = self.first_trans + self.n_bins_cal // 2
         self.data[:,0,:] += self.level
     for ii in range(self.ntime//self.n_bins_cal) :
         s = slice(self.first_trans + ii*self.n_bins_cal, self.first_trans +
                   (2*ii+1)*self.n_bins_cal//2)
         self.data[s, 0, :] += self.neg * self.level
     # Transition values and locations.
     self.t_slice = slice(self.first_trans, sys.maxint, self.n_bins_cal//2)
     self.t_vals = 0.5 + 0.1 * rand.randn(2*self.ntime//self.n_bins_cal,
                                          self.nfreq)
     self.t_vals *= - self.level
Пример #3
0
def pair_vectors(pairs, features, words, output_path):
    vectorizer = DictVectorizer()
    vectors = vectorizer.fit_transform(x[1] for x in features)

    vector_map = {word:vector for word, vector in
                  itertools.izip((x[0].split('/')[0] for x in features),
                                 vectors)}

    # Positive examples
    positive = []
    record = []
    for specific, general in pairs:
        positive.append(vector_map[general] - vector_map[specific])
        record.append( (specific, general, 1) )

    pair_set = set([tuple(x) for x in pairs])
    non_positive = []
    for i in range(len(positive)):
        first = second = None
        while first == second or (first, second) in pair_set:
            first = words[random.randint(len(words))]
            second = words[random.randint(len(words))]
        non_positive.append(vector_map[second] - vector_map[first])
        record.append( (first, second, 0) )
    
    data = vstack(positive + non_positive)
    target = [1]*len(positive) + [0]*len(non_positive)
    
    # Save dataset
    with open(os.path.join(output_path,'wn-noun-dependencies.mat'), 'wb') as data_file:
        dump_svmlight_file(data, target, data_file)

    with open(os.path.join(output_path,'wn-noun-dependencies.json'), 'w') as record_file:
        json.dump(record, record_file)
Пример #4
0
    def __trim_borders(self, x, target):
        y = x.reshape(3, 256, 256, x.shape[1])

        if self.test: # don't need to loop over cases
            if self.multiview:
                start_positions = [(0,0),  (0, self.border_size*2),
                                   (self.border_size, self.border_size),
                                  (self.border_size*2, 0), (self.border_size*2, self.border_size*2)]
                end_positions = [(sy+self.inner_size, sx+self.inner_size) for (sy,sx) in start_positions]
                for i in xrange(self.num_views/2):
                    pic = y[:,start_positions[i][0]:end_positions[i][0],start_positions[i][1]:end_positions[i][1],:]
                    target[:,i * x.shape[1]:(i+1)* x.shape[1]] = pic.reshape((self.get_data_dims(),x.shape[1]))
                    target[:,(self.num_views/2 + i) * x.shape[1]:(self.num_views/2 +i+1)* x.shape[1]] = pic[:,:,::-1,:].reshape((self.get_data_dims(),x.shape[1]))
            else:
                pic = y[:,self.border_size:self.border_size+self.inner_size,self.border_size:self.border_size+self.inner_size, :] # just take the center for now
                target[:,:] = pic.reshape((self.get_data_dims(), x.shape[1]))
        else:
            for c in xrange(x.shape[1]): # loop over cases
                #startY, startX = self.border_size, self.border_size 
                startY, startX = nr.randint(0,self.border_size*2 + 1), nr.randint(0,self.border_size*2 + 1)
                endY, endX = startY + self.inner_size, startX + self.inner_size
                pic = y[:,startY:endY,startX:endX, c]
                if nr.randint(2) == 0: # also flip the image with 50% probability
                    pic = pic[:,:,::-1]
                target[:,c] = pic.reshape((self.get_data_dims(),))
Пример #5
0
def read_new_file():
    global Xtest, Ytest, Ysig2, target, X, Y, thetaArgs, theta, EI, yoffset, hyperprior

    filename = filestem + str(rng.randint(10)) + '.txt'
    print 'This is %s' % (filename)
    data = np.loadtxt(filename)
    Xtest = data[:,0:-1] # everything except the last column
    target = data[:,-1]   # just the last column

    D = 1 # dimensionality of search space
    yoffset = 0.0 # to keep track of shifts up and down to y-axis
    initNumSamples = 2 # number of initial inputs
    #xlo,xhi =0.01,4.0 # just the plotting boundary, not a real constrait :(  
    #Xtest = np.arange(xlo,xhi,(xhi-xlo)/100.0) # the inputs we'll keep track of.
    d = len(np.ravel(Xtest))
    Xtest = Xtest.reshape((d,1))


    # take the initial samples
    X = np.zeros((initNumSamples)) 
    Y = np.zeros((initNumSamples,))
    for s in range(initNumSamples):
        i = rng.randint(0,d)
        X[s] = Xtest[i]
        Y[s] = target[i]
    initX,initY = X,Y

    # Here we initialise hyperparameters, and make initial predictions.
    (init_theta, hyperprior) = gp.setAndSampleHyperprior(D) # initial hyperparams
    thetaArgs = (X.reshape(len(X),1),Y,hyperprior) # fmin_cg needs these all in one box.
    theta = fmin_cg(gp.calcNegLogPosterior,init_theta, gp.calcNegGradLogPosterior, [thetaArgs], gtol=1e-2,disp=0)
    Ytest,Ysig2 = gp.calcGPPrediction(theta,thetaArgs,Xtest)
    EI = calcEI(Ytest,Ysig2,np.max(Y))
Пример #6
0
def simula(N, n, PM, beta, pmig, grupos, listafitness, listafitness_m, mpvencer, x):

    s = int(time.time() + random.randint(0, 2**32-1) + x) % (2**32-1)
    random.seed(s)

    s = int(time.time() + random.randint(0, 2**32-1) + x) % (2**32-1)
    np.random.seed(s)
    
    IT = 50002
    #IT = 5002
    precisao = 0.01

    AL = [] 
    AL.append(np.count_nonzero(grupos)/(N*n))
    crit = 0. if AL[0] > (1.-precisao) else 1.

    # Para cada periodo, os grupos entram em conflito e se reproduzem, e
    # os individuos sofrem mutacao e migram entre os grupos
    for it in xrange(1,IT):
        if abs(AL[it-1]-crit)<precisao:
            print "Acabou na geracao ", it -1
            break
        # 
        knums = [np.count_nonzero(line) for line in grupos]
        glabels = conflito(N,knums,beta,listafitness_m, mpvencer) if N>1 \
                    else knums
        grupos = reproducao_ind(N,n,listafitness,listafitness_m,glabels)
        grupos = mutacao(N,n,PM,grupos)
        grupos = migracao(N,n,grupos,pmig)
        freqA = float(np.count_nonzero(grupos))/(N*n)
        AL.append(freqA)

        logger.debug("%d \t----------->\t %f" %(it,freqA))

    return it-1
Пример #7
0
 def test_boolean(self):
     a = rand(3,5,8)
     V = rand(5,8)
     g1 = randint(0,5,size=15)
     g2 = randint(0,8,size=15)
     V[g1,g2] = -V[g1,g2]
     assert (array([a[0][V>0],a[1][V>0],a[2][V>0]]) == a[:,V>0]).all()
Пример #8
0
    def test_dot_mm_plus_equals(self, its=50):
        for it in range(its):
            size = random.choice([0, 1, randint(0, 10), randint(0, 100)])
            a_bm = gen_BandMat(size)
            b_bm = gen_BandMat(size)
            c_bm = gen_BandMat(size)
            diag = None if rand_bool() else randn(size)
            diag_value = np.ones((size,)) if diag is None else diag
            a_full = a_bm.full()
            b_full = b_bm.full()
            c_full = c_bm.full()
            l = c_bm.l
            u = c_bm.u
            array_mem = get_array_mem(a_bm.data, b_bm.data, c_bm.data)
            if diag is not None:
                diag_mem = get_array_mem(diag)

            bm.dot_mm_plus_equals(a_bm, b_bm, c_bm, diag=diag)
            c_full += fl.band_ec(
                l, u,
                np.dot(np.dot(a_full, np.diag(diag_value)), b_full)
            )
            assert_allclose(c_bm.full(), c_full)
            assert get_array_mem(a_bm.data, b_bm.data, c_bm.data) == array_mem
            if diag is not None:
                assert get_array_mem(diag) == diag_mem
Пример #9
0
    def test_dot_mm_partial(self, its=50):
        for it in range(its):
            size = random.choice([0, 1, randint(0, 10), randint(0, 100)])
            a_bm = gen_BandMat(size)
            b_bm = gen_BandMat(size)
            l = random.choice([0, 1, randint(0, 10)])
            u = random.choice([0, 1, randint(0, 10)])
            diag = None if rand_bool() else randn(size)
            diag_value = np.ones((size,)) if diag is None else diag
            a_full = a_bm.full()
            b_full = b_bm.full()

            c_bm = bm.dot_mm_partial(l, u, a_bm, b_bm, diag=diag)
            c_full = fl.band_ec(
                l, u,
                np.dot(np.dot(a_full, np.diag(diag_value)), b_full)
            )
            assert c_bm.l == l
            assert c_bm.u == u
            assert c_bm.size == size
            assert_allclose(c_bm.full(), c_full)
            assert not np.may_share_memory(c_bm.data, a_bm.data)
            assert not np.may_share_memory(c_bm.data, b_bm.data)
            if diag is not None:
                assert not np.may_share_memory(c_bm.data, diag)
Пример #10
0
 def test_grouped_hist_layout(self):
     import matplotlib.pyplot as plt
     n = 100
     df = DataFrame({'gender': np.array(['Male',
                                         'Female'])[random.randint(2,
                                                                   size=n)],
                     'height': random.normal(66, 4, size=n),
                     'weight': random.normal(161, 32, size=n),
                     'category': random.randint(4, size=n)})
     self.assertRaises(ValueError, df.hist, column='weight', by=df.gender,
                       layout=(1, 1))
     self.assertRaises(ValueError, df.hist, column='weight', by=df.gender,
                       layout=(1,))
     self.assertRaises(ValueError, df.hist, column='height', by=df.category,
                       layout=(1, 3))
     self.assertRaises(ValueError, df.hist, column='height', by=df.category,
                       layout=(2, 1))
     self.assertEqual(df.hist(column='height', by=df.gender,
                              layout=(2, 1)).shape, (2,))
     plt.close('all')
     self.assertEqual(df.hist(column='height', by=df.category,
                              layout=(4, 1)).shape, (4,))
     plt.close('all')
     self.assertEqual(df.hist(column='height', by=df.category,
                              layout=(4, 2)).shape, (4, 2))
Пример #11
0
def load_cropped_images(imagepath, imgdim, cropped_mean_image, crop_dim, \
                        eigvalue, eigvector, sigma=0.1, test=False ):
    """
    Please note that mean_image should be the cropped mean
    """

    dimX = crop_dim[0] * crop_dim[1] * crop_dim[2]
    ndata = len(imagepath)
    pb = np.sqrt(eigvalue).reshape((1,-1)) * eigvector
    a =  np.dot(pb, rd.randn(3, len(imagepath))) * sigma
    res = np.tile(-cropped_mean_image.reshape((dimX, 1),order='F'),[1, ndata])
    nr, nc, dummy = np.floor((np.asarray(imgdim) - np.asarray(crop_dim))/2) + 1

    sr_list = rd.randint(nr, size=ndata) if not test else [nr-1] * ndata
    sc_list = rd.randint(nc, size=ndata) if not test else [nc-1] * ndata
    if not test:
        f = lambda curimg,r,c,i: curimg[r:r+crop_dim[0],c:c+crop_dim[1],:].reshape((dimX),order='F') + np.tile(a[...,i].reshape((1,3)),[1,dimX/3]).reshape((dimX),order='F')
    else:
        f = lambda curimg,r,c,i: curimg[r:r+crop_dim[0],c:c+crop_dim[1],:].reshape((dimX),order='F')
    for i,p in enumerate(imagepath):
        curimg = np.array(Image.open(p))
        sr = sr_list[i]
        sc = sc_list[i]
        res[...,i] += f(curimg, sr,sc,i)
    return sr_list, sc_list, res
Пример #12
0
def test_pandas_groupby_apply():
    """ Test pandas.DataFrame.groupby(...).progress_apply """
    try:
        from numpy.random import randint
        from tqdm import tqdm_pandas
        import pandas as pd
    except:
        raise SkipTest

    with closing(StringIO()) as our_file:
        df = pd.DataFrame(randint(0, 50, (500, 3)))
        dfs = pd.DataFrame(randint(0, 50, (500, 3)),
                           columns=list('abc'))
        tqdm_pandas(tqdm(file=our_file, leave=False, ascii=True))
        df.groupby(0).progress_apply(lambda x: None)
        tqdm_pandas(tqdm(file=our_file, leave=False, ascii=True))
        dfs.groupby(['a']).progress_apply(lambda x: None)

        our_file.seek(0)

        # don't expect final output since no `leave` and
        # high dynamic `miniters`
        nexres = '100%|##########|'
        if nexres in our_file.read():
            our_file.seek(0)
            raise AssertionError("\nDid not expect:\n{0}\nIn:{1}\n".format(
                nexres, our_file.read()))
def run_training_and_return_test_results():
    print('START TRAINING_______________________________')
    # initialize variables to random values
    init = tf.initialize_all_variables()
    sess.run(init)
    # run optimizer on entire training data set many times
    train_size = train_ins.shape[0]
    for epoch in range(20000):
        start = rng.randint(train_size-15)
        batch_size = rng.randint(2,50)
        end = min(train_size, start+batch_size)

        sess.run(optimizer, feed_dict={x: train_ins[start:end], y_: train_outs[start:end]})#.reshape(1,-1).T})
        # every 1000 iterations record progress
        if (epoch+1)%1000== 0:
            t,s, c = sess.run([ total_return, sharpe, costfn], feed_dict={x: train_ins, y_: train_outs})#.reshape(1,-1).T})
            t = np.mean(t)
            s = np.mean(s)
            print("Epoch:", '%04d' % (epoch+1), "cost=",c, "total return=", "{:.9f}".format(t), 
                 "sharpe=", "{:.9f}".format(s))
            #print(t)

    print('DONE TRAINING _______________________________')

    d_tr, t_tr = sess.run([daily_returns, total_return], feed_dict={x: train_ins, y_: train_outs})

    d_te, t_te = sess.run([daily_returns, total_return], feed_dict={x: test_ins, y_: test_outs})

    t_tr = np.mean(t_tr)
    t_te = np.mean(t_te)

    print("total return train=", "{:.9f}".format(t_tr))
    print("total return test=", "{:.9f}".format(t_te))
    return t_tr, t_te
Пример #14
0
 def opponent_rollout(self,solver, s):
     acts = self.legal_actions(s)
     if len(acts) > 0:
         some_in_tree = False
         best_in_tree = 100
         best_action = 100
         count = 0
         for act in acts:
             s_prime, reward = self.generative_model(s, act, 2)
             if reward == -1.0:
                 return act
             if solver.to_tuple(s_prime) in solver.tree:
                 count += 1
                 if solver.tree[solver.to_tuple(s_prime)][0] < best_in_tree:
                     best_in_tree = solver.tree[solver.to_tuple(s_prime)][0]
                     best_action = act
         if count > 0:
             if uniform(0,1) > count/len(acts):
                 return best_action
             else:
                 return acts[randint(0, len(acts))]
         else:
             return acts[randint(0, len(acts))]
     else:
         return 'Draw'
Пример #15
0
def generate_multimask_test_data(num_masks, num_points, num_features):
    # step 1: generate masks
    found = set()
    all_masks = []
    for i in xrange(num_masks):
        while True:
            u, = randint(2, size=num_features).nonzero()
            h = u.tostring()
            if h not in found:
                found.add(h)
                all_masks.append(u)
                break
    assert len(all_masks)==num_masks
    # step 2: generate data
    fet = []
    fmask = []
    offsets = []
    unmasked = []
    n = 0
    offsets = [n]
    for i in xrange(num_points):
        u = all_masks[randint(num_masks)]
        fet.append(rand(len(u)))
        fmask.append(0.5+0.5*rand(len(u)))
        unmasked.append(u)
        n += len(u)
        offsets.append(n)
    assert len(offsets)==num_points+1
    fet = hstack(fet)
    fmask = hstack(fmask)
    unmasked = hstack(unmasked)
    offsets = array(offsets)
    return RawSparseData(full(num_features, 0.5), full(num_features, 1./12), # mean/var of rand()
                         fet, fmask, unmasked, offsets).to_sparse_data()
Пример #16
0
 def write_exam(self,teacher,toughness_level):
     for pupil in self.pupils:
         # will this pupil try to betray and copy?
         # let's decide random-influenced but probability-based
         random_number=rand()
         if random_number < pupil.honesty_level:
             will_try_betrayal=False
         else:
             will_try_betrayal=True
         if will_try_betrayal:
             # copying from who? imagine random seating and choosing the better of two neighbours
             # need to randomly sample two different ones from the list of pupils in the class
             while True:
                 fellowA=self.pupils[randint(self.size)]
                 fellowB=self.pupils[randint(self.size)]
                 if not (fellowA is fellowB):
                     break
             if fellowA.skill_level > fellowB.skill_level:
                 pupil.write_exam(copy_from_fellow=fellowA, exam_toughness=toughness_level)
             else:
                 pupil.write_exam(copy_from_fellow=fellowB, exam_toughness=toughness_level)
             if rand() < teacher.betrayal_check_probability:
                 betrayal_discovered=True
             else:
                 betrayal_discovered=False
             if betrayal_discovered:
                 # what happens then? grade becomes zero? or skill-level minus 3?
                 # discovery should lead to increased fear and honesty next time
                 raise NotImplementedError('This is up to you.')
             else:
                 # what happens then? grade will be influenced by own and fellow's skill level
                 # no discovery should lead to decreased fear less honesty next time
                 raise NotImplementedError('This is up to you.')
         else:
             pupil.write_exam(exam_toughness=toughness_level)
Пример #17
0
def sample_patch_masks(obs_count, im_shape, patch_shape, patch_count=1):
    """
    Sample a random patch mask for each image in X.
    """
    rows = patch_shape[0]
    cols = patch_shape[1]
    min_row = 0
    max_row = im_shape[0] - rows
    if (max_row <= min_row):
        off_row = np.zeros((obs_count, patch_count), dtype=np.int64)
    else:
        off_row = npr.randint(min_row, high=max_row,
                              size=(obs_count, patch_count))
    min_col = 0
    max_col = im_shape[1] - cols
    if (max_col <= min_col):
        off_col = np.zeros((obs_count, patch_count), dtype=np.int64)
    else:
        off_col = npr.randint(min_col, high=max_col,
                              size=(obs_count, patch_count))
    dummy = np.zeros(im_shape)
    mask = np.ones((obs_count, im_shape[0] * im_shape[1]))
    for i in range(obs_count):
        for j in range(patch_count):
            # reset the dummy mask
            dummy = (0. * dummy) + 1.
            # select a random patch in the dummy mask
            dummy[off_row[i, j]:(off_row[i, j] + rows), off_col[i, j]:(off_col[i, j] + cols)] = 0.
            # turn off the patch in the final mask
            mask[i, :] = mask[i, :] * dummy.ravel()
    return mask.astype(theano.config.floatX)
Пример #18
0
 def createPopulation(self, number, radius, fitness = None):
     """This method creates the agents and put them in the grid
     """
     for i in range(number):
         row = random.randint(self.rows)
         column = random.randint(self.columns)
         self.addAgent(Agent(row,column,radius, fitness))
Пример #19
0
def hc_only_explore_step(rl_config, Q, state, epsilon=0.9):
    rid2rl_actions = rl_config.rl_actions
    id2rl_state = rl_config.rl_state_ids
    rl_state2id = {v: k for k, v in id2rl_state.items()}

    act = -1
    while (act == -1):
        is_greed = rand(1) < epsilon
        if is_greed:
            idx = state.tolist() + [[x for x in range(len(rid2rl_actions.keys()))]]
            act = np.argmax(Q[tuple(idx)])
            val = np.max(Q[tuple(idx)])
            if val <= 0.00000000001:
                is_greed = False

        if not is_greed:
            if rand(1) < 0.9:
                act = randint(0, 7)
            else:
                act = randint(7, len(rid2rl_actions.keys()))

        (next_state, act, isFinished) = rl_config.transition_function(rl_config, state, act, Q)

    reward = rl_config.reward_function(rl_config, state, act, next_state)
    sarsa_state = np.concatenate((state, [act], [reward], next_state))
    length = sarsa_state.shape[0]
    sarsa_state = np.reshape(sarsa_state, (1,length))

    return (next_state, sarsa_state, isFinished)
Пример #20
0
 def __getVectorC(self, length):
     # ensure at least 1/3 positive values
     data = npr.randint(-10, 10, [length, 1])
     posCount = np.ceil(length / 3)
     data[:posCount, 0] = npr.randint(0, 10, posCount) 
     npr.shuffle(data)
     return np.matrix(data)
Пример #21
0
def draw_sinusoid(img, thickness, radius, clearance, bgr_color):
    """
    Draws a sinusoid primitive

    Args:
        img(:class:`numpy.ndarray(dtype=unit8)`): image to draw on
            (OpenCV format)
        thickness(int): line thickness
        radius(float): approx size of the primitive
        clearance(float): approx clearance from pic borders
    """
    [b, g, r] = [int(x) for x in bgr_color]
    h, w, _ = img.shape

    x_center = randint(low=clearance, high=(w - 1) - clearance)
    y_center = randint(low=0 + clearance, high=(h - 1) - clearance)

    start_angle = uniform(low=0, high=2 * numpy.pi)

    x_points = numpy.linspace(-pi / 2, pi / 2, 100)
    points = [[x / (pi / 2), sin(4 * x)] for x in x_points]

    points = warped_polyline(points, [x_center, y_center], start_angle, 40)
    points = numpy.array(points, numpy.int32)

    cv2.polylines(img, [points], False, [b, g, r], thickness=thickness)
Пример #22
0
def rand_word_pairs(phrase_list, pair_count, context_size):
    """Sample anchor/context LUT key pairs for skip-gram training.

    Parameters:
        phrase_list: list of lists/vectors of LUT keys representing phrases
        pair_count: number of training pairs of LUT keys to sample
        context_size: half-width of context window to sample positives from
            NOTE: Samples are always drawn uniformly from within a context
                  window that was already clipped to fit the source phrase.
    Outputs:
        anchor_keys: vector of np.uint32 (samp_count,)
        context_keys: vector of np.uint32 (samp_count,)
        phrase_keys: vector of np.uint32 (samp_count,)
    """
    phrase_count = len(phrase_list)
    anchor_keys = np.zeros((pair_count,), dtype=np.uint32)
    context_keys = np.zeros((pair_count,), dtype=np.uint32)
    phrase_keys = np.zeros((pair_count,), dtype=np.uint32)
    for i in range(pair_count):
        phrase_keys[i] = npr.randint(0, phrase_count)
        phrase = phrase_list[phrase_keys[i]]
        phrase_len = len(phrase)
        a_idx = npr.randint(0, phrase_len)
        c_max = min((a_idx+context_size+1), phrase_len)
        c_min = max((a_idx-context_size), 0)
        c_idx = a_idx
        while (c_idx == a_idx):
            c_idx = npr.randint(c_min, c_max)
        anchor_keys[i] = phrase[a_idx]
        context_keys[i] = phrase[c_idx]
    anchor_keys = anchor_keys.astype(np.uint32)
    context_keys = context_keys.astype(np.uint32)
    phrase_keys =  phrase_keys.astype(np.uint32)
    return [anchor_keys, context_keys, phrase_keys]
Пример #23
0
def bootstrap(y_true, probs):
    """
    bootstrap: bootstrap the training data, mainly used to increase volume of hard negative examples for training
    parameters:
        y_true: ground truth of training data
        probs: predictions of the model 
    """
    global  neg_pool

    neg_pool_size = len(neg_pool)
    hard_size = int(neg_pool_size * hard_ratio)
    easy_size = neg_pool_size - hard_size
    neg_idcs = np.arange(len(y_true))[y_true.sum(axis = 1) == 0]
    sort_idcs = np.argsort(probs[neg_idcs, :].max(axis = 1))
    hard_idcs = bootstrap_idcs[neg_idcs[sort_idcs[-hard_size:]]]

    if easy_mode == 'random':
        easy_idcs = bootstrap_idcs[neg_idcs[nr.randint(0, len(neg_idcs), (easy_size,))]]
    elif easy_mode == 'easy':
        easy_idcs = neg_pool[:easy_size]
    elif easy_mode == 'all':
        easy_idcs = neg_pool[nr.randint(0, len(neg_pool), (easy_size,))]
    else:
        sys.exit('Wrong easy mode')

    neg_pool = np.concatenate([easy_idcs, hard_idcs])
Пример #24
0
def initSim(N, n, A, c, alpha):    

    #grupos = np.zeros((N,n))
    #grupos = inicializa(N,n,A,grupos) if A<(N*n) else np.ones((N,n))
    if A == N*n:
        knums = [n]*N
    else:
        if A < n*N/2:
            knums = [0]*N
            for i in xrange(A):
                sorteio = random.randint(0,N-1)
                while(knums[sorteio]==n-1):
                    sorteio = random.randint(0,N-1)
                knums[sorteio] += 1
        else:
            knums = [n]*N
            for i in xrange(N*n-A):
                sorteio = random.randint(0,N-1)
                while(knums[sorteio]==0):
                    sorteio = random.randint(0,N-1)
                knums[sorteio] -= 1

        #grupos_com_A = [random.randint(0,N-1) for i in xrange(A)]
        #contagem = Counter(grupos_com_A)
        #knums = [contagem.get(k, 0) for k in xrange(N)]

    listafitness = cria_listaf(c,n)
    listafitness_m = cria_listafm(c,n)
    mpvencer = matriz_vencedores(alpha, n)
    
    #return grupos, listafitness, listafitness_m, mpvencer
    return knums, listafitness, listafitness_m, mpvencer
Пример #25
0
def run(N, K, S):
    random.seed(S)
    seed(S)
    s = ""
    for i in range(K):
        s += choice("abcdefghijklmnopqrstuvwxyz")
    Q = randint(1, N+1)
    trip = {}
    curr = 1
    for i in s:
        if (curr, i) in trip:
            curr = trip[(curr, i)]
        else:
            dest = randint(1, N+1)
            trip[(curr, i)] = dest
            curr = dest

    M = randint(K, MAXM+1)
    tent = 0
    while tent < 100 and len(trip) != M:
        curr = randint(1, N+1)
        c = choice("abcdefghijklmnopqrstuvwxyz")
        if (curr, c) not in trip:
            dest = randint(1, N+1)
            trip[(curr, c)] = dest
        else:
            tent += 1

    print len(trip), N, K
    for i in s:
        print i,
    print
    for i in trip:
        print i[0], trip[i], i[1]
Пример #26
0
def bootstrap_test(sample1, sample2, k = 1000, p_value = 0.05, two_tailed = True):
    """
    Test the null hypothesis that the two samples are independent from each other 
    thanks to pearson coefficients.
    Note that we keep nan values during the resampling (and eliminate them to compute 
    the pearson coefficient).
    
    Remember: if True, the coefficient is NOT significant.
    """
    # eliminate all entries which have a nan in one of the sample. 
    
    sample1_bis, sample2_bis = zip(*[zz for zz in zip(sample1, sample2) if not np.isnan(zz[0]) and not np.isnan(zz[1])])
    r_sample = pearsonr(sample1_bis, sample2_bis)[0]

    sample1_bis = np.array(sample1_bis)
    sample2_bis = np.array(sample2_bis)
    
    n = len(sample1_bis)
    try:
        assert n == len(sample2_bis)
    except:
        Exception("Samples must have same sizes.")

    r_resample = np.zeros(k)
    for i in xrange(k):
        s1_rand = sample1_bis[randint(0, n, n)] # Resampling with the same size
        s2_rand = sample2_bis[randint(0, n, n)] 
        s1_rand_bis, s2_rand_bis = zip(*[zz for zz in zip(s1_rand, s2_rand) if not np.isnan(zz[0]) and not np.isnan(zz[1])])
        r_resample[i] = pearsonr(s1_rand_bis, s2_rand_bis)[0]
        
    ci = np.percentile(r_resample, [p_value/2., 1.-p_value/2.])
    
    #print "Percentiles:", ci
    
    return  ci[0]<r_sample<ci[1]
Пример #27
0
def gen_BandMat_simple(size):
    """Generates a random BandMat."""
    l = random.choice([0, 1, randint(0, 10)])
    u = random.choice([0, 1, randint(0, 10)])
    data = randn(l + u + 1, size)
    transposed = rand_bool()
    return bm.BandMat(l, u, data, transposed=transposed)
Пример #28
0
def rand_word_seqs(phrase_list, seq_count, seq_len, null_key):
    """Sample LUT key n-grams from a list of phrases.

    Given a list of phrases, where each phrase is described by a list of
    keys into a look-up-table, sample random n-grams of keys from the
    sequences, where n is given by seq_len. The sampled n-grams are only
    constrained to have their final item inside the source phrase. When any
    of the first n-1 items in a sampled sequence are not in the source phrase,
    they are assigned the key given by null_key.
    """
    phrase_count = len(phrase_list)
    seq_keys = np.zeros((seq_count, seq_len), dtype=np.uint32)
    phrase_keys = np.zeros((seq_count,), dtype=np.uint32)
    for i in range(seq_count):
        phrase_keys[i] = npr.randint(0, phrase_count)
        phrase = phrase_list[phrase_keys[i]]
        phrase_len = len(phrase)
        final_key = npr.randint(0, phrase_len)
        seq_keys[i,-1] = phrase[final_key]
        for j in range(seq_len-1):
            preceding_key = final_key - seq_len + j + 1
            if (preceding_key < 0):
                seq_keys[i,j] = null_key
            else:
                seq_keys[i,j] = phrase[preceding_key]
    seq_keys = seq_keys.astype(np.uint32)
    phrase_keys = phrase_keys.astype(np.uint32)
    return [seq_keys, phrase_keys]
def wrd():
    import datetime
    from numpy import random as random

    return datetime.datetime(random.randint(1970, 2014),
                             random.randint(1, 10),
                             random.randint(1, 20))
def randintbasic(TEprobmat,amax,banvalue):
	#selection of jp: jp is a random node
	L=len(TEprobmat[banvalue,:])
	v=npr.randint(L)
	while v==banvalue:
		v=npr.randint(L)
	return v
Пример #31
0

def generate_varchar(length):
    return ''.join(chr(num) for num in randint(32, 128, length))


col_types = {
    'bool', 'tinyint', 'smallint', 'int', 'bigint', 'real', 'double', 'date',
    'datetime', 'varchar({})'.format(varchar_length),
    'nvarchar({})'.format(varchar_length)
}

pos_test_vals = {
    'bool': (0, 1, True, False, 2, 3.6, 'test', (1997, 5, 9), (1997, 12, 12,
                                                               10, 10, 10)),
    'tinyint': (randint(0, 255), randint(0, 255), 0, 255, True, False),
    'smallint': (randint(-32768, 32767), 0, -32768, 32767, True, False),
    'int': (randint(-2147483648,
                    2147483647), 0, -2147483648, 2147483647, True, False),
    'bigint':
    (randint(1 - max_bigint,
             max_bigint), 0, 1 - max_bigint, max_bigint, True, False),
    'real': (float('inf'), float('-inf'), float('+0'), float('-0'),
             round(uniform(1e-6, 1e6),
                   5), 837326.52428, True, False),  # float('nan')
    'double': (float('inf'), float('-inf'), float('+0'), float('-0'),
               uniform(1e-6, 1e6), True, False),  # float('nan')
    'date': (date(1998, 9, 24), date(2020, 12, 1), date(1997, 5,
                                                        9), date(1993, 7, 13)),
    'datetime':
    (datetime(1001, 1, 1, 10, 10, 10), datetime(1997, 11, 30, 10, 10, 10),
Пример #32
0
 def seek_key(self):
     self.private = randint(0, self.p-1)  # 秘密鍵
     self.public = self.r ** self.private   # 公開鍵
Пример #33
0
def main():
    li = [
        10, 25, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 1000, 1500,
        2000, 2500, 3000
    ]
    x = np.array(li)
    y = np.zeros((6, x.shape[0]))

    for i, s in enumerate(li):
        print '\n'
        print "n = {}".format(s**2)
        print '---------------------------'
        a = np.asfortranarray(randint(0, 10, size=(s, s)), dtype='d')
        #Conversion using copy from int64 to float64
        #Dot should ensure positive semi-definite
        data = np.dot(a, a.T)
        del a

        #Numpy Cholesky Decomposition (Dense Matrix)
        spd_matrix = data.copy()
        t1 = time.time()
        np_chol = cholesky(spd_matrix)
        t2 = time.time()
        print "Numpy Implementation took {} seconds".format(t2 - t1)
        y[0][i] = t2 - t1

        if s <= 200:
            #Naive
            spd_matrix = data.copy()
            t1 = time.time()
            out = naivechol(spd_matrix)
            t2 = time.time()
            np.testing.assert_allclose(out, np_chol, rtol=1e-07)
            print "Naive implementation took {} seconds".format(t2 - t1)
            y[1][i] = t2 - t1
        else:
            y[1][i] = np.nan

        #Cython
        spd_matrix = data.copy()
        t1 = time.time()
        out = cython_implementation(spd_matrix)
        t2 = time.time()
        #np.testing.assert_allclose(out, np_chol, rtol=1e-07)
        print "Cython implementation took {} seconds".format(t2 - t1)
        y[2][i] = t2 - t1

        if s <= 500:
            #Vectorized
            spd_matrix = data.copy()
            t1 = time.time()
            out = vectorizedchol(spd_matrix)
            t2 = time.time()
            #np.testing.assert_allclose(out, np_chol, rtol=1e-07)
            print "Vectorized implementation took {} seconds".format(t2 - t1)
            y[3][i] = t2 - t1
        else:
            y[3][i] = np.nan

        if s <= 500:
            #Mixed Naive / Cython
            spd_matrix = data.copy()
            t1 = time.time()
            out = mixedcython(spd_matrix)
            t2 = time.time()
            np.testing.assert_allclose(out, np_chol, rtol=1e-07)
            print "Mixed Cython/Python implementation took {} seconds".format(
                t2 - t1)
            y[4][i] = t2 - t1
        else:
            y[4][i] = np.nan

        if s <= 500:
            #new cholesky
            spd_matrix = data.copy()
            t1 = time.time()
            out = purepythoncholesky(spd_matrix)
            t2 = time.time()
            print "Pure Python Cholesky implementation took {} seconds".format(
                t2 - t1)
            y[5][i] = t2 - t1
        else:
            y[5][i] = np.nan

    #plot
    labels = ['NP', 'Naive', 'Cython', 'Vect', 'Mixed C/P']
    for i in range(y.shape[0]):
        plt.plot(x, y[i], label=labels[i])

    plt.show()
Пример #34
0
    passed_particles21 = 0  #particles which passed 0th site lattice 2 -> lattice 1
    passed_particles22 = 0  #particles which passed 0th site lattice 2 -> lattice 2
    current11 = 0
    current12 = 0
    current21 = 0
    current22 = 0
    densities1 = np.zeros(
        N)  #average occupation density for each site in lattice 1
    densities2 = np.zeros(
        N)  #average occupation density for each site in lattice 2

    L1, L2 = init_positions_particles1(N, int(M[mm]))

    for i in range(steps):
        for j in range(2 * N):
            site = rd.randint(0, 2 * N)
            update(site)

        #cutoff (steady state) period
        if i == steady_state:  #we start measuring from 0
            passed_particles11 = 0
            passed_particles12 = 0
            passed_particles21 = 0
            passed_particles22 = 0

        #update site densities
        if i >= steady_state:
            l1 = L1 > 0  #remove ones and twos -> boolean
            l1 = l1.astype(int)  #make them integers
            l2 = L2 > 0  #remove ones and twos -> boolean
            l2 = l2.astype(int)  #make them integers
Пример #35
0
def detect(save_img=False):
    out, source, weights, view_img, save_txt, imgsz, save_csv = \
        opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.save_csv
    webcam = source == '0' or source.startswith('rtsp') or source.startswith(
        'http') or source.endswith('.txt')

    # Initialize
    device = select_device(opt.device)
    # if os.path.exists(out):
    #     shutil.rmtree(out)  # delete output folder
    # os.makedirs(out)  # make new output folder
    half = device.type != 'cpu'  # half precision only supported on CUDA

    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    imgsz = check_img_size(imgsz, s=model.stride.max())  # check img_size
    if half:
        model.half()  # to FP16

    # Second-stage classifier
    classify = False
    if classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(
            torch.load('weights/resnet101.pt',
                       map_location=device)['model'])  # load weights
        modelc.to(device).eval()

    # Set Dataloader
    vid_path, vid_writer = None, None
    if webcam:
        view_img = True
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz)
    else:
        save_img = True
        dataset = LoadImages(source, img_size=imgsz)

    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)]
              for _ in range(len(names))]

    # csv output
    csv_output = []

    # Run inference
    t0 = time.time()
    img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img
    _ = model(img.half() if half else img
              ) if device.type != 'cpu' else None  # run once
    for path, img, im0s, vid_cap in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]

        # Apply NMS
        pred = non_max_suppression(pred,
                                   opt.conf_thres,
                                   opt.iou_thres,
                                   classes=opt.classes,
                                   agnostic=opt.agnostic_nms)
        t2 = time_synchronized()

        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            if webcam:  # batch_size >= 1
                p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
            else:
                p, s, im0 = path, '', im0s

            save_path = str(Path(out) / Path(p).name)
            txt_path = str(Path(out) / Path(p).stem) + (
                '_%g' % dataset.frame if dataset.mode == 'video' else '')
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1,
                                          0]]  # normalization gain whwh
            if det is not None and len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4],
                                          im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += '%g %ss, ' % (n, names[int(c)])  # add to string

                # Write results
                for *xyxy, conf, cls in det:
                    if save_txt:  # Write to file
                        with open(txt_path + '.txt', 'a') as f:
                            xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) /
                                    gn).view(-1).tolist()  # normalized xywh
                            f.write(('%g ' * 5 + '\n') %
                                    (cls, *xywh))  # label format

                    if save_csv:  # csv output append
                        xyxyNormalized = (torch.tensor(xyxy) / gn).tolist()
                        csv_output.append([
                            Path(p).name,
                            int(cls),
                            float(conf), *xyxyNormalized
                        ])

                    if save_img or view_img:  # Add bbox to image
                        # label = '%s' % (names[int(cls)])
                        label = '%s %.2f' % (names[int(cls)], conf)
                        # plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=2)
                        plot_one_box(xyxy,
                                     im0,
                                     label=label,
                                     color=colors[int(cls)])

            # Print time (inference + NMS)
            print('%sDone. (%.3fs)' % (s, t2 - t1))

            # Stream results
            if view_img:
                cv2.imshow(p, im0)
                if cv2.waitKey(1) == ord('q'):  # q to quit
                    raise StopIteration

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'images':
                    cv2.imwrite(save_path, im0)
                else:
                    if vid_path != save_path:  # new video
                        vid_path = save_path
                        if isinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release(
                            )  # release previous video writer

                        fourcc = 'mp4v'  # output video codec
                        fps = vid_cap.get(cv2.CAP_PROP_FPS)
                        w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                        h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        vid_writer = cv2.VideoWriter(
                            save_path, cv2.VideoWriter_fourcc(*fourcc), fps,
                            (w, h))
                    vid_writer.write(im0)

    # write csv output
    if save_csv:
        current_time = datetime.datetime.now(
            pytz.timezone('Asia/Seoul')).strftime('%Y-%m-%d-%H-%M')
        with open(
                f'/DL_data_big/AI_factory_dataset/tracking_recognition/ai_factory_tracking/dataset/yolo_output/output_{current_time}.csv',
                'w',
                newline='') as f:
            f_writer = csv.writer(f)
            f_writer.writerow([
                'ImageID', 'LabelName', 'Conf', 'XMin', 'XMax', 'YMin', 'YMax'
            ])
            f_writer.writerows(csv_output)
            print("csv saved")

    if save_txt or save_img:
        print('Results saved to %s' % Path(out))
        if platform == 'darwin' and not opt.update:  # MacOS
            os.system('open ' + save_path)

    print('Done. (%.3fs)' % (time.time() - t0))
Пример #36
0
def randomizeTexture(texture, level=1):
    '''
    Set the values for a texture from parameters.

    param: texture - bpy.data.texture to modify.
    level   - designated tweaked settings to use
    -> Below 10 is a displacement texture
    -> Between 10 and 20 is a base material texture
    '''
    noises = [
        'BLENDER_ORIGINAL', 'ORIGINAL_PERLIN', 'IMPROVED_PERLIN', 'VORONOI_F1',
        'VORONOI_F2', 'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2_F1',
        'VORONOI_CRACKLE'
    ]
    if texture.type == 'CLOUDS':
        if randint(0, 1) == 0:
            texture.noise_type = 'SOFT_NOISE'
        else:
            texture.noise_type = 'HARD_NOISE'
        if level != 11:
            tempInt = randint(0, 6)
        else:
            tempInt = randint(0, 8)
        texture.noise_basis = noises[tempInt]
        texture.noise_depth = 8

        if level == 0:
            texture.noise_scale = gauss(0.625, 1 / 24)
        elif level == 2:
            texture.noise_scale = 0.15
        elif level == 11:
            texture.noise_scale = gauss(0.5, 1 / 24)

            if texture.noise_basis in [
                    'BLENDER_ORIGINAL', 'ORIGINAL_PERLIN', 'IMPROVED_PERLIN',
                    'VORONOI_F1'
            ]:
                texture.intensity = gauss(1, 1 / 6)
                texture.contrast = gauss(4, 1 / 3)
            elif texture.noise_basis in [
                    'VORONOI_F2', 'VORONOI_F3', 'VORONOI_F4'
            ]:
                texture.intensity = gauss(0.25, 1 / 12)
                texture.contrast = gauss(2, 1 / 6)
            elif texture.noise_basis == 'VORONOI_F2_F1':
                texture.intensity = gauss(0.5, 1 / 6)
                texture.contrast = gauss(2, 1 / 6)
            elif texture.noise_basis == 'VORONOI_CRACKLE':
                texture.intensity = gauss(0.5, 1 / 6)
                texture.contrast = gauss(2, 1 / 6)
    elif texture.type == 'MUSGRAVE':
        # musgraveType = ['MULTIFRACTAL', 'RIDGED_MULTIFRACTAL',
        #                 'HYBRID_MULTIFRACTAL', 'FBM', 'HETERO_TERRAIN']
        texture.musgrave_type = 'MULTIFRACTAL'
        texture.dimension_max = abs(gauss(0, 0.6)) + 0.2
        texture.lacunarity = beta(3, 8) * 8.2 + 1.8

        if level == 0:
            texture.noise_scale = gauss(0.625, 1 / 24)
            texture.noise_intensity = 0.2
            texture.octaves = 1.0
        elif level == 2:
            texture.intensity = gauss(1, 1 / 6)
            texture.contrast = 0.2
            texture.noise_scale = 0.15
            texture.octaves = 8.0
        elif level == 10:
            texture.intensity = gauss(0.25, 1 / 12)
            texture.contrast = gauss(1.5, 1 / 6)
            texture.noise_scale = 0.5
            texture.octaves = 8.0
        elif level == 12:
            texture.octaves = uniform(1, 3)
        elif level > 12:
            texture.octaves = uniform(2, 8)
        else:
            texture.intensity = gauss(1, 1 / 6)
            texture.contrast = 0.2
            texture.octaves = 8.0
    elif texture.type == 'DISTORTED_NOISE':
        tempInt = randint(0, 8)
        texture.noise_distortion = noises[tempInt]
        tempInt = randint(0, 8)
        texture.noise_basis = noises[tempInt]
        texture.distortion = skewedGauss(2.0, 2.6666, (0.0, 10.0), False)

        if level == 0:
            texture.noise_scale = gauss(0.625, 1 / 24)
        elif level == 2:
            texture.noise_scale = 0.15
        elif level >= 12:
            texture.noise_scale = gauss(0.2, 1 / 48)
    elif texture.type == 'STUCCI':
        stucciTypes = ['PLASTIC', 'WALL_IN', 'WALL_OUT']
        if randint(0, 1) == 0:
            texture.noise_type = 'SOFT_NOISE'
        else:
            texture.noise_type = 'HARD_NOISE'
        tempInt = randint(0, 2)
        texture.stucci_type = stucciTypes[tempInt]

        if level == 0:
            tempInt = randint(0, 6)
            texture.noise_basis = noises[tempInt]
            texture.noise_scale = gauss(0.625, 1 / 24)
        elif level == 2:
            tempInt = randint(0, 6)
            texture.noise_basis = noises[tempInt]
            texture.noise_scale = 0.15
        elif level >= 12:
            tempInt = randint(0, 6)
            texture.noise_basis = noises[tempInt]
            texture.noise_scale = gauss(0.2, 1 / 30)
        else:
            tempInt = randint(0, 6)
            texture.noise_basis = noises[tempInt]
    elif texture.type == 'VORONOI':
        metrics = [
            'DISTANCE', 'DISTANCE_SQUARED', 'MANHATTAN', 'CHEBYCHEV',
            'MINKOVSKY_HALF', 'MINKOVSKY_FOUR', 'MINKOVSKY'
        ]
        # Settings for first dispalcement level:
        if level == 0:
            tempInt = randint(0, 1)
            texture.distance_metric = metrics[tempInt]
            texture.noise_scale = gauss(0.625, 1 / 24)
            texture.contrast = 0.5
            texture.intensity = 0.7
        elif level == 2:
            texture.noise_scale = 0.15
            tempInt = randint(0, 6)
            texture.distance_metric = metrics[tempInt]
        elif level >= 12:
            tempInt = randint(0, 1)
            texture.distance_metric = metrics[tempInt]
            texture.noise_scale = gauss(0.125, 1 / 48)
            texture.contrast = 0.5
            texture.intensity = 0.7
        else:
            tempInt = randint(0, 6)
            texture.distance_metric = metrics[tempInt]

    return
Пример #37
0
def generate_varchar(length):
    return ''.join(chr(num) for num in randint(32, 128, length))
 def __call__(self, image, boxes=None, labels=None):
     if random.randint(2):
         alpha = random.uniform(self.lower, self.upper)
         image *= alpha
     return image, boxes, labels
 def __call__(self, image, boxes=None, labels=None):
     if random.randint(2):
         image[:, :, 0] += random.uniform(-self.delta, self.delta)
         image[:, :, 0][image[:, :, 0] > 360.0] -= 360.0
         image[:, :, 0][image[:, :, 0] < 0.0] += 360.0
     return image, boxes, labels
 def __call__(self, image, boxes=None, labels=None):
     if random.randint(2):
         delta = random.uniform(-self.delta, self.delta)
         image += delta
     return image, boxes, labels
Пример #41
0
def generateObject(context, muX, sigmaX, scaleX, upperSkewX, muY, sigmaY,
                   scaleY, upperSkewY, muZ, sigmaZ, scaleZ, upperSkewZ, base,
                   shift, scaleDisplace, scale_fac):
    x = []
    y = []
    z = []
    shape = randint(0, 11)

    # Cube
    # Use parameters to re-scale cube:
    # Reversed if/for nesting.  Should be a little faster.
    if shape == 0:
        for j in range(8):
            if sigmaX == 0:
                x.append(scaleX[0] / 2)
            else:
                x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
            if sigmaY == 0:
                y.append(scaleY[0] / 2)
            else:
                y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
            if sigmaZ == 0:
                z.append(scaleZ[0] / 2)
            else:
                z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 1:
        for j in range(8):
            if j in [0, 1, 3, 4]:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j in [2, 5]:
                if sigmaX == 0:
                    x.append(0)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j in [6, 7]:
                if sigmaX == 0:
                    x.append(0)
                else:
                    x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 4)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 2:
        for j in range(8):
            if j in [0, 2, 5, 7]:
                if sigmaX == 0:
                    x.append(scaleX[0] / 4)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 4)
            elif j in [1, 3, 4, 6]:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 3:
        for j in range(8):
            if j > 0:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            else:
                if sigmaX == 0:
                    x.append(0)
                else:
                    x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 8)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 8)
                if sigmaZ == 0:
                    z.append(0)
                else:
                    z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 8)
    elif shape == 4:
        for j in range(10):
            if j in [0, 9]:
                if sigmaX == 0:
                    x.append(0)
                else:
                    x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j in [1, 2, 3, 4]:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j in [5, 7]:
                if sigmaX == 0:
                    x.append(0)
                else:
                    x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 3)
                if sigmaY == 0:
                    y.append(scaleY[0] / 3)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 3)
                if sigmaZ == 0:
                    z.append(0)
                else:
                    z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 6)
            elif j in [6, 8]:
                if sigmaX == 0:
                    x.append(scaleX[0] / 3)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 3)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 3)
                if sigmaZ == 0:
                    z.append(0)
                else:
                    z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 6)
    elif shape == 5:
        for j in range(10):
            if j == 0:
                if sigmaX == 0:
                    x.append(0)
                else:
                    x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 8)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 8)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j in [1, 2]:
                if sigmaX == 0:
                    x.append(scaleZ[0] * .125)
                else:
                    x.append(
                        skewedGauss(muX, sigmaX, scaleX, upperSkewX) * 0.125)
                if sigmaY == 0:
                    y.append(scaleZ[0] * 0.2165)
                else:
                    y.append(
                        skewedGauss(muY, sigmaY, scaleY, upperSkewY) * 0.2165)
                if sigmaZ == 0:
                    z.append(0)
                else:
                    z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 4)
            elif j == 3:
                if sigmaX == 0:
                    x.append(scaleX[0] / 4)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4)
                if sigmaZ == 0:
                    z.append(0)
                else:
                    z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 4)
            elif j in [4, 6]:
                if sigmaX == 0:
                    x.append(scaleX[0] * 0.25)
                else:
                    x.append(
                        skewedGauss(muX, sigmaX, scaleX, upperSkewX) * 0.25)
                if sigmaY == 0:
                    y.append(scaleY[0] * 0.433)
                else:
                    y.append(
                        skewedGauss(muY, sigmaY, scaleY, upperSkewY) * 0.433)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j == 5:
                if sigmaX == 0:
                    x.append(scaleX[0] / 4)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j in [7, 9]:
                if sigmaX == 0:
                    x.append(scaleX[0] * 0.10825)
                else:
                    x.append(
                        skewedGauss(muX, sigmaX, scaleX, upperSkewX) * 0.10825)
                if sigmaY == 0:
                    y.append(scaleY[0] * 0.2165)
                else:
                    y.append(
                        skewedGauss(muY, sigmaY, scaleY, upperSkewY) * 0.2165)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            elif j == 8:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 6:
        for j in range(7):
            if j > 0:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            else:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 7:
        for j in range(10):
            if j in [1, 3, 4, 5, 8, 9]:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(scaleY[0] / 2)
                else:
                    y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
            else:
                if sigmaX == 0:
                    x.append(scaleX[0] / 2)
                else:
                    x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
                if sigmaY == 0:
                    y.append(0)
                else:
                    y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2)
                if sigmaZ == 0:
                    z.append(scaleZ[0] / 2)
                else:
                    z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 8:
        for j in range(7):
            if sigmaX == 0:
                x.append(scaleX[0] / 2)
            else:
                x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
            if sigmaY == 0:
                y.append(scaleY[0] / 2)
            else:
                y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
            if sigmaZ == 0:
                z.append(scaleZ[0] / 2)
            else:
                z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 9:
        for j in range(8):
            if sigmaX == 0:
                x.append(scaleX[0] / 2)
            else:
                x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
            if sigmaY == 0:
                y.append(scaleY[0] / 2)
            else:
                y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
            if sigmaZ == 0:
                z.append(scaleZ[0] / 2)
            else:
                z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 10:
        for j in range(7):
            if sigmaX == 0:
                x.append(scaleX[0] / 2)
            else:
                x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
            if sigmaY == 0:
                y.append(scaleY[0] / 2)
            else:
                y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
            if sigmaZ == 0:
                z.append(scaleZ[0] / 2)
            else:
                z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)
    elif shape == 11:
        for j in range(7):
            if sigmaX == 0:
                x.append(scaleX[0] / 2)
            else:
                x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2)
            if sigmaY == 0:
                y.append(scaleY[0] / 2)
            else:
                y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2)
            if sigmaZ == 0:
                z.append(scaleZ[0] / 2)
            else:
                z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2)

    # This is for scaling the displacement textures.
    # Scale the vertices so that their average is equal to 1 * scale factor.
    if scaleDisplace:
        averageX = (sum(x) / len(x)) * scale_fac[0]
        for i in range(len(x)):
            x[i] /= averageX
        averageY = (sum(y) / len(y)) * scale_fac[1]
        for i in range(len(y)):
            y[i] /= averageY
        averageZ = (sum(z) / len(z)) * scale_fac[2]
        for i in range(len(z)):
            z[i] /= averageZ

    # Build vertex and face arrays:
    if shape == 1:
        verts = [(-x[0], -y[0], -z[0]), (x[1], -y[1], -z[1]),
                 (x[2], -y[2], z[2]), (-x[3], y[3], -z[3]),
                 (x[4], y[4], -z[4]), (x[5], y[5], z[5]), (x[6], y[6], z[6]),
                 (x[7], y[7], -z[7])]
        faces = [[0, 1, 2], [0, 1, 7], [3, 0, 7], [3, 4, 7], [1, 4, 7],
                 [3, 4, 5], [1, 2, 6], [1, 4, 6], [4, 5, 6], [0, 2, 6],
                 [0, 3, 6], [3, 5, 6]]
    elif shape == 2:
        verts = [(-x[0], y[0], -z[0]), (x[1], -y[1], -z[1]),
                 (x[2], y[2], -z[2]), (-x[3], y[3], -z[3]),
                 (-x[4], -y[4], z[4]), (x[5], y[5], z[5]), (x[6], y[6], z[6]),
                 (-x[7], y[7], z[7])]
        faces = [[0, 1, 2], [0, 2, 3], [0, 3, 7], [0, 7, 4], [1, 4, 5],
                 [0, 1, 4], [5, 1, 2], [5, 2, 6], [3, 2, 6], [3, 6, 7],
                 [5, 4, 7], [5, 6, 7]]
    elif shape == 3:
        verts = [(x[0], y[0], z[0]), (x[1], -y[1], -z[1]), (x[2], y[2], -z[2]),
                 (-x[3], y[3], -z[3]), (x[4], -y[4], z[4]), (x[5], y[5], z[5]),
                 (-x[6], y[6], z[6]), (-x[7], -y[7], z[7])]
        faces = [[0, 1, 2], [0, 2, 3], [0, 3, 6], [0, 6, 7], [0, 7, 4],
                 [0, 4, 1], [5, 4, 1, 2], [5, 6, 3, 2], [5, 4, 7, 6]]
    elif shape == 4:
        verts = [(x[0], y[0], z[0]), (x[1], -y[1], -z[1]), (x[2], y[2], -z[2]),
                 (-x[3], y[3], -z[3]), (-x[4], -y[4], -z[4]),
                 (x[5], -y[5], -z[5]), (x[6], y[6], -z[6]),
                 (x[7], y[7], -z[7]), (-x[8], y[8], -z[8]),
                 (x[9], y[9], -z[9])]
        faces = [[0, 1, 6], [0, 6, 2], [0, 2, 7], [0, 7, 3], [0, 3, 8],
                 [0, 8, 4], [0, 4, 5], [0, 5, 1], [1, 9, 2], [2, 9, 3],
                 [3, 9, 4], [4, 9, 1], [1, 6, 2], [2, 7, 3], [3, 8, 4],
                 [4, 5, 1]]
    elif shape == 5:
        verts = [(x[0], y[0], z[0]), (x[1], -y[1], z[1]), (x[2], y[2], z[2]),
                 (-x[3], y[3], z[3]), (x[4], -y[4], -z[4]),
                 (x[5], y[5], -z[5]), (x[6], y[6], -z[6]),
                 (-x[7], y[7], -z[7]), (-x[8], y[8], -z[8]),
                 (-x[9], -y[9], -z[9])]
        faces = [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 4, 5], [1, 5, 2],
                 [2, 5, 6], [2, 6, 7], [2, 7, 3], [3, 7, 8], [3, 8, 9],
                 [3, 9, 1], [1, 9, 4], [4, 5, 9], [5, 6, 7], [7, 8, 9],
                 [9, 5, 7]]
    elif shape == 6:
        verts = [(x[0], y[0], z[0]), (x[1], -y[1], -z[1]), (x[2], y[2], -z[2]),
                 (-x[3], y[3], -z[3]), (-x[4], y[4], z[4]),
                 (-x[5], -y[5], z[5]), (-x[6], -y[6], -z[6])]
        faces = [[0, 1, 2], [0, 2, 3, 4], [0, 1, 6, 5], [0, 4, 5],
                 [1, 2, 3, 6], [3, 4, 5, 6]]
    elif shape == 7:
        verts = [(x[0], y[0], z[0]), (x[1], -y[1], -z[1]), (x[2], y[2], -z[2]),
                 (x[3], y[3], -z[3]), (-x[4], y[4], -z[4]),
                 (-x[5], y[5], z[5]), (-x[6], y[6], z[6]),
                 (-x[7], y[7], -z[7]), (-x[8], -y[8], -z[8]),
                 (-x[9], -y[9], z[9])]
        faces = [[0, 1, 2], [0, 2, 3], [0, 5, 6], [0, 6, 9], [0, 1, 8, 9],
                 [0, 3, 4, 5], [1, 2, 7, 8], [2, 3, 4, 7], [4, 5, 6, 7],
                 [6, 7, 8, 9]]
    elif shape == 8:
        verts = [(x[0], y[0], z[0]), (x[1], -y[1], -z[1]), (x[2], y[2], -z[2]),
                 (-x[3], y[3], -z[3]), (-x[4], -y[4], -z[4]),
                 (-x[5], -y[5], z[5]), (-x[6], y[6], z[6])]
        faces = [[0, 2, 1], [0, 1, 4], [0, 4, 5], [0, 5, 6], [0, 6, 3, 2],
                 [2, 1, 4, 3], [3, 6, 5, 4]]
    elif shape == 9:
        verts = [(-x[0], -y[0], -z[0]), (-x[1], y[1], -z[1]),
                 (-x[2], y[2], z[2]), (-x[3], -y[3], z[3]),
                 (x[4], -y[4], -z[4]), (x[5], y[5], -z[5]), (x[6], y[6], z[6]),
                 (x[7], -y[7], z[7])]
        faces = [[0, 1, 6, 2], [1, 5, 7, 6], [5, 4, 3, 7], [4, 0, 2, 3],
                 [0, 1, 5, 4], [3, 2, 6, 7]]
    elif shape == 10:
        verts = [(-x[0], -y[0], -z[0]), (-x[1], y[1], -z[1]),
                 (-x[2], y[2], z[2]), (x[3], -y[3], z[3]), (x[4], y[4], z[4]),
                 (x[5], y[5], -z[5]), (x[6], -y[6], -z[6])]
        faces = [[0, 2, 3], [0, 3, 6], [0, 1, 5, 6], [2, 3, 4], [0, 1, 2],
                 [1, 2, 4, 5], [3, 4, 5, 6]]
    elif shape == 11:
        verts = [(-x[0], -y[0], -z[0]), (-x[1], y[1], -z[1]),
                 (-x[2], y[2], z[2]), (x[3], -y[3], z[3]), (x[4], y[4], z[4]),
                 (x[5], y[5], -z[5]), (x[6], -y[6], -z[6])]
        faces = [[0, 2, 3], [0, 3, 6], [0, 1, 5, 6], [2, 3, 4], [5, 6, 3],
                 [1, 5, 3, 4], [0, 1, 4, 2]]
    else:
        verts = [(-x[0], -y[0], -z[0]), (-x[1], y[1], -z[1]),
                 (-x[2], -y[2], z[2]), (-x[3], y[3], z[3]),
                 (x[4], -y[4], -z[4]), (x[5], y[5], -z[5]),
                 (x[6], -y[6], z[6]), (x[7], y[7], z[7])]
        faces = [[0, 1, 3, 2], [0, 1, 5, 4], [0, 4, 6, 2], [7, 5, 4, 6],
                 [7, 3, 2, 6], [7, 5, 1, 3]]

    # name = "Rock." + str(base + shift).zfill(3)
    name = "rock"

    # Make object:
    obj = createMeshObject(context, verts, [], faces, name)

    if scaleDisplace:
        # bpy.data.objects[name].scale = Vector((averageX, averageY, averageZ))
        obj.scale = Vector((averageX, averageY, averageZ))

    # For a slight speed bump / Readability:
    # mesh = bpy.data.meshes[name]
    mesh = obj.data

    # Apply creasing:
    if shape == 0:
        for i in range(12):
            # todo: "0.375 / 3"?  WTF?  That = 0.125. . . .
            #   *** Completed 7/15/2011: Changed second one ***
            mesh.edges[i].crease = gauss(0.125, 0.125)
    elif shape == 1:
        for i in [0, 2]:
            mesh.edges[i].crease = gauss(0.5, 0.125)
        for i in [6, 9, 11, 12]:
            mesh.edges[i].crease = gauss(0.25, 0.05)
        for i in [5, 7, 15, 16]:
            mesh.edges[i].crease = gauss(0.125, 0.025)
    elif shape == 2:
        for i in range(18):
            mesh.edges[i].crease = gauss(0.125, 0.025)
    elif shape == 3:
        for i in [0, 1, 6, 10, 13]:
            mesh.edges[i].crease = gauss(0.25, 0.05)
        mesh.edges[8].crease = gauss(0.5, 0.125)
    elif shape == 4:
        for i in [5, 6, 7, 10, 14, 16, 19, 21]:
            mesh.edges[i].crease = gauss(0.5, 0.125)
    elif shape == 7:
        for i in range(18):
            if i in [0, 1, 2, 3, 6, 7, 8, 9, 13, 16]:
                mesh.edges[i].crease = gauss(0.5, 0.125)
            elif i in [11, 17]:
                mesh.edges[i].crease = gauss(0.25, 0.05)
            else:
                mesh.edges[i].crease = gauss(0.125, 0.025)
    elif shape == 8:
        for i in range(12):
            if i in [0, 3, 8, 9, 10]:
                mesh.edges[i].crease = gauss(0.5, 0.125)
            elif i == 11:
                mesh.edges[i].crease = gauss(0.25, 0.05)
            else:
                mesh.edges[i].crease = gauss(0.125, 0.025)
    elif shape == 9:
        for i in range(12):
            if i in [0, 3, 4, 11]:
                mesh.edges[i].crease = gauss(0.5, 0.125)
            else:
                mesh.edges[i].crease = gauss(0.25, 0.05)
    elif shape == 10:
        for i in range(12):
            if i in [0, 2, 3, 4, 8, 11]:
                mesh.edges[i].crease = gauss(0.5, 0.125)
            elif i in [1, 5, 7]:
                mesh.edges[i].crease = gauss(0.25, 0.05)
            else:
                mesh.edges[i].crease = gauss(0.125, 0.025)
    elif shape == 11:
        for i in range(11):
            if i in [1, 2, 3, 4, 8, 11]:
                mesh.edges[i].crease = gauss(0.25, 0.05)
            else:
                mesh.edges[i].crease = gauss(0.125, 0.025)

    return obj
 def __call__(self, image, boxes=None, labels=None):
     if random.randint(2):
         swap = self.perms[random.randint(len(self.perms))]
         shuffle = SwapChannels(swap)  # shuffle channels
         image = shuffle(image)
     return image, boxes, labels
Пример #43
0
'''

from numpy import random

def moyenne(tab):
    s=0
    for x in tab:
        s+=x
    return s/len(tab)

def variance(tab):
    m=moyenne(tab)
    s=0
    for x in tab:
        s+=(x-m)**2
    return s/len(tab)

def var(tab):
    s=0;
    ss=0;
    for x in tab:
        s+=x
        ss+=x**2
    n=len(tab)
    return ss/n-(s/n)**2

tab=random.randint(1,100,20)
print(tab)
print(moyenne(tab))
print(variance(tab))
print(var(tab))
    def __call__(self, image, boxes=None, labels=None):
        if random.randint(2):
            image[:, :, 1] *= random.uniform(self.lower, self.upper)

        return image, boxes, labels
Пример #45
0
    def __init__(self,
                 n_in,
                 n_rec,
                 tau=20.,
                 thr=0.03,
                 dt=1.,
                 n_refractory=0,
                 dtype=tf.float32,
                 n_delay=1,
                 rewiring_connectivity=-1,
                 in_neuron_sign=None,
                 rec_neuron_sign=None,
                 dampening_factor=0.3,
                 injected_noise_current=0.,
                 V0=1.):
        """
        Tensorflow cell object that simulates a LIF neuron with an approximation of the spike derivatives.

        :param n_in: number of input neurons
        :param n_rec: number of recurrent neurons
        :param tau: membrane time constant
        :param thr: threshold voltage
        :param dt: time step of the simulation
        :param n_refractory: number of refractory time steps
        :param dtype: data type of the cell tensors
        :param n_delay: number of synaptic delay, the delay range goes from 1 to n_delay time steps
        :param reset: method of resetting membrane potential after spike thr-> by fixed threshold amount, zero-> to zero
        """

        if np.isscalar(tau): tau = tf.ones(n_rec, dtype=dtype) * np.mean(tau)
        if np.isscalar(thr): thr = tf.ones(n_rec, dtype=dtype) * np.mean(thr)
        tau = tf.cast(tau, dtype=dtype)
        dt = tf.cast(dt, dtype=dtype)

        self.dampening_factor = dampening_factor

        # Parameters
        self.n_delay = n_delay
        self.n_refractory = n_refractory

        self.dt = dt
        self.n_in = n_in
        self.n_rec = n_rec
        self.data_type = dtype

        self._num_units = self.n_rec

        self.tau = tf.Variable(tau, dtype=dtype, name="Tau", trainable=False)
        self._decay = tf.exp(-dt / tau)
        self.thr = tf.Variable(thr,
                               dtype=dtype,
                               name="Threshold",
                               trainable=False)

        self.V0 = V0
        self.injected_noise_current = injected_noise_current

        self.rewiring_connectivity = rewiring_connectivity
        self.in_neuron_sign = in_neuron_sign
        self.rec_neuron_sign = rec_neuron_sign

        with tf.variable_scope('InputWeights'):

            # Input weights
            if 0 < rewiring_connectivity < 1:
                self.w_in_val, self.w_in_sign, self.w_in_var, _ = weight_sampler(
                    n_in,
                    n_rec,
                    rewiring_connectivity,
                    neuron_sign=in_neuron_sign)
            else:
                self.w_in_var = tf.Variable(rd.randn(n_in, n_rec) /
                                            np.sqrt(n_in),
                                            dtype=dtype,
                                            name="InputWeight")
                self.w_in_val = self.w_in_var

            self.w_in_val = self.V0 * self.w_in_val
            self.w_in_delay = tf.Variable(rd.randint(
                self.n_delay, size=n_in * n_rec).reshape(n_in, n_rec),
                                          dtype=tf.int64,
                                          name="InDelays",
                                          trainable=False)
            self.W_in = weight_matrix_with_delay_dimension(
                self.w_in_val, self.w_in_delay, self.n_delay)

        with tf.variable_scope('RecWeights'):
            if 0 < rewiring_connectivity < 1:
                self.w_rec_val, self.w_rec_sign, self.w_rec_var, _ = weight_sampler(
                    n_rec,
                    n_rec,
                    rewiring_connectivity,
                    neuron_sign=rec_neuron_sign)
            else:
                if rec_neuron_sign is not None or in_neuron_sign is not None:
                    raise NotImplementedError(
                        'Neuron sign requested but this is only implemented with rewiring'
                    )
                self.w_rec_var = Variable(rd.randn(n_rec, n_rec) /
                                          np.sqrt(n_rec),
                                          dtype=dtype,
                                          name='RecurrentWeight')
                self.w_rec_val = self.w_rec_var

            recurrent_disconnect_mask = np.diag(np.ones(n_rec, dtype=bool))

            self.w_rec_val = self.w_rec_val * self.V0
            self.w_rec_val = tf.where(recurrent_disconnect_mask,
                                      tf.zeros_like(self.w_rec_val),
                                      self.w_rec_val)  # Disconnect autotapse
            self.w_rec_delay = tf.Variable(rd.randint(
                self.n_delay, size=n_rec * n_rec).reshape(n_rec, n_rec),
                                           dtype=tf.int64,
                                           name="RecDelays",
                                           trainable=False)
            self.W_rec = weight_matrix_with_delay_dimension(
                self.w_rec_val, self.w_rec_delay, self.n_delay)
Пример #46
0
def get_minibatch(roidb, num_classes):
    """Given a roidb, construct a minibatch sampled from it."""
    num_images = len(roidb)
    # Sample random scales to use for each image in this batch
    random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),
                                    size=num_images)
    assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \
        'num_images ({}) must divide BATCH_SIZE ({})'. \
        format(num_images, cfg.TRAIN.BATCH_SIZE)
    rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images
    fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)

    # Get the input image blob, formatted for caffe
    im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)

    blobs = {'data': im_blob}

    if cfg.TRAIN.HAS_RPN:
        assert len(im_scales) == 1, "Single batch only"
        assert len(roidb) == 1, "Single batch only"
        # gt boxes: (x1, y1, x2, y2, cls)
        gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]
        gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)
        gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]
        gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]
        blobs['gt_boxes'] = gt_boxes
        blobs['im_info'] = np.array(
            [[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],
            dtype=np.float32)
    else: # not using RPN
        # Now, build the region of interest and label blobs
        rois_blob = np.zeros((0, 5), dtype=np.float32)
        labels_blob = np.zeros((0), dtype=np.float32)
        bbox_targets_blob = np.zeros((0, 4 * num_classes), dtype=np.float32)
        bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)
        # all_overlaps = []
        for im_i in xrange(num_images):
            labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \
                = _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image,
                               num_classes)

            # Add to RoIs blob
            rois = _project_im_rois(im_rois, im_scales[im_i])
            batch_ind = im_i * np.ones((rois.shape[0], 1))
            rois_blob_this_image = np.hstack((batch_ind, rois))
            rois_blob = np.vstack((rois_blob, rois_blob_this_image))

            # Add to labels, bbox targets, and bbox loss blobs
            labels_blob = np.hstack((labels_blob, labels))
            bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))
            bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))
            # all_overlaps = np.hstack((all_overlaps, overlaps))

        # For debug visualizations
        # _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps)

        blobs['rois'] = rois_blob
        blobs['labels'] = labels_blob

        if cfg.TRAIN.BBOX_REG:
            blobs['bbox_targets'] = bbox_targets_blob
            blobs['bbox_inside_weights'] = bbox_inside_blob
            blobs['bbox_outside_weights'] = \
                np.array(bbox_inside_blob > 0).astype(np.float32)

    return blobs
Пример #47
0
def detect(opt):
    source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
    save_img = not opt.nosave and not source.endswith(
        '.txt')  # save inference images
    webcam = source.isnumeric() or source.endswith(
        '.txt') or source.lower().startswith(
            ('rtsp://', 'rtmp://', 'http://', 'https://'))

    # Directories
    save_dir = increment_path(Path(opt.project) / opt.name,
                              exist_ok=opt.exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(
        parents=True, exist_ok=True)  # make dir

    # Initialize
    set_logging()
    device = select_device(opt.device)
    half = device.type != 'cpu'  # half precision only supported on CUDA

    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    stride = int(model.stride.max())  # model stride
    imgsz = check_img_size(imgsz, s=stride)  # check img_size
    if half:
        model.half()  # to FP16

    # Second-stage classifier
    classify = False
    if classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(
            torch.load('weights/resnet101.pt',
                       map_location=device)['model']).to(device).eval()

    # Set Dataloader
    vid_path, vid_writer = None, None
    if webcam:
        view_img = check_imshow()
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride)
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride)

    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]

    # Run inference
    if device.type != 'cpu':
        model(
            torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(
                next(model.parameters())))  # run once
    t0 = time.time()
    for path, img, im0s, vid_cap in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]

        # Apply NMS
        pred = non_max_suppression(pred,
                                   opt.conf_thres,
                                   opt.iou_thres,
                                   classes=opt.classes,
                                   agnostic=opt.agnostic_nms)
        t2 = time_synchronized()

        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            if webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(
                ), dataset.count
            else:
                p, s, im0, frame = path, '', im0s.copy(), getattr(
                    dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # img.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + (
                '' if dataset.mode == 'image' else f'_{frame}')  # img.txt
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1,
                                          0]]  # normalization gain whwh
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4],
                                          im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) /
                                gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if opt.save_conf else (
                            cls, *xywh)  # label format
                        with open(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or opt.save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if opt.hide_labels else (
                            names[c]
                            if opt.hide_conf else f'{names[c]} {conf:.2f}')

                        plot_one_box(xyxy,
                                     im0,
                                     label=label,
                                     color=colors[c],
                                     line_thickness=opt.line_thickness)
                        if opt.save_crop:
                            save_one_box(xyxy,
                                         im0s,
                                         file=save_dir / 'crops' / names[c] /
                                         f'{p.stem}.jpg',
                                         BGR=True)

            # Print time (inference + NMS)
            print(f'{s}Done. ({t2 - t1:.3f}s)')

            # Stream results
            if view_img:
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path != save_path:  # new video
                        vid_path = save_path
                        if isinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release(
                            )  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                            save_path += '.mp4'
                        vid_writer = cv2.VideoWriter(
                            save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps,
                            (w, h))
                    vid_writer.write(im0)

    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        print(f"Results saved to {save_dir}{s}")

    print(f'Done. ({time.time() - t0:.3f}s)')
Пример #48
0
    if i == 0:      # Correção para o primeiro spin
        ve[i] = L-1
    vd[i] = i+1     # Vizinho à direita
    if i == L-1:    # Correção para o último spin
        vd[i] = 0

# Definimos uma função para calcular a energia de uma configuração
def Energia(s):
    soma = 0.0
    for i in range(L):
        soma += -J*s[i]*s[vd[i]] -B*s[i]
    return soma

# Simulação. Definimos uma função para implementar um único passo
# de Monte Carlo. Buscamos coletar médias apenas após a equilibração.
s = 1-2*random.randint(2, size=L)   # Estados iniciais aleatórios dos spins

def passo_MC(s,boltz):  # Função que implementa um passo de Monte Carlo
    z = random.rand(L)  # Sorteamos L números aleatórios
    # Damos a cada spin a chance de mudar de estado, mas aqui fazemos
    # isso aleatoriamente para minimizar correlações entre mudanças.
    for i in random.permutation(L):
        bf = boltz[s[i],s[ve[i]] + s[vd[i]]]
        if z[i] < bf or (bf == boltz[s[i],0] and z[i]<0.5):# Mudança foi aceita?
            s[i] = -s[i]                     # Registramos a mudança
    return s

for iT in range(nT):
    E_plot = []
    T = T_lista[iT]
    print("Simulando à temperatura T=",T)
Пример #49
0
def select(data, num):
    return data[random.randint(0, data.shape[0], num)]
Пример #50
0
def download_page_disease(department_code, page_num=1, try_num=3):
    #获取下载页面的编号
    code_page = '\\'.join([department_code, str(page_num)])

    #读取缓存
    html_text = read_page_cache(code_page)

    #如果没有缓存,则下载该网页并缓存
    if not html_text:
        #设定 post 内容
        request_payload = {
            "departmentCode": department_code,
            "icd10code": "",
            "pageNo": page_num,
            "pageSize": "50",
            "recordFlag": "record",
            "searchText": "",
            "symptomsWords": ""
        }
        #print (request_payload)

        #如果还有下载次数
        if try_num:
            #设定访问主页链接
            target_url = 'http://ccdas.ipmph.com/rwDisease/getRwDiseaseList'
            #设置 用户代理
            random_header = get_request_headers()
            #设置 IP代理
            random_proxy = get_ip_proxy()
            #print (random_header, '\t', random_proxy)

            #下载之前,暂停
            sleep_time = random.randint(5, 10)
            print('Sleep {}s .. Downloading {}'.format(sleep_time, code_page))
            sleep(sleep_time)

            #下载
            try:
                html_res = requests.request(method='POST',
                                            url=target_url,
                                            headers=random_header,
                                            proxies=random_proxy,
                                            json=request_payload)
                #print (html_res)
            except Exception as err:
                print('Download {} Error: {}'.format(code_page, err))
                print('The Rest Download Number is {} ..'.format(try_num - 1))
                return (download_page_disease(department_code, page_num,
                                              try_num - 1))
            else:
                #将下载的网页保存
                if html_res:
                    html_text = html_res.text
                    save_page_cache(html_text, code_page)
                    #print (html_text)
                    #print_to_json(html_text, 'test_post_1.txt')
        else:
            #如果下载次数用完,则不再下载,返回 None
            print('Download Number is 0 ! {} Return None'.format(code_page))
            html_text = None
    else:
        #再次缓存该文件
        save_page_cache(html_text, code_page)

    #返回 总页数
    if page_num == 1:
        try:
            html_json = json.loads(html_text)
        except:
            return (None)
        else:
            #print (html_json['result']['totlePage'])
            return (html_json['result']['totlePage'])
Пример #51
0
    def __init__(self, rare, iClass=None, iName=None):
        self.Rarity = rare
        # Pick the part to Augment
        if iClass is not None and iClass in self.Slots:
            self.Class = iClass
        else:
            self.Class = choice(self.Slots)

        m_name, m_info = self.__choose_material()

        if self.Class == 'Arm' and randint(4) == 1:
            self.Slot_Special = Firearm(self.Rarity)
            self.Name = self.Slot_Special.Name + " Arm"

        elif self.Class == 'Arm':
            self.Slot_Special = Weapon(self.Rarity,
                                       iClass=choice(
                                           list(possible_melee.keys())))
            self.Name = self.Slot_Special.Name + " Arm"

        elif self.Class == 'Leg':
            nam = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                   13][self.Rarity:self.Rarity + 9]
            self.Slot_Special = str(
                choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
                        ][self.Rarity:self.Rarity + 9],
                       p=[
                           0.360000001, 0.252839506, 0.169382716, 0.106666667,
                           0.061728395, 0.031604938, 0.013333333, 0.003950617,
                           0.000493827
                       ]) * 10)
            self.Slot_Special = '+' + self.Slot_Special + ' Base Movement Speed'
            self.Name = m_name + ' Legs'

        elif self.Class == 'Eye':
            self.Slot_Special = str(
                choice([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
                        ][self.Rarity:self.Rarity + 9],
                       p=[
                           0.360000001, 0.252839506, 0.169382716, 0.106666667,
                           0.061728395, 0.031604938, 0.013333333, 0.003950617,
                           0.000493827
                       ]) * 10) + " "
            self.Name = m_name + ' Optical Implant'

            if self.Rarity < 2:
                self.Slot_Special += ' ft. Darkvision'
            elif self.Rarity < 4:
                self.Slot_Special += ' ft. Thermal'
            elif self.Rarity == 4:
                self.Slot_Special = str(eval(self.Slot_Special) - 40)
                self.Slot_Special += ' ft. True Sight'

        elif self.Class == 'Nose':
            self.Slot_Special = ""

        elif self.Class == 'Brain':
            num = str(
                choice([1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 9,
                        9][self.Rarity:self.Rarity + 9],
                       p=[
                           0.360000001, 0.252839506, 0.169382716, 0.106666667,
                           0.061728395, 0.031604938, 0.013333333, 0.003950617,
                           0.000493827
                       ]))
            self.Slot_Special = "+" + num + " " + choice(
                ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'])
            self.Name = m_name + " " + self.Class + " Implant"

        elif self.Class == 'Chest':
            self.Slot_Special = Armor(self.Rarity, iName="")
            self.Name = self.Slot_Special.Name + " Natural Armor"

        # Are there potential Add-ins?
        self.__add_ins()

        # Change name if necessary
        if iName is not None:
            self.Name = iName
Пример #52
0
l = []
for k in xrange(2,maxK + 1):
    l.append([])
    dN = np.power(2,k-1)
    print k
    for i in xrange(numNBINS):
        l[k-2].append([])
        nMin = 1 + i*dN
        nMax = 1 + (1 + i)*dN

        bins = []
        for x in xrange(numHBINS):
            bins.append([[],[]])                    
        for j in xrange(NUMTRIALS/numNBINS):
            
            N = random.randint(nMin, nMax)
            vnum = random.randint(0, models[k-2].shape[0])
            verse = models[k-2][vnum].tolist()[0]
            obs = get_obs(verse, N, k)
            h = entropy(obs, k)
            bins[np.int(0.999999*h/HbinWidth)][0].append(obs)            
            bins[np.int(0.999999*h/HbinWidth)][1].append(vnum)

        for x in xrange(numHBINS):
            mbins = [np.asmatrix(bins[x][0]),np.asarray(bins[x][1])]
            l[k-2][i].append(mbins)

#Finally pickling the result for later use
f = open("obs.pkl", "wb")
cPickle.dump(l, f)
f.close()
Пример #53
0
def simulate(ntrials, region, T, printonswap=False, printbrackets=True):
    """
    If region is "west" "midwest" "south" or "east" we'll run a bracket based 
    just on those teams.
    If it's "all" we'll run a full bracket.
    If it's a list of teams, we'll run a bracket based just on that list.

    So, one way you might want to do things is to simulate 10000 runs for each 
    of the four brackets,
    then run your final four explicitly, e.g.

    T = 1.5
    simulate(10000,'midwest',T)
    # record results
    simulate(10000,'south',T)
    # record results
    simulate(10000,'west',T)
    # record results
    simulate(10000,'east',T)
    # record results

    simulate(10000,['Louisville','Kansas','Wisconsin','Indiana'],T)
    """

    if type(region) in (type([]), type(())):
        teams = region[:]
    else:
        teams = _teams.teams[region]
    b = Bracket(teams, T)
    energy = b.energy()
    ng = sum(b.games_in_rounds)  # total number of games
    # Let's collect some statistics
    brackets = []
    for trial in range(ntrials):
        g = randint(0, ng)  # choose a random game to swap
        #print "attempted swap for game",g#,"in round",round[g]
        #newbracket = deepcopy(b)
        newbracket = b.copy()
        newbracket.swap(g)
        newenergy = newbracket.energy()
        ediff = newenergy - energy
        if ediff <= 0:
            b = newbracket
            energy = newenergy
            if printonswap:
                print("LOWER")
                print(b)
        else:
            if random() < exp(-ediff / T):
                b = newbracket
                energy = newenergy
                if printonswap:
                    print("HIGHER")
                    print(b)
        brackets.append(b)


    lb, mcb, mcb_count, unique_brackets, lowest_sightings = \
        Stats.gather_uniquestats(brackets)
    sr = SimulationResults(brackets, unique_brackets, lb, lowest_sightings,
                           mcb, mcb_count)
    if printbrackets:
        print("Lowest energy bracket")
        print(lb)
        print("Most common bracket (%s)" % mcb_count)
        print(mcb)
    return sr
Пример #54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
select wd40s with repeats 6n,7n,8n
"""
from wdsp import Wdsp
import numpy as np
from numpy.random import randint

with open('wd648_uniprot_select_cd-hit_90_7.wdsp') as wdsp_f:
    wdsp = Wdsp(wdsp_f)
    pro_num = len(wdsp.pros)
    for i in range(100):
        with open('random_' + str(i) + '.fa', 'w') as w_f:
            for j in range(2):
                pro = wdsp.pros[randint(0, pro_num)]
                seq = wdsp.seqs[pro]
                print >> w_f, '> ', pro
                for s in [seq[i:i + 80] for i in range(0, len(seq), 80)]:
                    print >> w_f, s
Пример #55
0
# ## Task 2:  Implement a simple reflex agent
# 
# The simple reflex agent randomly walks around but reacts to the bumper sensor by not bumping into the wall and to dirt with sucking.

# In[1426]:


createSquares()

#for some reason, between task1 and task2, all squares were being initialized to clean (isDirty = False)
#even though I instantiate a new environment and even though numDirty is not zero
#this for loop takes numDirty and reallocates which squares are dirty just to take care of this problem
#not my favorite way to solve this problem, but it solves the problem
for x in range(numDirty):
    i = random.randint(0,n-1)
    j = random.randint(0, n-1)
    
    #if the random square is already dirty, find random indexes until find a clean square
    while(environment[i][j].isDirty == True):
        i = random.randint(0,n-1)
        j = random.randint(0, n-1)
        
    environment[i][j].isDirty = True

#assortment of actions that can be randomly selected from 
randomMove = ["north", "east", "west", "south"]
exNMove = ["east", "west", "south"]
exSMove = ["east", "west", "north"]
exEMove = ["south", "west", "north"]
exWMove = ["east", "south", "north"] 
Пример #56
0
def generatefigures(data_stage='training1', num_areas=8, area_dis=32, num_numerosities=32, num_fig=200,
                    pix_buffer=1, noise_lev1=0.15, noise_lev2=0.3, dim_fig=30, pickle_data=True):
    """Generate training and testing data for the RBM.

    Parameters:
    :param data_stage: function of the data to be produced (default: 'training1')
    :param num_areas: number of area levels (default: 8)
    :param area_dis: distance between areas in pixels (default: 32)
    :param num_numerosities: range of numerosities (default: 32)
    :param num_fig: number of figures to be generated per area - numerosity combination (default: 200)
    :param pix_buffer: buffer between objects in the figures (default: 1)
    :param noise_lev1: first noise level in generating object dimensions (default: 0.15)
    :param noise_lev2: second noise level in generating object dimensions (default: 0.3)
    :param dim_fig: dimensions in pixels of the (square) figures to be generated (default: 30)
    :param pickle_data: whether to pickle data or return it (default: True)
    :return: file or dictionary with data figures and supplementary information, depending on variable pickle_data.
     Dictionary elements:
     'data_array': array containing the figures as rows, shape: (num_fig_tot, dim_fig^2)
     'data_array_info': list of lists containing information about the dataset per figure [fig_index, area, numerosity]
     'obj_info': list of arrays. One array per figure, shape: [fig_numerosity, 4]. Each row of the array contains the
      dimensions and coordinates of an object: (obj_width, obj_height, obj_x, obj_y).
     'parameter_list': list containing information about the dataset at large: [num_areas (int), num_numerosities (int),
      num_fig (int), area_dis (int), areas (list), numerosities (list)
     'surf_area': list with length num_fig_tot containing the total surface area of all objects per figure in pixels
    """

    areas = [((x + 1) * area_dis) for x in range(num_areas)]            # List of cumulative surface areas [32-256]
    # (actual surface areas will vary slightly because of gaussian noise added in loop below)
    numerosities = [(x + 1) for x in range(num_numerosities)]           # Create list of numerosities [1-32]
    
    num_fig_tot = num_areas * num_numerosities * num_fig        # Total number of images to be created
    fig_counter = 0                                             # Figure counter, up to (num_fig_tot-1) (=51,200-1)
    dim_fig_tot = dim_fig**2                                    # Get length of input vector
    # Some parameters for future use
    parameter_list = [num_areas, num_numerosities, num_fig, area_dis, areas, numerosities]
    
    while_limit = 200                               # Set maximum times new coordinates are generated before quitting
    while_limit2 = 300                              # Set maximum times all object coordinates are reset before quitting
    
    data_array = np.zeros((num_fig_tot, dim_fig_tot))         # Make data array to insert images in, then to be pickled
    data_array_info = []                            # Empty list to append figure information to. Becomes list of lists
    obj_info = []                                   # Empty list to append all object info to, becomes list of arrays
    surf_area = []                                  # Empty list to append total surface area per figure to

    """Generate object dimensions and coordinates"""
    for area in areas:                                                  # Cycle over cumulative surface area levels
        
        for numerosity in numerosities:                                 # Cycle over numerosity levels
        
            for _ in range(num_fig):                                    # Cycle over number of figures per combination
                
                counter2 = 0                                            # Infinite while loop protections

                """Loop to assign dimensions to each object"""
                while counter2 < while_limit2:
                    
                    counter3 = 0                                        # Infinite while loop protection
                    
                    while counter3 < while_limit:
                        
                        res_area = area                                 # Get variable residual area
                        
                        fig_array = np.zeros((dim_fig, dim_fig))    # Make figure array to add obj_ones to
                        obj_array = np.zeros((numerosity, 4))       # Make object array to add dim and coordinates to:
                        # [x, :2] = dimensions, [x, 2:] = left upper corner. Mostly for debugging.

                        res_obj = numerosity
                        
                        for item in range(numerosity):
                            
                            res_obj = numerosity - item
                            obj_noise = elrandom.normal(0, noise_lev1, 1)       # Create first layer of noise
                            obj_area = (float(res_area) / res_obj) + obj_noise  # Calculate area plus first noise layer
                            
                            if obj_area <= 0:  # Exit for loop and restart while loop if obj area is zero to avoid error
                                counter3 += 1
                                break
                            
                            obj_dim = mt.sqrt(obj_area)       # Take root of area to obtain initial object dimensions
                            list_dim = [obj_dim] * 2          # Create list with two initial positive dimensions

                            """While loop to avoid negative or zero dimensions"""
                            while True:
                                dim_noise = elrandom.normal(0, noise_lev2, 2)
                                # Create random noise array to add to object dimensions
                                dim = list_dim + dim_noise           # Array 'dim' contains actual dimensions of object
                                dim_round = np.around(dim, 0)        # Round the dimensions
                                
                                """If all dimensions are greater than zero the while loop can be exited
                                NOTE: CAN CAUSE A SLIGHT BIAS TOWARDS LARGER CUMULATIVE SURFACE AREAS"""
                                if all(x > 0 for x in dim_round):
                                    break
                            
                            obj_array[item, :2] = dim_round           # Insert rounded dimensions into the object array
                            
                            act_area = dim_round[0] * dim_round[1]    # Calculate actual surface area
                            res_area -= act_area                      # Subtract actual object area from total area
                            
                            if res_obj == 1:               # Way to communicate all dimensions are assigned successfully
                                res_obj = 0

                        """If all objects are assigned successfully in for loop above, dimensions while loop can exit.
                        Otherwise initiate next round of dimension assignment."""
                        if res_obj == 0:
                            break
                        
                        if counter3 == while_limit:               # Let's check if this ever happens with these settings
                            print('Failed dimension assignment.')

                    obj_placed = 0                           # To keep track of all objects that are successfully placed
                    
                    """Now that all objects have dimensions, generate object coordinates one by one"""
                    for item in range(numerosity):
                        
                        counter1 = 0                              # Used to avoid infinite while Loop
                        
                        """Set some parameter used in this section"""
                        obj_width = obj_array[item, 0]
                        obj_height = obj_array[item, 1]
                        x_limit = dim_fig - obj_width
                        y_limit = dim_fig - obj_height
                        
                        # obj_area = obj_width * obj_height           # Used in debugging
                        
                        while counter1 < while_limit:
                            
                            # Generate random x-coordinate for left upper corner:
                            obj_array[item, 2] = elrandom.randint(0, (x_limit + 1))
                            obj_x = obj_array[item, 2]
                            # Generate random y-coordinate for left upper corner:
                            obj_array[item, 3] = elrandom.randint(0, (y_limit + 1))
                            obj_y = obj_array[item, 3]
                            # Object array is not really used for anything else after this, handy for debugging?
                            
                            # Make ones array in shape of object:
                            obj_ones = np.ones((obj_width, obj_height))

                            """Check if the assigned space in the figure array is available"""
                            
                            # Determine size of pixel buffer:
                            # X:
                            if obj_x == 0 or obj_x == (dim_fig - obj_width):
                                x_buffer = 1 * pix_buffer
                            else:
                                x_buffer = 2 * pix_buffer
                            # Y:
                            if obj_y == 0 or obj_y == (dim_fig - obj_height):
                                y_buffer = 1 * pix_buffer
                            else:
                                y_buffer = 2 * pix_buffer
                            
                            # Make zeros array shape of obj plus buffer, used to check availability of assigned space:
                            obj_zeros_width = int(obj_width + x_buffer)
                            obj_zeros_height = int(obj_height + y_buffer)
                            obj_zeros = np.zeros((obj_zeros_width, obj_zeros_height))
                            
                            # Assign coordinates to zeros array (= size of area to be checked).
                            # Coordinates depend on location of object (whether it is right at the edges of the figure)
                            if obj_x == 0:                          # X
                                x_obj_zeros = obj_x
                            else:
                                x_obj_zeros = obj_x - 1
                            
                            if obj_y == 0:                          # Y
                                y_obj_zeros = obj_y
                            else:
                                y_obj_zeros = obj_y - 1
                            
                            # Check if the space with buffer is available:
                            # For better overview:
                            obj_z_left = int(x_obj_zeros)
                            obj_z_right = int(x_obj_zeros + obj_zeros_width)
                            obj_z_up = int(y_obj_zeros)
                            obj_z_down = int(y_obj_zeros + obj_zeros_height)
                            
                            # Variable representing the target area in the figure array:
                            test_area = fig_array[obj_z_left:obj_z_right, obj_z_up:obj_z_down]

                            """If space is available, insert ones and move on to next object.
                            If not, loop again and get new coordinates to try."""
                            if (obj_zeros == test_area).all():
                                # If so, generated coordinates can be used:
                                obj_array[item, 2:4] = [obj_x, obj_y]   # Fill obj array with coordinates for debugging
                                
                                # For better overview:
                                obj_left = int(obj_x)
                                obj_right = int(obj_x + obj_width)
                                obj_up = int(obj_y)
                                obj_down = int(obj_y + obj_height)
                                
                                # Insert ones in the location of the object the figure array:
                                fig_array[obj_left:obj_right, obj_up:obj_down] = obj_ones
                                
                                # Once valid location is found and object is inserted, record that and exit while loop:
                                obj_placed += 1
                                break

                            else:
                                """If the space is not available, add 1 to while counter and do while loop again,
                                so new coordinates are generated and checked for this particular object."""
                                counter1 += 1                       # Loop will exit automatically once limit is reached

                    """If all objects are placed we can exit the while loop and store the object information"""
                    if obj_placed == numerosity:
                        new_info = [fig_counter, area, numerosity]
                        data_array_info.append(new_info)
                        obj_info.append(obj_array)
                        # print('Figure: %d, Area: %d, Numerosity: %d, Objects placed: %d'
                        # % ((fig_counter+1), area, numerosity, obj_placed))
                        break

                    """If not, the while loop needs to be executed again to generate new coordinates for all objects
                    in this particular image"""
                    counter2 += 1                                       # Infinite while loop protection 2
                    if counter2 == while_limit2:                        # Used in debugging
                        print('Failed figure.')
                        print('Area = {}, numerosity = {}'.format(area, numerosity))
                        print('Figure index = {}, objects placed = {}'.format(fig_counter, obj_placed))

                """Add complete figures to final array, and pickle final array"""
                fig_list = fig_array.flatten()                          # Flatten array to obtain vectorized figure
                data_array[fig_counter, :] = fig_list                    # Add obtained vector as row to final array
                surf_area.append(sum(fig_list))                         # Store surface area of this figure
                fig_counter += 1
                
    # Create main dictionary with all information
    return_dict = {'data_array': data_array, 'data_array_info': data_array_info, 'obj_info': obj_info,
                   'parameter_list': parameter_list, 'surf_area': surf_area}
    
    """Depending on pickle_data: pickle output file, otherwise return."""
    if pickle_data:
        pickle.dump(return_dict, open(data_stage, 'wb'))
    else:
        return return_dict
Пример #57
0
        
    Q = 10.0*2.0**L
    K = floor(n/L)-Q
    
    p = 2.0**L
    c = 0.7-0.8/L+(4.0+32.0/L)*(K**(-3.0/L))/15.0
    sigma = c*sqrt(variance[int(L)]/K)
    T = zeros(p)
    
    for i in range(1,int(Q+1)):
        decRep = 0.0
        for j in range(int(L)):
            decRep += bits[int((i-1)*L+j)]*2**(L-1-j)
        T[decRep] = i
    
    total = 0.0
    for i in range(int(Q+1),int(Q+K+1)):
        decRep = 0.0
        for j in range(int(L)):
            decRep += bits[int((i-1)*L+j)]*2**(L-1-j)
        total += log(i-T[decRep],2)
        T[decRep] = i
        
    phi = total/K
    arg = (phi-expected[int(L)])/sigma
    p_value = erfc(abs(arg)/sqrt(2))
    return p_value

if __name__ == "__main__":   
    bits = random.randint(0,2,4000)
    print '%.2f' % (UST(bits))
 def setUp(self) -> None:
     seed(seed=5)
     self.testData = randint(low=0, high=50, size=15)
     self.testData2 = randint(low=1, high=51, size=15)
Пример #59
0
                if j:
                    Nk[j] = Nk[j] * V(i, k - j,
                                      t) + Nk[j - 1] * (1 - V(i, k - j + 1, t))
                else:
                    Nk[j] = Nk[j] * V(i, k - j, t)
        Nk.reverse()

        return [
            sum(p[j] * N for p, N in zip(self.points[k - self.m:k + 1], Nk))
            for j in (0, 1)
        ]


if __name__ == '__main__':

    control_points = tuple([(random.randint(0, 10), random.randint(0, 10))
                            for k in range(random.randint(4, 7))])
    degree = 3
    N = 100

    bspline = Bspline(control_points, degree)

    points = map(bspline.curve, (i / N for i in xrange(N + 1)))
    x, y = ([p[j] for p in points] for j in (0, 1))
    plt.plot(x, y, 'b-')
    x, y = ([p[j] for p in control_points] for j in (0, 1))
    plt.plot(x, y, 'ro-')

    plt.grid(True)
    plt.show()
Пример #60
0
 def take_action_eval(self, state):
     if self.eval_epsilon > npr.uniform():
         return npr.randint(0, self.action_dim)
     else:
         action = self.policy_net.take_action(state).numpy()
         return action