def evaluateStatistically(self, board: np.array) -> int: """ Calculates the Evaluation at the depth limit :param board: current state of the board :return: evaluation value """ nonZeroPositions = np.array(list(zip(*board.nonzero()))) myEvaluationScore = 0 opponentEvaluationScore = 0 for position in nonZeroPositions: positionY, positionX = position[0], position[1] # If the current position has a piece of this Agent if board[positionY][positionX] == self._color: # Get the weight from hard-coded matrix myEvaluationScore += self.trainedWeights[positionY][positionX] else: opponentEvaluationScore += self.trainedWeights[positionY][ positionX] # The differences between this Agent and its opponent. return myEvaluationScore - opponentEvaluationScore
def Min_value(self,board:np.array,validactions:np.array,depth:int,level:int,alpha:float,beta:float,gain:bool): if depth == 0: countA: int = 0 countB: int = 0 evalBoard = np.array(list(zip(*board.nonzero()))) for row in evalBoard: if board[row[0]][row[1]] == self._color: countA += 1 else: countB += 1 return countA - countB MinBeta: float = beta Minevaluation = float('inf') player: int = self.getOpponent(self._color) best_state: np.array = None for a in validactions: newstate, newaction = self.createState(board,a,player) newstep = self.Max_value(newstate,newaction,depth-1,level + 1, alpha,MinBeta,not gain) if Minevaluation > newstep: Minevaluation = newstep # print(depth) if level == 0 : best_state = a MinBeta = min(MinBeta,Minevaluation) if MinBeta <= alpha: break if level != 0: return Minevaluation else: return Minevaluation,best_state
def Max_value(self, board: np.array, validactions: np.array, depth: int, level: int, alpha: float, beta: float, gain: bool): if depth == 0: countA: int = 0 countB: int = 0 evalBoard = np.array(list(zip(*board.nonzero()))) for row in evalBoard: if board[row[0]][row[1]] == self._color: countA += 1 else: countB += 1 return countA - countB best_state: np.array = None MaxAlpha: int = alpha Maxevaluation = -float('inf') player: int = self._color for a in validactions: newstate, newaction = self.createState(board, a, player) newstep = self.Min_value(newstate, newaction, depth - 1, level + 1, MaxAlpha, beta, not gain) if Maxevaluation < newstep: Maxevaluation = newstep if level == 0: best_state = a MaxAlpha = max(MaxAlpha, Maxevaluation) if beta <= MaxAlpha: break if level != 0: return Maxevaluation else: return Maxevaluation, best_state
def existing_line_search(binary_warped: np.array, left_fit: np.array, right_fit: np.array, margin: int=100): """ Assume you now have a new warped binary image from the next frame of video (also called "binary_warped") This function calculates the next lanes near the the previously found ones using a margin. :param binary_warped: the binary image containing the lines :param left_fit: left line fit :param right_fit: right line fit :param margin: the margin to search in near the actual line. :return: line fittings (left, right), line x pixels (left, right), line y pixels (for both the same), result picture """ nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = margin left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] + margin))) right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] + margin))) # Again, extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Create an image to draw on and an image to show the selection window out_img = np.dstack((binary_warped, binary_warped, binary_warped)) * 255 window_img = np.zeros_like(out_img) # Color in left and right line pixels out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0] out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255] ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) left_fitx = left_fit[0] * ploty ** 2 + left_fit[1] * ploty + left_fit[2] right_fitx = right_fit[0] * ploty ** 2 + right_fit[1] * ploty + right_fit[2] # Generate a polygon to illustrate the search window area # And recast the x and y points into usable format for cv2.fillPoly() left_line_window1 = np.array([np.transpose(np.vstack([left_fitx - margin, ploty]))]) left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx + margin, ploty])))]) left_line_pts = np.hstack((left_line_window1, left_line_window2)) right_line_window1 = np.array([np.transpose(np.vstack([right_fitx - margin, ploty]))]) right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx + margin, ploty])))]) right_line_pts = np.hstack((right_line_window1, right_line_window2)) # Draw the lane onto the warped blank image cv2.fillPoly(window_img, np.int_([left_line_pts]), (0, 255, 0)) cv2.fillPoly(window_img, np.int_([right_line_pts]), (0, 255, 0)) result = cv2.addWeighted(out_img, 1, window_img, 0.1, 0) return [left_fit, right_fit, left_fitx, right_fitx, ploty, result]
def get_most_populous_class(segment_mask: np.array, label_map: np.ndarray) -> int: """ Args: - segment_mask - label_map Returns: - class_mode_idx: integer representing most populous class index """ class_indices = label_map[segment_mask.nonzero()] class_mode_idx = get_np_mode(class_indices) return class_mode_idx
def evaluate(self, board: np.array): countSelf: int = 0 countOpponent: int = 0 evaluationBoard = np.array(list(zip(*board.nonzero()))) for i in evaluationBoard: if (board[i[0]][i[1]] == self._color): countSelf += 1 else: countOpponent += 1 return countSelf - countOpponent
def evaluateStatistically(self, board: np.array) -> int: countA: int = 0 countB: int = 0 evalBoard = np.array(list(zip(*board.nonzero()))) # print("Print Board: " + str(evalBoard)) for row in evalBoard: if board[row[0]][row[1]] == self._color: countA += 1 else: countB += 1 return countA - countB
def maximum_value(self, board: np.array, valid_actions: np.array, depth, level, alpha, beta, gain): if depth == 0: # do evaluation count_B = 0 count_W = 0 copy_weight = copy.deepcopy(self.evaluate) # pair two values in i index of array together to_evaluate = np.array(list(zip(*board.nonzero()))) for r in to_evaluate: x, y = r[0], r[1] if board[r[0]][r[1]] != self._color: count_W += (copy_weight[r[0]][r[1]]) else: count_B += (copy_weight[r[0]][r[1]]) return count_B - count_W best_move_board = None max_alpha_value = alpha player = self._color MAX = -100000 MIN = 100000 for take_turn in valid_actions: #print("try" , take_turn) r, c = self.create_board(board, take_turn, player) # r,c = transition(board, take_turn, player) new_turn = self.minimum_value(r, c, depth - 1, level + 1, max_alpha_value, beta, not gain) if MAX < new_turn: MAX = new_turn if level == 0: best_move_board = take_turn max_alpha_value = max(max_alpha_value, MAX) if beta <= max_alpha_value: break if level != 0: return MAX else: return MAX, best_move_board
def Evalustatis(self, board: np.array) -> int: MyScore = 0 OpponentScore = 0 total = 0 evalBoard = np.array(list(zip(*board.nonzero()))) for position in evalBoard: Y, X = position[0], position[1] if board[Y][X] == self._color: MyScore += (board[Y][X]) else: OpponentScore += (board[Y][X]) # print(" Eval Score: ", total) total = MyScore - OpponentScore return (MyScore - OpponentScore)
def convert_matrix_to_source_target( my_matrix: np.array) -> Tuple[np.array, np.array]: """ Converts a matrix into two arrays that give the indices of the non zero elements. (Source[i], Target[i]) gives the position of a non zero element. :param my_matrix: A matrix of zero or non zero elements. :type my_matrix: np.array :return: Two arrays of indices that indicate the non zero indices of the matrix :rtype: Tuple[np.array, np.array] """ # Return the indices of the elements that are non-zero. sources, targets = my_matrix.nonzero() sources = np.array(sources) targets = np.array(targets) return sources, targets
def evaluateStatistically(self, board: np.array) -> int: MyScore = 0 OpponentScore = 0 total = 0 new_weight = copy.deepcopy(self.weight_condition) evalBoard = np.array(list(zip(*board.nonzero()))) # print("Print Board: " + str(evalBoard)) for position in evalBoard: Y, X = position[0], position[1] if board[Y][X] == self._color: MyScore += (new_weight[Y][X]) else: OpponentScore += (new_weight[Y][X]) # print(" Eval Score: ", total) total = MyScore - OpponentScore return (MyScore - OpponentScore)
def _heapify_priorities(update_priority: np.array) -> List: """Build priority queue of (page, offset) ordered by update priority.""" # Use numpy vectorization to efficiently compute the list of # (priority, random nonce, page, offset) tuples to be heapified. pages, offsets = update_priority.nonzero() priorities = [ tuple(data) for data in np.stack(( -update_priority[pages, offsets], # Don't use deterministic order for page, offset np.random.randint(0, 2**8, size=pages.shape[0]), pages, offsets)).T.tolist() ] heapq.heapify(priorities) return priorities
def evaluateStatistically(self, board: np.array) -> int: """ Stupidly counts all pieces on the board :param board: a state of the board :return: the difference between both players in terms of piece counts """ countA: int = 0 countB: int = 0 # Eliminates all ZEROES in the board and return NON-ZERO as a position (Row, Col) nonZeroPositions = np.array(list(zip(*board.nonzero()))) # print("Print Board: " + str(nonZeroPositions)) for position in nonZeroPositions: if board[position[0]][position[1]] == self._color: countA += 1 else: countB += 1 return countA - countB
def evaluate(self, board: np.array): countX: int = 0 countY: int = 0 eval_board = np.array(list(zip(*board.nonzero()))) check = 0 # this while loop use for check that if it runs all of the value in eval_board # it will break to count the score while check is 0: for i in eval_board: # the value i is the matrix 2 x2 or 2 dimension # it means that it contains of position x and y # so we set to positionY and positionX for easy to understand positionY = i[0] positionX = i[1] if board[positionY][positionX] == self._color: countX += 1 else: countY += 1 check = check + 1 FinalScore = countX - countY # return the finalscore return FinalScore
def one_element_row_locs(A: np.array) -> set: ''' example input: [0 0 0 0 1] 1 [4] [0 0 1 1 0] 1 [2 3] [1 0 1 0 0] 0 [0 2] [1 1 0 0 0] 1 [0 1] defaultdict(<class 'list'>, {0: [4], 1: [2, 3], 2: [0, 2], 3: [0, 1]}) return {(0,4)} ''' nz = defaultdict(list) for rnz, cnz in zip(*A.nonzero()): nz[rnz].append(cnz) # reduce rcs so that columns are unique. Corresponding rows dont matter # {(0, 1), (3, 0), (1, 1), (4, 0)} => { 1:1, 0:4 } crs = {clist[0]:r for r, clist in nz.items() if len(clist) == 1} return {(r, c) for c, r in crs.items()}
def unique_neurons2_simp(totalmasks:sparse.csr_matrix, neuronstate:np.array, COMs:np.array, \ areas:np.array, probmapID:np.array, minArea=0, thresh_COM0=0, useMP=True): '''Initally merge neurons with close COM (COM distance smaller than "thresh_COM0") by adding them together. The outputs are the merged masks "uniques" and the indices of frames when they are active "times". Inputs: totalmasks (sparse.csr_matrix of float32, shape = (n,Lx*Ly)): the neuron masks to be merged. neuronstate (1D numpy.array of bool, shape = (n,)): Indicators of whether a neuron is obtained without watershed. COMs (2D numpy.array of float, shape = (n,2)): COMs of the neurons. areas (1D numpy.array of uint32, shape = (n,)): Areas of the neurons. probmapID (1D numpy.array of uint32, shape = (n,): indices of frames when the neuron is active. minArea (float or int, default to 0): Minimum neuron area. thresh_COM0 (float or int, default to 0): Threshold of COM distance. Masks have COM distance smaller than "thresh_COM0" are considered the same neuron and will be merged. useMP (bool, defaut to True): indicator of whether numba is used to speed up. Outputs: uniques (sparse.csr_matrix): the neuron masks after merging. times (list of 1D numpy.array): indices of frames when the neuron is active. ''' if minArea > 0: # screen out neurons with very small area area_select = (areas > minArea) totalmasks = totalmasks[area_select] neuronstate = neuronstate[area_select] COMs = COMs[area_select] areas = areas[area_select] probmapID = probmapID[area_select] maxN = neuronstate.size # Number of current masks if maxN > 0: # False: # # Only masks obtained without watershed can be neurons merged to coreneurons = neuronstate.nonzero()[0] rows, cols = [], [] cnt = 0 keeplist = np.zeros(maxN, dtype='bool') unusedneurons = np.ones(maxN, dtype='bool') for c in coreneurons: if neuronstate[c]: if useMP: r = np.zeros(COMs.shape[0]) fastCOMdistance(COMs, COMs[c], r) else: r = pairwise_distances(COMs, COMs[c:c + 1]).squeeze() # Find neighbors of a mask: the masks whose COM distance is smaller than "thresh_COM", including itself neighbors = np.logical_and(r <= thresh_COM0, unusedneurons).nonzero()[0] # those neighbors have been merged, so they will not be searched again neuronstate[neighbors] = False unusedneurons[neighbors] = False cols.append(neighbors) rows.append(c * np.ones(neighbors.size)) # This neuron will be kept, and its neighbors will be merged to it. keeplist[c] = True cnt += 1 ind_row = np.hstack(rows).astype('int') # indices of neurons merged to ind_col = np.hstack(cols).astype( 'int') # indices of neurons to be merged val = np.ones(ind_row.size) comb = sparse.csr_matrix((val, (ind_row, ind_col)), (maxN, maxN)) comb = comb[keeplist] uniques = comb.dot( totalmasks ) # Add merged neurons using sparse matrix multiplication times = [ probmapID[comb[ii].toarray().astype('bool').squeeze()] for ii in range(cnt) ] else: uniques = sparse.csc_matrix((0, totalmasks.shape[1]), dtype='bool') times = [] return uniques, times
def get_most_populous_class(segment_mask: np.array, label_map: np.ndarray): """ """ class_indices = label_map[segment_mask.nonzero()] class_mode_idx = get_np_mode(class_indices) return class_mode_idx
def evaluateStatistically(self, board: np.array) -> int: """ Calculates the Evaluation at the depth limit :param board: current state of the board :return: evaluation value """ nonZeroPositions = np.array(list(zip(*board.nonzero()))) myEvaluationScore = 0 opponentEvaluationScore = 0 stage = 0 countEdge = 0 myCorner = 0 yourCorner = 0 for i in range(0, board.shape[0]): for j in range(0, board.shape[1]): if board[i, j] == self._color or board[i, j] == -self._color: if i == 0 or j == 0 or i == 7 or j == 7: countEdge += 1 if board[i, j] == self._color: if i == 0 and j == 0: myCorner += 1 elif i == 0 and j == 7: myCorner += 1 elif i == 7 and j == 0: myCorner += 1 elif i == 7 and j == 7: myCorner += 1 if board[i, j] == -self._color: if i == 0 and j == 0: yourCorner += 1 elif i == 0 and j == 7: yourCorner += 1 elif i == 7 and j == 0: yourCorner += 1 elif i == 7 and j == 7: yourCorner += 1 if countEdge > 0: stage = 1 if myCorner >= 2 or yourCorner >= 2: stage = 2 if stage == 0: for position in nonZeroPositions: positionY, positionX = position[0], position[1] # If the current position has a piece of this Agent if board[positionY][positionX] == self._color: # Get the weight from hard-coded matrix myEvaluationScore += self.opening[positionY][positionX] else: opponentEvaluationScore += self.opening[positionY][positionX] elif stage == 1: for position in nonZeroPositions: positionY, positionX = position[0], position[1] # If the current position has a piece of this Agent if board[positionY][positionX] == self._color: # Get the weight from hard-coded matrix myEvaluationScore += self.middle[positionY][positionX] else: opponentEvaluationScore += self.middle[positionY][positionX] elif stage == 2: for position in nonZeroPositions: positionY, positionX = position[0], position[1] # If the current position has a piece of this Agent if board[positionY][positionX] == self._color: # Get the weight from hard-coded matrix myEvaluationScore += self.ending[positionY][positionX] else: opponentEvaluationScore += self.ending[positionY][positionX] # The differences between this Agent and its opponent. return myEvaluationScore - opponentEvaluationScore
def sliding_window(binary_warped: np.array): """ Assuming you have created a warped binary image called "binary_warped" This function takes a histogram of the bottom half of the image and gradually searches for a line in left and right half using a sliding window approach. :param binary_warped: :return: line fittings (left, right), line x pixels (left, right), line y pixels (for both the same), result picture """ histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0) # Create an output image to draw on and visualize the result out_img = np.dstack((binary_warped, binary_warped, binary_warped)) * 255 # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0] // 2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # Choose the number of sliding windows nwindows = 9 # Set height of windows window_height = np.int(binary_warped.shape[0] / nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated for each window leftx_current = leftx_base rightx_current = rightx_base # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window + 1) * window_height win_y_high = binary_warped.shape[0] - window * window_height win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin # Draw the windows on the visualization image cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2) cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2) # Identify the nonzero pixels in x and y within the window good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) # If you found > minpix pixels, recenter next window on their mean position if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Generate x and y values for plotting ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) left_fitx = left_fit[0] * ploty**2 + left_fit[1] * ploty + left_fit[2] right_fitx = right_fit[0] * ploty**2 + right_fit[1] * ploty + right_fit[2] out_img[lefty, leftx] = [255, 0, 0] out_img[righty, rightx] = [0, 0, 255] return [left_fit, right_fit, left_fitx, right_fitx, ploty, out_img]