Ejemplo n.º 1
1
def update_velocity(particle, global_best, max_v, c1, c2, omega):
    import random
    for i in range(len(particle['velocity'])):
        v = particle['velocity'][i]
        v1 = c1 * random.random() * (particle['b_position'][i] - particle['position'][i])
        v2 = c2 * random.random() * (global_best['position'][i] - particle['position'][i])
        particle['velocity'][i] = v*omega + v1 + v2
        if particle['velocity'][i] > max_v:
            particle['velocity'][i] = max_v
        if particle['velocity'][i] < -max_v:
            particle['velocity'][i] = -max_v
Ejemplo n.º 2
0
def initialize_network(n_inputs, n_hidden, n_outputs):
    network = list()
    hidden_layer = [{'weights': [random.random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]
    network.append(hidden_layer)
    output_layer = [{'weights': [random.random() for i in range(n_hidden + 1)]} for i in range(n_outputs)]
    network.append(output_layer)
    return network
 def update(self, fitness_population_):
     fitness_population = deepcopy(fitness_population_)
     allChildren = []
     generator = self.selectParents(fitness_population)
     nb_iterations = 0
     while len(allChildren) < len(fitness_population) and nb_iterations < 100000:
         nb_iterations+=1
         parents = next(generator)
         if random.random() > self.CrossThreshold:
             children = self.crossover(parents)
         else:
             children = parents
         for child in children:
             if random.random() > self.MutationThreshold:
                 ch = self.mutation(child)
                 if ch not in self.archive:
                     allChildren.append(ch)
             else:
                 if child not in self.archive:
                     allChildren.append(child)
     if len(allChildren) < len(fitness_population):
         tmp = []
         for i in range(len(fitness_population)-len(allChildren)):
             tmp.append(list(np.random.randint(0, self.space + 1, self.dim) * TICS))
         return allChildren.extend(tmp)
     return allChildren[:len(fitness_population)]  # May exceed
Ejemplo n.º 4
0
def bounce(particles):
    color = ["white", "green", "yellow", "red", "blue", "orange", "pink"]

    for i in range(100):
        xi = engine.width / 2
        yi = engine.width / 2
        dxi = random.randint(-10, 10) * random.random()
        dyi = random.randint(-10, 10) * random.random()
        r = random.randint(0, 5)

        ball = Particle(engine.canvas,
                        xi,
                        yi,
                        r,
                        dxi,
                        dyi,
                        color=random.choice(color),
                        charge=-10)
        particles.append(ball)

    while True:
        for particle in particles:
            particle.dy += 0.1
            particle.step()
            particle.constrain()

        engine.update()
    def __init__(self, ilosc):
        super(PunktyUderzajaceWKule, self).__init__(ilosc)
        self.polozenie_x_min = -0.74
        self.polozenie_x_max = 0.74
        self.polozenie_y_min = 1.74
        self.polozenie_y_max = 2.74
        self.polozenie_z_min = -0.74
        self.polozenie_z_max = 0.74
        self.predkosc_x_min = 1.2
        self.predkosc_x_max = 2.4

        wspolczynnik_odbicia = 0.1
        wspolczynnik_tarcia = 0.2
        srodek = Wektor(2.5, 0, 0)
        promien = 1.0
        self.obszar_zabroniony = Kula(wspolczynnik_odbicia,
                                      wspolczynnik_tarcia, srodek, promien)

        for i in range(0, ilosc):
            polozenie_x = random.random() * (
                self.polozenie_x_max -
                self.polozenie_x_min) + self.polozenie_x_min
            polozenie_y = random.random() * (
                self.polozenie_y_max -
                self.polozenie_y_min) + self.polozenie_y_min
            polozenie_z = random.random() * (
                self.polozenie_z_max -
                self.polozenie_z_min) + self.polozenie_z_min
            predkosc_x = random.random() * (
                self.predkosc_x_max -
                self.predkosc_x_min) + self.predkosc_x_min
            punkt = self.pobierz_punkt_materialny(i)
            punkt.ustaw_polozenie(Wektor(polozenie_x, polozenie_y,
                                         polozenie_z))
            punkt.ustaw_predkosc(Wektor(predkosc_x, 0, 0))
Ejemplo n.º 6
0
    def update(self):
        #

        if self.stateMachine != None:
            if self.hitWall == True:
                self.stateMachine.nextState((0,1,0)) 
            else:  
                self.stateMachine.nextState((0,0,0))        
            currentState = self.stateMachine.getCurrentState()
    
            if isinstance(currentState, StateMoveCurrentDirection):
                self.moveX = 0
                self.moveY = 0 
                if self.direction == LEFT:
                    self.next_frame()
                    self.isMoving = True
                    self.movement = (WALK_SPEED, 0, LEFT)
                    if random.random() > 0.9:
                        self.is_firing = True
                    else:
                        self.is_firing = False                     
                elif self.direction == RIGHT:
                    self.next_frame()
                    self.isMoving = True
                    self.movement = (WALK_SPEED, 0, RIGHT)
                    if random.random() > 0.9:
                        self.is_firing = True
                    else:
                        self.is_firing = False                     
    
            elif isinstance(currentState, StateChangeDirection):
                self.hitWall = False
                self.isMoving = False
                self.set_reverse_direction()          
Ejemplo n.º 7
0
 def renew(self, sv, num):
     #self.remove_dead()
     goodbois = self.Creatures[:sv]
     self.Creatures = []
     for i in range(num):
         if i < goodbois.__len__():
             id = goodbois[i].id
             if random.random(
             ) < self.mutate_rate and i > self.supremacy_num:
                 goodbois[i].brain.mutate()
                 id = None
             self.create_creature(
                 id=id,
                 brain=goodbois[i].brain.get_params(),
                 starting_energy=goodbois[i].starting_energy)
         else:
             if random.random() < self.breed_rate:
                 c_1 = random.choice(goodbois)
                 c_2 = random.choice(goodbois)
                 p_3 = self.breed(c_1, c_2)
                 self.create_creature(brain=p_3,
                                      starting_energy=c_1.starting_energy)
             else:
                 #self.create_creature(starting_energy= float(random.randint(1,10)))
                 self.create_creature(starting_energy=0.0)
Ejemplo n.º 8
0
 def plot(self,
          n_cluster=3,
          title='Clusters',
          xlabel='feature 1',
          ylabel='feature 2'):
     from random import random
     for i in range(n_cluster):
         r, g, b = random.random(), random.random(), random.random()
         color = (r, g, b)
         plt.scatter(self.X[self.y == i, 0],
                     self.X[self.y == i, 1],
                     s=100,
                     c=color,
                     label='Cluster' + str(i + 1))
     if self.kmeans:
         plt.scatter(self.clusterer.cluster_centers_[:, 0],
                     self.clusterer.cluster_centers_[:, 1],
                     s=300,
                     c='yellow',
                     label='Centroids')
     plt.title(title)
     plt.xlabel(xlabel)
     plt.ylabel(ylabel)
     plt.legend()
     plt.show()
Ejemplo n.º 9
0
    def train(self):

        best_rew = 0 
  
        
        for i in range(self.n_learning_trials):
            cum_rew = 0
            self.env.reset()
            state = self.env.state
#                 flag = 0
            
            action = [[random.random(), random.random()]]

            nx_state, rew, done, _ = self.env.evaluateAction(action[0])
            if rew > best_rew:
                best_rew = rew
                best_action = action
                
        

#         best_action = [[0,0.78]]
        for i in range(1,5):
          best_action.append(best_action[i-1][::-1])
        
        return best_action
Ejemplo n.º 10
0
def transform(image, boxes, labels, difficulties, split, config={}):
    """
    Apply the transformations above.
    :param image: image, a PIL Image
    :param boxes: bounding boxes in boundary coordinates, a tensor of dimensions (n_objects, 4)
    :param labels: labels of objects, a tensor of dimensions (n_objects)
    :param difficulties: difficulties of detection of these objects, a tensor of dimensions (n_objects)
    :param split: one of 'TRAIN' or 'TEST', since different sets of transformations are applied
    :return: transformed image, transformed bounding box coordinates, transformed labels, transformed difficulties
    """
    assert split in {'TRAIN', 'TEST'}

    # Mean and standard deviation of ImageNet data that our base VGG from torchvision was trained on
    # see: https://pytorch.org/docs/stable/torchvision/models.html
    mean = [0.485, 0.456, 0.406]
    std = [0.229, 0.224, 0.225]

    new_image = image
    new_boxes = boxes
    new_labels = labels
    new_difficulties = difficulties
    # Skip the following operations if validation/evaluation
    if split == 'TRAIN':
        # A series of photometric distortions in random order, each with 50% chance of occurrence, as in Caffe repo
        if 'distort' in config and config['distort']:
            new_image = photometric_distort(new_image)

        # Convert PIL image to Torch tensor
        new_image = FT.to_tensor(new_image)

        # Expand image (zoom out) with a 50% chance - helpful for training detection of small objects
        # Fill surrounding space with the mean of ImageNet data that our base VGG was trained on
        if random.random() < 0.5 and 'expand' in config and config['expand']:
            new_image, new_boxes = expand(new_image, boxes, filler=mean)

        # Randomly crop image (zoom in)
        if config['crop']:
            new_image, new_boxes, new_labels, new_difficulties = random_crop(
                new_image, new_boxes, new_labels, new_difficulties)

        # Convert Torch tensor to PIL image
        new_image = FT.to_pil_image(new_image)

        # Flip image with a 50% chance
        if random.random() < 0.5 and 'flip' in config and config['flip']:
            new_image, new_boxes = flip(new_image, new_boxes)

    # Resize image to (300, 300) - this also converts absolute boundary coordinates to their fractional form
    if 'resize' in config and config['resize']:
        new_image, new_boxes = resize(new_image, new_boxes, dims=(300, 300))

    # Convert PIL image to Torch tensor
    new_image = FT.to_tensor(new_image)

    # Normalize by mean and standard deviation of ImageNet data that our base VGG was trained on
    if 'normalise' in config and config['normalise']:
        new_image = FT.normalize(new_image, mean=mean, std=std)

    return new_image, new_boxes, new_labels, new_difficulties
Ejemplo n.º 11
0
    def get_random_letter_charin(length: int) -> str:
        result = ''

        for _ in range(length):
            result += chr(65 + int(random.random() * 25) +
                          (32 if random.random() > 0.5 else 0))

        return result
Ejemplo n.º 12
0
def generate_random_pos_3(center, xdiff=3, ydiff=3):
    """
    Generates a random position near the center within an elliptical radius of xdiff and ydiff
    """
    offset_x = 2 * xdiff * random.random() - xdiff  # bound by (-xdiff, xdiff)
    offset_y = 2 * ydiff * random.random() - ydiff  # bound by (-ydiff, ydiff)
    offset_theta = 2 * np.pi * random.random()  # bound by (0, 2*pi)
    return np.add(center, np.array([offset_x, offset_y, offset_theta]))
Ejemplo n.º 13
0
def get_rejection_sample_disk() -> (float, float):
    sx = sy = 0.0
    while True:
        sx = 1.0 - 2.0 * random.random()
        sy = 1.0 - 2.0 * random.random()
        if sx * sx + sy * sy > 1.0:
            break
    return sx, sy
    def FightPredator(self, targetPredator):
        preyDefeated = False
        strengthCheck = random.random()
        if self.Genotype[1] == "SS":
            if targetPredator.Genotype[1] == self.Genotype[1]:
                if random.random() >= 0.5:
                    if strengthCheck > 0.5:
                        preyDefeated = True
                else:
                    self.TimeGoingRandomDirection = 180
                    return
            elif targetPredator.Genotype[1] == "Ss" or targetPredator.Genotype[
                    1] == "sS":
                if strengthCheck > 0.75:
                    preyDefeated = True
            else:
                if strengthCheck > 0.95:
                    preyDefeated = True
        elif self.Genotype[1] == "Ss" or self.Genotype[1] == "sS":
            if targetPredator.Genotype[1] == self.Genotype[1]:
                if random.random() >= 0.5:
                    if strengthCheck > 0.5:
                        preyDefeated = True
                else:
                    self.TimeGoingRandomDirection = 180
                    return
            elif targetPredator.Genotype[1] == "SS":
                if strengthCheck > 0.25:
                    preyDefeated = True
            else:
                if strengthCheck > 0.75:
                    preyDefeated = True
        else:
            if targetPredator.Genotype[1] == self.Genotype[1]:
                if random.random() >= 0.5:
                    if strengthCheck > 0.5:
                        preyDefeated = True
                else:
                    self.TimeGoingRandomDirection = 180
                    return
            elif targetPredator.Genotype[1] == "Ss" or targetPredator.Genotype[
                    1] == "sS":
                if strengthCheck > 0.25:
                    preyDefeated = True
            else:
                if strengthCheck > 0.05:
                    preyDefeated = True

        if preyDefeated:
            dispatcher.send(signal=EventSignals.organismDeath,
                            sender=targetPredator)
            self.SetEnergyLevel(self.EnergyLevel +
                                (targetPredator.EnergyLevel * 0.9))
            self.TimeGoingRandomDirection = 180
        else:
            targetPredator.SetEnergyLevel(targetPredator.EnergyLevel +
                                          (self.EnergyLevel * 0.9))
            self.Death
Ejemplo n.º 15
0
def generate_pointwise_data(length, indexExistsProb=0.5, valueMean=2, fp=sys.stdout):
    """Generate random pointwise data.

    """

    import random
    for index in xrange(int(length/indexExistsProb)):
        if random.random() > indexExistsProb:
            fp.write("%i\t%f\n" % ( index, 2*valueMean*random.random() ))
Ejemplo n.º 16
0
 def rand_point(self) -> List[float]:
     x = (random.random() - 0.5) * 2
     y = (random.random() - 0.5) * 2
     new_r = pow(x, 2) + pow(y, 2)
     if new_r > 1:
         return self.rand_point()
     x = x * self.radius + self.x_center
     y = y * self.radius + self.y_center
     return [x, y]
Ejemplo n.º 17
0
	def CreateStudent(self, phone):
		cuser = self.CreateCUser(phone, "Student")
		if random.random() < 0.5:
			p = m.Person.objects.all()
			pind = int((len(p) - 1) * random.random())
			guard = p[pind]
			s = m.Student.objects.create(CUser = cuser, Guardian = guard)
		else:
			s = m.Student.objects.create(CUser = cuser)
		return s
Ejemplo n.º 18
0
    def test_rand(self):
        for _ in range(20):
            a, b = randint(2, 100000), randint(2, 100000)
            if a == b: continue
            self.assertEqual(find_uniq(generate_test_arr(a, b, 1000)), a)

        for _ in range(20):
            a, b = randint(2, 100000) + random.random(), randint(2, 100000) + random.random()
            if a == b: continue
            self.assertEqual(find_uniq(generate_test_arr(a, b, 1000)), a)
Ejemplo n.º 19
0
def estimate_pi(p):
    amount = 0
    for trial in range(1, p + 1):
        x = random.random()
        y = random.random()
        length = math.sqrt(x**2 + y**2)
        if length <= 1:
            amount += 1
    piEstimate = 4 * (amount / p)
    return piEstimate
Ejemplo n.º 20
0
def randomboards(numboards):
    boards = []
    for i in range(numboards):
        b = zeros((8,8))
        ran = random.randint(6,16)
        b[(random.random(ran)*7).astype(int), (random.random(ran)*8).astype(int)] = 1
        ran = random.randint(6,16)
        b[(random.random(ran)*7).astype(int)+1, (random.random(ran)*8).astype(int)] = 2
        boards.append(b)
    return boards
Ejemplo n.º 21
0
def getNewVelocity(particle,
                   nAntennae,
                   gBest,
                   initialVelocity=False,
                   inertiaCo=0.721,
                   socCogCo=1.1193):
    r1Vec = [random.random(), random.random()]
    r2Vec = [random.random(), random.random()]

    pos = particle['position']
    vel = particle['velocity']
    pBest = particle['personalBestPos']

    if initialVelocity:
        randPos = randDesign(nAntennae)
        iniVel = [
            velEl for velEl in [
                abs(pos[index] - randPos[index]) / 2
                for index in list(range(nAntennae - 1))
            ]
        ]
        print('###############')
        print('iniVel: ', iniVel)
        print('###############')
        return iniVel

    inertia = [inertiaCo * velEl for velEl in vel]
    print('subList: ',
          [pBest[index] - pos[index] for index, el in enumerate(vel)])
    cognitiveAttractionPt1 = [
        socCogCo * r1Vec * postEs for postEs in
        [pBest[index] - pos[index] for index, el in enumerate(vel)]
    ]
    socialAttraction = [
        socCogCo * float(r2Vec) * postEs for postEs in
        [gBest[index] - pos[index] for index, el in enumerate(vel)]
    ]

    print('###############')
    print('inertia: ', inertia)
    print('###############')
    print('cognitiveAttraction: ', cognitiveAttraction)
    print('###############')
    print('socialAttraction: ', socialAttraction)
    print('###############')
    newVel = [
        newVelEl for newVelEl in [
            inertia[index] + cognitiveAttraction[index] +
            socialAttraction[index] for index in enumerate(vel)
        ]
    ]
    print('newVelocity: ', newVel)
    print('###############')
    return newVel
Ejemplo n.º 22
0
def generate_points(npoints, radius):
    points = [Point() for _ in range(npoints)]

    # note: this is not a uniform 2-d distribution
    for p in points:
        r = random.random() * radius
        ang = random.random() * 2 * pi
        p.x = r * cos(ang)
        p.y = r * sin(ang)

    return points
Ejemplo n.º 23
0
	def CreateTutorObj(self, phone):
		myuser = self.CreateMyUser( phone, "Tutor")
		q = m.Qualification.objects.all()
		qind = int((len(q) - 1) * random.random())
		qual = q[qind]
		a = "".join([chr(int(i) + 97) for i in str(phone)])
		lat = random.random() * 0.3 + 24.7
		long = random.random() * 0.8 + 66.6
		latlong = str(lat) + ","+ str(long)
		hash = encode(lat, long, precision = 5)
		t = m.Tutor.objects.create(MyUser = myuser, Highest_Qualification = qual, Degree_Name = a, Institution = a, Degree_Image = self.photograph, location = latlong, hash = hash)
		return t
Ejemplo n.º 24
0
def generate_quaternion():
    s = random.uniform(0, 1)
    sig_1 = sqrt(1 - s)
    sig_2 = sqrt(s)
    angle_1 = 2 * pi * random.random()
    angle_2 = 2 * pi * random.random()
    w = cos(angle_2) * sig_2
    x = sin(angle_1) * sig_1
    y = cos(angle_1) * sig_1
    z = sin(angle_2) * sig_2

    return quaternion.quaternion(w, x, y, z)
Ejemplo n.º 25
0
def generate_pointwise_data(length,
                            indexExistsProb=0.5,
                            valueMean=2,
                            fp=sys.stdout):
    """Generate random pointwise data.

    """

    import random
    for index in xrange(int(length / indexExistsProb)):
        if random.random() > indexExistsProb:
            fp.write("%i\t%f\n" % (index, 2 * valueMean * random.random()))
Ejemplo n.º 26
0
    def jugar(self):

        self.apuesta_inicial = (1 + theta + self.ansiedad) * 1

        if self.destino.estado == True and self.accion == "ruleta":
            self.destino.visitas += 1

            for i in self.destino.personal:
                if i.coludido == True and self.coludido == True:
                    self.probabilidad_ganar += self.probabilidad_ganar * \
                                               kappa  / 100

            if self.prediciendo == True:
                self.probabilidad_ganar += psi / 100

            self.destino.numero_color = random.choice(["color", "numero"])
            self.destino.color = random.choice(["verde", "negro", "rojo"])
            self.probabilidad_ganar = self.destino.probabilidad_juego_ruleta + \
                                      0.2 * self.suerte - 0.1

            if random.random() <= self.probabilidad_ganar:
                self.dinero += self.apuesta_inicial * self.destino.ganancia
                self.destino.perdida += self.apuesta_inicial * \
                                        self.destino.ganancia
            else:

                self.destino.pozo_casino += self.apuesta_inicial * \
                                            self.destino.ganancia
        else:
            if self.destino.estado == True:
                self.destino.visitas += 1
                self.probabilidad_ganar = self.destino.probabilidad_tragamoneda\
                                          + 0.2 * self.suerte - 0.1

                if random.random() <= self.probabilidad_ganar:
                    self.dinero += self.destino.pozo
                    self.destino.perdida += self.destino.pozo
                    self.destino.pozo = 0
                else:
                    self.destino.pozo += self.apuesta_inicial * 0.9
                    self.destino.pozo_casino += self.apuesta_inicial * 0.1

        if self.tiempo < int(self.tiempo_espera) and self.destino.estado == \
                True and self.prediciendo == True and self.personalidad == \
                "kibitzer":
            self.tiempo += 1
            self.estado = True
            self.accion = "ruleta"

        else:
            self.tiempo = 0
            self.estado = False
Ejemplo n.º 27
0
    def __init__(self,n,rnd=False):
        self.dim = n
	self.w = np.zeros(n)
	self.m = np.zeros((n,n))
	self.cw = np.zeros((n,n,n))
	self.quartw = np.zeros((n,n,n,n))
        if rnd:
            self.b += 5*(2*random.random() -1)
	    for i in range(self.dim):
		self.w[i] += 20*(2*random.random() -1)
	    for i in range(self.dim):
                for j in range(self.dim):
		    self.m[i][j] += 10*(2*random.random() -1)
Ejemplo n.º 28
0
def update_velocity(particle, global_best, max_v, c1, c2, omega):
    import random
    for i in range(len(particle['velocity'])):
        v = particle['velocity'][i]
        v1 = c1 * random.random() * (particle['b_position'][i] -
                                     particle['position'][i])
        v2 = c2 * random.random() * (global_best['position'][i] -
                                     particle['position'][i])
        particle['velocity'][i] = v * omega + v1 + v2
        if particle['velocity'][i] > max_v:
            particle['velocity'][i] = max_v
        if particle['velocity'][i] < -max_v:
            particle['velocity'][i] = -max_v
Ejemplo n.º 29
0
 def environment_update(self):
     #reset some parameters after a day
     prev_home_range=self.dragon.home_range
     self.world.set_dragon_home_range()
     d_range=self.dragon.home_range-prev_home_range
     d_l_num=(d_range*self.world.dens_l_anim)
     d_s_num=(d_range*self.world.dens_s_anim)
     #if d_range>0:
         #print(self.world.dens_l_anim, "\033[32m New in sight:\033[0m",int(d_l_num)," ",int(d_s_num))
     if d_l_num>1.0:
         for i in range(int(d_l_num)):
             self.new_l_agent()
     else:
         self.accum_l+=d_l_num
         while self.accum_l >1.0:
             self.accum_l-=1.0
             self.new_l_agent()
     if d_s_num>1.0:
         for i in range(int(d_s_num)):
             self.new_s_agent()
     else:
         self.accum_s+=d_s_num
         while self.accum_s >1.0:
             self.accum_s-=1.0
             self.new_s_agent()
     #daily update for new born animals
     growth_seed=random.random()
     self.anim_update()
     ds=self.world.dens_l_anim*self.dragon.home_range
     n=self.n_l
     prob=n*self.world.l_growth_coef*(ds-n)/(ds)
     #print("curr l_dens:",n/self.dragon.home_range, "\texp:",self.world.dens_l_anim)
     #print(self.dragon.home_range," large  ",prob)
     if prob>1.0:
         for i in range(int(prob)):
             self.new_l_agent()
     elif growth_seed<prob:
         #print("born l agent")
         self.new_l_agent()
     growth_seed=random.random()
     ds=self.world.dens_s_anim*self.dragon.home_range
     n=self.n_s
     prob=n*self.world.s_growth_coef*(ds-n)/(ds)
     #print(self.dragon.home_range," small  ",prob)
     #print("curr s_dens:",n/self.dragon.home_range, "\texp:",self.world.dens_s_anim)
     if prob>1.0:
         for i in range(int(prob)):
             self.new_s_agent()
     elif growth_seed<prob:
         #print("born l agent")
         self.new_s_agent()
Ejemplo n.º 30
0
def profit(unit_price, findprofit):
    item1 = random.choice(
        ['pens', 'pencils', 'rulers', 'sweets', 'KitKats', 'Mars Bars'])
    item2 = random.choice(
        ['Twix', 'Kitkats', 'cans of coke', 'bottles of Lucozade'])
    name = name_chooser()
    if unit_price == 0:
        total = random.randint(10, 20)
        profit = random.randint(total, 2 * total)
        total = total + round(random.random(), 2)
        profit = profit + round(random.random(), 2)
        if findprofit == 1:
            q = name + " buys some " + item1 + " for £" + round_2_money(
                total) + " and sells them all for £" + round_2_money(
                    total +
                    profit) + ". How much profit does " + name + " make?"
            ans = round_2_money(profit)
        else:
            q = name + " buys some " + item1 + " for £" + round_2_money(
                total) + " and sells them all for £" + round_2_money(
                    profit
                ) + " profit. How much does " + name + " sell them for?"
            ans = round_2_money(profit + total)
    else:
        unit_spend_price = random.randint(0, 2) + round(random.random(), 2)
        quantity = random.choice([10, 20, 30, 40])
        total_spend = unit_spend_price * quantity
        if unit_price == 1:
            total_sales = random.randint(round(total_spend, 0),
                                         2 * round(total_spend, 0))
            profit = total_sales - total_spend
            q = name + " buys " + str(
                quantity) + " " + item1 + " for £" + round_2_money(
                    unit_spend_price
                ) + " each and sells them all for £" + round_2_money(
                    total_sales) + ". How much profit does " + name + " make?"
            ans = round_2_money(total_sales - total_spend)
        else:
            unit_sale_price = random.randint(
                round(unit_spend_price + 1, 0), 2 *
                round(unit_spend_price + 1, 0)) + round(random.random(), 2)
            total_sales = unit_sale_price * quantity
            q = name + " buys " + str(
                quantity) + " " + item1 + " for £" + round_2_money(
                    unit_spend_price
                ) + " each and sells them for £" + round_2_money(
                    unit_sale_price
                ) + " each. How much profit does " + name + " make?"
            ans = round_2_money(total_sales - total_spend)

    return q, ans
Ejemplo n.º 31
0
 def CastSeedLocation(self):
     valid = False
     while not valid:
         radius = random.random() * self.dataParser.MaxSeedCastDistance
         angle = random.random() * 2 * math.pi
         if (int(self.X + radius * math.cos(angle)) > 1000
                 or int(self.X + radius * math.cos(angle)) < 0
                 or int(self.Y + radius * math.sin(angle)) > 750
                 or int(self.Y + radius * math.sin(angle)) < 0):
             valid = False
         else:
             valid = True
     return (int(self.X + radius * math.cos(angle)),
             int(self.Y + radius * math.sin(angle)))
Ejemplo n.º 32
0
    def _adv_training(self,
                      segmentators: List[Segmentator],
                      lab_data_iterators: List[iterator_],
                      unlab_data_iterator: iterator_,
                      eplision: float = 0.05,
                      fsgm_ratio=0.5):
        assert segmentators.__len__(
        ) == 2, 'only implemented for 2 segmentators'
        axises = range(self.C)
        adv_losses = []
        ## draw first term from labeled1 or unlabeled
        img, img_adv = None, None
        if random.random() <= fsgm_ratio:
            [[img, gt], _, _] = lab_data_iterators[0].__next__()
            img, gt = img.to(self.device), gt.to(self.device)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                img_adv, _ = FSGMGenerator(segmentators[0].torchnet, eplision=eplision) \
                    (dcopy(img), gt, criterion=self.criterions['sup'])
        else:
            [[img, _], _, _] = unlab_data_iterator.__next__()
            img = img.to(self.device)
            img_adv, _ = VATGenerator(segmentators[0].torchnet,
                                      eplision=eplision,
                                      axises=axises)(dcopy(img))
        assert img.shape == img_adv.shape
        adv_pred = segmentators[1].predict(img_adv, logit=False)
        real_pred = segmentators[0].predict(img, logit=False)
        adv_losses.append(
            KL_Divergence_2D(reduce=True)(adv_pred, real_pred.detach()))

        if random.random() <= fsgm_ratio:
            [[img, gt], _, _] = lab_data_iterators[1].__next__()
            img, gt = img.to(self.device), gt.to(self.device)
            img_adv, _ = FSGMGenerator(segmentators[1].torchnet, eplision=eplision) \
                (img, gt, criterion=CrossEntropyLoss2d())
        else:
            [[img, _], _, _] = unlab_data_iterator.__next__()
            img = img.to(self.device)
            img_adv, _ = VATGenerator(segmentators[1].torchnet,
                                      eplision=eplision,
                                      axises=axises)(dcopy(img))

        adv_pred = segmentators[0].predict(img_adv, logit=False)
        real_pred = segmentators[1].predict(img, logit=False)
        adv_losses.append(
            KL_Divergence_2D(reduce=True)(adv_pred, real_pred.detach()))
        adv_loss = sum(adv_losses) / adv_losses.__len__()
        return adv_loss
Ejemplo n.º 33
0
def download_map_sat(dir_out, t, lat, lng, zoom, out_w, out_h):
    '''
	Download images
	'''
    #path_map = "%s/map/map%05d_%f,%f.%s"%(dir_out, t,lat,lng, 'jpg')
    path_sat = "%s/sat/sat%05d_%f,%f.%s" % (dir_out, t, lat, lng, 'jpg')
    w, h = out_w, out_h
    if args.augment:
        w, h = min(1280, 1.5 * out_w), min(1280, 1.5 * out_h)

    #url_map = get_style(args.style_map, (lat, lng), zoom, int(w), int(h), 'jpg')
    url_sat = get_style(args.style_sat, (lat, lng), zoom, int(w), int(h),
                        'jpg')
    #urllib.urlretrieve(url_map, path_map)
    urllib.urlretrieve(url_sat, path_sat)
    #with open(path_map,'wb') as img:
    #	img.write(requests.get(url_map).content)
    #with open(path_sat,'wb') as img:
    #	img.write(requests.get(url_sat).content)
    #pdb.set_trace()

    if args.augment:
        #img_map = Image.open(path_map)
        img_sat = Image.open(path_sat)

        ang = -19 + 38 * random.random()

        #img_map = img_map.rotate(ang, resample=Image.BICUBIC, expand=False)
        img_sat = img_sat.rotate(ang, resample=Image.BICUBIC, expand=False)

        #x1, y1 = int((img_map.width-out_w)*0.5), int((img_map.height-out_h)*0.5)
        x1, y1 = int((img_sat.width - out_w) * 0.5), int(
            (img_sat.height - out_h) * 0.5)

        #img_map = img_map.crop((x1, y1, x1+out_w, y1+out_h))
        img_sat = img_sat.crop((x1, y1, x1 + out_w, y1 + out_h))

        flipv = random.random() < 0.25
        fliph = random.random() < 0.25

        if flipv:
            #img_map = img_map.transpose(Image.FLIP_TOP_BOTTOM)
            img_sat = img_sat.transpose(Image.FLIP_TOP_BOTTOM)
        if fliph:
            #img_map = img_map.transpose(Image.FLIP_LEFT_RIGHT)
            img_sat = img_sat.transpose(Image.FLIP_LEFT_RIGHT)

        #img_map.save(path_map)
        img_sat.save(path_sat)
Ejemplo n.º 34
0
 def explorar(self):
     if random.random() <= 0.2:
         pokemon = random.choice(POKEMONS)
         print(
             'Um pokemon selvagem apareceu.Que sorte!: {}'.format(pokemon))
         escolha = input('Deseja capturar pokemon?(s/n)')
         if escolha == 's':
             if random.random() >= 0.2:
                 self.capturar(pokemon)
             else:
                 print('Pokemon escapou')
         else:
             print('Ok, boa viagem')
     else:
         print('Essa exploração nao deu em nada')
 def q(x):
     if x == min_bin:
         return min_bin + 1
     elif x == max_bin:
         return max_bin - 1
     else:
         return x- 1 if random.random() < .5 else x + 1
Ejemplo n.º 36
0
def sim_anneal(state,splits,merges):
    old_cost = cost(state,splits,merges)
    T = 10.0
    T_min = 0.01
    alpha = 0.97
    iterations = 500
    old_cost_plot = []
    new_cost_plot = []
    oplist = [1,2]

    while T > T_min:
        i = 1
        if i <= iterations:
            if i < 4*iterations/5.0 :
                operator = choice(oplist)
                if operator==1:
                    [new_state,new_splits,new_merges] = neighbor_switch_jumps(state,splits,merges)
                else:
                    [new_state,new_splits,new_merges] = look_ahead(state,splits,merges)
            else:
                new_state,new_splits,new_merges = neighbor_merge_split(state,splits,merges)
            new_cost = cost(new_state,new_splits,new_merges)
            ap = acceptance_probability(old_cost, new_cost, T)
            print('new cost: ' +str(new_cost) +' vs old cost: '+ str(old_cost))
            if ap > random.random() and old_cost != new_cost:
                print('accepted')
                state = deepcopy(new_state)
                splits=new_splits
                merges=new_merges
                plot(state,splits,merges)
                old_cost = new_cost
            i += 1
            T = T * alpha
    return state,splits,merges,old_cost
    def __init__(self, retention):
        self.retention = retention

        for x in range(0, self.initial_amount):
            new_user = User()
            new_user.idle = random.random() < retention
            self.users.append(new_user)
Ejemplo n.º 38
0
def runcmd_threadpool(cm,runwith):
    shell = 'bash'
    #runwith ='ssh auv@archipelago srun /bin/bash '
    if len(runwith) > 0:
        match = re.search('([\w.-]+)@([\w.-]+)', runwith)
        if match:
            username = match.group(1)
            curruser = getpass.getuser()
            if curruser != username:
                reps = {curruser:username}
                cm = replace_all(cm, reps)
        cmd= '%s "%s -c \'%s\' "' % (runwith[:-1],shell,cm[:-1])
    else:
        cmd= '%s -c \'%s\' ' % (shell,cm[:-1])

    s,o = commands.getstatusoutput(cmd)
    if s != 0:
        print 'problem running: ', cmd
        print 'output : ',o
        errfn='./%s/%d-cmd-%03d.txt'% ('.',os.getpid(),random.random())
        print 'wrote log to %s ' % errfn
        f = open(errfn, 'w')
        f.write( 'problem running: %s' % cmd)
        f.write('output : %s' % o)
        f.close()
    return 0
Ejemplo n.º 39
0
def runIC2(G, S, p=.01):
    ''' Runs independent cascade model (finds levels of propagation).
    Let A0 be S. A_i is defined as activated nodes at ith step by nodes in A_(i-1).
    We call A_0, A_1, ..., A_i, ..., A_l levels of propagation.
    Input: G -- networkx graph object
    S -- initial set of vertices
    p -- propagation probability
    Output: T -- resulted influenced set of vertices (including S)
    '''
    from copy import deepcopy
    import random
    T = deepcopy(S)
    Acur = deepcopy(S)
    Anext = []
    i = 0
    while Acur:
        values = dict()
        for u in Acur:
            for v in G[u]:
                if v not in T:
                    w = G[u][v]['weight']
                    if random.random() < 1 - (1-p)**w:
                        Anext.append((v, u))
        Acur = [edge[0] for edge in Anext]
        print i, Anext
        i += 1
        T.extend(Acur)
        Anext = []
    return T
Ejemplo n.º 40
0
 def add_informe(self, date):
     
     ''' 
     figure out the last date
     '''
     list_fechas = self.__finacial_inform.keys()
     list_fechas_order = list_fechas.sort()
     fecha_anterior = list_fechas_order[-1]
     
     '''
     new account year:
         frist, it was good (>0.5) or bad year, improve = generate better range of
         bad year company less money =  0.9
         good year company improve, more money= 1.1  
         then change the value 
     '''
     
     if random.random() < 0.5:
         value = 0.9
     else:
         value = 1.1
     
     self.__finacial_inform[date] = financial_inform(value*self.__finacial_inform[fecha_anterior]._activo_inm,
                                                      value*self.__finacial_inform[fecha_anterior]._activo_cir,
                                                      value*self.__finacial_inform[fecha_anterior]._pasivo_lar,
                                                      value*self.__finacial_inform[fecha_anterior]._pasivo_cor,
                                                      value*self.__finacial_inform[fecha_anterior]._ingresos,
                                                      value*self.__finacial_inform[fecha_anterior]._costes,
                                                      value*self.__finacial_inform[fecha_anterior]._amortia,                          
                                                     )
Ejemplo n.º 41
0
	def getRandom(min, max, k):

		ints = dict()
		k -= 1
		while k >= 0:
			ints.update(  math.floor(min + (max-min)*random.random())  )
			k -= 1
		return ints
    def update(obj, event):
        if l.getIteration() < args.steps and l.getIteration() > 0:
            # add the new point
            points.InsertPoint(l.getIteration(), l.getValue())
            points.Modified()
    
            # and update the lines accordingly
            lines.InsertNextCell(2)
            lines.InsertCellPoint(l.getIteration()-1)
            lines.InsertCellPoint(l.getIteration())
            lines.Modified()
    
        else:
            sigma, r, b = randomLorenzParameters()
            print "starting with new parameters (sigma, r, b) = ", sigma, r, b
            l.setParams(sigma, r, b)
    
            # reset the points array, does not free the space
            # and therefore makes sure we don't always allocate/free memory
            points.Reset()
            points.InsertPoint(l.getIteration(), l.getValue())
            points.Modified()

            # ... and do the ame for the lines
            lines.Reset()
            lines.InsertNextCell(1)
            lines.InsertCellPoint(0)
            lines.Modified()

            # let the actor paint in a new random color
            actor.GetProperty().SetColor(random.random(), random.random(), random.random())

        if not l.eval():
            import sys.exit
            exit(1)

        # resets the camera (only "zoom out") to include the complete line
        ren.ResetCamera()

        # and rotate the view a little (we could have used Yaw instead to rotate the scene instead of the camera)
        ren.GetActiveCamera().Azimuth(0.5)

        # the obj is the RenderWindowInteractor since the callback was registered for it
        # render again
        obj.GetRenderWindow().Render()
Ejemplo n.º 43
0
def mutate(individual, mutation_rate):
    """ (list of int, double) -> list of int
    
    Return the individual which mutated each parameter with the chance given by the mutation_rate.
    """
    for j in xrange(len(individual)):
        if random.random() < mutation_rate:
            individual[i] = (individual[i] + 1) % 2
    return individual
Ejemplo n.º 44
0
 def mutate(ind):
     if len(ind) < 2:
         raise TypeError("Individuum too short")
     for i in range(len(ind)):
         if random.random() < 1/len(ind):
             if ind[i] == '0':
                 replace = '1'
             else:
                 replace = '0'
             ind = ind[:i] + replace + ind[i+1:]
Ejemplo n.º 45
0
def mutate(an_individual, p):
    """
    Change each bit by chance p
    
    individual: the individual to mutate
    p: probability for each parameter to mutate    
    """
    for i in xrange(len(an_individual)):
        if random.random() < p:
            an_individual[i] = not an_individual[i]
    return an_individual
Ejemplo n.º 46
0
 def mutate(self, mutate_prob, parents):
     """
     Add or subtract 0.01 from every solution that is going to be mutated
     the sign of the operation is decided at random with .5 probability
     at each option (.5 for + and .5 for -)
     """
     for i in range(len(parents)):
         if mutate_prob > random.random():
             if random() > 0.5:
                 parents[i] += 0.01 if parents[i] <= 0.99 else 0.0
             else:
                 parents[i] -= 0.01 if parents[i] >= 0.01 else 0.0
Ejemplo n.º 47
0
def generate_weights(layers):
   input_layer_size = layers[0]
   output_layer_size = layers[len(layers)-1]
   hidden_layers = layers[1:len(layers)-1]
   thetas = []
   prevSize = input_layer_size
   for i in range(0,len(hidden_layers)):
      eint = sqrt(6)/sqrt(prevSize + hidden_layers[i])
      temp = []
      for j in range(0,(hidden_layers[i] * (prevSize + 1))):
         temp.append(random.random() * 2 * eint - eint)
      thetas.append(array(temp))
      thetas[i].resize(hidden_layers[i],(prevSize + 1))
      prevSize = hidden_layers[i]
   eint = sqrt(6)/sqrt(prevSize + output_layer_size)
   temp = []
   for j in range(0,output_layer_size * (prevSize + 1)):
      temp.append(random.random() * 2 * eint - eint)
   thetas.append(array(temp))
   thetas[len(thetas)-1].resize(output_layer_size,(prevSize + 1))
   return thetas
Ejemplo n.º 48
0
def vector(base_seq, mut_factor, CDR_list):
    """base_seq - sequense in str format,
    mut_factor in range (0,1)
    return vector of integers"""
    vector = []
    list_ref = [translator(i) for i in base_seq]
    for i in range(len(list_ref)):
        if i not in CDR_list and mut_factor > random.random() and list_ref[i] not in ['C', 2]:
            vector.append(translator(res_choice()))
        else:
            vector.append(list_ref[i])
    return vector
Ejemplo n.º 49
0
def acceptance(E1,E2):
    if E2<E1:
        return True
    elif E2>E1:
        #probability
        pr = np.exp(-beta*(E2-E1))
        #choosing a random number to check with the probability distribution
        ran = random.random()
        if ran < pr:
            return True
        elif ran > pr:
            return False
Ejemplo n.º 50
0
def runcmd_threadpool(cm):
    cmd= 'csh -c \'%s\'' % cm[:-1]
    s,o = commands.getstatusoutput(cmd)
    if s != 0:
        print 'problem running: ', cmd
        print 'output : ',o
        errfn='./%s/%d-cmd-%03d.txt'% ('.',os.getpid(),random.random())
        print 'wrote log to %s ' % errfn
        f = open(errfn, 'w')
        f.write( 'problem running: %s' % cmd)
        f.write('output : %s' % o)
        f.close()
    return 0
Ejemplo n.º 51
0
def addRandomLittleJump(w):
    """
        Adds a small and random change to the
        weight vector.
    """
    out = list(w)

    counter = 1 + w[0]

    for index in range(len(w)-counter):
        #Try to keep the hypothesis sparse.
        if(w[index+counter] != 0 or random.random() < 0.05):
            out[index+counter] += random.gauss(0.0, 0.005)
    return out
Ejemplo n.º 52
0
def randomHypothesis(n, database):
    """
        Returns a set of weights in the form of
        a vector. These are to be used in the ANN.
        The idea is that this should return a random
        function. But a random ANN is the next best
        thing.

        It uses the Pearson r-correlation coefficient
        to find out which of the the attributes that
        might be connected.

        n is the number of inputs of the function.
    """
    #Generate the hidden layers!
    #The number of hidden layers is geometrically random
    numHiddenLayers = georand(0.8)
    hiddenLayers = [0]*numHiddenLayers
    #The number of nodes in each layer is geometrically random as well
    for i in range(numHiddenLayers):
        hiddenLayers[i] = georand(0.95)

    #How many weights are required in the ANN?
    numWeights = howManyWeightsInTheANN(hiddenLayers, numHiddenLayers, n)


    out = [0.0]*(numWeights+numHiddenLayers+1)
    out[0] = numHiddenLayers
    index = 1
    for element in hiddenLayers:
        out[index] = element
        index += 1

    #Decide which attributes that are important
    attributesInHypothesis = chooseAttributes(database, n)

    #Set the first row of the network
    numWeightsFirstRow = n*hiddenLayers[0]
    for i in range(hiddenLayers[0]):
        for j in range(n):
            if(attributesInHypothesis[j] == True):
                out[index] = random.gauss(0,10)
            index += 1

    #And then all of the other rows
    for i in range(numWeights-numWeightsFirstRow):
        if(random.random()<0.2):
            out[index] = 10.0*random.gauss(0.0,1.0)
        index += 1
    return out
Ejemplo n.º 53
0
 def get_object(self):
     #for q in Question.objects.all():
     #    q.created_by=User.objects.get(username='******'); q.save()
     pk = self.request.GET.get("question")
     q = None
     if pk:
         q = Question.objects.get(pk=pk)
     if not q:
         l1 = Question.objects.filter(Q(difficulty__isnull=True) | Q(reviewed=False))
         if l1.exists() and random.random()>.25:
             q = l1.order_by('?').first()
         else:
             q = Question.objects.all().order_by('?').first()
     return q
Ejemplo n.º 54
0
def act_as_baboon(my_id, init_side):
    side = init_side
    random.seed(my_id)
    global westers
    global easters
    for i in xrange(NUM_CROSSINGS):

        print (side)
        print (westers)
        print (easters)
        if side == 0:
            westqueue.acquire()
        else:
            eastqueue.acquire()

        with mutex:
            if (easters > westers) or (westers <= 0):
                #print ("east")
                eastqueue.release()
            elif (easters <= westers) or (easters <= 0):
                westqueue.release()
                #print ("west")

        #print("Got here")

        with turnstile:
            switches[side].lock(rope)
        with multiplex:
            sleep(random.random())  # crossing; Seeded random number
        switches[side].unlock(rope)
        with mutex2:
            if side == 0:
                easters += 1
                westers -= 1
            else:
                westers += 1
                easters -= 1
            side = 1 - side
            if (easters > westers) or (westers <= 0):
                #print ("east")
                eastqueue.release()
            elif (easters <= westers) or (easters <= 0):
                westqueue.release()
                #print ("west")

        #print("Got to run")
    print ("Baboon %d finished" % my_id)
 def create_a_close_parties(self):
     print 'begin'
     #creates many parties close to UCSB
     server_url = self.server_url
     self.get(server_url + "/users/sign_up", description="View the user signup page")
     auth_token = extract_token(self.getBody(), 'name="authenticity_token" type="hidden" value="', '"')
     email = Lipsum().getUniqWord() + "@" + Lipsum().getWord() + ".com"
     name = Lipsum().getUniqWord()
     print 'create a user'
     self.post(self.server_url + "/users",
             params=[['user[name]',name],
             ['user[email]', email],
               ['user[password]', 'alphabet'],
               ['user[password_confirmation]', 'alphabet'],
               ['authenticity_token', auth_token],
               ['commit', 'Sign up']],
             description="Create New User")
     print 'go to party page '
     self.get(server_url + "/new", description="create party page")
     auth_token = extract_token(self.getBody(), 'name="authenticity_token" type="hidden" value="', '"')
    
     rand = random.random()
     
     ran=rand/10
     
     lat=34.42
         
     lon=-119.9+ran
     print 'posting a party'
     self.post(self.server_url + "/parties",
         params=[['party[name]', Lipsum().getUniqWord()],
           ['party[owner]', name],
           ['party[date]', '2016-12-03'],
           ['party[time]', '17:00'],
           ['party[location]',''+str(lat)+', -'+str(lon)],
           ['party[latitude]',lat],
           ['party[longitude]',lon],
           ['party[description]',Lipsum().getUniqWord()],
           ['authenticity_token', auth_token],
           ['commit', 'Sign up']],
         description="Create New party")
     print 'all done'
def downsample(states,M):
    p_total = sum(p for m,p in states)
    new_states = states[:]
    n = len(new_states)
    while n > M:
        i,j = randrange(n),randrange(n)
        if i == j:
            continue
        mi,pi = new_states[i]
        mj,pj = new_states[j]
        r = random.random()
        if r > pi/(pi+pj): #i gets killed
            new_states[j] = (mj,pi+pj)
            new_states.pop(i)
        else:              #j gets killed
            new_states[i] = (mi,pi+pj)
            new_states.pop(j)
        n = len(new_states)
    p_after = sum(p for m,p in new_states)
    return new_states
Ejemplo n.º 57
0
def randomPlay(board, gui):
    board, dummy, dummy, dummy = spawn(board)
    while True:
        empty = board.count(0)
        if empty == 0:
            if not legalMoves(board):
                break
        # gui.drawBoard(board)
        var = random.random()
        if var < 0.25:
            dir = 'w'
        elif var < 0.5:
            dir = 'd'
        elif var < 0.75:
            dir = 's'
        elif var < 1:
            dir = 'a'
        board, modified = move(board, dir)
        if modified:
            board, dummy, dummy, dummy = spawn(board)
    gui.drawBoard(board)
    return board
Ejemplo n.º 58
0
Archivo: crawler.py Proyecto: h/eureka
    def fetch_html(self, *args, **kwargs):
        '''
        Like ``fetch_xml``, but we expect an HTML response.

        A keyword argument ``encoding`` can be specified to override the page's
        default encoding.

        '''

        from eureka.xml import HTMLParser
        from lxml import etree

        encoding = kwargs.pop('encoding', None)

        error = None
        for retry in xrange(self.retries+1):
          try:
            with self.fetch(*args, **kwargs) as fp:
                if self.sanitize:
                    from StringIO import StringIO
                    raw = fp.read()
                    processed = raw.decode('ascii', 'ignore').encode(
                            'utf-8', 'ignore')
                    result = etree.parse(
                            StringIO(processed), parser=HTMLParser(encoding=encoding)
                            ).getroot()
                else:
                    result = etree.parse(
                        fp, parser=HTMLParser(encoding=encoding)).getroot()

                result.make_links_absolute(fp.geturl(), handle_failures='ignore')
                return result
          except httplib.IncompleteRead, e:
            error = error or e
            import time
            import random
            print 'passing_INCOMPLETE_READ.retry:' + str(retry)
            time.sleep(5 * 2**min(retry, 8) * random.random())
def findCCs(G, Ep):
    # remove blocked edges from graph G
    E = deepcopy(G)
    edge_rem = [e for e in E.edges() if random.random() < (1-Ep[e])**(E[e[0]][e[1]]['weight'])]
    E.remove_edges_from(edge_rem)

    # initialize CC
    CCs = dict() # each component is reflection of the number of a component to its members
    explored = dict(zip(E.nodes(), [False]*len(E)))
    c = 0
    # perform BFS to discover CC
    for node in E:
        if not explored[node]:
            c += 1
            explored[node] = True
            CCs[c] = [node]
            component = E[node].keys()
            for neighbor in component:
                if not explored[neighbor]:
                    explored[neighbor] = True
                    CCs[c].append(neighbor)
                    component.extend(E[neighbor].keys())
    return CCs
Ejemplo n.º 60
0
def sim_anneal(state):
    old_cost = cost(state)
    T = 0.001
    T_min = 0.00001
    alpha = 0.9
    old_cost_plot = []
    new_cost_plot = []
    while T > T_min:
        i = 1
        while i <= 500:
            print(i)
            new_state = neighbor_onespot(state)
            new_cost = cost(state)
            ap = acceptance_probability(old_cost, new_cost, T)
            print(str(new_cost) +'vs'+ str(old_cost))
            if ap > random.random():
                print('accepted')
                state = new_state
                plot(new_state)
                old_cost = new_cost
            i += 1
            T = T * alpha
    return state, old_cost