def AdvanceTime(TimeList,ObservableList):
     
     PTrans, PAnnih, PSpawn, Norm, TranslateableLinks, AnnihilateableLinks, SpawnableLinks = Probabilities()
     
     r = random.rand()
     DeltaTau = (-1./Norm)*log(r)
     
     if (r < PTrans):
         RandLink = random.randint(len(TranslateableLinks))
         LinkCoords = TranslateableLinks[RandLink]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         MyLattice.TranslateExcitation(MyLattice.ReturnExcitationIndex(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension), XDisplacement, YDisplacement)
         
     if (r >= PTrans and r < PTrans + PAnnih):
         RandLink = random.randint(len(AnnihilateableLinks))
         LinkCoords = AnnihilateableLinks[RandLink]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         #if(LinkCoords[2]==MyLattice.Dimension or LinkCoords[0] == MyLattice.Dimension - 1):
             #print str(LinkCoords[2]) + "\t" + str(LinkCoords[0])
             #print str(LinkCoords[3]) + "\t" + str(LinkCoords[1])
         MyLattice.AnnihilateExcitation(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension)
         MyLattice.AnnihilateExcitation(LinkCoords[2]%MyLattice.Dimension,LinkCoords[3]%MyLattice.Dimension)
         MyLattice.CheckSector(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension, XDisplacement, YDisplacement)
     
     if (r >= PTrans + PAnnih):
         RandLink = random.randint(len(SpawnableLinks))
         LinkCoords = SpawnableLinks[RandLink]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         #if(LinkCoords[2]==MyLattice.Dimension or LinkCoords[0] == MyLattice.Dimension - 1):
         RandLink = random.randint(len(AnnihilateableLinks))
         LinkCoords = AnnihilateableLinks[RandLink]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         #if(LinkCoords[2]==MyLattice.Dimension or LinkCoords[0] == MyLattice.Dimension - 1):
             #print str(LinkCoords[2]) + "\t" + str(LinkCoords[0])
             #print str(LinkCoords[3]) + "\t" + str(LinkCoords[1])
         MyLattice.AnnihilateExcitation(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension)
         MyLattice.AnnihilateExcitation(LinkCoords[2]%MyLattice.Dimension,LinkCoords[3]%MyLattice.Dimension)
         MyLattice.CheckSector(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension, XDisplacement, YDisplacement)
     
     if (r >= PTrans + PAnnih):
         RandLink = random.randint(len(SpawnableLinks))
         LinkCoords = SpawnableLinks[RandLink]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         #if(LinkCoords[2]==MyLattice.Dimension or LinkCoords[0] == MyLattice.Dimension - 1):
             #print str(LinkCoords[2]) + "\t" + str(LinkCoords[0])
             #print str(LinkCoords[3]) + "\t" + str(LinkCoords[1])
         MyLattice.SpawnExcitation(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension)
         MyLattice.SpawnExcitation(LinkCoords[2]%MyLattice.Dimension,LinkCoords[3]%MyLattice.Dimension)
         MyLattice.CheckSector(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension, XDisplacement, YDisplacement)
     
     return DeltaTau, MyLattice.Sector
示例#2
0
def gen_bounds():
    '''
    Get bounds for master gen
    '''

    x_l = random.randint(10, 90)
    x_h = random.randint(x_l + 30, x_l + 50)
    y_l = random.randint(10, 90)
    y_h = random.randint(y_l + 30, y_l + 50)

    return x_l, x_h, y_l, y_h
    def AdvanceTime(TimeList,ObservableList):
        
        TranslateableLinks = MyLattice.TranslateableList
        AnnihilateableLinks = MyLattice.AnnihilateableList
        
        Norm = len(TranslateableLinks)*TranslateRate + len(AnnihilateableLinks)*AnnihilationRate + \
        ((2*(MyLattice.Dimension)**2) - len(AnnihilateableLinks) - len(TranslateableLinks))*SpawnRate
        
        PTrans = len(TranslateableLinks)*TranslateRate/Norm
        PAnnih = len(AnnihilateableLinks)*AnnihilationRate/Norm
        PSpawn = ((2*(MyLattice.Dimension)**2) - len(AnnihilateableLinks) - len(TranslateableLinks))*SpawnRate/Norm
        
        
        r = random.rand()
        DeltaTau = (-1./Norm)*log(r)
        
        if (r < PTrans):
            RandLink = random.randint(len(TranslateableLinks))
            LinkCoords = [TranslateableLinks[RandLink].x1,TranslateableLinks[RandLink].y1,TranslateableLinks[RandLink].x2,TranslateableLinks[RandLink].y2]
            XDisplacement = LinkCoords[2] - LinkCoords[0]
            YDisplacement = LinkCoords[3] - LinkCoords[1]
            MyLattice.TranslateExcitations(MyLattice.ReturnExcitationIndex(LinkCoords[0],LinkCoords[1]), XDisplacement, YDisplacement)
            
        if (r >= PTrans and r < PTrans + PAnnih):
            RandLink = random.randint(len(AnnihilateableLinks))
            LinkCoords = [AnnihilateableLinks[RandLink].x1,AnnihilateableLinks[RandLink].y1,AnnihilateableLinks[RandLink].x2,AnnihilateableLinks[RandLink].y2]
            XDisplacement = LinkCoords[2] - LinkCoords[0]
            YDisplacement = LinkCoords[3] - LinkCoords[1]
            MyLattice.AnnihilateExcitations(LinkCoords[0],LinkCoords[1],LinkCoords[2],LinkCoords[3])

        if (r >= PTrans + PAnnih):
            Occupancies = MyLattice.ReturnOccupancies()
            FoundCreatableLink = False
            RandX = 0
            RandY = 0
            RandDir = 0
            
            while FoundCreatableLink == False:
                RandX = random.randint(MyLattice.Dimension)
                RandY = random.randint(MyLattice.Dimension)
                RandDir = random.randint(2)
                if(Occupancies[RandX,RandY]==0 and \
                   Occupancies[(RandX + RandDir)%MyLattice.Dimension,(RandY + (1-RandDir))%MyLattice.Dimension] == 0):
                    FoundCreatableLink = True
        
            LinkCoords = [RandX,RandY,RandX + RandDir, RandY + (1-RandDir)]
            XDisplacement = LinkCoords[2] - LinkCoords[0]
            YDisplacement = LinkCoords[3] - LinkCoords[1]

            MyLattice.CreateExcitations(LinkCoords[0],LinkCoords[1],LinkCoords[2],LinkCoords[3])
        
        return DeltaTau, MyLattice.Sector, len(MyLattice.ExcitationList)
 def TrialMove(InitLat):
     InitialLattice = deepcopy(InitLat)
     InitialEnergy = 2*Je*len(InitialLattice.ExcitationList)
     
     i = 0
     ListLength = len(InitialLattice.ExcitationList)
     while i < ListLength:
         RandomDirection = random.randint(0,5)
         if InitialLattice.MoveExcitation(i,RandomDirection) == False:
             #if there was a collision, and this collision killed all the excitations
             #exit the loop
             if len(InitialLattice.ExcitationList) == 0:
                 i = 1
             #else, you've just popped the excitation under consideration, so now i is
             #point to something else
             else:
                 i = i
         #if you didn't collide with anything, continue iterating over excitations
         else:
             i += 1
         
         #The number of excitations may have gone down, so we need to keep track of that:
         ListLength = len(InitialLattice.ExcitationList)
     
     for x in xrange(InitialLattice.Dimension):
         for y in xrange(InitialLattice.Dimension):
             SpawnPairUpDown = random.randint(0,2)
             SpawnPairLeftRight = random.randint(0,2)
             
             if SpawnPairUpDown == 1:
                 InitialLattice.SpawnExcitation(x,y)
                 InitialLattice.SpawnExcitation(x,(y+1)%InitialLattice.Dimension)
                 InitialLattice.CheckSector(x,y,0,1)
             
             if SpawnPairLeftRight == 1:
                 InitialLattice.SpawnExcitation(x,y)
                 InitialLattice.SpawnExcitation((x+1)%InitialLattice.Dimension,y)
                 InitialLattice.CheckSector(x,y,1,0)
                 
     FinalEnergy = 2*Je*len(InitialLattice.ExcitationList)
     
     if(FinalEnergy <= InitialEnergy):
         return InitialLattice
     
     else:
         r = random.rand()
         print(exp(-(FinalEnergy-InitialEnergy)/Temperature))
         if r < exp(-(FinalEnergy-InitialEnergy)/Temperature):
             return InitialLattice
         else:
             return InitLat
示例#5
0
def generate_batch(batch_size, num_skips, skip_window):
    """
    生成训练样本
    args:
        batch_size: 每一批训练样本的数量
        num_skips: 每个单词生成多少个样本,不能大于skip_window的两倍,batch_size必须是num_skip的整数倍,确保每个batch包含一个词汇对应的所有样本
        skip_window: 单词最远可以联系的距离
    """
    global data_index
    assert batch_size % num_skips == 0
    assert num_skips <= 2 * skip_window
    batch = np.ndarray(shape=(batch_size), dtype=np.int32)
    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
    span = 2 * skip_window + 1
    buffer = collections.deque(maxlen=span)  #deque使用append添加变量时,只保留最后插入的那个变量

    for _ in range(span):
        buffer.append(data[data_index])
        data_index = (data_index + 1) % len(data)

    for i in range(batch_size // num_skips):
        target = skip_window
        target_to_aviod = [skip_window]
        for j in range(num_skips):
            while target in target_to_aviod:
                target = random.randint(0, span - 1)
            target_to_aviod.append(target)
            batch[i * num_skips + j] = buffer[skip_window]
            labels[i * num_skips + j, 0] = buffer[target]
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
    return batch, labels
示例#6
0
        def forceAngleOutward(self,n_pts,runs=100):
		p = self.disperseRand(n_pts)
		f,eOld = self.forceVectors(p)
		count = 0
		number = [len(p)*runs]
		randIndxs = random.randint(0,len(p),[len(p)*runs])
		for r in range(0,runs):
     			for i in range(0,len(p)):
			#for q in range(0,len(p)):
					#print q*(r+1)
			#	i = randIndxs[q*(r+1)]	
					#print i
				magnitude = self.distance(f[i])			
				dirForce = [f[i][0]/magnitude,f[i][1]/magnitude,f[i][2]/magnitude]

				angle = arccos((p[i][0]*dirForce[0])+(p[i][1]*dirForce[1])+(p[i][2]*dirForce[2]))
				if angle>0.01:
					p[i] = dirForce
					count +=1
					
				self.window.update(p)
				self.window.updateGL()
				self.window.show()
				self.window.raise_()
			
				f,e = self.forceVectors(p)			
				#print eOld,count

			print angle, e	
			self.window.lines=[]
			self.drawEdges(p)
		print count
示例#7
0
 def MEStep(alpha,
            rfac,
            Aw,
            temp,
            Ker,
            sxt,
            Gt,
            model,
            f0,
            Asteps,
            itt,
            reset=True):
     if (reset):
         temp = 0.001
         rfac = 0.05
     print 'Restarting maxent with rfac=', rfac, 'alpha=', alpha
     iseed = random.randint(0, maxint)
     me.maxent(Aw, rfac, alpha, temp, Ker, sxt, Gt, model, f0, Asteps,
               iseed)
     S = me.entropy(Aw, model, f0)
     Trc = me.lambdac(alpha, Aw, omega, dlda)
     ratio = -2 * S * alpha / Trc
     print 'Finished maxent with alpha=', alpha, '-2*alpha*S=', -2 * alpha * S, 'Trace=', Trc
     print '   ratio=', ratio
     savetxt('dos_' + str(itt), vstack((omega, Aw)).transpose())
     return ratio
def save_data(image, x, y, type_id=0, samples=11):
    global sample_count
    img_data = extract_data(image, x, y)
    writer.write(img_data)
    label_writer.write(numpy.array(type_id, dtype=numpy.uint8))
    sample_count += 1
    for index in range(1, samples):
        img_data = extract_data(image, x, y)
        for index_point in range(0, 20):
            point = random.randint(0, img_data.size)
            min_val = max(img_data[point] - 20, 0)
            max_val = min(img_data[point] + 20, 255)
            img_data[point] = random.randint(min_val, max_val)
        writer.write(img_data)
        label_writer.write(numpy.array(type_id, dtype=numpy.uint8))
        sample_count += 1
示例#9
0
    def newEpisode(self):
        if self.learning:
            params = ravel(self.explorationlayer.module.params)
            target = ravel(sum(self.history.getSequence(self.history.getNumSequences()-1)[2]) / 500)
        
            if target != 0.0:
                self.gp.addSample(params, target)
                if len(self.gp.trainx) > 20:
                    self.gp.trainx = self.gp.trainx[-20:, :]
                    self.gp.trainy = self.gp.trainy[-20:]
                    self.gp.noise = self.gp.noise[-20:]
                    
                self.gp._calculate()
                        
                # get new parameters where mean was highest
                max_cov = diag(self.gp.pred_cov).max()
                indices = where(diag(self.gp.pred_cov) == max_cov)[0]
                pick = indices[random.randint(len(indices))]
                new_param = self.gp.testx[pick]
            
                # check if that one exists already in gp training set
                if len(where(self.gp.trainx == new_param)[0]) > 0:
                    # add some normal noise to it
                    new_param += random.normal(0, 1, len(new_param))

                self.explorationlayer.module._setParameters(new_param)

            else:
                self.explorationlayer.drawRandomWeights()
        
        # don't call StateDependentAgent.newEpisode() because it randomizes the params
        LearningAgent.newEpisode(self)
示例#10
0
    def _row(self, sim=None, slide_id=1):
        """
        Produce a simburst table row for this waveform.

        Parameters
        ----------
        sim : table
           The table which the row should be made for.
           If this is left empty the table is assumed to be a 
           sim_burst_table.

        slide_id : int
           The timeslide id. Defaults to 1.
        """
        if not sim: sim = self.sim
        row = sim.RowType()

        for a in lsctables.SimBurstTable.validcolumns.keys():
            setattr(row, a, self.params[a])

        row.waveform = self.waveform
        # Fill in the time
        row.set_time_geocent(GPS(float(self.time)))
        # Get the sky locations
        row.ra, row.dec, row.psi = self.sky_dist()
        row.simulation_id = sim.get_next_id()
        row.waveform_number = random.randint(0,int(2**32)-1)
        ### !! This needs to be updated.
        row.process_id = "process:process_id:0" #procrow.process_id
        row.time_slide_id = ilwd.ilwdchar("time_slide:time_slide_id:%d" % slide_id)

        return row
示例#11
0
    def find_conservative_MPPS(self, n_MPP=2, n_MPP_tries=100, err_g_max=0.2):
        """
        Search for MPPs
        
        Input:
        
        n_MPP        -  try to find this number of MPP's
        n_MPP_tries  -  max number of tries in search for new MPP 
        err_g_max    -  convergence criterion in MPP search
        """

        k = 0
        U_MPP = []
        for i in range(n_MPP_tries):
            u0 = random.normal(size=(self.X_dist.dim))
            self.e = self.E_conservative[random.randint(
                len(self.E_conservative))]

            conv, u_MPP = self.MPP_search(u0=u0,
                                          N_max=100,
                                          err_g_max=err_g_max)
            if conv:
                k += 1
                U_MPP.append(u_MPP)
                if k >= n_MPP: break

        return np.array(U_MPP)
示例#12
0
 def perturbation(self):
     # generates a uniform difference vector with the given epsilon
     deltas = (random.randint(0, 2, self.numParameters) * 2 - 1) * self.epsilon
     # reduce epsilon by factor gamma
     # as another simplification we let the exploration just decay with gamma. 
     # Is similar to the decreasing exploration in SPSA but simpler.        
     self.epsilon *= self.gamma
     return deltas
示例#13
0
文件: spsa.py 项目: Angeliqe/pybrain
 def perturbation(self):
     # generates a uniform difference vector with the given epsilon
     deltas = (random.randint(0, 2, self.numParameters) * 2 - 1) * self.epsilon
     # reduce epsilon by factor gamma
     # as another simplification we let the exploration just decay with gamma.
     # Is similar to the decreasing exploration in SPSA but simpler.
     self.epsilon *= self.gamma
     return deltas
示例#14
0
def gen_master(x_l, x_h, y_l, y_h):
    '''
    Decide exponential or uniform
    '''

    if random.randint(1, 2, 1) > 1:
        return gen_exponential(random.uniform(x_l, x_h),
                               random.uniform(y_l, y_h))
    else:
        return gen_uniform(x_l, x_h, y_l, y_h)
示例#15
0
文件: sampler.py 项目: cagrell/HAL
    def sample(self, N):
        """
        Generate N samples
        """

        # Standard normal samples
        U = random.normal(size=(N, self.dim))

        # Sample random means with equal probability
        random_means = self.means[list(random.randint(self.m, size=N)), :]

        return U + random_means
示例#16
0
def chaos_game(polygon, seed, N, f):
    nDim = np.size(polygon, 0)
    nVerts = np.size(polygon, 1)
    fractal = np.zeros([nDim, N])
    current_point = seed
    for idx in xrange(0, N):
        ndx = rnd.randint(0, nVerts)
        vert = polygon[:, ndx]
        next_point = current_point + f*(vert-current_point)
        fractal[:,idx] = next_point
        current_point = next_point
    return fractal
示例#17
0
    def test_random(self):
        for n_row in [1,2,3,10,100,200]:
            for n_col in [1,2,3,4,5]:
                s = arange(n_row*n_col).reshape((n_row,n_col))

                for n_searches in [1,2,3,n_row,2*n_row]:
                    expected = random.randint(0,n_row,n_searches)

                    v = s[expected,:]

                    result = simplex_array_searchsorted(s,v)

                    assert_equal(result,expected)
示例#18
0
    def _forwardImplementation(self, inbuf, outbuf):
        """ Draws a random number between 0 and 1. If the number is less
            than epsilon, a random action is chosen. If it is equal or
            larger than epsilon, the greedy action is returned.
        """
        assert self.module

        if random.random() < self.epsilon:
            outbuf[:] = array([random.randint(self.module.numActions)])
        else:
            outbuf[:] = inbuf

        self.epsilon *= self.decay
示例#19
0
    def _forwardImplementation(self, inbuf, outbuf):
        """ Draws a random number between 0 and 1. If the number is less
            than epsilon, a random action is chosen. If it is equal or
            larger than epsilon, the greedy action is returned.
        """
        assert self.module

        if random.random() < self.epsilon:
            outbuf[:] = array([random.randint(self.module.numActions)])
        else:
            outbuf[:] = inbuf

        self.epsilon *= self.decay
示例#20
0
 def getAction(self):
     """ activates the module with the last observation and stores the result as last action. """
     # get greedy action
     action = LearningAgent.getAction(self)
     
     # explore by chance
     if random.random() < self.epsilon:
         action = array([random.randint(self.module.numActions)])
     
     # reduce epsilon
     self.epsilon *= self.epsilondecay
     
     return action
示例#21
0
 def random_values(self, n):
     probability = absolute(self.vector)**2
     probability = probability * 10000  # 有効数字を3ケタ以上取るために10000倍する
     probability_naturalized = probability.astype(int)
     target = []
     for i in range(self.mesh.x_num):
         weight = probability_naturalized[i]
         if not weight == 0:
             weight_array = i * ones(weight, dtype=int)
             target.extend(weight_array.tolist())
     max_random = len(target)
     target_index = random.randint(0, max_random, n)
     random_index = array(target)[target_index]
     return self.mesh.x_vector[random_index]
示例#22
0
文件: sampler.py 项目: cagrell/HAL
    def prune(self, include_list, default_values, N_max):
        """
        Input: 
        include_list    -  boolean list of length N_warmup
        default_values  -  array of length N_warmup with default values
        
        Creates a reduced sample of size <= N_max as follows:
        1. Remove samples where include_list = False
        2. If the number of remaining samples is > N_max, generate N_max subsamples
        """

        # The samples to include
        self.samples_pruned = self.samples_warmup[include_list]
        self.pdf_pruned = self.pdf_warmup[include_list]
        self.N_pruned = self.samples_pruned.shape[0]
        self.ratio_pruned = self.N_pruned / self.N_warmup

        # Downsample if necessary
        if self.N_pruned > N_max:

            idx = list(random.randint(self.N_pruned, size=N_max))
            self.samples_pruned = self.samples_pruned[idx, :]
            self.pdf_pruned = self.pdf_pruned[idx]
            self.N_pruned = N_max

        # When MCIS is run on the pruned subset, we must also include
        # the assumed expectation on the left-out samples

        # The excluded samples
        exclude_list = np.logical_not(include_list)
        samples_excluded = self.samples_warmup[exclude_list]
        pdf_excluded = self.pdf_warmup[exclude_list]
        default_excluded = default_values[exclude_list]

        normal_pdf_excluded = np.prod(stats.norm.pdf(samples_excluded), 1)
        q_excluded = normal_pdf_excluded / pdf_excluded

        if len(default_excluded) == 0:
            self.expectation_excluded = 0
        else:
            self.expectation_excluded = (default_excluded * q_excluded).mean(
            )  # The assumed expectation of excluded samples

        # The density of each pruned sample in the standard normal space
        self.normal_pdf_pruned = np.prod(stats.norm.pdf(self.samples_pruned),
                                         1)

        # The density fractions used in MCIS
        self.q_pruned = self.normal_pdf_pruned / self.pdf_pruned
示例#23
0
	def disperseRand(self,n):
		a=[]	
		c=[]
		i=0
		while i<n:
			xy=[random.uniform(-1,1),random.uniform(-1,1)]
			if (xy[0]**2+xy[1]**2)<=1:
				a.append(xy)
				i+=1		
		for i in range(0,len(a)):
			c.append([a[i][0],a[i][1],sqrt(1-(a[i][0]**2+a[i][1]**2))])
		for i in range(0,len(c)):	#randomly change sign of the z coord
			if random.randint(0,1):
				c[i][2]=c[i][2]*-1
		return c
示例#24
0
    def animate(self, *fargs):
        # Randomly generate some data to plot
        for queue in self.backend.queues:
            length = len(queue) - 1
            for j in range(1, 11):
                queue.append((random.randint(0, 1000), queue[length][1] + j))
                # queue.append((queue[length][1] + j, queue[length][1] + j))
            # print (queue)
        # print (self.backend.queues[0][-10:])

        # Only graph if we are on the mission control tab
        if self.notebook.index(self.notebook.select()) == 0:
            self.update_graphs()
        elif self.notebook.index(self.notebook.select()) == 1:
            self.update_log_displays()
示例#25
0
 def disperseRand(self, n):
     a = []
     c = []
     i = 0
     while i < n:
         xy = [random.uniform(-1, 1), random.uniform(-1, 1)]
         if (xy[0]**2 + xy[1]**2) <= 1:
             a.append(xy)
             i += 1
     for i in range(0, len(a)):
         c.append([a[i][0], a[i][1], sqrt(1 - (a[i][0]**2 + a[i][1]**2))])
     for i in range(0, len(c)):  #randomly change sign of the z coord
         if random.randint(0, 1):
             c[i][2] = c[i][2] * -1
     return c
示例#26
0
文件: main.py 项目: pelluch/gmm_t3
def generate_data(num_dims, n_components):
    X = np.empty([0, num_dims])
    all_means = []
    for i in range(n_components):
        # Con esto aseguramos de generar matriz positiva semi definida
        cov = random.rand(num_dims, num_dims)
        cov = np.dot(cov, cov.transpose())
        means = []
        for j in range(num_dims):
            # Medias aleatorias
            means.append(random.uniform(-5, 5))
        new_data = np.random.multivariate_normal(means, cov,
                                                 random.randint(100, 400))
        X = np.concatenate((X, new_data))
        all_means.append(means)
    return X
示例#27
0
    def mCarlo(self, n_pts, runs=100):
        p = self.disperseRand(n_pts)
        #eOld = energySystem(p)
        f, eOld = self.forceVectors(p)
        count = 0
        angle = 1.0
        number = [len(p) * runs]
        randIndxs = random.randint(0, len(p), [len(p) * runs])
        #		print len(randIndxs)
        while angle > 0.01:
            for r in range(0, runs):

                #for i in range(0,len(p)):
                for q in range(0, len(p)):
                    #print q*(r+1)
                    i = randIndxs[q * (r + 1)]
                    #print i
                    magnitude = self.distance(f[i])
                    dirForce = [
                        f[i][0] / magnitude, f[i][1] / magnitude,
                        f[i][2] / magnitude
                    ]
                    nangle = angle / sqrt(count + 1)
                    pOld = p[i]
                    p[i] = self.rotateBy(p[i], dirForce, -1 * angle)

                    eNew = self.energySystem(p)

                    if eNew > eOld:  #revert back
                        p[i] = pOld
                        count += 1
                    else:
                        eOld = eNew

                self.window.update(p)
                self.window.updateGL()
                self.window.show()
                self.window.raise_()

                f, e = self.forceVectors(p)
                #print eOld,count
            angle = angle / 2
            print angle, eOld
            self.window.lines = []
            self.drawEdges(p)
        print count
示例#28
0
 def randomlist(self,mode=1,size=1000,low=0,high=100):
     "generate a list followed given distribution"
     "IN:distribution model code which refer to randomlist method; sequence size; sequence range"
     "OUT:a sequence followed distribution like"
     x = []
     if mode == 1:        
         x = random.randint(low,high,size=size)
     if mode == 2:
         x = map(float,random.normal(loc=(low+high)/2.0, scale=(high-low)/6.0, size=size))
     if mode == 3:
         x = map(long,random.exponential(scale=1, size=size)+low)
     if mode == 4:
         x = map(long,random.pareto(1,size=size)+low)
     if mode == 5:
         x = map(long,random.poisson(lam=(low+high)/2.0, size=size))    
 #     x = random.choice(x,size=100)    
     return x
示例#29
0
def rand_arrange(c,fle='names.xls'):
    """n= Number of Students in a batch \n
    c= number of students in a group\n
    fle = name of students in excel csv format"""
    a=[]
    dic = {}
    namereader = ow(fle)
#    namereader = csv.reader(namedata)
    i = 1
#    rand_dic= {}
    s = namereader.sheets()[0]
#    for s in namereader.sheets():
    for rows in range(1,s.nrows):
        val=[]
        for cols in range(s.ncols):
            val.append(s.cell(rows,cols).value)
        dic[i]=val
        a.append(i)
        i+=1
    b=[]
    i=0
#    namewriter = csv.DictWriter(fle,fieldnames=['Sr.No.','names'])
#    writing in xls
    book = Workbook()
    sheet1 = book.add_sheet('result')
    sheet1.row(0).write(0,'Sr.no.')
    sheet1.row(0).write(1,'Roll No')
    sheet1.row(0).write(2,'Name')
    sheet1.row(0).write(3,'Group No.')
    sheet1.col(0).width = 2000
    sheet1.col(1).width = 4000
    sheet1.col(2).width = 5750
    sheet1.col(3).width = 2750
    while len(a)!=0:
        b.append(a.pop(rd.randint(len(a))))
        d=0
        for val in dic[b[i]]:
            sheet1.row(i+1).write(d,val)
            d += 1
        if i%c==0:
            e=i/c+1
#        sheet1.row(i+1).write(d,'Group %d'%(e))
        sheet1.row(i+1).write(d,e)
        i += 1
    book.save('result.xls')
示例#30
0
    def calc_levels(self,data,fraction=(0.1,0.9),nbins=500,samples=None):
        """ fraction is a tuple with (low, high) in the range of 0 to 1 
        nbins is the number of bins for the histogram resolution

        if samples: draw this number of samples (random inds) for faster
        calculation
        """
        if samples:
            data = data.flatten()[random.randint(sp.prod(data.shape),size=samples)]
        else:
            data = data.flatten()
        y,x = sp.histogram(data,bins=nbins)
        cy = sp.cumsum(y).astype('float32')
        cy = cy / cy.max()
        minInd = sp.argmin(sp.absolute(cy - fraction[0]))
        maxInd = sp.argmin(sp.absolute(cy - fraction[1]))
        levels = (x[minInd],x[maxInd])
        return levels
示例#31
0
    def calc_levels(self, data, fraction=(0.1, 0.9), nbins=500, samples=None):
        """ fraction is a tuple with (low, high) in the range of 0 to 1 
        nbins is the number of bins for the histogram resolution

        if samples: draw this number of samples (random inds) for faster
        calculation
        """
        if samples:
            data = data.flatten()[random.randint(sp.prod(data.shape),
                                                 size=samples)]
        else:
            data = data.flatten()
        y, x = sp.histogram(data, bins=nbins)
        cy = sp.cumsum(y).astype('float32')
        cy = cy / cy.max()
        minInd = sp.argmin(sp.absolute(cy - fraction[0]))
        maxInd = sp.argmin(sp.absolute(cy - fraction[1]))
        levels = (x[minInd], x[maxInd])
        return levels
示例#32
0
	def mCarlo(self,n_pts,runs=100):
		p = self.disperseRand(n_pts)
		#eOld = energySystem(p)
		f,eOld = self.forceVectors(p)
		count = 0
		angle = 1.0
		number = [len(p)*runs]
		randIndxs = random.randint(0,len(p),[len(p)*runs])
#		print len(randIndxs)
		while angle > 0.01 :
			for r in range(0,runs):
				
				#for i in range(0,len(p)):
				for q in range(0,len(p)):
					#print q*(r+1)
					i = randIndxs[q*(r+1)]	
					#print i
					magnitude = self.distance(f[i])			
					dirForce = [f[i][0]/magnitude,f[i][1]/magnitude,f[i][2]/magnitude]
					nangle = angle/sqrt(count+1)
					pOld = p[i]
					p[i] = self.rotateBy(p[i],dirForce,-1*angle)
					
					eNew = self.energySystem(p)
					
					if eNew > eOld:	#revert back
						p[i] = pOld
						count +=1
					else:
						eOld = eNew
				
				self.window.update(p)
				self.window.updateGL()
				self.window.show()
				self.window.raise_()
			
				f,e = self.forceVectors(p)			
				#print eOld,count
			angle = angle / 2
			print angle, eOld	
			self.window.lines=[]
			self.drawEdges(p)
		print count
示例#33
0
    def getObservation(self):
        """ a filtered mapping to getSample of the underlying environment. """
        sensors = self.env.getSensors()
        sensSort = []
        #Angle and angleVelocity
        for i in range(32):
            sensSort.append(sensors[i])
        #Angles wanted (old action)
        for i in self.oldAction:
            sensSort.append(i)
        #Hand position
        for i in range(3):
            sensSort.append((sensors[38 + i] + sensors[41 + i]) / 2)
        #Hand orientation (Hack - make correkt!!!!)
        sensSort.append((sensors[38] - sensors[41]) / 2 - sensors[35])  #pitch
        sensSort.append(
            (sensors[38 + 1] - sensors[41 + 1]) / 2 - sensors[35 + 1])  #yaw
        sensSort.append((sensors[38 + 1] - sensors[41 + 1]))  #roll
        #Target position
        for i in range(3):
            sensSort.append(self.target[i])
        #Target orientation
        for i in range(3):
            sensSort.append(0.0)
        #Object type (start with random)
        sensSort.append(float(random.randint(-1, 1)))  #roll

        #normalisation
        if self.sensor_limits:
            sensors = self.normalize(sensors)
        sens = []
        for i in range(32):
            sens.append(sensors[i])
        for i in range(29):
            sens.append(sensSort[i + 32])

        #calc dist to target
        self.dist = array([(sens[54] - sens[48]) * 10.0,
                           (sens[55] - sens[49]) * 10.0,
                           (sens[56] - sens[50]) * 10.0, sens[51], sens[52],
                           sens[53], 1.0 + sens[15]])
        return sens
def rollDice(n):
    # Rolls n amount of dice and stores the results in a dictionary of each
    # possible outcome tagged with their number of occurrences.

    hand = []
    for i in range(n):
        hand.append(random.randint(1, 6))

    occurrences = dict((x, hand.count(x)) for x in set(hand))
    keys_seen = [1, 2, 3, 4, 5, 6]

    for key in occurrences.keys():  #loop through each dictionary's keys
        if key not in keys_seen:  #if we haven't seen this key before, then...
            keys_seen.append(key)  #add it to the list of keys seen

    for key in keys_seen:  #loop through the list of keys that we've seen
        if key not in occurrences:  #if the dictionary is missing that key, then...
            occurrences[key] = 0  #add it and set it to 0

    return occurrences
示例#35
0
def get_noise_sample(idx=None, size=None, filename=None):
    """get some noise from a recording of maquaque prefrontal cortex"""

    # inits and checks
    if filename is None:
        filename = '/home/phil/monkey-data/Louis/L011/L0110985.xpd'
    if size is None:
        size = 10000

    # load data
    from common.datafile import XpdFile
    data = XpdFile(filename).get_data(item=15)

    # return
    if size >= data.shape[0]:
        size = data.shape[0] - 1
        idx = 0
    if idx is None:
        idx = NR.randint(data.shape[0] - size)
    return data[idx:idx + size].copy()
示例#36
0
def get_noise_sample(idx=None, size=None, filename=None):
    """get some noise from a recording of maquaque prefrontal cortex"""

    # inits and checks
    if filename is None:
        filename = '/home/phil/monkey-data/Louis/L011/L0110985.xpd'
    if size is None:
        size = 10000

    # load data
    from common.datafile import XpdFile
    data = XpdFile(filename).get_data(item=15)

    # return
    if size >= data.shape[0]:
        size = data.shape[0] - 1
        idx = 0
    if idx is None:
        idx = NR.randint(data.shape[0] - size)
    return data[idx:idx + size].copy()
示例#37
0
	def mask_data(data):
		thids = [d.header["TARGETID"] for d in data.data.values()]
		thids = sp.unique(thids)
		thid_map = dict()

		for th in thids:
			old_th = str(th)
			new_th = ''
			for (i,oth) in enumerate(old_th):
				aux = random.randint(9)
				if aux==0 and i==0:aux=1
				new_th = new_th+str(aux)
			thid_map[th]=int(new_th)
		
		plates = [d.header["BOSS_PLATE"] for d in data.data.values()]
		plates = sp.unique(plates)
		print plates
		plate_map = dict()
		for (i,p) in enumerate(plates):
			plate_map[p]=i
		
		data.plates = plate_map.values()
		for d in data.data.values():
			d.header["OBJTYPE"] = "HIDDEN"
			d.header["TARGETCAT"]="HIDDEN"
			d.header["TARGETID"] = thid_map[d.header["TARGETID"]]
			d.header["MAG"]=23
			d.header["SPECTROID"] = d.header["TARGETID"]
			d.header["FIBERID"]=0
			d.header["RA_TARGET"]=3.14
			d.header["DEC_TARGET"]=3.14
			d.header["RA_OBS"]=3.14
			d.header["DEC_OBS"]=3.14
			d.header["BOSS_CLASS"]="HIDDEN"
			d.header["BOSS_SUBCLASS"]="HIDDEN"
			d.header["BOSS_Z"]=42
			d.header["BOSS_PLATE"]=plate_map[d.header["BOSS_PLATE"]]
			d.header["BOSS_MJD"] = 43689
			d.header["BOSS_ZWARNINGNOQSO"]=4

		return thid_map,plate_map
示例#38
0
    def mask_data(data):
        thids = [d.header["TARGETID"] for d in data.data.values()]
        thids = sp.unique(thids)
        thid_map = dict()

        for th in thids:
            old_th = str(th)
            new_th = ''
            for (i, oth) in enumerate(old_th):
                aux = random.randint(9)
                if aux == 0 and i == 0: aux = 1
                new_th = new_th + str(aux)
            thid_map[th] = int(new_th)

        plates = [d.header["BOSS_PLATE"] for d in data.data.values()]
        plates = sp.unique(plates)
        print plates
        plate_map = dict()
        for (i, p) in enumerate(plates):
            plate_map[p] = i

        data.plates = plate_map.values()
        for d in data.data.values():
            d.header["OBJTYPE"] = "HIDDEN"
            d.header["TARGETCAT"] = "HIDDEN"
            d.header["TARGETID"] = thid_map[d.header["TARGETID"]]
            d.header["MAG"] = 23
            d.header["SPECTROID"] = d.header["TARGETID"]
            d.header["FIBERID"] = 0
            d.header["RA_TARGET"] = 3.14
            d.header["DEC_TARGET"] = 3.14
            d.header["RA_OBS"] = 3.14
            d.header["DEC_OBS"] = 3.14
            d.header["BOSS_CLASS"] = "HIDDEN"
            d.header["BOSS_SUBCLASS"] = "HIDDEN"
            d.header["BOSS_Z"] = 42
            d.header["BOSS_PLATE"] = plate_map[d.header["BOSS_PLATE"]]
            d.header["BOSS_MJD"] = 43689
            d.header["BOSS_ZWARNINGNOQSO"] = 4

        return thid_map, plate_map
 def Advance(xPos,yPos,xDistance,yDistance,SectorX,SectorY,lifetime):
     MoveX,MoveY = Directions[random.randint(0,4)]
     
     xDistance+=MoveX
     yDistance+=MoveY
     lifetime+=1
     
     if xPos == WindingAxisX and MoveX == -1:
         SectorX = (SectorX + 1)%2
     if xPos == WindingAxisX - 1 and MoveX == 1:
         SectorX = (SectorX + 1)%2
     
     if yPos == WindingAxisY and MoveY == -1:
         SectorY = (SectorY + 1)%2
     if yPos == WindingAxisY - 1 and MoveY == 1:
         SectorY = (SectorY + 1)%2
     
     xPos = (xPos + MoveX)%Dimx
     yPos = (yPos + MoveY)%Dimy
     
     return xPos,yPos,xDistance,yDistance,SectorX,SectorY,lifetime
def categorize(categories, data, words):
	nnodes = sqrt(categories)
	# make a kohonen map
	som = KohonenMap(len(data[1])-1, nnodes)
	
	# train the network

	for i in range(25000):
		# one forward and one backward (training) pass on a random line
		som.activate(data[random.randint(1, len(data)-1)][1:])
		som.backward()

	# run on the data

	if not words:
		for point in data[1:-1]:
			#find the category for a point of data
			print(point[0] + ',' + str(som.activate(point[1:])))


	#make wordlist output similar to ICA for use in GAs
	if words:
		results = [[] for i in range(categories)]
		for point in data[1:-1]:
			# find the cluster for this word and add in the word's data
			result = som.activate(point[1:])
			results[int(result[0]*nnodes + result[1])].append(point)
		# print out the clusters
		for i in range(NWORDS):
		# TODO: This is super inefficient
			for cluster in results:
				if len(cluster) == 0:
					sys.stdout.write('EMPTY')
					continue
				for j in range(len(cluster)):
					for k in range(1, len(cluster[j])):
						cluster[j][k] = float(cluster[j][k])
				tempCluster = sorted(cluster, key=lambda point: -sum(point[1:]))
				sys.stdout.write(str(tempCluster[i%len(cluster)][0]) + ',')
			sys.stdout.write('\n')
示例#41
0
    def getObservation(self):
        """ a filtered mapping to getSample of the underlying environment. """
        sensors = self.env.getSensors()
        sensSort = []
        #Angle and angleVelocity
        for i in range(32):
            sensSort.append(sensors[i])
        #Angles wanted (old action)
        for i in self.oldAction:
            sensSort.append(i)
        #Hand position
        for i in range(3):
            sensSort.append((sensors[38 + i] + sensors[41 + i]) / 2)
        #Hand orientation (Hack - make correkt!!!!)
        sensSort.append((sensors[38] - sensors[41]) / 2 - sensors[35]) #pitch
        sensSort.append((sensors[38 + 1] - sensors[41 + 1]) / 2 - sensors[35 + 1]) #yaw
        sensSort.append((sensors[38 + 1] - sensors[41 + 1])) #roll
        #Target position
        for i in range(3):
            sensSort.append(self.target[i])
        #Target orientation
        for i in range(3):
            sensSort.append(0.0)
        #Object type (start with random)
        sensSort.append(float(random.randint(-1, 1))) #roll

        #normalisation
        if self.sensor_limits:
            sensors = self.normalize(sensors)
        sens = []
        for i in range(32):
            sens.append(sensors[i])
        for i in range(29):
            sens.append(sensSort[i + 32])

        #calc dist to target
        self.dist = array([(sens[54] - sens[48]) * 10.0, (sens[55] - sens[49]) * 10.0, (sens[56] - sens[50]) * 10.0, sens[51], sens[52], sens[53], 1.0 + sens[15]])
        return sens
示例#42
0
文件: kmeans.py 项目: DanSGraham/code
def kinit(X, k):
    'init k seeds according to kmeans++'
    n = X.shape[0]

    'choose the 1st seed randomly, and store D(x)^2 in D[]'
    centers = [X[random.randint(n)]]
    D = [norm(x - centers[0]) ** 2 for x in X]

    for _ in range(k - 1):
        bestDsum = bestIdx = -1

        for i in range(n):
            'Dsum = sum_{x in X} min(D(x)^2,||x-xi||^2)'
            Dsum = reduce(lambda x, y:x + y,
                          (min(D[j], norm(X[j] - X[i]) ** 2) for j in xrange(n)))

            if bestDsum < 0 or Dsum < bestDsum:
                bestDsum, bestIdx = Dsum, i

        centers.append (X[bestIdx])
        D = [min(D[i], norm(X[i] - X[bestIdx]) ** 2) for i in xrange(n)]

    return array (centers)
示例#43
0
def kinit(X, k):
    'init k seeds according to kmeans++'
    n = X.shape[0]

    'choose the 1st seed randomly, and store D(x)^2 in D[]'
    centers = [X[random.randint(n)]]
    D = [norm(x - centers[0]) ** 2 for x in X]

    for _ in range(k - 1):
        bestDsum = bestIdx = -1

        for i in range(n):
            'Dsum = sum_{x in X} min(D(x)^2,||x-xi||^2)'
            Dsum = reduce(lambda x, y:x + y,
                          (min(D[j], norm(X[j] - X[i]) ** 2) for j in xrange(n)))

            if bestDsum < 0 or Dsum < bestDsum:
                bestDsum, bestIdx = Dsum, i

        centers.append (X[bestIdx])
        D = [min(D[i], norm(X[i] - X[bestIdx]) ** 2) for i in xrange(n)]

    return array (centers)
 def TrialMove2(InitLat):
     InitialLattice = deepcopy(InitLat)
     InitialEnergy = 2*Je*len(InitialLattice.ExcitationList)
     
     if(len(InitialLattice.ExcitationList)!=0):
         RandomExcitation = random.randint(len(InitialLattice.ExcitationList))
         RandomDirection = random.randint(0,5)
         
         InitialLattice.MoveExcitation(RandomExcitation,RandomDirection)
         
     SpawnOrientation = random.randint(0,3) #0 don't do anything, 1 updown, 2 leftright
     
     if(SpawnOrientation == 1):
         RandomX = random.randint(0,InitialLattice.Dimension)
         RandomY = random.randint(0,InitialLattice.Dimension)
         
         InitialLattice.SpawnExcitation(RandomX,RandomY)
         InitialLattice.SpawnExcitation(RandomX,(RandomY+1)%InitialLattice.Dimension)
         InitialLattice.CheckSector(RandomX,RandomY,0,1)
         
     if(SpawnOrientation == 2):
         RandomX = random.randint(0,InitialLattice.Dimension)
         RandomY = random.randint(0,InitialLattice.Dimension)
         
         InitialLattice.SpawnExcitation(RandomX,RandomY)
         InitialLattice.SpawnExcitation((RandomX+1)%InitialLattice.Dimension,RandomY)
         InitialLattice.CheckSector(RandomX,RandomY,1,0)
         
     FinalEnergy = 2*Je*len(InitialLattice.ExcitationList)
     
     if(FinalEnergy <= InitialEnergy):
         return InitialLattice
     
     else:
         r = random.rand()
         #print(exp(-(FinalEnergy-InitialEnergy)/Temperature))
         if r < exp(-(FinalEnergy-InitialEnergy)/Temperature):
             return InitialLattice
         else:
             return InitLat
示例#45
0
    def forceAngleOutward(self, n_pts, runs=100):
        p = self.disperseRand(n_pts)
        f, eOld = self.forceVectors(p)
        count = 0
        number = [len(p) * runs]
        randIndxs = random.randint(0, len(p), [len(p) * runs])
        for r in range(0, runs):
            for i in range(0, len(p)):
                #for q in range(0,len(p)):
                #print q*(r+1)
                #	i = randIndxs[q*(r+1)]
                #print i
                magnitude = self.distance(f[i])
                dirForce = [
                    f[i][0] / magnitude, f[i][1] / magnitude,
                    f[i][2] / magnitude
                ]

                angle = arccos((p[i][0] * dirForce[0]) +
                               (p[i][1] * dirForce[1]) +
                               (p[i][2] * dirForce[2]))
                if angle > 0.01:
                    p[i] = dirForce
                    count += 1

                self.window.update(p)
                self.window.updateGL()
                self.window.show()
                self.window.raise_()

                f, e = self.forceVectors(p)
                #print eOld,count

            print angle, e
            self.window.lines = []
            self.drawEdges(p)
        print count
def get_distance(Quad, offset, Leader):
    Sigma = np.zeros((n, n))
    data = loadmat('error_data_jelena_NLOS_LOS.mat')
    data1 = data['error_LOS_truncated']
    Var = np.std(data1)
    dis = np.zeros((n, n))
    Sigma = np.zeros((n, n))

    for i in np.arange(start=0, stop=n, step=1):
        if i == Leader:
            X = np.array([Quad[i].X, Quad[i].Y]) + offset
        else:
            X = np.array([Quad[i].X, Quad[i].Y])

        for jj in np.arange(start=i, stop=n, step=1):

            Y = np.array([Quad[jj].X, Quad[jj].Y])
            value_i = random.randint(0, 20000)
            dis[i, jj] = np.linalg.norm(X - Y)
            Sigma[i, jj] = Var
            Sigma[jj, i] = Var
            dis[i, jj] = dis[i, jj] + (data1[value_i] - 0.16) / 5
            dis[jj, i] = dis[i, jj]
    return dis, Sigma
示例#47
0
from scipy.linalg import expm, expm2, expm3
from expf import expf
from time import time


s = range(3, 100)
t = zeros(size(s))
t2 = zeros(size(s))
t3 = zeros(size(s))
t4 = zeros(size(s))
tt = 0
for i in s:
    print "Matrix size %d" %(i)
    m = zeros((i,i), float64)
    half = int(round(i*i/2))+1
    r = random.randint(0,i, (half*2, ))
    n = random.random((half, ))
    for z in range(0, half*2, 2):
        m[r[z], r[z+1]] = n[z/2]
    start = time()
    expm(m)
    t[tt] = time() - start

    start = time()
    expm2(m)
    t2[tt] = time() - start

    start = time()
    expm3(m)
    t3[tt] = time() - start
示例#48
0
 def genDifVect(self):
     # generates a uniform difference vector with the given epsilon
     self.deltas = (random.randint(0, 2, self.numOParas) * 2 -
                    1) * self.epsilon
示例#49
0
def is_prime(pn):
    for m in range(1,100):
        random_int = random.randint(1,pn)
        if not (pow(random_int, int(pn-1), int(pn)) == 1):
            return False
    return True
示例#50
0
def uniform_time(tstart, tstop, number):
    """
    Get a set of randomized (integer) event times.
    """
    return random.randint(tstart, tstop, number) + random.rand(number)
filenames = []

testset = []

indir = 'train'
for file in os.listdir(indir):
   if(file.endswith('.jpg')):
      filenames.append(file)

testdir = 'test'
for file in os.listdir(testdir):
   if(file.endswith('.jpg')):
      testset.append(file)

for i in xrange(len(whales)):
    if(labelsDict[whales[i]] == -1):
        labelsDict[whales[i]] = []
    labelsDict[whales[i]].append(images[i])

testset = [int(re.search("w_(\\d+)\.jpg", x).group(1)) for x in testset]

for w in set(whales):
    allExamplesForW = labelsDict[w]
    allExamplesForW = [x for x in allExamplesForW if x not in testset]
    allExamplesForW = random.permutation(allExamplesForW)
    for i in allExamplesForW[0:(len(allExamplesForW)/2)+(random.randint(0,(len(allExamplesForW))%2+1))]:
        print("copying %d\n"%i)
        os.rename(("%s/w_%d.jpg") % (indir, i), ("%s/w_%d.jpg") %(validationDir, i))


示例#52
0
                       'rates_sweep_result.csv')
Results.to_csv(outpath)

# ██████  ██       ██████  ████████ ████████ ██ ███    ██  ██████
# ██   ██ ██      ██    ██    ██       ██    ██ ████   ██ ██
# ██████  ██      ██    ██    ██       ██    ██ ██ ██  ██ ██   ███
# ██      ██      ██    ██    ██       ██    ██ ██  ██ ██ ██    ██
# ██      ███████  ██████     ██       ██    ██ ██   ████  ██████

Results = pd.read_csv(
    os.path.join(exp_name + '_results', 'benchmark', 'rates_sweep_result.csv'))

colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

# %% randomly inspect single sorting results
rand_inds = random.randint(len(Blk.segments), size=5)
for i, seg in enumerate([Blk.segments[ind] for ind in rand_inds]):
    outpath = os.path.join(exp_name + '_results', 'benchmark',
                           'segment_' + str(rand_inds[i]))
    figures = plot_TM_result(seg, Config, zoom=0.25 * pq.s, save=outpath)

    for j, unit in enumerate(unit_names):
        fig = figures[unit]
        for k, unit_ in enumerate(unit_names):
            st, = select_by_dict(seg.spiketrains, unit=unit_, kind='truth')
            for ax in fig.axes:
                plot_SpikeTrain(st,
                                ax=ax,
                                lw=3,
                                color=colors[k],
                                zorder=-10,
 def AdvanceTime(TimeList,ObservableList):
     
     #Norm = len(Trans)*TranslateRate + len(Annih)*AnnihilationRate + ((2*(MyLattice.Dimension)**2) - len(Annih) - len(Trans))*SpawnRate
     
     
     
     #print "Advancing time!"
     
     TranslateableLinks = MyLattice.TranslateableList
     AnnihilateableLinks = MyLattice.AnnihilateableList
     
     #print "Translateable: " + str(len(TranslateableLinks)) + str(TranslateableLinks)
     #print "Annihilateable: " + str(len(AnnihilateableLinks)) + str(AnnihilateableLinks)
     
     Norm = len(TranslateableLinks)*TranslateRate + len(AnnihilateableLinks)*AnnihilationRate + \
     ((2*(MyLattice.Dimension)**2) - len(AnnihilateableLinks) - len(TranslateableLinks))*SpawnRate
     
     PTrans = len(TranslateableLinks)*TranslateRate/Norm
     PAnnih = len(AnnihilateableLinks)*AnnihilationRate/Norm
     PSpawn = ((2*(MyLattice.Dimension)**2) - len(AnnihilateableLinks) - len(TranslateableLinks))*SpawnRate/Norm
     
     
     r = random.rand()
     DeltaTau = (-1./Norm)*log(r)
     
     if (r < PTrans):
         
         #print "Translating!"
         #MyLattice.PrintState()
         RandLink = random.randint(len(TranslateableLinks))
         LinkCoords = [TranslateableLinks[RandLink].x1,TranslateableLinks[RandLink].y1,TranslateableLinks[RandLink].x2,TranslateableLinks[RandLink].y2]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         MyLattice.TranslateExcitations(MyLattice.ReturnExcitationIndex(LinkCoords[0],LinkCoords[1]), XDisplacement, YDisplacement)
         
     if (r >= PTrans and r < PTrans + PAnnih):
         
         #print "Annihilating!"
         
         RandLink = random.randint(len(AnnihilateableLinks))
         LinkCoords = [AnnihilateableLinks[RandLink].x1,AnnihilateableLinks[RandLink].y1,AnnihilateableLinks[RandLink].x2,AnnihilateableLinks[RandLink].y2]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         #if(LinkCoords[2]==MyLattice.Dimension or LinkCoords[0] == MyLattice.Dimension - 1):
             #print str(LinkCoords[2]) + "\t" + str(LinkCoords[0])
             #print str(LinkCoords[3]) + "\t" + str(LinkCoords[1])
         MyLattice.AnnihilateExcitations(LinkCoords[0],LinkCoords[1],LinkCoords[2],LinkCoords[3])
         #MyLattice.CheckSector(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension, XDisplacement, YDisplacement)
     
     if (r >= PTrans + PAnnih):
         
         #print "Creating!"
         
         Occupancies = MyLattice.ReturnOccupancies()
         FoundCreatableLink = False
         RandX = 0
         RandY = 0
         RandDir = 0
         
         while FoundCreatableLink == False:
             RandX = random.randint(MyLattice.Dimension)
             RandY = random.randint(MyLattice.Dimension)
             RandDir = random.randint(2)
             if(Occupancies[RandX,RandY]==0 and \
                Occupancies[(RandX + RandDir)%MyLattice.Dimension,(RandY + (1-RandDir))%MyLattice.Dimension] == 0):
                 FoundCreatableLink = True
     
         LinkCoords = [RandX,RandY,RandX + RandDir, RandY + (1-RandDir)]
         XDisplacement = LinkCoords[2] - LinkCoords[0]
         YDisplacement = LinkCoords[3] - LinkCoords[1]
         #if(LinkCoords[2]==MyLattice.Dimension or LinkCoords[0] == MyLattice.Dimension - 1):
             #print str(LinkCoords[2]) + "\t" + str(LinkCoords[0])
             #print str(LinkCoords[3]) + "\t" + str(LinkCoords[1])
         MyLattice.CreateExcitations(LinkCoords[0],LinkCoords[1],LinkCoords[2],LinkCoords[3])
         #MyLattice.CheckSector(LinkCoords[0]%MyLattice.Dimension,LinkCoords[1]%MyLattice.Dimension, XDisplacement, YDisplacement)
     
     return DeltaTau, MyLattice.Sector, len(MyLattice.ExcitationList)
示例#54
0
def runProblem1():
    x = random.randint(-5,5,(3))
    basin(x)
示例#55
0
文件: spsa.py 项目: HKou/pybrain
 def genDifVect(self):
     # generates a uniform difference vector with the given epsilon
     self.deltas = (random.randint(0,2,self.numOParas)*2-1)*self.epsilon
def SingleRun(Dimx,Dimy):

    def mapped(x,y):
        return ((x%Dimx),(y%Dimy))

    #For the calculation we want to perform, the dynamics look like a pair of random walkers appearing on a lattice in cells adjacent to one another.
    #The dynamics of these walkers allow them to randomly wiggle around the lattice, or annihilate each other (if they happen to be next to each other,
    #and if they happen to decide to annihilate--they don't necessarily annihilate if they are next to each other (although it is incredibly likely
    #they will annihilate one another if they're next to each other)).
    #This set of starting positions mimics the situation of a pair of walkers appearing and *NOT* immediately annihilating.  Thus, one of the walkers
    #moves either left, right, or up (you can see this by plotting the three starting positions).  If your lattice size was 10x10, (-1%Dimx) would
    #yield 9.
    StartingPositions = []
    StartingPositions.append(mapped(0,2))
    StartingPositions.append(mapped(0,-2))
    StartingPositions.append(mapped(2,0))
    StartingPositions.append(mapped(-2,0))
    StartingPositions.append(mapped(1,1))
    StartingPositions.append(mapped(-1,-1))
    StartingPositions.append(mapped(-1,1))
    StartingPositions.append(mapped(1,-1))

    
    StartingPositions.append(mapped(1,1))
    StartingPositions.append(mapped(-1,-1))
    StartingPositions.append(mapped(-1,1))
    StartingPositions.append(mapped(1,-1))
    
    #StartingPositions.append(((-1%Dimx),1))


    #We want to randomly sample from these three starting positions as they are all equally likely
    xPos,yPos = StartingPositions[random.randint(0,11)]
    
    #These are just some variables I care about for the simulation.
    xDistance,yDistance = 0,0
    lifetime = 0
    SectorX = 0
    SectorY = 0
    WindingAxisX = math.floor(Dimx/2.)
    WindingAxisY = math.floor(Dimy/2.)
    
    
    #A simple output statement to check that the random walker code works.
    def PrintState():
        for i in xrange(Dimx):
            print "\n"
            for j in xrange(Dimy):
                if (i,j) == (xPos,yPos):
                    print "1",
                else: print "0",
        print "\n"
    
    #This code advances everything I care about.  It takes the current position of the walker, and some other variables, and iterates them as necessary
    def Advance(xPos,yPos,xDistance,yDistance,SectorX,SectorY,lifetime):
        MoveX,MoveY = Directions[random.randint(0,4)]
        
        xDistance+=MoveX
        yDistance+=MoveY
        lifetime+=1
        
        if xPos == WindingAxisX and MoveX == -1:
            SectorX = (SectorX + 1)%2
        if xPos == WindingAxisX - 1 and MoveX == 1:
            SectorX = (SectorX + 1)%2
        
        if yPos == WindingAxisY and MoveY == -1:
            SectorY = (SectorY + 1)%2
        if yPos == WindingAxisY - 1 and MoveY == 1:
            SectorY = (SectorY + 1)%2
        
        xPos = (xPos + MoveX)%Dimx
        yPos = (yPos + MoveY)%Dimy
        
        return xPos,yPos,xDistance,yDistance,SectorX,SectorY,lifetime
    
    #This is the end condition for the random walk.  If the random walker comes within 1 unit of (0,0), the program ends because
    #it's overwhelming more likely for the random walkers to self-annihilate than they are to keep random walking.  Note that only one of the random
    #walkers is actually randomly walking in this simulation--one of them is pinned at 0,0.  This is valid because 2 random walkers walking on a lattice
    #can be thought of as just one random walker walking around, where we fix the origin on the other random walker.
    def CheckEnd(xPos,yPos):
        if ((xPos,yPos) == (1,0) or (xPos,yPos) == (0,1) or (xPos,yPos) == (Dimx-1,0) or (xPos,yPos) == (0,Dimy-1)):
            return True
        else:
            return False
        
    #This loop makes the random walker wiggle until the end condition
    while(CheckEnd(xPos,yPos)==False):
        xPos, yPos, xDistance, yDistance, SectorX,SectorY, lifetime = Advance(xPos,yPos,xDistance,yDistance,SectorX,SectorY,lifetime)
    return SectorX,SectorY, lifetime, xDistance, yDistance
示例#57
0
def MaximumEntropy(p, tau, Gt):

    beta = tau[-1]

    random.seed(1)  # seed for random numbers

    omega = linspace(-p['L'], p['L'], 2 * p['Nw'] + 1)
    f0, f1, f2 = me.initf0(omega)
    fsg = 1
    if p['statistics'] == 'fermi':
        Gt = -Gt
        fsg = -1
        normalization = Gt[0] + Gt[-1]
        Ker = me.initker_fermion(omega, beta, tau)
    elif p['statistics'] == 'bose':
        normalization = integrate.trapz(Gt, x=tau)
        Ker = me.initker_boson(omega, beta, tau)

    print 'beta=', beta
    print 'normalization=', normalization

    # Set error
    if p['idg']:
        sxt = ones(len(tau)) / (p['deltag']**2)
    else:
        sxt = Gt * p['deltag']
        for i in range(len(sxt)):
            if sxt[i] < 1e-5: sxt[i] = 1e-5
        sxt = 1. / sxt**2

    # Set model
    if p['iflat'] == 0:
        model = normalization * ones(len(omega)) / sum(f0)
    elif p['iflat'] == 1:
        model = exp(-omega**2 / p['gwidth'])
        model *= normalization / dot(model, f0)
    else:
        dat = loadtxt('model.dat').transpose()
        fm = interpolate.interp1d(dat[0], dat[1])
        model = fm(omega)
        model *= normalization / dot(model, f0)
        #savetxt('brisi_test', vstack((tau, fsg*dot(model,Ker))).transpose())

    print 'Model normalization=', dot(model, f0)

    # Set starting Aw(omega)
    Aw = random.rand(len(omega))
    Aw = Aw * (normalization / dot(Aw, f0))
    print 'Aw normalization=', dot(Aw, f0)

    dlda = me.initdlda(omega, Ker, sxt)

    temp = 10.
    rfac = 1.
    alpha = p['alpha0']

    for itt in range(p['Nitt']):
        print itt, 'Restarting maxent with rfac=', rfac, 'alpha=', alpha
        iseed = random.randint(0, maxint)

        me.maxent(Aw, rfac, alpha, temp, Ker, sxt, Gt, model, f0, p['Asteps'],
                  iseed)
        S = me.entropy(Aw, model, f0)
        Trc = me.lambdac(alpha, Aw, omega, dlda)

        ratio = -2 * S * alpha / Trc
        print 'Finished maxent with alpha=', alpha, '-2*alpha*S=', -2 * alpha * S, 'Trace=', Trc
        print '   ratio=', ratio

        savetxt('dos_' + str(itt), vstack((omega, Aw)).transpose())
        temp = 0.001
        rfac = 0.05

        if abs(ratio - 1) < p['min_ratio']: break

        if (abs(ratio) < 0.05):
            alpha *= 0.5
        else:
            alpha *= (1. + 0.001 * (random.rand() - 0.5)) / ratio

    for itt in range(p['Nr']):
        print 'Smoothing itt ', itt
        Aw = Broad(p['bwdth'], omega, Aw)
        Aw *= (normalization / dot(Aw, f0))  # Normalizing Aw

        savetxt('dos_' + str(p['Nitt']), vstack((omega, Aw)).transpose())

        temp = 0.005
        rfac = 0.005
        iseed = random.randint(0, maxint)
        me.maxent(Aw, rfac, alpha, temp, Ker, sxt, Gt, model, f0, p['Asteps'],
                  iseed)

        S = me.entropy(Aw, model, f0)
        Trc = me.lambdac(alpha, Aw, omega, dlda)
        ratio = -2 * S * alpha / Trc
        print 'Finished smoothing run with alpha=', alpha, '-2*alpha*S=', -2 * alpha * S, 'Trace=', Trc
        print '   ratio=', ratio

    savetxt('gtn', vstack((tau, fsg * dot(Aw, Ker))).transpose())
    Aw = Broad(p['bwdth'], omega, Aw)
    savetxt('dos.out', vstack((omega, Aw)).transpose())
    return (Aw, omega)