Example #1
0
def path_experiment(p_mat, sources=None, sinks=None, verbose=False):
    counts = {}
    for i in range(p_mat.shape[0]):
        counts[i + 1] = 0

    n_paths = 10**4
    paths = generate_random_routes(p_mat,
                                   n_paths,
                                   1,
                                   12,
                                   sources=sources,
                                   sinks=sinks)
    for path in paths:
        for vtx in path:
            counts[vtx + 1] += 1

    total = sum(list(map(lambda x: counts[x], counts)))

    pcts = []
    if total == 0:
        debug()
    for i in range(p_mat.shape[0]):
        pcts.append((i + 1, round(100 * counts[i + 1] / total, 2)))
    if verbose:
        print('Vertex\tPercent of Total Visits')
        for row in pcts:
            print(row)
    else:
        return np.array(pcts)
Example #2
0
def xferToTarget(cell, target, amount, resource):
    target_dir = 'X'
    for dir, child in cell.adjacent.iteritems():
        if child == target:
            target_dir = dir
            break
    if target_dir == 'X':
    # Tried to transfer to a non-adjacent target
        debug()
    else:
        xferResource(cell, target_dir, amount, resource)
Example #3
0
    def choose_move(self):
        # empty board
        sleep(0.4)
        if self.game.state.moves_on_board==0:
            rand1 = randrange(self.game.board_dimension)
            rand2 = randrange(self.game.board_dimension)
            self.game.move(self, (rand1, rand2))
            return

        self.timer = time()
        next_states = list(self.game.state.next_states())
        num_states = len(next_states)
        # scores = [0]*len(next_states)
        
        max_score = (-float('inf'), None) # (score, coords)
        all_max = []

        stop_interval = .03*(self.time_limit/num_states)
        
        # debug()
        for index, state in enumerate(next_states):
            new_state = GomokuState(self.game.state, (self.symbol, state))
            self.node_count+=1
            # if time()<(self.timer+self.time_limit):
            #     s = 'not beyond stop time in choose #{}/{}'.format(index+1, len(next_states))
            #     print s
            #     self.print_debug(s)

            s = 'branch #{}/{}'.format(index+1, len(next_states))
            # self.print_debug(s)

            # scores[index]=self.max_value(new_state, stop_time)
            # if new_state.is_win_state:
            #     self.game.move(self, state)
            #     return

            my_max = self.min_value(new_state, time()+stop_interval, -float('inf'), float('inf'), 1)
            print 'score: {}'.format(my_max)
            all_max.append(my_max)
            if my_max>max_score[0]:
                max_score = (my_max, state)

        all_hugely_negative = True
        for thing in all_max:
            if thing>-10000000000:
                all_hugely_negative = False
        if all_hugely_negative:
            debug()
            # self.game.move(self, (-1,-1))
            # return
        self.game.move(self,max_score[1])
Example #4
0
 def add_daughter(self, cell, direction, init_sugar, init_water, newMemory={}):
     x, y = self.coordinates[cell]
     coordinate = adjacent_coords(x, y, direction)
     program = cell.program
     
     if coordinate not in self.coordinates:
         newCell = Cell(self, program, newMemory, 'GENERIC', init_sugar, init_water)
         self.add_cell(newCell, coordinate)
         for adjcell in self.get_adjacent(newCell).itervalues():
             adjcell.update_world_state()
         return newCell
     else:
         # Attempted to divide into a spot where a cell already existed
         debug()
Example #5
0
def initialize(cell):
    if cell == 'EMPTY':
        print "ERROR: Failed division"
        debug()
    if 'growth_sugar' not in cell.memory:
        cell.memory['growth_sugar'] = cell.sugar_consumption * 20
    if 'growth_water' not in cell.memory:
        cell.memory['growth_water'] = cell.water_consumption * 20
    if 'sugar_children' not in cell.memory:
        cell.memory['sugar_children'] = []
    if 'water_children' not in cell.memory:
        cell.memory['water_children'] = []
    cell.memory['initialized'] = 1
    if 'demand' not in cell.memory:
        cell.memory['demand'] = ((0, 0), (0, 0))
Example #6
0
    def getRegularlySampledPrfByOffset(self, singlePrfObj, colOffset,
                                       rowOffset):
        """Private function of `getSingleRegularlySampledPrf()`
        
        The 13x13 pixel PRFs on at each grid location are sampled at a 9x9 intra-pixel grid, to 
        describe how the PRF changes as the star moves by a fraction of a pixel in row or column.
        To extract out a single PRF, you need to address the 117x117 array in a slightly funny way
        (117 = 13x9),
        
        .. code-block:: python

            img = array[ [colOffset, colOffset+9, colOffset+18, ...], 
                         [rowOffset, rowOffset+9, ...] ]
        
        """
        #TODO Reference documentation about samplesPerPixel

        gridSize = self.gridSize

        #TODO: Bounds checks like this don't belong in an inner loop. Remove them
        #once you're sure they never get triggered.
        if colOffset >= gridSize:
            raise ValueError("Requested column offset (%i) too large" %
                             (colOffset))
        if rowOffset >= gridSize:
            raise ValueError("Requested row offset (%i) too large" %
                             (colOffset))

        assert colOffset < gridSize
        assert rowOffset < gridSize

        fullImage = singlePrfObj.values / float(singlePrfObj.samplesPerPixel)

        #Number of pixels in regularly sampled PRF. Typically 13x13
        nColOut, nRowOut = fullImage.shape
        nColOut /= float(gridSize)
        nRowOut /= float(gridSize)

        iCol = colOffset + (np.arange(nColOut) * gridSize).astype(np.int)
        iRow = rowOffset + (np.arange(nRowOut) * gridSize).astype(np.int)

        if np.max(iCol) == 117:
            debug()

        #Don't understand why this must be a twoliner
        tmp = fullImage[iRow, :]
        return tmp[:, iCol]
 def get_kubernetes_version_info(self):
     """
     fetching the kubernetes version installed on the host
     :return: None
     """
     try:
         res = requests.get(urljoin(base_url, 'version'),
                            headers=def_header)
         debug()
         if res.status_code == 200:
             print(f" Kubernetes version installed is {res.text}")
         else:
             print("Kubernetes Version Not available")
     except ApiException as e:
         print(f"Error : {e}")
     except Exception as e:
         print(f"Error: {e}")
Example #8
0
def optimize_model(memory, BATCH_SIZE, policy_net, target_net, optimizer, GAMMA, device = 'cpu'):
    if len(memory) < BATCH_SIZE:
        return
    transitions = memory.sample(BATCH_SIZE)
    # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for
    # detailed explanation). This converts batch-array of Transitions
    # to Transition of batch-arrays.
    batch = Transition(*zip(*transitions))

    # Compute a mask of non-final states and concatenate the batch elements
    # (a final state would've been the one after which simulation ended)
    non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
                                          batch.next_state)), device=device, dtype=torch.bool)
    non_final_next_states = torch.cat([s for s in batch.next_state
                                                if s is not None])
    state_batch = torch.cat(batch.state)
    action_batch = torch.cat(batch.action)
    reward_batch = torch.cat(batch.reward)

    # Compute Q(s_t, a) - the model computes Q(s_t), then we select the
    # columns of actions taken. These are the actions which would've been taken
    # for each batch state according to policy_net
    state_action_values = policy_net(state_batch).gather(1, action_batch)

    # Compute V(s_{t+1}) for all next states.
    # Expected values of actions for non_final_next_states are computed based
    # on the "older" target_net; selecting their best reward with max(1)[0].
    # This is merged based on the mask, such that we'll have either the expected
    # state value or 0 in case the state was final.
    next_state_values = torch.zeros(BATCH_SIZE, device=device)
    next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()
    # Compute the expected Q values
    expected_state_action_values = (next_state_values * GAMMA) + reward_batch

    # Compute Huber loss
    loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))
    debug()

    # Optimize the model
    optimizer.zero_grad()
    loss.backward()
    for param in policy_net.parameters():
        param.grad.data.clamp_(-1, 1)
    optimizer.step()
Example #9
0
 def divide(self, direction, sugar_transfer, water_transfer, newMemory={}):
     """Spawn a daughter cell in the given direction. 
     
     New cell starts with specified sugar and water, and memory initialized to newMemory. Note division has additional costs (specified in cell_types.py as COSTS['GENERIC']). 
     If the cell doesn't have enough water or sugar for the division, then division will fail but resources will not be lost.
     """
     sugar_transfer = max(0, sugar_transfer)
     water_transfer = max(0, water_transfer)
     if direction not in self.adjacent:
         sugar_cost, water_cost = COSTS['GENERIC']
         if self.sugar >= sugar_transfer + sugar_cost and \
                 self.water >= water_transfer + water_cost:
               self.sugar -= sugar_transfer + sugar_cost
               self.water -= water_transfer + water_cost
               return self.world.add_daughter(self, direction, sugar_transfer, water_transfer, newMemory)
               
     else:  
         print "Warning: Bad division!!!"
         debug()
Example #10
0
def dna_grass(cell):
    """Entry point for the program. Automates cell behavior."""
    if getMem(cell, 'initialized') == 0:
        initialize(cell)
    role = getMem(cell, 'role')
    if role == 0:
        print "Error: Cell has no role!"
        debug()
    elif role == 'stem':
        automate_stem(cell)
    elif role == 'root':
        automate_root(cell)
    elif role == 'leaf':
        automate_leaf(cell)
    elif role == 'store':
        automate_store(cell)
    elif role == 'origin':
        automate_origin(cell)
    elif role == 'bud':
        automate_bud(cell)
    manage_resource_flow(cell)
Example #11
0
def add_station(p, vtx_idx, alpha=1.25):
    for i in range(p.shape[0]):
        edge_prob = p[i][vtx_idx]
        if edge_prob < 10e-5:
            continue
        beta = (1 - edge_prob * alpha) / (1 - edge_prob)
        p[i] = p[i] * beta
        p[i, vtx_idx] = p[i, vtx_idx] / beta * alpha

    if np.max(p) > 1:
        print('Error: chosen alpha produces invalid matrix')
        raise ValueError
    for i in range(p.shape[0]):
        try:
            assert (np.sum(p[i]) - 1.0) < 10e-4
        except:
            print('Invalid row', i)
            print(alpha, beta)
            debug()

    return p
Example #12
0
def generate_random_routes(p,
                           num_routes,
                           route_min_len,
                           route_max_len,
                           sources=None,
                           sinks=None):
    num_steps = np.random.uniform(route_min_len, route_max_len, num_routes)
    start_vtxs = []
    for i in range(num_routes):
        start_vtxs.append(sources[np.floor(np.random.uniform(
            0, len(sources))).astype(int)])
    paths = []
    for i in tqdm(range(num_routes), desc='computing paths', ncols=80):
        # debug()
        if start_vtxs[i] not in sources:
            continue
        paths.append(random_route(start_vtxs[i], int(num_steps[i]), p))
    paths1 = list(
        filter(lambda path: path[0] in sources and path[-1] in sinks, paths))
    if not paths1:
        debug()
    return paths
Example #13
0
def distribute(cell, amount, resource, pattern):
    """Automates distribution of resource (given amount) to adjacent cells according to pattern
    
    cell: A cell
    amount: A float
    resource: 'sugar' or 'water'
    pattern: 'high' distributes according to high demand profile for given resource, 'low' according to the low demand profile, 'even' gives equally to each adjacent cell
    """

    report(cell, 'Distributing {0} {1} in pattern {2}'.format(amount, resource, pattern))
    
    index1 = int(resource == 'water')
    if pattern in ('high', 'low'):
        index2 = int(pattern == 'low')
        demand = get_children_demand(cell)[index1][index2]
        if demand == 0:
            distribution_factor = 1
        else:
            distribution_factor = float(amount) / demand
        # The proportion of amount demanded to give to each adjacent cell
        
        if resource == 'sugar' and getMem(cell, 'sugar_children') != 0:
            for (sugar_child, dir) in getMem(cell, 'sugar_children'):
                amt_to_send = getMem(sugar_child, 'demand')[index1][index2] * distribution_factor
                xferResource(cell, dir, amt_to_send, resource)
        elif resource == 'water' and getMem(cell, 'water_children') != 0:
                for (water_child, dir) in getMem(cell, 'water_children'):
                    amt_to_send = getMem(water_child, 'demand')[index1][index2] * distribution_factor
                    xferResource(cell, dir, amt_to_send, resource)
    else:
        if pattern != 'even':
            debug()
        num_adjacent_cells = 9 - cell.free_spaces
        # Used 9 as starting number so that the cell will always keep a portion for itself!
        amt_to_send = float(amount) / num_adjacent_cells
        
        for dir, adjcell in cell.adjacent.iteritems():
            if adjcell != 'EMPTY':
                xferResource(cell, dir, amt_to_send, resource)
Example #14
0
    def forward(self, x):
        crop_h, crop_w = int(x.size()[-2]), int(x.size()[-1])
        x = self.stages[0](x)

        side = []
        side_out = []
        for i in range(1, len(self.stages)):
            x = self.stages[i](x)
            side_temp = self.side_prep[i - 1](x)
            side.append(
                center_crop(self.upscale[i - 1](side_temp), crop_h, crop_w))
            side_out.append(
                center_crop(
                    self.upscale_[i - 1](self.score_dsn[i - 1](side_temp)),
                    crop_h, crop_w))

        out = torch.cat(side[:], dim=1)
        out = self.fuse(out)
        side_out.append(out)
        debug()
        print(side_out)
        return side_out
Example #15
0
def automate_bud(cell):
    if getMem(cell.adjacent['S'], 'role') == 'stem':
        # Bud to the NW, NE, and revert to stem with budcounter
        if   isEmpty(cell, 'NW'): dir = 'NW'
        elif isEmpty(cell, 'NE'): dir = 'NE'
        elif isEmpty(cell, 'N' ): dir = 'N'
        else: 
            dir = 'X'
            debug()
        if dir in ('NW', 'NE'):
            if cell.sugar > 40 and cell.water > 40:
                new_mem = {'role': 'bud', 'growth_dir': dir, 'bud_growth_limit': 5}
                new_cell = cell.divide(dir, 10, 10, new_mem)
                initialize(new_cell)
                add_sugar_child(new_cell, cell)
                add_water_child(cell, new_cell)
            else:
                cell.memory['growth_sugar'] = 40
                cell.memory['growth_water'] = 40
        if dir == 'N':
            cell.memory['role'] = 'stem'
            cell.memory['growth_to_bud'] = 3
    else:
        growth_limit = getMem(cell, 'bud_growth_limit')
        growth_dir = getMem(cell, 'growth_dir')
        leafdir = 'X'
        for dir in outsideDirs(growth_dir):
            if isEmpty(cell, dir):
                leafdir = dir
        if leafdir != 'X':
            grow_leaf(cell, leafdir)
        elif isEmpty(cell, growth_dir) and growth_limit > 0 and can_grow(cell, 40, 40):
            new_mem = {'role': 'bud', 'growth_dir': growth_dir, 'bud_growth_limit': growth_limit - 1, 'sugar_children': [cell]}
            new_bud = cell.divide(growth_dir, 10, 10, new_mem)
            initialize(new_bud)
            add_water_child(cell, new_bud)
Example #16
0
import cPickle as pk
from plot import plotLines
import numpy as np
import theano
from pylearn2.space import Conv2DSpace, VectorSpace
from pdb import set_trace as debug

mon = np.array(pk.load(open('monitor.pkle')))
axis = [x for x in xrange(len(mon))]
plotLines([
    [axis, mon[:, 1]],
    [axis, mon[:, 0]],
], title='Training Graph')

debug()
net = pk.load(open('best.pkle'))
debug()
vec_space = VectorSpace(28**2)
# test_X = vec_space.np_format_as(test_X, net.get_input_space())
# train_X = vec_space.np_format_as(train_X, net.get_input_space())
i = 0
X = net.get_input_space().make_theano_batch()
Y = net.fprop(X)
predict = theano.function([X], Y)
debug()
Example #17
0
	def get_sets(self):
		"""
		Get a training and a test set for the ESN learning.
		These are picked from all the samples we got in 'get_samples'
		"""
		
		
		if not self.testing_set_speakers:
			
			# Chose test and training set at random!
			
			# Refresh initialisation
			self.training_set = []
			self.test_set = []
		
			# We created representative samples of /a/, /e/ etc. as well as null samples in ambient_speech.py.
			# Now, we'll see how many null, or /a/, or /e/ sounds we want.
			n_train = self.n_samples['train'] * self.n_speakers
			# (remember: self.n_samples[...] was defined as 'per speaker'.
		
			# Same for test samples
			n_test = self.n_samples['test'] * self.n_speakers
		
		
			for vowel in self.vowels_and_null:
			
				# Get representative part of training/test set.
				random.shuffle(self.labeled_samples[vowel])
			
				# If many vowels were moved out of a folder, our list of labeled samples might
				# be quite short - shorter even than training_samples + test_samples!
				for sample in range(n_train):
					try:
						self.training_set.append(self.labeled_samples[vowel][sample])
					except IndexError:
						raise RuntimeError('Too few '+vowel+' samples!')
						#self.training_set.append(random.choice(self.labeled_samples[vowel]))
					
			
				for sample in range(n_train,n_train+n_test):
					try:
						self.test_set.append(self.labeled_samples[vowel][sample])
					except IndexError:
						raise RuntimeError('Too few '+vowel+' samples!')
						#self.test_set.append(random.choice(self.labeled_samples[vowel]))
		
		
		
		
		
		elif type(self.testing_set_speakers) == list and not self.training_set and not self.test_set:
			# This is the case of excluding speakers from the training set and using them for the test set.
			
			# Refresh initialisation
			self.training_set = []
			self.test_set = []
			
			for vowel in self.vowels_and_null:
			
				for sample in range(len(self.labeled_samples[vowel])):
					
					if self.labeled_samples[vowel+'_speaker_label'][sample] in self.testing_set_speakers:
						self.test_set.append(self.labeled_samples[vowel][sample])
					else:
						self.training_set.append(self.labeled_samples[vowel][sample])		
					
			
			# Change this from a list to a string (this is a flag for the next time round.)
			self.testing_set_speakers = "already set"
		
			
			
		elif self.testing_set_speakers == "already set":
		
			# in this case, we only need to shuffle them..
			pass
			
		else:
		
			# Something has gone wrong.
			print self.testing_set_speakers
			debug()
			print "Length of training set "+str(len(self.training_set))
			print "Length of test set "+str(len(self.test_set))
			raise RuntimeError("Illegal use of get_sets()")
			
		
		
		
		# Shuffle representative with non-represantive training elements.
		random.shuffle(self.training_set)
		random.shuffle(self.test_set)
		
		
		def check_for_rotten_eggs(x):#
			"""
			Check for 'rotten eggs' in set
			"""
			i_rotten=0
			i = 0
			while i in range(len(x)):
				if x[i][0] == []:
					i_rotten+=1
					x.pop(i)
				else:
					i+=1
			print '('+str(i_rotten)+' rotten samples found in set)'
		
		check_for_rotten_eggs(self.training_set)
		check_for_rotten_eggs(self.test_set)
Example #18
0
	def simulate_ESN(self):
		""" main function simulating both leaky and non-leaky ESNs
			globals:
			- self.reservoir_sizes: list of reservoir sizes
			- self.n_vowels: number of vowels used
			- self.do_plot_hearing: boolean defining if plots are created
			- self.separate: boolean defining if infant samples are used as test data
			- self.n_channels: number of used channels
		"""
		# Compare leaky networks with non-leaky networks?
		# ------------------------------------------------------------------------
	
		for j in xrange(len(self.reservoir_sizes)):     # loop over network sizes
			self.current_reservoir = j
			for train in xrange(self.trains_per_worker):
				
				# Leaky (done anyway)
				# ...........................................................
				
				print('worker', self.rank+1, 'of', self.n_workers, 'simulating leaky network of size', self.reservoir_sizes[self.current_reservoir], 
																							'('+str(train+1)+'/'+str(self.trains_per_worker)+')')
																							
				# call learn function
				error_leaky, c_matrix_leaky = self.learn(output_dim=self.reservoir_sizes[self.current_reservoir], leaky=True)

				if (train==0) and self.do_plot_hearing and (self.rank == 0):
					self.plot_prototypes(N=self.reservoir_sizes[self.current_reservoir])
				# ...........................................................
				
				
				if self.do_compare_leaky:
					# Non-leaky (optional)
					# ...........................................................
					
					print('worker', self.rank+1, 'of', self.n_workers, 'simulating non-leaky network of size', self.reservoir_sizes[self.current_reservoir], 
																							'('+str(train+1)+'/'+str(self.trains_per_worker)+')')
					
					# call learn function to execute one simulation run
					error_nonleaky, c_matrix_nonleaky = self.learn(output_dim=self.reservoir_sizes[self.current_reservoir], leaky=False)
																			
					if (train==0) and self.do_plot_hearing and (self.rank == 0):
						self.plot_prototypes(N=self.reservoir_sizes[self.current_reservoir])
					# ...........................................................
					
				
				# Collect current error rates and append current confusion matrix.
				# ----------------------------------------------------------------
					self.errors['non-leaky'][train][self.current_reservoir] = error_nonleaky
					self.c_matrices['non-leaky'][self.current_reservoir] += c_matrix_nonleaky
					
				self.errors['leaky'][train][self.current_reservoir] = error_leaky
				self.c_matrices['leaky'][self.current_reservoir] += c_matrix_leaky
				# ----------------------------------------------------------------
				
				if (c_matrix_leaky>1).any():
					debug()
				
				# Print current cmatrices?
				if self.verbose and self.do_compare_leaky:
					print('c_matrix_leaky:', c_matrix_leaky)
					print('c_matrix_nonleaky:', c_matrix_nonleaky)
					
				elif self.verbose:
					print('c_matrix_leaky:', c_matrix_leaky)
					
				
						

		# Divide by number of trains per worker
		if self.do_compare_leaky:
			self.c_matrices['leaky'] /= self.trains_per_worker
			self.c_matrices['non-leaky'] /= self.trains_per_worker
		else:
			self.c_matrices['leaky'] /= self.trains_per_worker
		
		if (self.c_matrices['leaky']>1).any():
			debug()
		
		# Print cmatrices?
		if self.do_compare_leaky and self.verbose:
			print('total_c_matrices_leaky:', self.c_matrices['leaky'])
			print('total_c_matrices_nonleaky:', self.c_matrices['non-leaky'])
		elif self.verbose:
			print('total_c_matrices_leaky:', self.c_matrices['leaky'])
Example #19
0
	def main(self):	
		"""
		hear.main() does the auditory learning with the BRIAN hears and the echo state
		network (ESN).
		Initialize..

		Murakami:
		# n_training used to be 183
		# n_samples used to be 204
		"""
		
		# Setting up correct paths and folders
		self.setup_folders()
			
	
		# Make reservoir states inspectable for plotting..
		self.make_Oger_inspectable()
		
		
		# Only partially train the ESN.  analysis. See get_params.
		if self.generalisation_age:
			# Basically run through most of what we've done already, but for different sample data.
			# Train only on speakers that are over the age of firstspeaker_male.
			# --------------------------------------------------------------------------------------------------------------
			
			# Get the first speaker to include in data samples.
			# -------------------------------------------------------------------------
			try:
				firstspeaker_male = self.age_m.index(self.generalisation_age)
			except ValueError:
				print "Error! No generalisation age!"
				debug()
			try:
				firstspeaker_female = self.age_f.index(self.generalisation_age)
			except ValueError:
				print "Error! No generalisation age!"
				debug()
			firstspeaker = min(firstspeaker_female,firstspeaker_male)
			# -------------------------------------------------------------------------
			
			# Execute this 'setup' only by master.
			if self.rank == 0: 
				# A list of speakers that are excluded in training, but used for testing.
				self.testing_set_speakers = [speaker for speaker in self.speakers if speaker < firstspeaker]
				
		else:
			# The normal case. Train using data from all speakers. Training set and test set are randomly drawn.
			self.testing_set_speakers = False
		
		
		# Get all the samples produced in ambient speech..
		self.get_samples()
	
	
		# Simulate ESN (basically the main function, which then in itself calls the interesting function 'learn')..
		self.simulate_ESN()
					
		
		if self.rank == 0:
			self.master_collect_and_postprocess(choose=False) # SEE BELOW. Set choose True if you want to chose one of the produced ESNs for learning (essentially rename it).
		
		
		# Save this class instance
		# ---------------------------------------------------
		f = open('data/classes/hear_instance.pickle', 'w+')
		f.truncate()
		pickle.dump(self,f)
		f.close()
Example #20
0
 def parse_download_url(self, response):
     hxs = HtmlXPathSelector(response)
     debug()
     yum = hxs.select("//img")
Example #21
0
def _get_kaggle_passwd(username):
    debug()
Example #22
0
world.draw_messageboard(screen, MESSAGE_RECT)
world.updateDisplay()
pygame.display.flip()
autoRunning = False
tick_amount = 500
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                world.update_cells()
                world.draw_messageboard(screen, MESSAGE_RECT)
                pygame.display.flip()
            if event.key == pygame.K_x:
                debug()
            if event.key == pygame.K_q:
                running = False
            if event.key == pygame.K_g:
                if autoRunning:
                    tick_amount = 500
                else:
                    tick_amount = 6
                autoRunning = not(autoRunning)
        elif (  event.type == pygame.MOUSEBUTTONDOWN and
                pygame.mouse.get_pressed()[0]):
            world.change_selected_cell(pygame.mouse.get_pos())
            world.draw_messageboard(screen, MESSAGE_RECT)
            pygame.display.flip()
            
    if autoRunning:
Example #23
0
    def evaluate_score(self):

        if self.score != None:
            return self.score
        else:
            self.score = 0

        if self.new_move[0]=='X':
            eval_dict = self.x_dict
            other_dict = self.o_dict
            inst_dict = self.o_instant
        elif self.new_move[0]=='O':
            eval_dict = self.o_dict
            other_dict = self.x_dict
            inst_dict = self.x_instant


        # check all horizontal strings
        for column in range(len(self.board)-self.win_length):
            for row in range(len(self.board)):
                s = ''
                for i in range(self.win_length+1):
                    s+=self.board[row][column+i]
                self.score+=0.1*eval_dict[s]
                self.score-=other_dict[s]
                if inst_dict[s]:
                    self.instant_lose.append(s)
                    self.score += -10000000000
                    # return

        # check all vertical strings
        for row in range(len(self.board)-self.win_length):
            for column in range(len(self.board)):
                s = ''
                for i in range(self.win_length+1):
                    s+=self.board[row+i][column]
                self.score+=0.1*eval_dict[s]
                self.score-=other_dict[s]
                if inst_dict[s]:
                    self.instant_lose.append(s)
                    self.score += -10000000000
                    # return

        # check all diagonal strings len(8-5)
        for column in range(self.board_dimension-self.win_length):
            for up_row in range(self.board_dimension-self.win_length):
                low_row = up_row+5

                south_east = ''
                north_east = ''
                for i in range(self.win_length+1):
                    south_east+=self.board[up_row+i][column+i]
                    try:
                        north_east+=self.board[low_row-i][column+i]
                    except:
                        debug()
                # if 'XXXX' in north_east:
                    # debug()
                self.score+=0.1*eval_dict[south_east]
                self.score-=other_dict[south_east]
                self.score+=0.1*eval_dict[north_east]
                self.score-=other_dict[north_east]
                if inst_dict[south_east]:
                    self.instant_lose.append(south_east)
                    self.score += -10000000000
                    # return
                if inst_dict[north_east]:
                    self.instant_lose.append(north_east)
                    self.score += -10000000000

        # check four remaining
        # top right corner
        r = 0
        c = self.board_dimension-self.win_length
        s='.'
        for i in range(self.win_length):
            s+=self.board[r+i][c+i]
        if not self.new_move[0] in s:
            self.score+=0.1*eval_dict[s]
            self.score-=other_dict[s]
            if inst_dict[s]:
                self.instant_lose.append(s)
                self.score += -10000000000
                # return

        # top left corner
        r = self.win_length-1
        c = 0
        s='.'
        for i in range(self.win_length):
            s+=self.board[r-i][c+i]
        if not self.new_move[0] in s:
            self.score+=0.1*eval_dict[s]
            self.score-=other_dict[s]
            if inst_dict[s]:
                self.instant_lose.append(s)
                self.score += -10000000000
                # return

        # bottom left corner
        r = self.board_dimension-self.win_length
        c = 0
        s='.'
        for i in range(self.win_length):
            s+=self.board[r+i][c+i]
        if not self.new_move[0] in s:
            self.score+=0.1*eval_dict[s]
            self.score-=other_dict[s]
            if inst_dict[s]:
                self.instant_lose.append(s)
                self.score += -10000000000
                # return

        # bottom right corner
        r = self.board_dimension-1
        c = self.board_dimension-self.win_length
        s='.'
        for i in range(self.win_length):
            s+=self.board[r-i][c+i]
        if not self.new_move[0] in s:
            self.score+=0.1*eval_dict[s]
            self.score-=other_dict[s]
            if inst_dict[s]:
                self.instant_lose.append(s)